blob: 557b6dec5b501b1695b66914c85c3c0b184b9d12 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Test the support for SSL and sockets
2
3import sys
4import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Thomas Woutersed03b412007-08-28 21:37:11 +00006import socket
Bill Janssen6e027db2007-11-15 22:23:56 +00007import select
Thomas Woutersed03b412007-08-28 21:37:11 +00008import time
Christian Heimes9424bb42013-06-17 15:32:57 +02009import datetime
Antoine Pitroucfcd8ad2010-04-23 23:31:47 +000010import gc
Thomas Woutersed03b412007-08-28 21:37:11 +000011import os
Antoine Pitroucfcd8ad2010-04-23 23:31:47 +000012import errno
Thomas Woutersed03b412007-08-28 21:37:11 +000013import pprint
Antoine Pitrou152efa22010-05-16 18:19:27 +000014import tempfile
Antoine Pitrou803e6d62010-10-13 10:36:15 +000015import urllib.request
Thomas Woutersed03b412007-08-28 21:37:11 +000016import traceback
Bill Janssen54cc54c2007-12-14 22:08:56 +000017import asyncore
Antoine Pitrou9d543662010-04-23 23:10:32 +000018import weakref
Antoine Pitrou15cee622010-08-04 16:45:21 +000019import platform
Antoine Pitrou23df4832010-08-04 17:14:06 +000020import functools
Thomas Woutersed03b412007-08-28 21:37:11 +000021
Antoine Pitrou05d936d2010-10-13 11:38:36 +000022ssl = support.import_module("ssl")
23
Martin Panter3840b2a2016-03-27 01:53:46 +000024try:
25 import threading
26except ImportError:
27 _have_threads = False
28else:
29 _have_threads = True
30
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010031PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000032HOST = support.HOST
Christian Heimes598894f2016-09-05 23:19:05 +020033IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL')
34IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0)
35
Antoine Pitrou152efa22010-05-16 18:19:27 +000036
Christian Heimesefff7062013-11-21 03:35:02 +010037def data_file(*name):
38 return os.path.join(os.path.dirname(__file__), *name)
Antoine Pitrou152efa22010-05-16 18:19:27 +000039
Antoine Pitrou81564092010-10-08 23:06:24 +000040# The custom key and certificate files used in test_ssl are generated
41# using Lib/test/make_ssl_certs.py.
42# Other certificates are simply fetched from the Internet servers they
43# are meant to authenticate.
44
Antoine Pitrou152efa22010-05-16 18:19:27 +000045CERTFILE = data_file("keycert.pem")
Victor Stinner313a1202010-06-11 23:56:51 +000046BYTES_CERTFILE = os.fsencode(CERTFILE)
Antoine Pitrou152efa22010-05-16 18:19:27 +000047ONLYCERT = data_file("ssl_cert.pem")
48ONLYKEY = data_file("ssl_key.pem")
Victor Stinner313a1202010-06-11 23:56:51 +000049BYTES_ONLYCERT = os.fsencode(ONLYCERT)
50BYTES_ONLYKEY = os.fsencode(ONLYKEY)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020051CERTFILE_PROTECTED = data_file("keycert.passwd.pem")
52ONLYKEY_PROTECTED = data_file("ssl_key.passwd.pem")
53KEY_PASSWORD = "somepass"
Antoine Pitrou152efa22010-05-16 18:19:27 +000054CAPATH = data_file("capath")
Victor Stinner313a1202010-06-11 23:56:51 +000055BYTES_CAPATH = os.fsencode(CAPATH)
Christian Heimesefff7062013-11-21 03:35:02 +010056CAFILE_NEURONIO = data_file("capath", "4e1295a3.0")
57CAFILE_CACERT = data_file("capath", "5ed36f99.0")
58
Antoine Pitrou152efa22010-05-16 18:19:27 +000059
Christian Heimes22587792013-11-21 23:56:13 +010060# empty CRL
61CRLFILE = data_file("revocation.crl")
62
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010063# Two keys and certs signed by the same CA (for SNI tests)
64SIGNED_CERTFILE = data_file("keycert3.pem")
65SIGNED_CERTFILE2 = data_file("keycert4.pem")
Martin Panter3840b2a2016-03-27 01:53:46 +000066# Same certificate as pycacert.pem, but without extra text in file
67SIGNING_CA = data_file("capath", "ceff1710.0")
Christian Heimes1c03abd2016-09-06 23:25:35 +020068# cert with all kinds of subject alt names
69ALLSANFILE = data_file("allsans.pem")
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010070
Martin Panter3d81d932016-01-14 09:36:00 +000071REMOTE_HOST = "self-signed.pythontest.net"
Antoine Pitrou152efa22010-05-16 18:19:27 +000072
73EMPTYCERT = data_file("nullcert.pem")
74BADCERT = data_file("badcert.pem")
Martin Panter407b62f2016-01-30 03:41:43 +000075NONEXISTINGCERT = data_file("XXXnonexisting.pem")
Antoine Pitrou152efa22010-05-16 18:19:27 +000076BADKEY = data_file("badkey.pem")
Antoine Pitroud8c347a2011-10-01 19:20:25 +020077NOKIACERT = data_file("nokia.pem")
Christian Heimes824f7f32013-08-17 00:54:47 +020078NULLBYTECERT = data_file("nullbytecert.pem")
Antoine Pitrou152efa22010-05-16 18:19:27 +000079
Benjamin Petersona7eaf562015-04-02 00:04:06 -040080DHFILE = data_file("dh1024.pem")
Antoine Pitrou0e576f12011-12-22 10:03:38 +010081BYTES_DHFILE = os.fsencode(DHFILE)
Thomas Woutersed03b412007-08-28 21:37:11 +000082
Christian Heimes358cfd42016-09-10 22:43:48 +020083# Not defined in all versions of OpenSSL
84OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0)
85OP_SINGLE_DH_USE = getattr(ssl, "OP_SINGLE_DH_USE", 0)
86OP_SINGLE_ECDH_USE = getattr(ssl, "OP_SINGLE_ECDH_USE", 0)
87OP_CIPHER_SERVER_PREFERENCE = getattr(ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
88
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010089
Thomas Woutersed03b412007-08-28 21:37:11 +000090def handle_error(prefix):
91 exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
Benjamin Petersonee8712c2008-05-20 21:35:26 +000092 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +000093 sys.stdout.write(prefix + exc_format)
Thomas Woutersed03b412007-08-28 21:37:11 +000094
Antoine Pitroub5218772010-05-21 09:56:06 +000095def can_clear_options():
96 # 0.9.8m or higher
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020097 return ssl._OPENSSL_API_VERSION >= (0, 9, 8, 13, 15)
Antoine Pitroub5218772010-05-21 09:56:06 +000098
99def no_sslv2_implies_sslv3_hello():
100 # 0.9.7h or higher
101 return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15)
102
Christian Heimes2427b502013-11-23 11:24:32 +0100103def have_verify_flags():
104 # 0.9.8 or higher
105 return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 0, 15)
106
Antoine Pitrouc695c952014-04-28 20:57:36 +0200107def utc_offset(): #NOTE: ignore issues like #1647654
108 # local time = utc time + utc offset
109 if time.daylight and time.localtime().tm_isdst > 0:
110 return -time.altzone # seconds
111 return -time.timezone
112
Christian Heimes9424bb42013-06-17 15:32:57 +0200113def asn1time(cert_time):
114 # Some versions of OpenSSL ignore seconds, see #18207
115 # 0.9.8.i
116 if ssl._OPENSSL_API_VERSION == (0, 9, 8, 9, 15):
117 fmt = "%b %d %H:%M:%S %Y GMT"
118 dt = datetime.datetime.strptime(cert_time, fmt)
119 dt = dt.replace(second=0)
120 cert_time = dt.strftime(fmt)
121 # %d adds leading zero but ASN1_TIME_print() uses leading space
122 if cert_time[4] == "0":
123 cert_time = cert_time[:4] + " " + cert_time[5:]
124
125 return cert_time
Thomas Woutersed03b412007-08-28 21:37:11 +0000126
Antoine Pitrou23df4832010-08-04 17:14:06 +0000127# Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2
128def skip_if_broken_ubuntu_ssl(func):
Victor Stinner3de49192011-05-09 00:42:58 +0200129 if hasattr(ssl, 'PROTOCOL_SSLv2'):
130 @functools.wraps(func)
131 def f(*args, **kwargs):
132 try:
133 ssl.SSLContext(ssl.PROTOCOL_SSLv2)
134 except ssl.SSLError:
135 if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
136 platform.linux_distribution() == ('debian', 'squeeze/sid', '')):
137 raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
138 return func(*args, **kwargs)
139 return f
140 else:
141 return func
Antoine Pitrou23df4832010-08-04 17:14:06 +0000142
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100143needs_sni = unittest.skipUnless(ssl.HAS_SNI, "SNI support needed for this test")
144
Antoine Pitrou23df4832010-08-04 17:14:06 +0000145
Christian Heimesd0486372016-09-10 23:23:33 +0200146def test_wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS, *,
147 cert_reqs=ssl.CERT_NONE, ca_certs=None,
148 ciphers=None, certfile=None, keyfile=None,
149 **kwargs):
150 context = ssl.SSLContext(ssl_version)
151 if cert_reqs is not None:
152 context.verify_mode = cert_reqs
153 if ca_certs is not None:
154 context.load_verify_locations(ca_certs)
155 if certfile is not None or keyfile is not None:
156 context.load_cert_chain(certfile, keyfile)
157 if ciphers is not None:
158 context.set_ciphers(ciphers)
159 return context.wrap_socket(sock, **kwargs)
160
Antoine Pitrou152efa22010-05-16 18:19:27 +0000161class BasicSocketTests(unittest.TestCase):
Thomas Woutersed03b412007-08-28 21:37:11 +0000162
Antoine Pitrou480a1242010-04-28 21:37:09 +0000163 def test_constants(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000164 ssl.CERT_NONE
165 ssl.CERT_OPTIONAL
166 ssl.CERT_REQUIRED
Antoine Pitrou6db49442011-12-19 13:27:11 +0100167 ssl.OP_CIPHER_SERVER_PREFERENCE
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100168 ssl.OP_SINGLE_DH_USE
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100169 if ssl.HAS_ECDH:
170 ssl.OP_SINGLE_ECDH_USE
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100171 if ssl.OPENSSL_VERSION_INFO >= (1, 0):
172 ssl.OP_NO_COMPRESSION
Antoine Pitroud5323212010-10-22 18:19:07 +0000173 self.assertIn(ssl.HAS_SNI, {True, False})
Antoine Pitrou501da612011-12-21 09:27:41 +0100174 self.assertIn(ssl.HAS_ECDH, {True, False})
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
Antoine Pitrou172f0252014-04-18 20:33:08 +0200176 def test_str_for_enums(self):
177 # Make sure that the PROTOCOL_* constants have enum-like string
178 # reprs.
Christian Heimes598894f2016-09-05 23:19:05 +0200179 proto = ssl.PROTOCOL_TLS
180 self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS')
Antoine Pitrou172f0252014-04-18 20:33:08 +0200181 ctx = ssl.SSLContext(proto)
182 self.assertIs(ctx.protocol, proto)
183
Antoine Pitrou480a1242010-04-28 21:37:09 +0000184 def test_random(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000185 v = ssl.RAND_status()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000186 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000187 sys.stdout.write("\n RAND_status is %d (%s)\n"
188 % (v, (v and "sufficient randomness") or
189 "insufficient randomness"))
Victor Stinner99c8b162011-05-24 12:05:19 +0200190
191 data, is_cryptographic = ssl.RAND_pseudo_bytes(16)
192 self.assertEqual(len(data), 16)
193 self.assertEqual(is_cryptographic, v == 1)
194 if v:
195 data = ssl.RAND_bytes(16)
196 self.assertEqual(len(data), 16)
Victor Stinner2e2baa92011-05-25 11:15:16 +0200197 else:
198 self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16)
Victor Stinner99c8b162011-05-24 12:05:19 +0200199
Victor Stinner1e81a392013-12-19 16:47:04 +0100200 # negative num is invalid
201 self.assertRaises(ValueError, ssl.RAND_bytes, -5)
202 self.assertRaises(ValueError, ssl.RAND_pseudo_bytes, -5)
203
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100204 if hasattr(ssl, 'RAND_egd'):
205 self.assertRaises(TypeError, ssl.RAND_egd, 1)
206 self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000207 ssl.RAND_add("this is a random string", 75.0)
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +0200208 ssl.RAND_add(b"this is a random bytes object", 75.0)
209 ssl.RAND_add(bytearray(b"this is a random bytearray object"), 75.0)
Thomas Woutersed03b412007-08-28 21:37:11 +0000210
Christian Heimesf77b4b22013-08-21 13:26:05 +0200211 @unittest.skipUnless(os.name == 'posix', 'requires posix')
212 def test_random_fork(self):
213 status = ssl.RAND_status()
214 if not status:
215 self.fail("OpenSSL's PRNG has insufficient randomness")
216
217 rfd, wfd = os.pipe()
218 pid = os.fork()
219 if pid == 0:
220 try:
221 os.close(rfd)
222 child_random = ssl.RAND_pseudo_bytes(16)[0]
223 self.assertEqual(len(child_random), 16)
224 os.write(wfd, child_random)
225 os.close(wfd)
226 except BaseException:
227 os._exit(1)
228 else:
229 os._exit(0)
230 else:
231 os.close(wfd)
232 self.addCleanup(os.close, rfd)
233 _, status = os.waitpid(pid, 0)
234 self.assertEqual(status, 0)
235
236 child_random = os.read(rfd, 16)
237 self.assertEqual(len(child_random), 16)
238 parent_random = ssl.RAND_pseudo_bytes(16)[0]
239 self.assertEqual(len(parent_random), 16)
240
241 self.assertNotEqual(child_random, parent_random)
242
Antoine Pitrou480a1242010-04-28 21:37:09 +0000243 def test_parse_cert(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244 # note that this uses an 'unofficial' function in _ssl.c,
245 # provided solely for this test, to exercise the certificate
246 # parsing code
Antoine Pitroufb046912010-11-09 20:21:19 +0000247 p = ssl._ssl._test_decode_cert(CERTFILE)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000248 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000249 sys.stdout.write("\n" + pprint.pformat(p) + "\n")
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200250 self.assertEqual(p['issuer'],
251 ((('countryName', 'XY'),),
252 (('localityName', 'Castle Anthrax'),),
253 (('organizationName', 'Python Software Foundation'),),
254 (('commonName', 'localhost'),))
255 )
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100256 # Note the next three asserts will fail if the keys are regenerated
Christian Heimes9424bb42013-06-17 15:32:57 +0200257 self.assertEqual(p['notAfter'], asn1time('Oct 5 23:01:56 2020 GMT'))
258 self.assertEqual(p['notBefore'], asn1time('Oct 8 23:01:56 2010 GMT'))
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200259 self.assertEqual(p['serialNumber'], 'D7C7381919AFC24E')
260 self.assertEqual(p['subject'],
261 ((('countryName', 'XY'),),
262 (('localityName', 'Castle Anthrax'),),
263 (('organizationName', 'Python Software Foundation'),),
264 (('commonName', 'localhost'),))
265 )
266 self.assertEqual(p['subjectAltName'], (('DNS', 'localhost'),))
267 # Issue #13034: the subjectAltName in some certificates
268 # (notably projects.developer.nokia.com:443) wasn't parsed
269 p = ssl._ssl._test_decode_cert(NOKIACERT)
270 if support.verbose:
271 sys.stdout.write("\n" + pprint.pformat(p) + "\n")
272 self.assertEqual(p['subjectAltName'],
273 (('DNS', 'projects.developer.nokia.com'),
274 ('DNS', 'projects.forum.nokia.com'))
275 )
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100276 # extra OCSP and AIA fields
277 self.assertEqual(p['OCSP'], ('http://ocsp.verisign.com',))
278 self.assertEqual(p['caIssuers'],
279 ('http://SVRIntl-G3-aia.verisign.com/SVRIntlG3.cer',))
280 self.assertEqual(p['crlDistributionPoints'],
281 ('http://SVRIntl-G3-crl.verisign.com/SVRIntlG3.crl',))
Thomas Woutersed03b412007-08-28 21:37:11 +0000282
Christian Heimes824f7f32013-08-17 00:54:47 +0200283 def test_parse_cert_CVE_2013_4238(self):
284 p = ssl._ssl._test_decode_cert(NULLBYTECERT)
285 if support.verbose:
286 sys.stdout.write("\n" + pprint.pformat(p) + "\n")
287 subject = ((('countryName', 'US'),),
288 (('stateOrProvinceName', 'Oregon'),),
289 (('localityName', 'Beaverton'),),
290 (('organizationName', 'Python Software Foundation'),),
291 (('organizationalUnitName', 'Python Core Development'),),
292 (('commonName', 'null.python.org\x00example.org'),),
293 (('emailAddress', 'python-dev@python.org'),))
294 self.assertEqual(p['subject'], subject)
295 self.assertEqual(p['issuer'], subject)
Christian Heimes157c9832013-08-25 14:12:41 +0200296 if ssl._OPENSSL_API_VERSION >= (0, 9, 8):
297 san = (('DNS', 'altnull.python.org\x00example.com'),
298 ('email', 'null@python.org\x00user@example.org'),
299 ('URI', 'http://null.python.org\x00http://example.org'),
300 ('IP Address', '192.0.2.1'),
301 ('IP Address', '2001:DB8:0:0:0:0:0:1\n'))
302 else:
303 # OpenSSL 0.9.7 doesn't support IPv6 addresses in subjectAltName
304 san = (('DNS', 'altnull.python.org\x00example.com'),
305 ('email', 'null@python.org\x00user@example.org'),
306 ('URI', 'http://null.python.org\x00http://example.org'),
307 ('IP Address', '192.0.2.1'),
308 ('IP Address', '<invalid>'))
309
310 self.assertEqual(p['subjectAltName'], san)
Christian Heimes824f7f32013-08-17 00:54:47 +0200311
Christian Heimes1c03abd2016-09-06 23:25:35 +0200312 def test_parse_all_sans(self):
313 p = ssl._ssl._test_decode_cert(ALLSANFILE)
314 self.assertEqual(p['subjectAltName'],
315 (
316 ('DNS', 'allsans'),
317 ('othername', '<unsupported>'),
318 ('othername', '<unsupported>'),
319 ('email', 'user@example.org'),
320 ('DNS', 'www.example.org'),
321 ('DirName',
322 ((('countryName', 'XY'),),
323 (('localityName', 'Castle Anthrax'),),
324 (('organizationName', 'Python Software Foundation'),),
325 (('commonName', 'dirname example'),))),
326 ('URI', 'https://www.python.org/'),
327 ('IP Address', '127.0.0.1'),
328 ('IP Address', '0:0:0:0:0:0:0:1\n'),
329 ('Registered ID', '1.2.3.4.5')
330 )
331 )
332
Antoine Pitrou480a1242010-04-28 21:37:09 +0000333 def test_DER_to_PEM(self):
Martin Panter3d81d932016-01-14 09:36:00 +0000334 with open(CAFILE_CACERT, 'r') as f:
Antoine Pitrou480a1242010-04-28 21:37:09 +0000335 pem = f.read()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336 d1 = ssl.PEM_cert_to_DER_cert(pem)
337 p2 = ssl.DER_cert_to_PEM_cert(d1)
338 d2 = ssl.PEM_cert_to_DER_cert(p2)
Antoine Pitrou18c913e2010-04-27 10:59:39 +0000339 self.assertEqual(d1, d2)
Antoine Pitrou9bfbe612010-04-27 22:08:08 +0000340 if not p2.startswith(ssl.PEM_HEADER + '\n'):
341 self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2)
342 if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'):
343 self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000345 def test_openssl_version(self):
346 n = ssl.OPENSSL_VERSION_NUMBER
347 t = ssl.OPENSSL_VERSION_INFO
348 s = ssl.OPENSSL_VERSION
349 self.assertIsInstance(n, int)
350 self.assertIsInstance(t, tuple)
351 self.assertIsInstance(s, str)
352 # Some sanity checks follow
353 # >= 0.9
354 self.assertGreaterEqual(n, 0x900000)
Antoine Pitroudfab9352014-07-21 18:35:01 -0400355 # < 3.0
356 self.assertLess(n, 0x30000000)
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000357 major, minor, fix, patch, status = t
358 self.assertGreaterEqual(major, 0)
Antoine Pitroudfab9352014-07-21 18:35:01 -0400359 self.assertLess(major, 3)
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000360 self.assertGreaterEqual(minor, 0)
361 self.assertLess(minor, 256)
362 self.assertGreaterEqual(fix, 0)
363 self.assertLess(fix, 256)
364 self.assertGreaterEqual(patch, 0)
Ned Deily05784a72015-02-05 17:20:13 +1100365 self.assertLessEqual(patch, 63)
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000366 self.assertGreaterEqual(status, 0)
367 self.assertLessEqual(status, 15)
Antoine Pitroudfab9352014-07-21 18:35:01 -0400368 # Version string as returned by {Open,Libre}SSL, the format might change
Christian Heimes598894f2016-09-05 23:19:05 +0200369 if IS_LIBRESSL:
370 self.assertTrue(s.startswith("LibreSSL {:d}".format(major)),
Victor Stinner789b8052015-01-06 11:51:06 +0100371 (s, t, hex(n)))
Antoine Pitroudfab9352014-07-21 18:35:01 -0400372 else:
373 self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
Victor Stinner789b8052015-01-06 11:51:06 +0100374 (s, t, hex(n)))
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000375
Antoine Pitrou9d543662010-04-23 23:10:32 +0000376 @support.cpython_only
377 def test_refcycle(self):
378 # Issue #7943: an SSL object doesn't create reference cycles with
379 # itself.
380 s = socket.socket(socket.AF_INET)
Christian Heimesd0486372016-09-10 23:23:33 +0200381 ss = test_wrap_socket(s)
Antoine Pitrou9d543662010-04-23 23:10:32 +0000382 wr = weakref.ref(ss)
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100383 with support.check_warnings(("", ResourceWarning)):
384 del ss
Victor Stinnere0b75b72016-03-21 17:26:04 +0100385 self.assertEqual(wr(), None)
Antoine Pitrou9d543662010-04-23 23:10:32 +0000386
Antoine Pitroua468adc2010-09-14 14:43:44 +0000387 def test_wrapped_unconnected(self):
388 # Methods on an unconnected SSLSocket propagate the original
Andrew Svetlov0832af62012-12-18 23:10:48 +0200389 # OSError raise by the underlying socket object.
Antoine Pitroua468adc2010-09-14 14:43:44 +0000390 s = socket.socket(socket.AF_INET)
Christian Heimesd0486372016-09-10 23:23:33 +0200391 with test_wrap_socket(s) as ss:
Antoine Pitroue9bb4732013-01-12 21:56:56 +0100392 self.assertRaises(OSError, ss.recv, 1)
393 self.assertRaises(OSError, ss.recv_into, bytearray(b'x'))
394 self.assertRaises(OSError, ss.recvfrom, 1)
395 self.assertRaises(OSError, ss.recvfrom_into, bytearray(b'x'), 1)
396 self.assertRaises(OSError, ss.send, b'x')
397 self.assertRaises(OSError, ss.sendto, b'x', ('0.0.0.0', 0))
Antoine Pitroua468adc2010-09-14 14:43:44 +0000398
Antoine Pitrou40f08742010-04-24 22:04:40 +0000399 def test_timeout(self):
400 # Issue #8524: when creating an SSL socket, the timeout of the
401 # original socket should be retained.
402 for timeout in (None, 0.0, 5.0):
403 s = socket.socket(socket.AF_INET)
404 s.settimeout(timeout)
Christian Heimesd0486372016-09-10 23:23:33 +0200405 with test_wrap_socket(s) as ss:
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100406 self.assertEqual(timeout, ss.gettimeout())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000407
Christian Heimesd0486372016-09-10 23:23:33 +0200408 def test_errors_sslwrap(self):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000409 sock = socket.socket()
Ezio Melottied3a7d22010-12-01 02:32:32 +0000410 self.assertRaisesRegex(ValueError,
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000411 "certfile must be specified",
412 ssl.wrap_socket, sock, keyfile=CERTFILE)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000413 self.assertRaisesRegex(ValueError,
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000414 "certfile must be specified for server-side operations",
415 ssl.wrap_socket, sock, server_side=True)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000416 self.assertRaisesRegex(ValueError,
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000417 "certfile must be specified for server-side operations",
Christian Heimesd0486372016-09-10 23:23:33 +0200418 ssl.wrap_socket, sock, server_side=True, certfile="")
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100419 with ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE) as s:
420 self.assertRaisesRegex(ValueError, "can't connect in server-side mode",
Christian Heimesd0486372016-09-10 23:23:33 +0200421 s.connect, (HOST, 8080))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200422 with self.assertRaises(OSError) as cm:
Antoine Pitroud2eca372010-10-29 23:41:37 +0000423 with socket.socket() as sock:
Martin Panter407b62f2016-01-30 03:41:43 +0000424 ssl.wrap_socket(sock, certfile=NONEXISTINGCERT)
Giampaolo Rodolà4a656eb2010-08-29 22:50:39 +0000425 self.assertEqual(cm.exception.errno, errno.ENOENT)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200426 with self.assertRaises(OSError) as cm:
Antoine Pitroud2eca372010-10-29 23:41:37 +0000427 with socket.socket() as sock:
Martin Panter407b62f2016-01-30 03:41:43 +0000428 ssl.wrap_socket(sock,
429 certfile=CERTFILE, keyfile=NONEXISTINGCERT)
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000430 self.assertEqual(cm.exception.errno, errno.ENOENT)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200431 with self.assertRaises(OSError) as cm:
Antoine Pitroud2eca372010-10-29 23:41:37 +0000432 with socket.socket() as sock:
Martin Panter407b62f2016-01-30 03:41:43 +0000433 ssl.wrap_socket(sock,
434 certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT)
Giampaolo Rodolà4a656eb2010-08-29 22:50:39 +0000435 self.assertEqual(cm.exception.errno, errno.ENOENT)
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000436
Martin Panter3464ea22016-02-01 21:58:11 +0000437 def bad_cert_test(self, certfile):
438 """Check that trying to use the given client certificate fails"""
439 certfile = os.path.join(os.path.dirname(__file__) or os.curdir,
440 certfile)
441 sock = socket.socket()
442 self.addCleanup(sock.close)
443 with self.assertRaises(ssl.SSLError):
Christian Heimesd0486372016-09-10 23:23:33 +0200444 test_wrap_socket(sock,
Martin Panter3464ea22016-02-01 21:58:11 +0000445 certfile=certfile,
446 ssl_version=ssl.PROTOCOL_TLSv1)
447
448 def test_empty_cert(self):
449 """Wrapping with an empty cert file"""
450 self.bad_cert_test("nullcert.pem")
451
452 def test_malformed_cert(self):
453 """Wrapping with a badly formatted certificate (syntax error)"""
454 self.bad_cert_test("badcert.pem")
455
456 def test_malformed_key(self):
457 """Wrapping with a badly formatted key (syntax error)"""
458 self.bad_cert_test("badkey.pem")
459
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000460 def test_match_hostname(self):
461 def ok(cert, hostname):
462 ssl.match_hostname(cert, hostname)
463 def fail(cert, hostname):
464 self.assertRaises(ssl.CertificateError,
465 ssl.match_hostname, cert, hostname)
466
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100467 # -- Hostname matching --
468
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000469 cert = {'subject': ((('commonName', 'example.com'),),)}
470 ok(cert, 'example.com')
471 ok(cert, 'ExAmple.cOm')
472 fail(cert, 'www.example.com')
473 fail(cert, '.example.com')
474 fail(cert, 'example.org')
475 fail(cert, 'exampleXcom')
476
477 cert = {'subject': ((('commonName', '*.a.com'),),)}
478 ok(cert, 'foo.a.com')
479 fail(cert, 'bar.foo.a.com')
480 fail(cert, 'a.com')
481 fail(cert, 'Xa.com')
482 fail(cert, '.a.com')
483
Georg Brandl72c98d32013-10-27 07:16:53 +0100484 # only match one left-most wildcard
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000485 cert = {'subject': ((('commonName', 'f*.com'),),)}
486 ok(cert, 'foo.com')
487 ok(cert, 'f.com')
488 fail(cert, 'bar.com')
489 fail(cert, 'foo.a.com')
490 fail(cert, 'bar.foo.com')
491
Christian Heimes824f7f32013-08-17 00:54:47 +0200492 # NULL bytes are bad, CVE-2013-4073
493 cert = {'subject': ((('commonName',
494 'null.python.org\x00example.org'),),)}
495 ok(cert, 'null.python.org\x00example.org') # or raise an error?
496 fail(cert, 'example.org')
497 fail(cert, 'null.python.org')
498
Georg Brandl72c98d32013-10-27 07:16:53 +0100499 # error cases with wildcards
500 cert = {'subject': ((('commonName', '*.*.a.com'),),)}
501 fail(cert, 'bar.foo.a.com')
502 fail(cert, 'a.com')
503 fail(cert, 'Xa.com')
504 fail(cert, '.a.com')
505
506 cert = {'subject': ((('commonName', 'a.*.com'),),)}
507 fail(cert, 'a.foo.com')
508 fail(cert, 'a..com')
509 fail(cert, 'a.com')
510
511 # wildcard doesn't match IDNA prefix 'xn--'
512 idna = 'püthon.python.org'.encode("idna").decode("ascii")
513 cert = {'subject': ((('commonName', idna),),)}
514 ok(cert, idna)
515 cert = {'subject': ((('commonName', 'x*.python.org'),),)}
516 fail(cert, idna)
517 cert = {'subject': ((('commonName', 'xn--p*.python.org'),),)}
518 fail(cert, idna)
519
520 # wildcard in first fragment and IDNA A-labels in sequent fragments
521 # are supported.
522 idna = 'www*.pythön.org'.encode("idna").decode("ascii")
523 cert = {'subject': ((('commonName', idna),),)}
524 ok(cert, 'www.pythön.org'.encode("idna").decode("ascii"))
525 ok(cert, 'www1.pythön.org'.encode("idna").decode("ascii"))
526 fail(cert, 'ftp.pythön.org'.encode("idna").decode("ascii"))
527 fail(cert, 'pythön.org'.encode("idna").decode("ascii"))
528
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000529 # Slightly fake real-world example
530 cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT',
531 'subject': ((('commonName', 'linuxfrz.org'),),),
532 'subjectAltName': (('DNS', 'linuxfr.org'),
533 ('DNS', 'linuxfr.com'),
534 ('othername', '<unsupported>'))}
535 ok(cert, 'linuxfr.org')
536 ok(cert, 'linuxfr.com')
537 # Not a "DNS" entry
538 fail(cert, '<unsupported>')
539 # When there is a subjectAltName, commonName isn't used
540 fail(cert, 'linuxfrz.org')
541
542 # A pristine real-world example
543 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
544 'subject': ((('countryName', 'US'),),
545 (('stateOrProvinceName', 'California'),),
546 (('localityName', 'Mountain View'),),
547 (('organizationName', 'Google Inc'),),
548 (('commonName', 'mail.google.com'),))}
549 ok(cert, 'mail.google.com')
550 fail(cert, 'gmail.com')
551 # Only commonName is considered
552 fail(cert, 'California')
553
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100554 # -- IPv4 matching --
555 cert = {'subject': ((('commonName', 'example.com'),),),
556 'subjectAltName': (('DNS', 'example.com'),
557 ('IP Address', '10.11.12.13'),
558 ('IP Address', '14.15.16.17'))}
559 ok(cert, '10.11.12.13')
560 ok(cert, '14.15.16.17')
561 fail(cert, '14.15.16.18')
562 fail(cert, 'example.net')
563
564 # -- IPv6 matching --
565 cert = {'subject': ((('commonName', 'example.com'),),),
566 'subjectAltName': (('DNS', 'example.com'),
567 ('IP Address', '2001:0:0:0:0:0:0:CAFE\n'),
568 ('IP Address', '2003:0:0:0:0:0:0:BABA\n'))}
569 ok(cert, '2001::cafe')
570 ok(cert, '2003::baba')
571 fail(cert, '2003::bebe')
572 fail(cert, 'example.net')
573
574 # -- Miscellaneous --
575
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000576 # Neither commonName nor subjectAltName
577 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
578 'subject': ((('countryName', 'US'),),
579 (('stateOrProvinceName', 'California'),),
580 (('localityName', 'Mountain View'),),
581 (('organizationName', 'Google Inc'),))}
582 fail(cert, 'mail.google.com')
583
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200584 # No DNS entry in subjectAltName but a commonName
585 cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT',
586 'subject': ((('countryName', 'US'),),
587 (('stateOrProvinceName', 'California'),),
588 (('localityName', 'Mountain View'),),
589 (('commonName', 'mail.google.com'),)),
590 'subjectAltName': (('othername', 'blabla'), )}
591 ok(cert, 'mail.google.com')
592
593 # No DNS entry subjectAltName and no commonName
594 cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT',
595 'subject': ((('countryName', 'US'),),
596 (('stateOrProvinceName', 'California'),),
597 (('localityName', 'Mountain View'),),
598 (('organizationName', 'Google Inc'),)),
599 'subjectAltName': (('othername', 'blabla'),)}
600 fail(cert, 'google.com')
601
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000602 # Empty cert / no cert
603 self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com')
604 self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com')
605
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200606 # Issue #17980: avoid denials of service by refusing more than one
607 # wildcard per fragment.
608 cert = {'subject': ((('commonName', 'a*b.com'),),)}
609 ok(cert, 'axxb.com')
610 cert = {'subject': ((('commonName', 'a*b.co*'),),)}
Georg Brandl72c98d32013-10-27 07:16:53 +0100611 fail(cert, 'axxb.com')
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200612 cert = {'subject': ((('commonName', 'a*b*.com'),),)}
613 with self.assertRaises(ssl.CertificateError) as cm:
614 ssl.match_hostname(cert, 'axxbxxc.com')
615 self.assertIn("too many wildcards", str(cm.exception))
616
Antoine Pitroud5323212010-10-22 18:19:07 +0000617 def test_server_side(self):
618 # server_hostname doesn't work for server sockets
619 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitroud2eca372010-10-29 23:41:37 +0000620 with socket.socket() as sock:
621 self.assertRaises(ValueError, ctx.wrap_socket, sock, True,
622 server_hostname="some.hostname")
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000623
Antoine Pitroud6494802011-07-21 01:11:30 +0200624 def test_unknown_channel_binding(self):
625 # should raise ValueError for unknown type
626 s = socket.socket(socket.AF_INET)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200627 s.bind(('127.0.0.1', 0))
628 s.listen()
629 c = socket.socket(socket.AF_INET)
630 c.connect(s.getsockname())
Christian Heimesd0486372016-09-10 23:23:33 +0200631 with test_wrap_socket(c, do_handshake_on_connect=False) as ss:
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100632 with self.assertRaises(ValueError):
633 ss.get_channel_binding("unknown-type")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200634 s.close()
Antoine Pitroud6494802011-07-21 01:11:30 +0200635
636 @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES,
637 "'tls-unique' channel binding not available")
638 def test_tls_unique_channel_binding(self):
639 # unconnected should return None for known type
640 s = socket.socket(socket.AF_INET)
Christian Heimesd0486372016-09-10 23:23:33 +0200641 with test_wrap_socket(s) as ss:
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100642 self.assertIsNone(ss.get_channel_binding("tls-unique"))
Antoine Pitroud6494802011-07-21 01:11:30 +0200643 # the same for server-side
644 s = socket.socket(socket.AF_INET)
Christian Heimesd0486372016-09-10 23:23:33 +0200645 with test_wrap_socket(s, server_side=True, certfile=CERTFILE) as ss:
Antoine Pitroue1ceb502013-01-12 21:54:44 +0100646 self.assertIsNone(ss.get_channel_binding("tls-unique"))
Antoine Pitroud6494802011-07-21 01:11:30 +0200647
Benjamin Peterson36f7b972013-01-10 14:16:20 -0600648 def test_dealloc_warn(self):
Christian Heimesd0486372016-09-10 23:23:33 +0200649 ss = test_wrap_socket(socket.socket(socket.AF_INET))
Benjamin Peterson36f7b972013-01-10 14:16:20 -0600650 r = repr(ss)
651 with self.assertWarns(ResourceWarning) as cm:
652 ss = None
653 support.gc_collect()
654 self.assertIn(r, str(cm.warning.args[0]))
655
Christian Heimes6d7ad132013-06-09 18:02:55 +0200656 def test_get_default_verify_paths(self):
657 paths = ssl.get_default_verify_paths()
658 self.assertEqual(len(paths), 6)
659 self.assertIsInstance(paths, ssl.DefaultVerifyPaths)
660
661 with support.EnvironmentVarGuard() as env:
662 env["SSL_CERT_DIR"] = CAPATH
663 env["SSL_CERT_FILE"] = CERTFILE
664 paths = ssl.get_default_verify_paths()
665 self.assertEqual(paths.cafile, CERTFILE)
666 self.assertEqual(paths.capath, CAPATH)
667
Christian Heimes44109d72013-11-22 01:51:30 +0100668 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
669 def test_enum_certificates(self):
670 self.assertTrue(ssl.enum_certificates("CA"))
671 self.assertTrue(ssl.enum_certificates("ROOT"))
672
673 self.assertRaises(TypeError, ssl.enum_certificates)
674 self.assertRaises(WindowsError, ssl.enum_certificates, "")
675
Christian Heimesc2d65e12013-11-22 16:13:55 +0100676 trust_oids = set()
677 for storename in ("CA", "ROOT"):
678 store = ssl.enum_certificates(storename)
679 self.assertIsInstance(store, list)
680 for element in store:
681 self.assertIsInstance(element, tuple)
682 self.assertEqual(len(element), 3)
683 cert, enc, trust = element
684 self.assertIsInstance(cert, bytes)
685 self.assertIn(enc, {"x509_asn", "pkcs_7_asn"})
686 self.assertIsInstance(trust, (set, bool))
687 if isinstance(trust, set):
688 trust_oids.update(trust)
Christian Heimes44109d72013-11-22 01:51:30 +0100689
690 serverAuth = "1.3.6.1.5.5.7.3.1"
Christian Heimesc2d65e12013-11-22 16:13:55 +0100691 self.assertIn(serverAuth, trust_oids)
Christian Heimes6d7ad132013-06-09 18:02:55 +0200692
Christian Heimes46bebee2013-06-09 19:03:31 +0200693 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
Christian Heimes44109d72013-11-22 01:51:30 +0100694 def test_enum_crls(self):
695 self.assertTrue(ssl.enum_crls("CA"))
696 self.assertRaises(TypeError, ssl.enum_crls)
697 self.assertRaises(WindowsError, ssl.enum_crls, "")
Christian Heimes46bebee2013-06-09 19:03:31 +0200698
Christian Heimes44109d72013-11-22 01:51:30 +0100699 crls = ssl.enum_crls("CA")
700 self.assertIsInstance(crls, list)
701 for element in crls:
702 self.assertIsInstance(element, tuple)
703 self.assertEqual(len(element), 2)
704 self.assertIsInstance(element[0], bytes)
705 self.assertIn(element[1], {"x509_asn", "pkcs_7_asn"})
Christian Heimes46bebee2013-06-09 19:03:31 +0200706
Christian Heimes46bebee2013-06-09 19:03:31 +0200707
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100708 def test_asn1object(self):
709 expected = (129, 'serverAuth', 'TLS Web Server Authentication',
710 '1.3.6.1.5.5.7.3.1')
711
712 val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1')
713 self.assertEqual(val, expected)
714 self.assertEqual(val.nid, 129)
715 self.assertEqual(val.shortname, 'serverAuth')
716 self.assertEqual(val.longname, 'TLS Web Server Authentication')
717 self.assertEqual(val.oid, '1.3.6.1.5.5.7.3.1')
718 self.assertIsInstance(val, ssl._ASN1Object)
719 self.assertRaises(ValueError, ssl._ASN1Object, 'serverAuth')
720
721 val = ssl._ASN1Object.fromnid(129)
722 self.assertEqual(val, expected)
723 self.assertIsInstance(val, ssl._ASN1Object)
724 self.assertRaises(ValueError, ssl._ASN1Object.fromnid, -1)
Christian Heimes5398e1a2013-11-22 16:20:53 +0100725 with self.assertRaisesRegex(ValueError, "unknown NID 100000"):
726 ssl._ASN1Object.fromnid(100000)
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100727 for i in range(1000):
728 try:
729 obj = ssl._ASN1Object.fromnid(i)
730 except ValueError:
731 pass
732 else:
733 self.assertIsInstance(obj.nid, int)
734 self.assertIsInstance(obj.shortname, str)
735 self.assertIsInstance(obj.longname, str)
736 self.assertIsInstance(obj.oid, (str, type(None)))
737
738 val = ssl._ASN1Object.fromname('TLS Web Server Authentication')
739 self.assertEqual(val, expected)
740 self.assertIsInstance(val, ssl._ASN1Object)
741 self.assertEqual(ssl._ASN1Object.fromname('serverAuth'), expected)
742 self.assertEqual(ssl._ASN1Object.fromname('1.3.6.1.5.5.7.3.1'),
743 expected)
Christian Heimes5398e1a2013-11-22 16:20:53 +0100744 with self.assertRaisesRegex(ValueError, "unknown object 'serverauth'"):
745 ssl._ASN1Object.fromname('serverauth')
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100746
Christian Heimes72d28502013-11-23 13:56:58 +0100747 def test_purpose_enum(self):
748 val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1')
749 self.assertIsInstance(ssl.Purpose.SERVER_AUTH, ssl._ASN1Object)
750 self.assertEqual(ssl.Purpose.SERVER_AUTH, val)
751 self.assertEqual(ssl.Purpose.SERVER_AUTH.nid, 129)
752 self.assertEqual(ssl.Purpose.SERVER_AUTH.shortname, 'serverAuth')
753 self.assertEqual(ssl.Purpose.SERVER_AUTH.oid,
754 '1.3.6.1.5.5.7.3.1')
755
756 val = ssl._ASN1Object('1.3.6.1.5.5.7.3.2')
757 self.assertIsInstance(ssl.Purpose.CLIENT_AUTH, ssl._ASN1Object)
758 self.assertEqual(ssl.Purpose.CLIENT_AUTH, val)
759 self.assertEqual(ssl.Purpose.CLIENT_AUTH.nid, 130)
760 self.assertEqual(ssl.Purpose.CLIENT_AUTH.shortname, 'clientAuth')
761 self.assertEqual(ssl.Purpose.CLIENT_AUTH.oid,
762 '1.3.6.1.5.5.7.3.2')
763
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100764 def test_unsupported_dtls(self):
765 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
766 self.addCleanup(s.close)
767 with self.assertRaises(NotImplementedError) as cx:
Christian Heimesd0486372016-09-10 23:23:33 +0200768 test_wrap_socket(s, cert_reqs=ssl.CERT_NONE)
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100769 self.assertEqual(str(cx.exception), "only stream sockets are supported")
770 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
771 with self.assertRaises(NotImplementedError) as cx:
772 ctx.wrap_socket(s)
773 self.assertEqual(str(cx.exception), "only stream sockets are supported")
774
Antoine Pitrouc695c952014-04-28 20:57:36 +0200775 def cert_time_ok(self, timestring, timestamp):
776 self.assertEqual(ssl.cert_time_to_seconds(timestring), timestamp)
777
778 def cert_time_fail(self, timestring):
779 with self.assertRaises(ValueError):
780 ssl.cert_time_to_seconds(timestring)
781
782 @unittest.skipUnless(utc_offset(),
783 'local time needs to be different from UTC')
784 def test_cert_time_to_seconds_timezone(self):
785 # Issue #19940: ssl.cert_time_to_seconds() returns wrong
786 # results if local timezone is not UTC
787 self.cert_time_ok("May 9 00:00:00 2007 GMT", 1178668800.0)
788 self.cert_time_ok("Jan 5 09:34:43 2018 GMT", 1515144883.0)
789
790 def test_cert_time_to_seconds(self):
791 timestring = "Jan 5 09:34:43 2018 GMT"
792 ts = 1515144883.0
793 self.cert_time_ok(timestring, ts)
794 # accept keyword parameter, assert its name
795 self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts)
796 # accept both %e and %d (space or zero generated by strftime)
797 self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts)
798 # case-insensitive
799 self.cert_time_ok("JaN 5 09:34:43 2018 GmT", ts)
800 self.cert_time_fail("Jan 5 09:34 2018 GMT") # no seconds
801 self.cert_time_fail("Jan 5 09:34:43 2018") # no GMT
802 self.cert_time_fail("Jan 5 09:34:43 2018 UTC") # not GMT timezone
803 self.cert_time_fail("Jan 35 09:34:43 2018 GMT") # invalid day
804 self.cert_time_fail("Jon 5 09:34:43 2018 GMT") # invalid month
805 self.cert_time_fail("Jan 5 24:00:00 2018 GMT") # invalid hour
806 self.cert_time_fail("Jan 5 09:60:43 2018 GMT") # invalid minute
807
808 newyear_ts = 1230768000.0
809 # leap seconds
810 self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts)
811 # same timestamp
812 self.cert_time_ok("Jan 1 00:00:00 2009 GMT", newyear_ts)
813
814 self.cert_time_ok("Jan 5 09:34:59 2018 GMT", 1515144899)
815 # allow 60th second (even if it is not a leap second)
816 self.cert_time_ok("Jan 5 09:34:60 2018 GMT", 1515144900)
817 # allow 2nd leap second for compatibility with time.strptime()
818 self.cert_time_ok("Jan 5 09:34:61 2018 GMT", 1515144901)
819 self.cert_time_fail("Jan 5 09:34:62 2018 GMT") # invalid seconds
820
821 # no special treatement for the special value:
822 # 99991231235959Z (rfc 5280)
823 self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0)
824
825 @support.run_with_locale('LC_ALL', '')
826 def test_cert_time_to_seconds_locale(self):
827 # `cert_time_to_seconds()` should be locale independent
828
829 def local_february_name():
830 return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0))
831
832 if local_february_name().lower() == 'feb':
833 self.skipTest("locale-specific month name needs to be "
834 "different from C locale")
835
836 # locale-independent
837 self.cert_time_ok("Feb 9 00:00:00 2007 GMT", 1170979200.0)
838 self.cert_time_fail(local_february_name() + " 9 00:00:00 2007 GMT")
839
Martin Panter3840b2a2016-03-27 01:53:46 +0000840 def test_connect_ex_error(self):
841 server = socket.socket(socket.AF_INET)
842 self.addCleanup(server.close)
843 port = support.bind_port(server) # Reserve port but don't listen
Christian Heimesd0486372016-09-10 23:23:33 +0200844 s = test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +0000845 cert_reqs=ssl.CERT_REQUIRED)
846 self.addCleanup(s.close)
847 rc = s.connect_ex((HOST, port))
848 # Issue #19919: Windows machines or VMs hosted on Windows
849 # machines sometimes return EWOULDBLOCK.
850 errors = (
851 errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT,
852 errno.EWOULDBLOCK,
853 )
854 self.assertIn(rc, errors)
855
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100856
Antoine Pitrou152efa22010-05-16 18:19:27 +0000857class ContextTests(unittest.TestCase):
858
Antoine Pitrou23df4832010-08-04 17:14:06 +0000859 @skip_if_broken_ubuntu_ssl
Antoine Pitrou152efa22010-05-16 18:19:27 +0000860 def test_constructor(self):
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100861 for protocol in PROTOCOLS:
862 ssl.SSLContext(protocol)
Christian Heimes598894f2016-09-05 23:19:05 +0200863 ctx = ssl.SSLContext()
864 self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000865 self.assertRaises(ValueError, ssl.SSLContext, -1)
866 self.assertRaises(ValueError, ssl.SSLContext, 42)
867
Antoine Pitrou23df4832010-08-04 17:14:06 +0000868 @skip_if_broken_ubuntu_ssl
Antoine Pitrou152efa22010-05-16 18:19:27 +0000869 def test_protocol(self):
870 for proto in PROTOCOLS:
871 ctx = ssl.SSLContext(proto)
872 self.assertEqual(ctx.protocol, proto)
873
874 def test_ciphers(self):
875 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
876 ctx.set_ciphers("ALL")
877 ctx.set_ciphers("DEFAULT")
Ezio Melottied3a7d22010-12-01 02:32:32 +0000878 with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
Antoine Pitrou30474062010-05-16 23:46:26 +0000879 ctx.set_ciphers("^$:,;?*'dorothyx")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000880
Christian Heimes25bfcd52016-09-06 00:04:45 +0200881 @unittest.skipIf(ssl.OPENSSL_VERSION_INFO < (1, 0, 2, 0, 0), 'OpenSSL too old')
882 def test_get_ciphers(self):
883 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Christian Heimesea9b2dc2016-09-06 10:45:44 +0200884 ctx.set_ciphers('AESGCM')
Christian Heimes25bfcd52016-09-06 00:04:45 +0200885 names = set(d['name'] for d in ctx.get_ciphers())
Christian Heimes582282b2016-09-06 11:27:25 +0200886 self.assertIn('AES256-GCM-SHA384', names)
887 self.assertIn('AES128-GCM-SHA256', names)
Christian Heimes25bfcd52016-09-06 00:04:45 +0200888
Antoine Pitrou23df4832010-08-04 17:14:06 +0000889 @skip_if_broken_ubuntu_ssl
Antoine Pitroub5218772010-05-21 09:56:06 +0000890 def test_options(self):
891 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Benjamin Petersona9dcdab2015-11-11 22:38:41 -0800892 # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
Christian Heimes598894f2016-09-05 23:19:05 +0200893 default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
Christian Heimes358cfd42016-09-10 22:43:48 +0200894 # SSLContext also enables these by default
895 default |= (OP_NO_COMPRESSION | OP_CIPHER_SERVER_PREFERENCE |
896 OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE)
Christian Heimes598894f2016-09-05 23:19:05 +0200897 self.assertEqual(default, ctx.options)
Benjamin Petersona9dcdab2015-11-11 22:38:41 -0800898 ctx.options |= ssl.OP_NO_TLSv1
Christian Heimes598894f2016-09-05 23:19:05 +0200899 self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options)
Antoine Pitroub5218772010-05-21 09:56:06 +0000900 if can_clear_options():
Christian Heimes598894f2016-09-05 23:19:05 +0200901 ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1)
902 self.assertEqual(default, ctx.options)
Antoine Pitroub5218772010-05-21 09:56:06 +0000903 ctx.options = 0
Matthias Klosef7c56242016-06-12 23:40:00 -0700904 # Ubuntu has OP_NO_SSLv3 forced on by default
905 self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
Antoine Pitroub5218772010-05-21 09:56:06 +0000906 else:
907 with self.assertRaises(ValueError):
908 ctx.options = 0
909
Christian Heimes22587792013-11-21 23:56:13 +0100910 def test_verify_mode(self):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000911 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
912 # Default value
913 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
914 ctx.verify_mode = ssl.CERT_OPTIONAL
915 self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL)
916 ctx.verify_mode = ssl.CERT_REQUIRED
917 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
918 ctx.verify_mode = ssl.CERT_NONE
919 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
920 with self.assertRaises(TypeError):
921 ctx.verify_mode = None
922 with self.assertRaises(ValueError):
923 ctx.verify_mode = 42
924
Christian Heimes2427b502013-11-23 11:24:32 +0100925 @unittest.skipUnless(have_verify_flags(),
926 "verify_flags need OpenSSL > 0.9.8")
Christian Heimes22587792013-11-21 23:56:13 +0100927 def test_verify_flags(self):
928 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Benjamin Peterson990fcaa2015-03-04 22:49:41 -0500929 # default value
930 tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
931 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf)
Christian Heimes22587792013-11-21 23:56:13 +0100932 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
933 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF)
934 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
935 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN)
936 ctx.verify_flags = ssl.VERIFY_DEFAULT
937 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT)
938 # supports any value
939 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT
940 self.assertEqual(ctx.verify_flags,
941 ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT)
942 with self.assertRaises(TypeError):
943 ctx.verify_flags = None
944
Antoine Pitrou152efa22010-05-16 18:19:27 +0000945 def test_load_cert_chain(self):
946 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
947 # Combined key and cert in a single file
Benjamin Peterson1ea070e2014-11-03 21:05:01 -0500948 ctx.load_cert_chain(CERTFILE, keyfile=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000949 ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE)
950 self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200951 with self.assertRaises(OSError) as cm:
Martin Panter407b62f2016-01-30 03:41:43 +0000952 ctx.load_cert_chain(NONEXISTINGCERT)
Giampaolo Rodolà4a656eb2010-08-29 22:50:39 +0000953 self.assertEqual(cm.exception.errno, errno.ENOENT)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000954 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000955 ctx.load_cert_chain(BADCERT)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000956 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000957 ctx.load_cert_chain(EMPTYCERT)
958 # Separate key and cert
Antoine Pitroud0919502010-05-17 10:30:00 +0000959 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000960 ctx.load_cert_chain(ONLYCERT, ONLYKEY)
961 ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
962 ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000963 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000964 ctx.load_cert_chain(ONLYCERT)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000965 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000966 ctx.load_cert_chain(ONLYKEY)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000967 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000968 ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)
969 # Mismatching key and cert
Antoine Pitroud0919502010-05-17 10:30:00 +0000970 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000971 with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"):
Martin Panter3d81d932016-01-14 09:36:00 +0000972 ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200973 # Password protected key and cert
974 ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD)
975 ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode())
976 ctx.load_cert_chain(CERTFILE_PROTECTED,
977 password=bytearray(KEY_PASSWORD.encode()))
978 ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD)
979 ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode())
980 ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED,
981 bytearray(KEY_PASSWORD.encode()))
982 with self.assertRaisesRegex(TypeError, "should be a string"):
983 ctx.load_cert_chain(CERTFILE_PROTECTED, password=True)
984 with self.assertRaises(ssl.SSLError):
985 ctx.load_cert_chain(CERTFILE_PROTECTED, password="badpass")
986 with self.assertRaisesRegex(ValueError, "cannot be longer"):
987 # openssl has a fixed limit on the password buffer.
988 # PEM_BUFSIZE is generally set to 1kb.
989 # Return a string larger than this.
990 ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400)
991 # Password callback
992 def getpass_unicode():
993 return KEY_PASSWORD
994 def getpass_bytes():
995 return KEY_PASSWORD.encode()
996 def getpass_bytearray():
997 return bytearray(KEY_PASSWORD.encode())
998 def getpass_badpass():
999 return "badpass"
1000 def getpass_huge():
1001 return b'a' * (1024 * 1024)
1002 def getpass_bad_type():
1003 return 9
1004 def getpass_exception():
1005 raise Exception('getpass error')
1006 class GetPassCallable:
1007 def __call__(self):
1008 return KEY_PASSWORD
1009 def getpass(self):
1010 return KEY_PASSWORD
1011 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode)
1012 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes)
1013 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray)
1014 ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable())
1015 ctx.load_cert_chain(CERTFILE_PROTECTED,
1016 password=GetPassCallable().getpass)
1017 with self.assertRaises(ssl.SSLError):
1018 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass)
1019 with self.assertRaisesRegex(ValueError, "cannot be longer"):
1020 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge)
1021 with self.assertRaisesRegex(TypeError, "must return a string"):
1022 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type)
1023 with self.assertRaisesRegex(Exception, "getpass error"):
1024 ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception)
1025 # Make sure the password function isn't called if it isn't needed
1026 ctx.load_cert_chain(CERTFILE, password=getpass_exception)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001027
1028 def test_load_verify_locations(self):
1029 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1030 ctx.load_verify_locations(CERTFILE)
1031 ctx.load_verify_locations(cafile=CERTFILE, capath=None)
1032 ctx.load_verify_locations(BYTES_CERTFILE)
1033 ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None)
1034 self.assertRaises(TypeError, ctx.load_verify_locations)
Christian Heimesefff7062013-11-21 03:35:02 +01001035 self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001036 with self.assertRaises(OSError) as cm:
Martin Panter407b62f2016-01-30 03:41:43 +00001037 ctx.load_verify_locations(NONEXISTINGCERT)
Giampaolo Rodolà4a656eb2010-08-29 22:50:39 +00001038 self.assertEqual(cm.exception.errno, errno.ENOENT)
Ezio Melottied3a7d22010-12-01 02:32:32 +00001039 with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
Antoine Pitrou152efa22010-05-16 18:19:27 +00001040 ctx.load_verify_locations(BADCERT)
1041 ctx.load_verify_locations(CERTFILE, CAPATH)
1042 ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH)
1043
Victor Stinner80f75e62011-01-29 11:31:20 +00001044 # Issue #10989: crash if the second argument type is invalid
1045 self.assertRaises(TypeError, ctx.load_verify_locations, None, True)
1046
Christian Heimesefff7062013-11-21 03:35:02 +01001047 def test_load_verify_cadata(self):
1048 # test cadata
1049 with open(CAFILE_CACERT) as f:
1050 cacert_pem = f.read()
1051 cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem)
1052 with open(CAFILE_NEURONIO) as f:
1053 neuronio_pem = f.read()
1054 neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem)
1055
1056 # test PEM
1057 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1058 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 0)
1059 ctx.load_verify_locations(cadata=cacert_pem)
1060 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 1)
1061 ctx.load_verify_locations(cadata=neuronio_pem)
1062 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1063 # cert already in hash table
1064 ctx.load_verify_locations(cadata=neuronio_pem)
1065 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1066
1067 # combined
1068 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1069 combined = "\n".join((cacert_pem, neuronio_pem))
1070 ctx.load_verify_locations(cadata=combined)
1071 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1072
1073 # with junk around the certs
1074 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1075 combined = ["head", cacert_pem, "other", neuronio_pem, "again",
1076 neuronio_pem, "tail"]
1077 ctx.load_verify_locations(cadata="\n".join(combined))
1078 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1079
1080 # test DER
1081 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1082 ctx.load_verify_locations(cadata=cacert_der)
1083 ctx.load_verify_locations(cadata=neuronio_der)
1084 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1085 # cert already in hash table
1086 ctx.load_verify_locations(cadata=cacert_der)
1087 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1088
1089 # combined
1090 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1091 combined = b"".join((cacert_der, neuronio_der))
1092 ctx.load_verify_locations(cadata=combined)
1093 self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
1094
1095 # error cases
1096 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1097 self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object)
1098
1099 with self.assertRaisesRegex(ssl.SSLError, "no start line"):
1100 ctx.load_verify_locations(cadata="broken")
1101 with self.assertRaisesRegex(ssl.SSLError, "not enough data"):
1102 ctx.load_verify_locations(cadata=b"broken")
1103
1104
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001105 def test_load_dh_params(self):
1106 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1107 ctx.load_dh_params(DHFILE)
1108 if os.name != 'nt':
1109 ctx.load_dh_params(BYTES_DHFILE)
1110 self.assertRaises(TypeError, ctx.load_dh_params)
1111 self.assertRaises(TypeError, ctx.load_dh_params, None)
1112 with self.assertRaises(FileNotFoundError) as cm:
Martin Panter407b62f2016-01-30 03:41:43 +00001113 ctx.load_dh_params(NONEXISTINGCERT)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001114 self.assertEqual(cm.exception.errno, errno.ENOENT)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02001115 with self.assertRaises(ssl.SSLError) as cm:
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001116 ctx.load_dh_params(CERTFILE)
1117
Antoine Pitroueb585ad2010-10-22 18:24:20 +00001118 @skip_if_broken_ubuntu_ssl
Antoine Pitroub0182c82010-10-12 20:09:02 +00001119 def test_session_stats(self):
1120 for proto in PROTOCOLS:
1121 ctx = ssl.SSLContext(proto)
1122 self.assertEqual(ctx.session_stats(), {
1123 'number': 0,
1124 'connect': 0,
1125 'connect_good': 0,
1126 'connect_renegotiate': 0,
1127 'accept': 0,
1128 'accept_good': 0,
1129 'accept_renegotiate': 0,
1130 'hits': 0,
1131 'misses': 0,
1132 'timeouts': 0,
1133 'cache_full': 0,
1134 })
1135
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001136 def test_set_default_verify_paths(self):
1137 # There's not much we can do to test that it acts as expected,
1138 # so just check it doesn't crash or raise an exception.
1139 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1140 ctx.set_default_verify_paths()
1141
Antoine Pitrou501da612011-12-21 09:27:41 +01001142 @unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build")
Antoine Pitrou923df6f2011-12-19 17:16:51 +01001143 def test_set_ecdh_curve(self):
1144 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1145 ctx.set_ecdh_curve("prime256v1")
1146 ctx.set_ecdh_curve(b"prime256v1")
1147 self.assertRaises(TypeError, ctx.set_ecdh_curve)
1148 self.assertRaises(TypeError, ctx.set_ecdh_curve, None)
1149 self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo")
1150 self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo")
1151
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001152 @needs_sni
1153 def test_sni_callback(self):
1154 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1155
1156 # set_servername_callback expects a callable, or None
1157 self.assertRaises(TypeError, ctx.set_servername_callback)
1158 self.assertRaises(TypeError, ctx.set_servername_callback, 4)
1159 self.assertRaises(TypeError, ctx.set_servername_callback, "")
1160 self.assertRaises(TypeError, ctx.set_servername_callback, ctx)
1161
1162 def dummycallback(sock, servername, ctx):
1163 pass
1164 ctx.set_servername_callback(None)
1165 ctx.set_servername_callback(dummycallback)
1166
1167 @needs_sni
1168 def test_sni_callback_refcycle(self):
1169 # Reference cycles through the servername callback are detected
1170 # and cleared.
1171 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1172 def dummycallback(sock, servername, ctx, cycle=ctx):
1173 pass
1174 ctx.set_servername_callback(dummycallback)
1175 wr = weakref.ref(ctx)
1176 del ctx, dummycallback
1177 gc.collect()
1178 self.assertIs(wr(), None)
1179
Christian Heimes9a5395a2013-06-17 15:44:12 +02001180 def test_cert_store_stats(self):
1181 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1182 self.assertEqual(ctx.cert_store_stats(),
1183 {'x509_ca': 0, 'crl': 0, 'x509': 0})
1184 ctx.load_cert_chain(CERTFILE)
1185 self.assertEqual(ctx.cert_store_stats(),
1186 {'x509_ca': 0, 'crl': 0, 'x509': 0})
1187 ctx.load_verify_locations(CERTFILE)
1188 self.assertEqual(ctx.cert_store_stats(),
1189 {'x509_ca': 0, 'crl': 0, 'x509': 1})
Martin Panterb55f8b72016-01-14 12:53:56 +00001190 ctx.load_verify_locations(CAFILE_CACERT)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001191 self.assertEqual(ctx.cert_store_stats(),
1192 {'x509_ca': 1, 'crl': 0, 'x509': 2})
1193
1194 def test_get_ca_certs(self):
1195 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1196 self.assertEqual(ctx.get_ca_certs(), [])
1197 # CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE
1198 ctx.load_verify_locations(CERTFILE)
1199 self.assertEqual(ctx.get_ca_certs(), [])
Martin Panterb55f8b72016-01-14 12:53:56 +00001200 # but CAFILE_CACERT is a CA cert
1201 ctx.load_verify_locations(CAFILE_CACERT)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001202 self.assertEqual(ctx.get_ca_certs(),
1203 [{'issuer': ((('organizationName', 'Root CA'),),
1204 (('organizationalUnitName', 'http://www.cacert.org'),),
1205 (('commonName', 'CA Cert Signing Authority'),),
1206 (('emailAddress', 'support@cacert.org'),)),
1207 'notAfter': asn1time('Mar 29 12:29:49 2033 GMT'),
1208 'notBefore': asn1time('Mar 30 12:29:49 2003 GMT'),
1209 'serialNumber': '00',
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 'crlDistributionPoints': ('https://www.cacert.org/revoke.crl',),
Christian Heimes9a5395a2013-06-17 15:44:12 +02001211 'subject': ((('organizationName', 'Root CA'),),
1212 (('organizationalUnitName', 'http://www.cacert.org'),),
1213 (('commonName', 'CA Cert Signing Authority'),),
1214 (('emailAddress', 'support@cacert.org'),)),
1215 'version': 3}])
1216
Martin Panterb55f8b72016-01-14 12:53:56 +00001217 with open(CAFILE_CACERT) as f:
Christian Heimes9a5395a2013-06-17 15:44:12 +02001218 pem = f.read()
1219 der = ssl.PEM_cert_to_DER_cert(pem)
1220 self.assertEqual(ctx.get_ca_certs(True), [der])
1221
Christian Heimes72d28502013-11-23 13:56:58 +01001222 def test_load_default_certs(self):
1223 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1224 ctx.load_default_certs()
1225
1226 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1227 ctx.load_default_certs(ssl.Purpose.SERVER_AUTH)
1228 ctx.load_default_certs()
1229
1230 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1231 ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH)
1232
1233 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1234 self.assertRaises(TypeError, ctx.load_default_certs, None)
1235 self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
1236
Benjamin Peterson91244e02014-10-03 18:17:15 -04001237 @unittest.skipIf(sys.platform == "win32", "not-Windows specific")
Christian Heimes598894f2016-09-05 23:19:05 +02001238 @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars")
Benjamin Peterson5915b0f2014-10-03 17:27:05 -04001239 def test_load_default_certs_env(self):
1240 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1241 with support.EnvironmentVarGuard() as env:
1242 env["SSL_CERT_DIR"] = CAPATH
1243 env["SSL_CERT_FILE"] = CERTFILE
1244 ctx.load_default_certs()
1245 self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0})
1246
Benjamin Peterson91244e02014-10-03 18:17:15 -04001247 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
1248 def test_load_default_certs_env_windows(self):
1249 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1250 ctx.load_default_certs()
1251 stats = ctx.cert_store_stats()
1252
1253 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1254 with support.EnvironmentVarGuard() as env:
1255 env["SSL_CERT_DIR"] = CAPATH
1256 env["SSL_CERT_FILE"] = CERTFILE
1257 ctx.load_default_certs()
1258 stats["x509"] += 1
1259 self.assertEqual(ctx.cert_store_stats(), stats)
1260
Christian Heimes358cfd42016-09-10 22:43:48 +02001261 def _assert_context_options(self, ctx):
1262 self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2)
1263 if OP_NO_COMPRESSION != 0:
1264 self.assertEqual(ctx.options & OP_NO_COMPRESSION,
1265 OP_NO_COMPRESSION)
1266 if OP_SINGLE_DH_USE != 0:
1267 self.assertEqual(ctx.options & OP_SINGLE_DH_USE,
1268 OP_SINGLE_DH_USE)
1269 if OP_SINGLE_ECDH_USE != 0:
1270 self.assertEqual(ctx.options & OP_SINGLE_ECDH_USE,
1271 OP_SINGLE_ECDH_USE)
1272 if OP_CIPHER_SERVER_PREFERENCE != 0:
1273 self.assertEqual(ctx.options & OP_CIPHER_SERVER_PREFERENCE,
1274 OP_CIPHER_SERVER_PREFERENCE)
1275
Christian Heimes4c05b472013-11-23 15:58:30 +01001276 def test_create_default_context(self):
1277 ctx = ssl.create_default_context()
Christian Heimes358cfd42016-09-10 22:43:48 +02001278
Donald Stufft6a2ba942014-03-23 19:05:28 -04001279 self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23)
Christian Heimes4c05b472013-11-23 15:58:30 +01001280 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
Christian Heimes1aa9a752013-12-02 02:41:19 +01001281 self.assertTrue(ctx.check_hostname)
Christian Heimes358cfd42016-09-10 22:43:48 +02001282 self._assert_context_options(ctx)
1283
Christian Heimes4c05b472013-11-23 15:58:30 +01001284
1285 with open(SIGNING_CA) as f:
1286 cadata = f.read()
1287 ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH,
1288 cadata=cadata)
Donald Stufft6a2ba942014-03-23 19:05:28 -04001289 self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23)
Christian Heimes4c05b472013-11-23 15:58:30 +01001290 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
Christian Heimes358cfd42016-09-10 22:43:48 +02001291 self._assert_context_options(ctx)
Christian Heimes4c05b472013-11-23 15:58:30 +01001292
1293 ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
Donald Stufft6a2ba942014-03-23 19:05:28 -04001294 self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23)
Christian Heimes4c05b472013-11-23 15:58:30 +01001295 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
Christian Heimes358cfd42016-09-10 22:43:48 +02001296 self._assert_context_options(ctx)
Christian Heimes4c05b472013-11-23 15:58:30 +01001297
Christian Heimes67986f92013-11-23 22:43:47 +01001298 def test__create_stdlib_context(self):
1299 ctx = ssl._create_stdlib_context()
1300 self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23)
1301 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
Christian Heimes1aa9a752013-12-02 02:41:19 +01001302 self.assertFalse(ctx.check_hostname)
Christian Heimes358cfd42016-09-10 22:43:48 +02001303 self._assert_context_options(ctx)
Christian Heimes67986f92013-11-23 22:43:47 +01001304
1305 ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1)
1306 self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1)
1307 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
Christian Heimes358cfd42016-09-10 22:43:48 +02001308 self._assert_context_options(ctx)
Christian Heimes67986f92013-11-23 22:43:47 +01001309
1310 ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1,
Christian Heimesa02c69a2013-12-02 20:59:28 +01001311 cert_reqs=ssl.CERT_REQUIRED,
1312 check_hostname=True)
Christian Heimes67986f92013-11-23 22:43:47 +01001313 self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1)
1314 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
Christian Heimesa02c69a2013-12-02 20:59:28 +01001315 self.assertTrue(ctx.check_hostname)
Christian Heimes358cfd42016-09-10 22:43:48 +02001316 self._assert_context_options(ctx)
Christian Heimes67986f92013-11-23 22:43:47 +01001317
1318 ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH)
1319 self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23)
1320 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
Christian Heimes358cfd42016-09-10 22:43:48 +02001321 self._assert_context_options(ctx)
Christian Heimes4c05b472013-11-23 15:58:30 +01001322
Christian Heimes1aa9a752013-12-02 02:41:19 +01001323 def test_check_hostname(self):
1324 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1325 self.assertFalse(ctx.check_hostname)
1326
1327 # Requires CERT_REQUIRED or CERT_OPTIONAL
1328 with self.assertRaises(ValueError):
1329 ctx.check_hostname = True
1330 ctx.verify_mode = ssl.CERT_REQUIRED
1331 self.assertFalse(ctx.check_hostname)
1332 ctx.check_hostname = True
1333 self.assertTrue(ctx.check_hostname)
1334
1335 ctx.verify_mode = ssl.CERT_OPTIONAL
1336 ctx.check_hostname = True
1337 self.assertTrue(ctx.check_hostname)
1338
1339 # Cannot set CERT_NONE with check_hostname enabled
1340 with self.assertRaises(ValueError):
1341 ctx.verify_mode = ssl.CERT_NONE
1342 ctx.check_hostname = False
1343 self.assertFalse(ctx.check_hostname)
1344
Christian Heimes5fe668c2016-09-12 00:01:11 +02001345 def test_context_client_server(self):
1346 # PROTOCOL_TLS_CLIENT has sane defaults
1347 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1348 self.assertTrue(ctx.check_hostname)
1349 self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
1350
1351 # PROTOCOL_TLS_SERVER has different but also sane defaults
1352 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
1353 self.assertFalse(ctx.check_hostname)
1354 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
1355
Antoine Pitrou152efa22010-05-16 18:19:27 +00001356
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02001357class SSLErrorTests(unittest.TestCase):
1358
1359 def test_str(self):
1360 # The str() of a SSLError doesn't include the errno
1361 e = ssl.SSLError(1, "foo")
1362 self.assertEqual(str(e), "foo")
1363 self.assertEqual(e.errno, 1)
1364 # Same for a subclass
1365 e = ssl.SSLZeroReturnError(1, "foo")
1366 self.assertEqual(str(e), "foo")
1367 self.assertEqual(e.errno, 1)
1368
1369 def test_lib_reason(self):
1370 # Test the library and reason attributes
1371 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1372 with self.assertRaises(ssl.SSLError) as cm:
1373 ctx.load_dh_params(CERTFILE)
1374 self.assertEqual(cm.exception.library, 'PEM')
1375 self.assertEqual(cm.exception.reason, 'NO_START_LINE')
1376 s = str(cm.exception)
1377 self.assertTrue(s.startswith("[PEM: NO_START_LINE] no start line"), s)
1378
1379 def test_subclass(self):
1380 # Check that the appropriate SSLError subclass is raised
1381 # (this only tests one of them)
1382 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1383 with socket.socket() as s:
1384 s.bind(("127.0.0.1", 0))
Charles-François Natali6e204602014-07-23 19:28:13 +01001385 s.listen()
Antoine Pitroue1ceb502013-01-12 21:54:44 +01001386 c = socket.socket()
1387 c.connect(s.getsockname())
1388 c.setblocking(False)
1389 with ctx.wrap_socket(c, False, do_handshake_on_connect=False) as c:
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02001390 with self.assertRaises(ssl.SSLWantReadError) as cm:
1391 c.do_handshake()
1392 s = str(cm.exception)
1393 self.assertTrue(s.startswith("The operation did not complete (read)"), s)
1394 # For compatibility
1395 self.assertEqual(cm.exception.errno, ssl.SSL_ERROR_WANT_READ)
1396
1397
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001398class MemoryBIOTests(unittest.TestCase):
1399
1400 def test_read_write(self):
1401 bio = ssl.MemoryBIO()
1402 bio.write(b'foo')
1403 self.assertEqual(bio.read(), b'foo')
1404 self.assertEqual(bio.read(), b'')
1405 bio.write(b'foo')
1406 bio.write(b'bar')
1407 self.assertEqual(bio.read(), b'foobar')
1408 self.assertEqual(bio.read(), b'')
1409 bio.write(b'baz')
1410 self.assertEqual(bio.read(2), b'ba')
1411 self.assertEqual(bio.read(1), b'z')
1412 self.assertEqual(bio.read(1), b'')
1413
1414 def test_eof(self):
1415 bio = ssl.MemoryBIO()
1416 self.assertFalse(bio.eof)
1417 self.assertEqual(bio.read(), b'')
1418 self.assertFalse(bio.eof)
1419 bio.write(b'foo')
1420 self.assertFalse(bio.eof)
1421 bio.write_eof()
1422 self.assertFalse(bio.eof)
1423 self.assertEqual(bio.read(2), b'fo')
1424 self.assertFalse(bio.eof)
1425 self.assertEqual(bio.read(1), b'o')
1426 self.assertTrue(bio.eof)
1427 self.assertEqual(bio.read(), b'')
1428 self.assertTrue(bio.eof)
1429
1430 def test_pending(self):
1431 bio = ssl.MemoryBIO()
1432 self.assertEqual(bio.pending, 0)
1433 bio.write(b'foo')
1434 self.assertEqual(bio.pending, 3)
1435 for i in range(3):
1436 bio.read(1)
1437 self.assertEqual(bio.pending, 3-i-1)
1438 for i in range(3):
1439 bio.write(b'x')
1440 self.assertEqual(bio.pending, i+1)
1441 bio.read()
1442 self.assertEqual(bio.pending, 0)
1443
1444 def test_buffer_types(self):
1445 bio = ssl.MemoryBIO()
1446 bio.write(b'foo')
1447 self.assertEqual(bio.read(), b'foo')
1448 bio.write(bytearray(b'bar'))
1449 self.assertEqual(bio.read(), b'bar')
1450 bio.write(memoryview(b'baz'))
1451 self.assertEqual(bio.read(), b'baz')
1452
1453 def test_error_types(self):
1454 bio = ssl.MemoryBIO()
1455 self.assertRaises(TypeError, bio.write, 'foo')
1456 self.assertRaises(TypeError, bio.write, None)
1457 self.assertRaises(TypeError, bio.write, True)
1458 self.assertRaises(TypeError, bio.write, 1)
1459
1460
Martin Panter3840b2a2016-03-27 01:53:46 +00001461@unittest.skipUnless(_have_threads, "Needs threading module")
1462class SimpleBackgroundTests(unittest.TestCase):
1463
1464 """Tests that connect to a simple server running in the background"""
1465
1466 def setUp(self):
1467 server = ThreadedEchoServer(SIGNED_CERTFILE)
1468 self.server_addr = (HOST, server.port)
1469 server.__enter__()
1470 self.addCleanup(server.__exit__, None, None, None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitrou480a1242010-04-28 21:37:09 +00001472 def test_connect(self):
Christian Heimesd0486372016-09-10 23:23:33 +02001473 with test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001474 cert_reqs=ssl.CERT_NONE) as s:
1475 s.connect(self.server_addr)
1476 self.assertEqual({}, s.getpeercert())
Antoine Pitrou350c7222010-09-09 13:31:46 +00001477
Martin Panter3840b2a2016-03-27 01:53:46 +00001478 # this should succeed because we specify the root cert
Christian Heimesd0486372016-09-10 23:23:33 +02001479 with test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001480 cert_reqs=ssl.CERT_REQUIRED,
1481 ca_certs=SIGNING_CA) as s:
1482 s.connect(self.server_addr)
1483 self.assertTrue(s.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484
Martin Panter3840b2a2016-03-27 01:53:46 +00001485 def test_connect_fail(self):
1486 # This should fail because we have no verification certs. Connection
1487 # failure crashes ThreadedEchoServer, so run this in an independent
1488 # test method.
Christian Heimesd0486372016-09-10 23:23:33 +02001489 s = test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001490 cert_reqs=ssl.CERT_REQUIRED)
1491 self.addCleanup(s.close)
1492 self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
1493 s.connect, self.server_addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001494
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001495 def test_connect_ex(self):
1496 # Issue #11326: check connect_ex() implementation
Christian Heimesd0486372016-09-10 23:23:33 +02001497 s = test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001498 cert_reqs=ssl.CERT_REQUIRED,
1499 ca_certs=SIGNING_CA)
1500 self.addCleanup(s.close)
1501 self.assertEqual(0, s.connect_ex(self.server_addr))
1502 self.assertTrue(s.getpeercert())
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001503
1504 def test_non_blocking_connect_ex(self):
1505 # Issue #11326: non-blocking connect_ex() should allow handshake
1506 # to proceed after the socket gets ready.
Christian Heimesd0486372016-09-10 23:23:33 +02001507 s = test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001508 cert_reqs=ssl.CERT_REQUIRED,
1509 ca_certs=SIGNING_CA,
1510 do_handshake_on_connect=False)
1511 self.addCleanup(s.close)
1512 s.setblocking(False)
1513 rc = s.connect_ex(self.server_addr)
1514 # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
1515 self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK))
1516 # Wait for connect to finish
1517 select.select([], [s], [], 5.0)
1518 # Non-blocking handshake
1519 while True:
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001520 try:
Martin Panter3840b2a2016-03-27 01:53:46 +00001521 s.do_handshake()
1522 break
1523 except ssl.SSLWantReadError:
1524 select.select([s], [], [], 5.0)
1525 except ssl.SSLWantWriteError:
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001526 select.select([], [s], [], 5.0)
Martin Panter3840b2a2016-03-27 01:53:46 +00001527 # SSL established
1528 self.assertTrue(s.getpeercert())
Antoine Pitrou40f12ab2012-12-28 19:03:43 +01001529
Antoine Pitrou152efa22010-05-16 18:19:27 +00001530 def test_connect_with_context(self):
Martin Panter3840b2a2016-03-27 01:53:46 +00001531 # Same as test_connect, but with a separately created context
1532 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1533 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1534 s.connect(self.server_addr)
1535 self.assertEqual({}, s.getpeercert())
1536 # Same with a server hostname
1537 with ctx.wrap_socket(socket.socket(socket.AF_INET),
1538 server_hostname="dummy") as s:
1539 s.connect(self.server_addr)
1540 ctx.verify_mode = ssl.CERT_REQUIRED
1541 # This should succeed because we specify the root cert
1542 ctx.load_verify_locations(SIGNING_CA)
1543 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1544 s.connect(self.server_addr)
1545 cert = s.getpeercert()
1546 self.assertTrue(cert)
1547
1548 def test_connect_with_context_fail(self):
1549 # This should fail because we have no verification certs. Connection
1550 # failure crashes ThreadedEchoServer, so run this in an independent
1551 # test method.
1552 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1553 ctx.verify_mode = ssl.CERT_REQUIRED
1554 s = ctx.wrap_socket(socket.socket(socket.AF_INET))
1555 self.addCleanup(s.close)
1556 self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
1557 s.connect, self.server_addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001558
1559 def test_connect_capath(self):
1560 # Verify server certificates using the `capath` argument
Antoine Pitrou467f28d2010-05-16 19:22:44 +00001561 # NOTE: the subject hashing algorithm has been changed between
1562 # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must
1563 # contain both versions of each certificate (same content, different
Antoine Pitroud7e4c1c2010-05-17 14:13:10 +00001564 # filename) for this test to be portable across OpenSSL releases.
Martin Panter3840b2a2016-03-27 01:53:46 +00001565 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1566 ctx.verify_mode = ssl.CERT_REQUIRED
1567 ctx.load_verify_locations(capath=CAPATH)
1568 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1569 s.connect(self.server_addr)
1570 cert = s.getpeercert()
1571 self.assertTrue(cert)
1572 # Same with a bytes `capath` argument
1573 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1574 ctx.verify_mode = ssl.CERT_REQUIRED
1575 ctx.load_verify_locations(capath=BYTES_CAPATH)
1576 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1577 s.connect(self.server_addr)
1578 cert = s.getpeercert()
1579 self.assertTrue(cert)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580
Christian Heimesefff7062013-11-21 03:35:02 +01001581 def test_connect_cadata(self):
Martin Panter3840b2a2016-03-27 01:53:46 +00001582 with open(SIGNING_CA) as f:
Christian Heimesefff7062013-11-21 03:35:02 +01001583 pem = f.read()
1584 der = ssl.PEM_cert_to_DER_cert(pem)
Martin Panter3840b2a2016-03-27 01:53:46 +00001585 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1586 ctx.verify_mode = ssl.CERT_REQUIRED
1587 ctx.load_verify_locations(cadata=pem)
1588 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1589 s.connect(self.server_addr)
1590 cert = s.getpeercert()
1591 self.assertTrue(cert)
Christian Heimesefff7062013-11-21 03:35:02 +01001592
Martin Panter3840b2a2016-03-27 01:53:46 +00001593 # same with DER
1594 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1595 ctx.verify_mode = ssl.CERT_REQUIRED
1596 ctx.load_verify_locations(cadata=der)
1597 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1598 s.connect(self.server_addr)
1599 cert = s.getpeercert()
1600 self.assertTrue(cert)
Christian Heimesefff7062013-11-21 03:35:02 +01001601
Antoine Pitroue3220242010-04-24 11:13:53 +00001602 @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows")
1603 def test_makefile_close(self):
1604 # Issue #5238: creating a file-like object with makefile() shouldn't
1605 # delay closing the underlying "real socket" (here tested with its
1606 # file descriptor, hence skipping the test under Windows).
Christian Heimesd0486372016-09-10 23:23:33 +02001607 ss = test_wrap_socket(socket.socket(socket.AF_INET))
Martin Panter3840b2a2016-03-27 01:53:46 +00001608 ss.connect(self.server_addr)
1609 fd = ss.fileno()
1610 f = ss.makefile()
1611 f.close()
1612 # The fd is still open
1613 os.read(fd, 0)
1614 # Closing the SSL socket should close the fd too
1615 ss.close()
1616 gc.collect()
1617 with self.assertRaises(OSError) as e:
Antoine Pitroue3220242010-04-24 11:13:53 +00001618 os.read(fd, 0)
Martin Panter3840b2a2016-03-27 01:53:46 +00001619 self.assertEqual(e.exception.errno, errno.EBADF)
Antoine Pitroue3220242010-04-24 11:13:53 +00001620
Antoine Pitrou480a1242010-04-28 21:37:09 +00001621 def test_non_blocking_handshake(self):
Martin Panter3840b2a2016-03-27 01:53:46 +00001622 s = socket.socket(socket.AF_INET)
1623 s.connect(self.server_addr)
1624 s.setblocking(False)
Christian Heimesd0486372016-09-10 23:23:33 +02001625 s = test_wrap_socket(s,
Martin Panter3840b2a2016-03-27 01:53:46 +00001626 cert_reqs=ssl.CERT_NONE,
1627 do_handshake_on_connect=False)
1628 self.addCleanup(s.close)
1629 count = 0
1630 while True:
1631 try:
1632 count += 1
1633 s.do_handshake()
1634 break
1635 except ssl.SSLWantReadError:
1636 select.select([s], [], [])
1637 except ssl.SSLWantWriteError:
1638 select.select([], [s], [])
1639 if support.verbose:
1640 sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001641
Antoine Pitrou480a1242010-04-28 21:37:09 +00001642 def test_get_server_certificate(self):
Martin Panter3840b2a2016-03-27 01:53:46 +00001643 _test_get_server_certificate(self, *self.server_addr, cert=SIGNING_CA)
Antoine Pitrou5aefa662011-04-28 19:24:46 +02001644
Martin Panter3840b2a2016-03-27 01:53:46 +00001645 def test_get_server_certificate_fail(self):
1646 # Connection failure crashes ThreadedEchoServer, so run this in an
1647 # independent test method
1648 _test_get_server_certificate_fail(self, *self.server_addr)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001649
Antoine Pitrouf4c7bad2010-08-15 23:02:22 +00001650 def test_ciphers(self):
Christian Heimesd0486372016-09-10 23:23:33 +02001651 with test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001652 cert_reqs=ssl.CERT_NONE, ciphers="ALL") as s:
1653 s.connect(self.server_addr)
Christian Heimesd0486372016-09-10 23:23:33 +02001654 with test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001655 cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") as s:
1656 s.connect(self.server_addr)
1657 # Error checking can happen at instantiation or when connecting
1658 with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
1659 with socket.socket(socket.AF_INET) as sock:
Christian Heimesd0486372016-09-10 23:23:33 +02001660 s = test_wrap_socket(sock,
Martin Panter3840b2a2016-03-27 01:53:46 +00001661 cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
1662 s.connect(self.server_addr)
Antoine Pitroufec12ff2010-04-21 19:46:23 +00001663
Christian Heimes9a5395a2013-06-17 15:44:12 +02001664 def test_get_ca_certs_capath(self):
1665 # capath certs are loaded on request
Martin Panter3840b2a2016-03-27 01:53:46 +00001666 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1667 ctx.verify_mode = ssl.CERT_REQUIRED
1668 ctx.load_verify_locations(capath=CAPATH)
1669 self.assertEqual(ctx.get_ca_certs(), [])
1670 with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s:
1671 s.connect(self.server_addr)
1672 cert = s.getpeercert()
1673 self.assertTrue(cert)
1674 self.assertEqual(len(ctx.get_ca_certs()), 1)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001675
Christian Heimes575596e2013-12-15 21:49:17 +01001676 @needs_sni
Christian Heimes8e7f3942013-12-05 07:41:08 +01001677 def test_context_setget(self):
1678 # Check that the context of a connected socket can be replaced.
Martin Panter3840b2a2016-03-27 01:53:46 +00001679 ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1680 ctx2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1681 s = socket.socket(socket.AF_INET)
1682 with ctx1.wrap_socket(s) as ss:
1683 ss.connect(self.server_addr)
1684 self.assertIs(ss.context, ctx1)
1685 self.assertIs(ss._sslobj.context, ctx1)
1686 ss.context = ctx2
1687 self.assertIs(ss.context, ctx2)
1688 self.assertIs(ss._sslobj.context, ctx2)
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001689
1690 def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs):
1691 # A simple IO loop. Call func(*args) depending on the error we get
1692 # (WANT_READ or WANT_WRITE) move data between the socket and the BIOs.
1693 timeout = kwargs.get('timeout', 10)
1694 count = 0
1695 while True:
1696 errno = None
1697 count += 1
1698 try:
1699 ret = func(*args)
1700 except ssl.SSLError as e:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001701 if e.errno not in (ssl.SSL_ERROR_WANT_READ,
Martin Panter40b97ec2016-01-14 13:05:46 +00001702 ssl.SSL_ERROR_WANT_WRITE):
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001703 raise
1704 errno = e.errno
1705 # Get any data from the outgoing BIO irrespective of any error, and
1706 # send it to the socket.
1707 buf = outgoing.read()
1708 sock.sendall(buf)
1709 # If there's no error, we're done. For WANT_READ, we need to get
1710 # data from the socket and put it in the incoming BIO.
1711 if errno is None:
1712 break
1713 elif errno == ssl.SSL_ERROR_WANT_READ:
1714 buf = sock.recv(32768)
1715 if buf:
1716 incoming.write(buf)
1717 else:
1718 incoming.write_eof()
1719 if support.verbose:
1720 sys.stdout.write("Needed %d calls to complete %s().\n"
1721 % (count, func.__name__))
1722 return ret
1723
Martin Panter3840b2a2016-03-27 01:53:46 +00001724 def test_bio_handshake(self):
1725 sock = socket.socket(socket.AF_INET)
1726 self.addCleanup(sock.close)
1727 sock.connect(self.server_addr)
1728 incoming = ssl.MemoryBIO()
1729 outgoing = ssl.MemoryBIO()
1730 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1731 ctx.verify_mode = ssl.CERT_REQUIRED
1732 ctx.load_verify_locations(SIGNING_CA)
1733 ctx.check_hostname = True
1734 sslobj = ctx.wrap_bio(incoming, outgoing, False, 'localhost')
1735 self.assertIs(sslobj._sslobj.owner, sslobj)
1736 self.assertIsNone(sslobj.cipher())
Christian Heimes01113fa2016-09-05 23:23:24 +02001737 self.assertIsNotNone(sslobj.shared_ciphers())
Martin Panter3840b2a2016-03-27 01:53:46 +00001738 self.assertRaises(ValueError, sslobj.getpeercert)
1739 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1740 self.assertIsNone(sslobj.get_channel_binding('tls-unique'))
1741 self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
1742 self.assertTrue(sslobj.cipher())
Christian Heimes01113fa2016-09-05 23:23:24 +02001743 self.assertIsNotNone(sslobj.shared_ciphers())
Martin Panter3840b2a2016-03-27 01:53:46 +00001744 self.assertTrue(sslobj.getpeercert())
1745 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1746 self.assertTrue(sslobj.get_channel_binding('tls-unique'))
1747 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001748 self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap)
Martin Panter3840b2a2016-03-27 01:53:46 +00001749 except ssl.SSLSyscallError:
1750 # If the server shuts down the TCP connection without sending a
1751 # secure shutdown message, this is reported as SSL_ERROR_SYSCALL
1752 pass
1753 self.assertRaises(ssl.SSLError, sslobj.write, b'foo')
1754
1755 def test_bio_read_write_data(self):
1756 sock = socket.socket(socket.AF_INET)
1757 self.addCleanup(sock.close)
1758 sock.connect(self.server_addr)
1759 incoming = ssl.MemoryBIO()
1760 outgoing = ssl.MemoryBIO()
1761 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1762 ctx.verify_mode = ssl.CERT_NONE
1763 sslobj = ctx.wrap_bio(incoming, outgoing, False)
1764 self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
1765 req = b'FOO\n'
1766 self.ssl_io_loop(sock, incoming, outgoing, sslobj.write, req)
1767 buf = self.ssl_io_loop(sock, incoming, outgoing, sslobj.read, 1024)
1768 self.assertEqual(buf, b'foo\n')
1769 self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap)
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001770
1771
Martin Panter3840b2a2016-03-27 01:53:46 +00001772class NetworkedTests(unittest.TestCase):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773
Martin Panter3840b2a2016-03-27 01:53:46 +00001774 def test_timeout_connect_ex(self):
1775 # Issue #12065: on a timeout, connect_ex() should return the original
1776 # errno (mimicking the behaviour of non-SSL sockets).
1777 with support.transient_internet(REMOTE_HOST):
Christian Heimesd0486372016-09-10 23:23:33 +02001778 s = test_wrap_socket(socket.socket(socket.AF_INET),
Martin Panter3840b2a2016-03-27 01:53:46 +00001779 cert_reqs=ssl.CERT_REQUIRED,
1780 do_handshake_on_connect=False)
1781 self.addCleanup(s.close)
1782 s.settimeout(0.0000001)
1783 rc = s.connect_ex((REMOTE_HOST, 443))
1784 if rc == 0:
1785 self.skipTest("REMOTE_HOST responded too quickly")
1786 self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK))
1787
1788 @unittest.skipUnless(support.IPV6_ENABLED, 'Needs IPv6')
1789 def test_get_server_certificate_ipv6(self):
1790 with support.transient_internet('ipv6.google.com'):
1791 _test_get_server_certificate(self, 'ipv6.google.com', 443)
1792 _test_get_server_certificate_fail(self, 'ipv6.google.com', 443)
1793
1794 def test_algorithms(self):
1795 # Issue #8484: all algorithms should be available when verifying a
1796 # certificate.
1797 # SHA256 was added in OpenSSL 0.9.8
1798 if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15):
1799 self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION)
1800 # sha256.tbs-internet.com needs SNI to use the correct certificate
1801 if not ssl.HAS_SNI:
1802 self.skipTest("SNI needed for this test")
1803 # https://sha2.hboeck.de/ was used until 2011-01-08 (no route to host)
1804 remote = ("sha256.tbs-internet.com", 443)
1805 sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem")
1806 with support.transient_internet("sha256.tbs-internet.com"):
1807 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1808 ctx.verify_mode = ssl.CERT_REQUIRED
1809 ctx.load_verify_locations(sha256_cert)
1810 s = ctx.wrap_socket(socket.socket(socket.AF_INET),
1811 server_hostname="sha256.tbs-internet.com")
1812 try:
1813 s.connect(remote)
1814 if support.verbose:
1815 sys.stdout.write("\nCipher with %r is %r\n" %
1816 (remote, s.cipher()))
1817 sys.stdout.write("Certificate is:\n%s\n" %
1818 pprint.pformat(s.getpeercert()))
1819 finally:
1820 s.close()
1821
1822
1823def _test_get_server_certificate(test, host, port, cert=None):
1824 pem = ssl.get_server_certificate((host, port))
1825 if not pem:
1826 test.fail("No server certificate on %s:%s!" % (host, port))
1827
1828 pem = ssl.get_server_certificate((host, port), ca_certs=cert)
1829 if not pem:
1830 test.fail("No server certificate on %s:%s!" % (host, port))
1831 if support.verbose:
1832 sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem))
1833
1834def _test_get_server_certificate_fail(test, host, port):
1835 try:
1836 pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE)
1837 except ssl.SSLError as x:
1838 #should fail
1839 if support.verbose:
1840 sys.stdout.write("%s\n" % x)
1841 else:
1842 test.fail("Got server certificate %s for %s:%s!" % (pem, host, port))
1843
1844
1845if _have_threads:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001846 from test.ssl_servers import make_https_server
1847
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001848 class ThreadedEchoServer(threading.Thread):
1849
1850 class ConnectionHandler(threading.Thread):
1851
1852 """A mildly complicated class, because we want it to work both
1853 with and without the SSL wrapper around the socket connection, so
1854 that we can test the STARTTLS functionality."""
1855
Bill Janssen6e027db2007-11-15 22:23:56 +00001856 def __init__(self, server, connsock, addr):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001857 self.server = server
1858 self.running = False
1859 self.sock = connsock
Bill Janssen6e027db2007-11-15 22:23:56 +00001860 self.addr = addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001861 self.sock.setblocking(1)
1862 self.sslconn = None
1863 threading.Thread.__init__(self)
Benjamin Peterson4171da52008-08-18 21:11:09 +00001864 self.daemon = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001865
Antoine Pitrou480a1242010-04-28 21:37:09 +00001866 def wrap_conn(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867 try:
Antoine Pitroub5218772010-05-21 09:56:06 +00001868 self.sslconn = self.server.context.wrap_socket(
1869 self.sock, server_side=True)
Benjamin Petersoncca27322015-01-23 16:35:37 -05001870 self.server.selected_npn_protocols.append(self.sslconn.selected_npn_protocol())
1871 self.server.selected_alpn_protocols.append(self.sslconn.selected_alpn_protocol())
Nadeem Vawdaad246bf2013-03-03 22:44:22 +01001872 except (ssl.SSLError, ConnectionResetError) as e:
1873 # We treat ConnectionResetError as though it were an
1874 # SSLError - OpenSSL on Ubuntu abruptly closes the
1875 # connection when asked to use an unsupported protocol.
1876 #
Antoine Pitrou18c913e2010-04-27 10:59:39 +00001877 # XXX Various errors can have happened here, for example
1878 # a mismatching protocol version, an invalid certificate,
1879 # or a low-level bug. This should be made more discriminating.
Antoine Pitrou8f85f902012-01-03 22:46:48 +01001880 self.server.conn_errors.append(e)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001881 if self.server.chatty:
Bill Janssen6e027db2007-11-15 22:23:56 +00001882 handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n")
Antoine Pitrou18c913e2010-04-27 10:59:39 +00001883 self.running = False
1884 self.server.stop()
Bill Janssen6e027db2007-11-15 22:23:56 +00001885 self.close()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886 return False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887 else:
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001888 self.server.shared_ciphers.append(self.sslconn.shared_ciphers())
Antoine Pitroub5218772010-05-21 09:56:06 +00001889 if self.server.context.verify_mode == ssl.CERT_REQUIRED:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890 cert = self.sslconn.getpeercert()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001891 if support.verbose and self.server.chatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001892 sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n")
1893 cert_binary = self.sslconn.getpeercert(True)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001894 if support.verbose and self.server.chatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001895 sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n")
1896 cipher = self.sslconn.cipher()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001897 if support.verbose and self.server.chatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001898 sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n")
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001899 sys.stdout.write(" server: selected protocol is now "
1900 + str(self.sslconn.selected_npn_protocol()) + "\n")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901 return True
1902
1903 def read(self):
1904 if self.sslconn:
1905 return self.sslconn.read()
1906 else:
1907 return self.sock.recv(1024)
1908
1909 def write(self, bytes):
1910 if self.sslconn:
1911 return self.sslconn.write(bytes)
1912 else:
1913 return self.sock.send(bytes)
1914
1915 def close(self):
1916 if self.sslconn:
1917 self.sslconn.close()
1918 else:
1919 self.sock.close()
1920
Antoine Pitrou480a1242010-04-28 21:37:09 +00001921 def run(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922 self.running = True
1923 if not self.server.starttls_server:
1924 if not self.wrap_conn():
1925 return
1926 while self.running:
1927 try:
1928 msg = self.read()
Antoine Pitrou480a1242010-04-28 21:37:09 +00001929 stripped = msg.strip()
1930 if not stripped:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001931 # eof, so quit this handler
1932 self.running = False
Martin Panter3840b2a2016-03-27 01:53:46 +00001933 try:
1934 self.sock = self.sslconn.unwrap()
1935 except OSError:
1936 # Many tests shut the TCP connection down
1937 # without an SSL shutdown. This causes
1938 # unwrap() to raise OSError with errno=0!
1939 pass
1940 else:
1941 self.sslconn = None
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001942 self.close()
Antoine Pitrou480a1242010-04-28 21:37:09 +00001943 elif stripped == b'over':
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001944 if support.verbose and self.server.connectionchatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001945 sys.stdout.write(" server: client closed connection\n")
1946 self.close()
1947 return
Bill Janssen6e027db2007-11-15 22:23:56 +00001948 elif (self.server.starttls_server and
Antoine Pitrou764b8782010-04-28 22:57:15 +00001949 stripped == b'STARTTLS'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001950 if support.verbose and self.server.connectionchatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001951 sys.stdout.write(" server: read STARTTLS from client, sending OK...\n")
Antoine Pitrou480a1242010-04-28 21:37:09 +00001952 self.write(b"OK\n")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001953 if not self.wrap_conn():
1954 return
Bill Janssen40a0f662008-08-12 16:56:25 +00001955 elif (self.server.starttls_server and self.sslconn
Antoine Pitrou764b8782010-04-28 22:57:15 +00001956 and stripped == b'ENDTLS'):
Bill Janssen40a0f662008-08-12 16:56:25 +00001957 if support.verbose and self.server.connectionchatty:
1958 sys.stdout.write(" server: read ENDTLS from client, sending OK...\n")
Antoine Pitrou480a1242010-04-28 21:37:09 +00001959 self.write(b"OK\n")
Bill Janssen40a0f662008-08-12 16:56:25 +00001960 self.sock = self.sslconn.unwrap()
1961 self.sslconn = None
1962 if support.verbose and self.server.connectionchatty:
1963 sys.stdout.write(" server: connection is now unencrypted...\n")
Antoine Pitroud6494802011-07-21 01:11:30 +02001964 elif stripped == b'CB tls-unique':
1965 if support.verbose and self.server.connectionchatty:
1966 sys.stdout.write(" server: read CB tls-unique from client, sending our CB data...\n")
1967 data = self.sslconn.get_channel_binding("tls-unique")
1968 self.write(repr(data).encode("us-ascii") + b"\n")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969 else:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001970 if (support.verbose and
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001971 self.server.connectionchatty):
1972 ctype = (self.sslconn and "encrypted") or "unencrypted"
Antoine Pitrou480a1242010-04-28 21:37:09 +00001973 sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n"
1974 % (msg, ctype, msg.lower(), ctype))
1975 self.write(msg.lower())
Andrew Svetlov0832af62012-12-18 23:10:48 +02001976 except OSError:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001977 if self.server.chatty:
1978 handle_error("Test server failure:\n")
1979 self.close()
1980 self.running = False
1981 # normally, we'd just stop here, but for the test
1982 # harness, we want to stop the server
1983 self.server.stop()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984
Antoine Pitroub5218772010-05-21 09:56:06 +00001985 def __init__(self, certificate=None, ssl_version=None,
Antoine Pitrou18c913e2010-04-27 10:59:39 +00001986 certreqs=None, cacerts=None,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001987 chatty=True, connectionchatty=False, starttls_server=False,
Benjamin Petersoncca27322015-01-23 16:35:37 -05001988 npn_protocols=None, alpn_protocols=None,
1989 ciphers=None, context=None):
Antoine Pitroub5218772010-05-21 09:56:06 +00001990 if context:
1991 self.context = context
1992 else:
1993 self.context = ssl.SSLContext(ssl_version
1994 if ssl_version is not None
1995 else ssl.PROTOCOL_TLSv1)
1996 self.context.verify_mode = (certreqs if certreqs is not None
1997 else ssl.CERT_NONE)
1998 if cacerts:
1999 self.context.load_verify_locations(cacerts)
2000 if certificate:
2001 self.context.load_cert_chain(certificate)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002002 if npn_protocols:
2003 self.context.set_npn_protocols(npn_protocols)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002004 if alpn_protocols:
2005 self.context.set_alpn_protocols(alpn_protocols)
Antoine Pitroub5218772010-05-21 09:56:06 +00002006 if ciphers:
2007 self.context.set_ciphers(ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002008 self.chatty = chatty
2009 self.connectionchatty = connectionchatty
2010 self.starttls_server = starttls_server
2011 self.sock = socket.socket()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002012 self.port = support.bind_port(self.sock)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002013 self.flag = None
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002014 self.active = False
Benjamin Petersoncca27322015-01-23 16:35:37 -05002015 self.selected_npn_protocols = []
2016 self.selected_alpn_protocols = []
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002017 self.shared_ciphers = []
Antoine Pitrou8f85f902012-01-03 22:46:48 +01002018 self.conn_errors = []
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002019 threading.Thread.__init__(self)
Benjamin Peterson4171da52008-08-18 21:11:09 +00002020 self.daemon = True
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002021
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002022 def __enter__(self):
2023 self.start(threading.Event())
2024 self.flag.wait()
Antoine Pitrou8f85f902012-01-03 22:46:48 +01002025 return self
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002026
2027 def __exit__(self, *args):
2028 self.stop()
2029 self.join()
2030
Antoine Pitrou480a1242010-04-28 21:37:09 +00002031 def start(self, flag=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002032 self.flag = flag
2033 threading.Thread.start(self)
2034
Antoine Pitrou480a1242010-04-28 21:37:09 +00002035 def run(self):
Antoine Pitrouaf7c6022010-04-27 09:56:02 +00002036 self.sock.settimeout(0.05)
Charles-François Natali6e204602014-07-23 19:28:13 +01002037 self.sock.listen()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002038 self.active = True
2039 if self.flag:
2040 # signal an event
2041 self.flag.set()
2042 while self.active:
2043 try:
2044 newconn, connaddr = self.sock.accept()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002045 if support.verbose and self.chatty:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002046 sys.stdout.write(' server: new connection from '
Bill Janssen6e027db2007-11-15 22:23:56 +00002047 + repr(connaddr) + '\n')
2048 handler = self.ConnectionHandler(self, newconn, connaddr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002049 handler.start()
Antoine Pitroueced82e2012-01-27 17:33:01 +01002050 handler.join()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002051 except socket.timeout:
2052 pass
2053 except KeyboardInterrupt:
2054 self.stop()
Bill Janssen6e027db2007-11-15 22:23:56 +00002055 self.sock.close()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002056
Antoine Pitrou480a1242010-04-28 21:37:09 +00002057 def stop(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002058 self.active = False
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002059
Bill Janssen54cc54c2007-12-14 22:08:56 +00002060 class AsyncoreEchoServer(threading.Thread):
2061
2062 # this one's based on asyncore.dispatcher
2063
2064 class EchoServer (asyncore.dispatcher):
2065
2066 class ConnectionHandler (asyncore.dispatcher_with_send):
2067
2068 def __init__(self, conn, certfile):
Christian Heimesd0486372016-09-10 23:23:33 +02002069 self.socket = test_wrap_socket(conn, server_side=True,
Bill Janssen54cc54c2007-12-14 22:08:56 +00002070 certfile=certfile,
2071 do_handshake_on_connect=False)
2072 asyncore.dispatcher_with_send.__init__(self, self.socket)
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002073 self._ssl_accepting = True
2074 self._do_ssl_handshake()
Bill Janssen54cc54c2007-12-14 22:08:56 +00002075
2076 def readable(self):
2077 if isinstance(self.socket, ssl.SSLSocket):
2078 while self.socket.pending() > 0:
2079 self.handle_read_event()
2080 return True
2081
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002082 def _do_ssl_handshake(self):
2083 try:
2084 self.socket.do_handshake()
Antoine Pitrou41032a62011-10-27 23:56:55 +02002085 except (ssl.SSLWantReadError, ssl.SSLWantWriteError):
2086 return
2087 except ssl.SSLEOFError:
2088 return self.handle_close()
2089 except ssl.SSLError:
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002090 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +02002091 except OSError as err:
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002092 if err.args[0] == errno.ECONNABORTED:
2093 return self.handle_close()
Bill Janssen54cc54c2007-12-14 22:08:56 +00002094 else:
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002095 self._ssl_accepting = False
2096
2097 def handle_read(self):
2098 if self._ssl_accepting:
2099 self._do_ssl_handshake()
2100 else:
2101 data = self.recv(1024)
2102 if support.verbose:
2103 sys.stdout.write(" server: read %s from client\n" % repr(data))
2104 if not data:
2105 self.close()
2106 else:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002107 self.send(data.lower())
Bill Janssen54cc54c2007-12-14 22:08:56 +00002108
2109 def handle_close(self):
Bill Janssen2f5799b2008-06-29 00:08:12 +00002110 self.close()
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002111 if support.verbose:
Bill Janssen54cc54c2007-12-14 22:08:56 +00002112 sys.stdout.write(" server: closed connection %s\n" % self.socket)
2113
2114 def handle_error(self):
2115 raise
2116
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002117 def __init__(self, certfile):
Bill Janssen54cc54c2007-12-14 22:08:56 +00002118 self.certfile = certfile
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002119 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2120 self.port = support.bind_port(sock, '')
2121 asyncore.dispatcher.__init__(self, sock)
Bill Janssen54cc54c2007-12-14 22:08:56 +00002122 self.listen(5)
2123
Giampaolo Rodolà977c7072010-10-04 21:08:36 +00002124 def handle_accepted(self, sock_obj, addr):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002125 if support.verbose:
Bill Janssen54cc54c2007-12-14 22:08:56 +00002126 sys.stdout.write(" server: new connection from %s:%s\n" %addr)
2127 self.ConnectionHandler(sock_obj, self.certfile)
2128
2129 def handle_error(self):
2130 raise
2131
Trent Nelson78520002008-04-10 20:54:35 +00002132 def __init__(self, certfile):
Bill Janssen54cc54c2007-12-14 22:08:56 +00002133 self.flag = None
2134 self.active = False
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002135 self.server = self.EchoServer(certfile)
2136 self.port = self.server.port
Bill Janssen54cc54c2007-12-14 22:08:56 +00002137 threading.Thread.__init__(self)
Benjamin Peterson4171da52008-08-18 21:11:09 +00002138 self.daemon = True
Bill Janssen54cc54c2007-12-14 22:08:56 +00002139
2140 def __str__(self):
2141 return "<%s %s>" % (self.__class__.__name__, self.server)
2142
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002143 def __enter__(self):
2144 self.start(threading.Event())
2145 self.flag.wait()
Antoine Pitrou8f85f902012-01-03 22:46:48 +01002146 return self
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002147
2148 def __exit__(self, *args):
2149 if support.verbose:
2150 sys.stdout.write(" cleanup: stopping server.\n")
2151 self.stop()
2152 if support.verbose:
2153 sys.stdout.write(" cleanup: joining server thread.\n")
2154 self.join()
2155 if support.verbose:
2156 sys.stdout.write(" cleanup: successfully joined.\n")
2157
Bill Janssen54cc54c2007-12-14 22:08:56 +00002158 def start (self, flag=None):
2159 self.flag = flag
2160 threading.Thread.start(self)
2161
Antoine Pitrou480a1242010-04-28 21:37:09 +00002162 def run(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +00002163 self.active = True
2164 if self.flag:
2165 self.flag.set()
2166 while self.active:
2167 try:
2168 asyncore.loop(1)
2169 except:
2170 pass
2171
Antoine Pitrou480a1242010-04-28 21:37:09 +00002172 def stop(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +00002173 self.active = False
2174 self.server.close()
2175
Antoine Pitroub5218772010-05-21 09:56:06 +00002176 def server_params_test(client_context, server_context, indata=b"FOO\n",
Christian Heimes99a65702016-09-10 23:44:53 +02002177 chatty=True, connectionchatty=False, sni_name=None,
2178 session=None):
Antoine Pitrou480a1242010-04-28 21:37:09 +00002179 """
2180 Launch a server, connect a client to it and try various reads
2181 and writes.
2182 """
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002183 stats = {}
Antoine Pitroub5218772010-05-21 09:56:06 +00002184 server = ThreadedEchoServer(context=server_context,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002185 chatty=chatty,
Bill Janssen6e027db2007-11-15 22:23:56 +00002186 connectionchatty=False)
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002187 with server:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002188 with client_context.wrap_socket(socket.socket(),
Christian Heimes99a65702016-09-10 23:44:53 +02002189 server_hostname=sni_name, session=session) as s:
Antoine Pitroueba63c42012-01-28 17:38:34 +01002190 s.connect((HOST, server.port))
2191 for arg in [indata, bytearray(indata), memoryview(indata)]:
2192 if connectionchatty:
2193 if support.verbose:
2194 sys.stdout.write(
2195 " client: sending %r...\n" % indata)
2196 s.write(arg)
2197 outdata = s.read()
2198 if connectionchatty:
2199 if support.verbose:
2200 sys.stdout.write(" client: read %r\n" % outdata)
2201 if outdata != indata.lower():
2202 raise AssertionError(
2203 "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n"
2204 % (outdata[:20], len(outdata),
2205 indata[:20].lower(), len(indata)))
2206 s.write(b"over\n")
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002207 if connectionchatty:
2208 if support.verbose:
Antoine Pitroueba63c42012-01-28 17:38:34 +01002209 sys.stdout.write(" client: closing connection.\n")
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002210 stats.update({
Antoine Pitrouce816a52012-01-28 17:40:23 +01002211 'compression': s.compression(),
2212 'cipher': s.cipher(),
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002213 'peercert': s.getpeercert(),
Benjamin Petersoncca27322015-01-23 16:35:37 -05002214 'client_alpn_protocol': s.selected_alpn_protocol(),
Antoine Pitrou47e40422014-09-04 21:00:10 +02002215 'client_npn_protocol': s.selected_npn_protocol(),
2216 'version': s.version(),
Christian Heimes99a65702016-09-10 23:44:53 +02002217 'session_reused': s.session_reused,
2218 'session': s.session,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002219 })
Antoine Pitroueba63c42012-01-28 17:38:34 +01002220 s.close()
Benjamin Petersoncca27322015-01-23 16:35:37 -05002221 stats['server_alpn_protocols'] = server.selected_alpn_protocols
2222 stats['server_npn_protocols'] = server.selected_npn_protocols
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002223 stats['server_shared_ciphers'] = server.shared_ciphers
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002224 return stats
Thomas Woutersed03b412007-08-28 21:37:11 +00002225
Antoine Pitroub5218772010-05-21 09:56:06 +00002226 def try_protocol_combo(server_protocol, client_protocol, expect_success,
2227 certsreqs=None, server_options=0, client_options=0):
Antoine Pitrou47e40422014-09-04 21:00:10 +02002228 """
2229 Try to SSL-connect using *client_protocol* to *server_protocol*.
2230 If *expect_success* is true, assert that the connection succeeds,
2231 if it's false, assert that the connection fails.
2232 Also, if *expect_success* is a string, assert that it is the protocol
2233 version actually used by the connection.
2234 """
Benjamin Peterson2a691a82008-03-31 01:51:45 +00002235 if certsreqs is None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002236 certsreqs = ssl.CERT_NONE
Antoine Pitrou480a1242010-04-28 21:37:09 +00002237 certtype = {
2238 ssl.CERT_NONE: "CERT_NONE",
2239 ssl.CERT_OPTIONAL: "CERT_OPTIONAL",
2240 ssl.CERT_REQUIRED: "CERT_REQUIRED",
2241 }[certsreqs]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002242 if support.verbose:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002243 formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n"
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002244 sys.stdout.write(formatstr %
2245 (ssl.get_protocol_name(client_protocol),
2246 ssl.get_protocol_name(server_protocol),
2247 certtype))
Antoine Pitroub5218772010-05-21 09:56:06 +00002248 client_context = ssl.SSLContext(client_protocol)
Antoine Pitrou32c49152014-01-09 21:28:48 +01002249 client_context.options |= client_options
Antoine Pitroub5218772010-05-21 09:56:06 +00002250 server_context = ssl.SSLContext(server_protocol)
Antoine Pitrou32c49152014-01-09 21:28:48 +01002251 server_context.options |= server_options
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002252
2253 # NOTE: we must enable "ALL" ciphers on the client, otherwise an
2254 # SSLv23 client will send an SSLv3 hello (rather than SSLv2)
2255 # starting from OpenSSL 1.0.0 (see issue #8322).
2256 if client_context.protocol == ssl.PROTOCOL_SSLv23:
2257 client_context.set_ciphers("ALL")
2258
Antoine Pitroub5218772010-05-21 09:56:06 +00002259 for ctx in (client_context, server_context):
2260 ctx.verify_mode = certsreqs
Antoine Pitroub5218772010-05-21 09:56:06 +00002261 ctx.load_cert_chain(CERTFILE)
2262 ctx.load_verify_locations(CERTFILE)
2263 try:
Antoine Pitrou47e40422014-09-04 21:00:10 +02002264 stats = server_params_test(client_context, server_context,
2265 chatty=False, connectionchatty=False)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002266 # Protocol mismatch can result in either an SSLError, or a
2267 # "Connection reset by peer" error.
2268 except ssl.SSLError:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002269 if expect_success:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002270 raise
Andrew Svetlov0832af62012-12-18 23:10:48 +02002271 except OSError as e:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002272 if expect_success or e.errno != errno.ECONNRESET:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002273 raise
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002274 else:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002275 if not expect_success:
Antoine Pitroud75b2a92010-05-06 14:15:10 +00002276 raise AssertionError(
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002277 "Client protocol %s succeeded with server protocol %s!"
2278 % (ssl.get_protocol_name(client_protocol),
2279 ssl.get_protocol_name(server_protocol)))
Antoine Pitrou47e40422014-09-04 21:00:10 +02002280 elif (expect_success is not True
2281 and expect_success != stats['version']):
2282 raise AssertionError("version mismatch: expected %r, got %r"
2283 % (expect_success, stats['version']))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002284
2285
Bill Janssen6e027db2007-11-15 22:23:56 +00002286 class ThreadedTests(unittest.TestCase):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002287
Antoine Pitrou23df4832010-08-04 17:14:06 +00002288 @skip_if_broken_ubuntu_ssl
Antoine Pitrou480a1242010-04-28 21:37:09 +00002289 def test_echo(self):
2290 """Basic test of an SSL client connecting to a server"""
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002291 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002292 sys.stdout.write("\n")
Antoine Pitroub5218772010-05-21 09:56:06 +00002293 for protocol in PROTOCOLS:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002294 if protocol in {ssl.PROTOCOL_TLS_CLIENT, ssl.PROTOCOL_TLS_SERVER}:
2295 continue
Antoine Pitrou972d5bb2013-03-29 17:56:03 +01002296 with self.subTest(protocol=ssl._PROTOCOL_NAMES[protocol]):
2297 context = ssl.SSLContext(protocol)
2298 context.load_cert_chain(CERTFILE)
2299 server_params_test(context, context,
2300 chatty=True, connectionchatty=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301
Christian Heimes5fe668c2016-09-12 00:01:11 +02002302 client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2303 client_context.load_verify_locations(SIGNING_CA)
2304 server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
2305 # server_context.load_verify_locations(SIGNING_CA)
2306 server_context.load_cert_chain(SIGNED_CERTFILE2)
2307
2308 with self.subTest(client='PROTOCOL_TLS_CLIENT', server='PROTOCOL_TLS_SERVER'):
2309 server_params_test(client_context=client_context,
2310 server_context=server_context,
2311 chatty=True, connectionchatty=True,
2312 sni_name='fakehostname')
2313
2314 with self.subTest(client='PROTOCOL_TLS_SERVER', server='PROTOCOL_TLS_CLIENT'):
2315 with self.assertRaises(ssl.SSLError):
2316 server_params_test(client_context=server_context,
2317 server_context=client_context,
2318 chatty=True, connectionchatty=True,
2319 sni_name='fakehostname')
2320
Antoine Pitrou480a1242010-04-28 21:37:09 +00002321 def test_getpeercert(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002322 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002323 sys.stdout.write("\n")
Antoine Pitroub5218772010-05-21 09:56:06 +00002324 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
2325 context.verify_mode = ssl.CERT_REQUIRED
2326 context.load_verify_locations(CERTFILE)
2327 context.load_cert_chain(CERTFILE)
2328 server = ThreadedEchoServer(context=context, chatty=False)
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002329 with server:
Antoine Pitrou20b85552013-09-29 19:50:53 +02002330 s = context.wrap_socket(socket.socket(),
2331 do_handshake_on_connect=False)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002332 s.connect((HOST, server.port))
Antoine Pitrou20b85552013-09-29 19:50:53 +02002333 # getpeercert() raise ValueError while the handshake isn't
2334 # done.
2335 with self.assertRaises(ValueError):
2336 s.getpeercert()
2337 s.do_handshake()
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002338 cert = s.getpeercert()
2339 self.assertTrue(cert, "Can't get peer certificate.")
2340 cipher = s.cipher()
2341 if support.verbose:
2342 sys.stdout.write(pprint.pformat(cert) + '\n')
2343 sys.stdout.write("Connection cipher is " + str(cipher) + '.\n')
2344 if 'subject' not in cert:
2345 self.fail("No subject field in certificate: %s." %
2346 pprint.pformat(cert))
2347 if ((('organizationName', 'Python Software Foundation'),)
2348 not in cert['subject']):
2349 self.fail(
2350 "Missing or invalid 'organizationName' field in certificate subject; "
2351 "should be 'Python Software Foundation'.")
Antoine Pitroufb046912010-11-09 20:21:19 +00002352 self.assertIn('notBefore', cert)
2353 self.assertIn('notAfter', cert)
2354 before = ssl.cert_time_to_seconds(cert['notBefore'])
2355 after = ssl.cert_time_to_seconds(cert['notAfter'])
2356 self.assertLess(before, after)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002357 s.close()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002358
Christian Heimes2427b502013-11-23 11:24:32 +01002359 @unittest.skipUnless(have_verify_flags(),
2360 "verify_flags need OpenSSL > 0.9.8")
Christian Heimes22587792013-11-21 23:56:13 +01002361 def test_crl_check(self):
2362 if support.verbose:
2363 sys.stdout.write("\n")
2364
2365 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2366 server_context.load_cert_chain(SIGNED_CERTFILE)
2367
2368 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2369 context.verify_mode = ssl.CERT_REQUIRED
2370 context.load_verify_locations(SIGNING_CA)
Benjamin Petersonc3d9c5c2015-03-04 23:18:48 -05002371 tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
2372 self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf)
Christian Heimes22587792013-11-21 23:56:13 +01002373
2374 # VERIFY_DEFAULT should pass
2375 server = ThreadedEchoServer(context=server_context, chatty=True)
2376 with server:
2377 with context.wrap_socket(socket.socket()) as s:
2378 s.connect((HOST, server.port))
2379 cert = s.getpeercert()
2380 self.assertTrue(cert, "Can't get peer certificate.")
2381
2382 # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails
Christian Heimes32f0c7a2013-11-22 03:43:48 +01002383 context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
Christian Heimes22587792013-11-21 23:56:13 +01002384
2385 server = ThreadedEchoServer(context=server_context, chatty=True)
2386 with server:
2387 with context.wrap_socket(socket.socket()) as s:
2388 with self.assertRaisesRegex(ssl.SSLError,
2389 "certificate verify failed"):
2390 s.connect((HOST, server.port))
2391
2392 # now load a CRL file. The CRL file is signed by the CA.
2393 context.load_verify_locations(CRLFILE)
2394
2395 server = ThreadedEchoServer(context=server_context, chatty=True)
2396 with server:
2397 with context.wrap_socket(socket.socket()) as s:
2398 s.connect((HOST, server.port))
2399 cert = s.getpeercert()
2400 self.assertTrue(cert, "Can't get peer certificate.")
2401
Christian Heimes1aa9a752013-12-02 02:41:19 +01002402 def test_check_hostname(self):
2403 if support.verbose:
2404 sys.stdout.write("\n")
2405
2406 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2407 server_context.load_cert_chain(SIGNED_CERTFILE)
2408
2409 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2410 context.verify_mode = ssl.CERT_REQUIRED
2411 context.check_hostname = True
2412 context.load_verify_locations(SIGNING_CA)
2413
2414 # correct hostname should verify
2415 server = ThreadedEchoServer(context=server_context, chatty=True)
2416 with server:
2417 with context.wrap_socket(socket.socket(),
2418 server_hostname="localhost") as s:
2419 s.connect((HOST, server.port))
2420 cert = s.getpeercert()
2421 self.assertTrue(cert, "Can't get peer certificate.")
2422
2423 # incorrect hostname should raise an exception
2424 server = ThreadedEchoServer(context=server_context, chatty=True)
2425 with server:
2426 with context.wrap_socket(socket.socket(),
2427 server_hostname="invalid") as s:
2428 with self.assertRaisesRegex(ssl.CertificateError,
2429 "hostname 'invalid' doesn't match 'localhost'"):
2430 s.connect((HOST, server.port))
2431
2432 # missing server_hostname arg should cause an exception, too
2433 server = ThreadedEchoServer(context=server_context, chatty=True)
2434 with server:
2435 with socket.socket() as s:
2436 with self.assertRaisesRegex(ValueError,
2437 "check_hostname requires server_hostname"):
2438 context.wrap_socket(s)
2439
Martin Panter407b62f2016-01-30 03:41:43 +00002440 def test_wrong_cert(self):
Martin Panter3464ea22016-02-01 21:58:11 +00002441 """Connecting when the server rejects the client's certificate
2442
2443 Launch a server with CERT_REQUIRED, and check that trying to
2444 connect to it with a wrong client certificate fails.
2445 """
2446 certfile = os.path.join(os.path.dirname(__file__) or os.curdir,
2447 "wrongcert.pem")
2448 server = ThreadedEchoServer(CERTFILE,
2449 certreqs=ssl.CERT_REQUIRED,
2450 cacerts=CERTFILE, chatty=False,
2451 connectionchatty=False)
2452 with server, \
2453 socket.socket() as sock, \
Christian Heimesd0486372016-09-10 23:23:33 +02002454 test_wrap_socket(sock,
Martin Panter3464ea22016-02-01 21:58:11 +00002455 certfile=certfile,
2456 ssl_version=ssl.PROTOCOL_TLSv1) as s:
2457 try:
2458 # Expect either an SSL error about the server rejecting
2459 # the connection, or a low-level connection reset (which
2460 # sometimes happens on Windows)
2461 s.connect((HOST, server.port))
2462 except ssl.SSLError as e:
2463 if support.verbose:
2464 sys.stdout.write("\nSSLError is %r\n" % e)
2465 except OSError as e:
2466 if e.errno != errno.ECONNRESET:
2467 raise
2468 if support.verbose:
2469 sys.stdout.write("\nsocket.error is %r\n" % e)
2470 else:
2471 self.fail("Use of invalid cert should have failed!")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002472
Antoine Pitrou480a1242010-04-28 21:37:09 +00002473 def test_rude_shutdown(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002474 """A brutal shutdown of an SSL server should raise an OSError
Antoine Pitrou480a1242010-04-28 21:37:09 +00002475 in the client when attempting handshake.
2476 """
Trent Nelson6b240cd2008-04-10 20:12:06 +00002477 listener_ready = threading.Event()
2478 listener_gone = threading.Event()
Antoine Pitrou480a1242010-04-28 21:37:09 +00002479
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002480 s = socket.socket()
2481 port = support.bind_port(s, HOST)
Trent Nelson6b240cd2008-04-10 20:12:06 +00002482
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002483 # `listener` runs in a thread. It sits in an accept() until
2484 # the main thread connects. Then it rudely closes the socket,
2485 # and sets Event `listener_gone` to let the main thread know
2486 # the socket is gone.
Trent Nelson6b240cd2008-04-10 20:12:06 +00002487 def listener():
Charles-François Natali6e204602014-07-23 19:28:13 +01002488 s.listen()
Trent Nelson6b240cd2008-04-10 20:12:06 +00002489 listener_ready.set()
Antoine Pitroud2eca372010-10-29 23:41:37 +00002490 newsock, addr = s.accept()
2491 newsock.close()
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002492 s.close()
Trent Nelson6b240cd2008-04-10 20:12:06 +00002493 listener_gone.set()
2494
2495 def connector():
2496 listener_ready.wait()
Antoine Pitroud2eca372010-10-29 23:41:37 +00002497 with socket.socket() as c:
2498 c.connect((HOST, port))
2499 listener_gone.wait()
2500 try:
Christian Heimesd0486372016-09-10 23:23:33 +02002501 ssl_sock = test_wrap_socket(c)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002502 except OSError:
Antoine Pitroud2eca372010-10-29 23:41:37 +00002503 pass
2504 else:
2505 self.fail('connecting to closed SSL socket should have failed')
Trent Nelson6b240cd2008-04-10 20:12:06 +00002506
2507 t = threading.Thread(target=listener)
2508 t.start()
Antoine Pitrou773b5db2010-04-27 08:53:36 +00002509 try:
2510 connector()
2511 finally:
2512 t.join()
Trent Nelson6b240cd2008-04-10 20:12:06 +00002513
Antoine Pitrou23df4832010-08-04 17:14:06 +00002514 @skip_if_broken_ubuntu_ssl
Victor Stinner3de49192011-05-09 00:42:58 +02002515 @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'),
2516 "OpenSSL is compiled without SSLv2 support")
Antoine Pitrou480a1242010-04-28 21:37:09 +00002517 def test_protocol_sslv2(self):
2518 """Connecting to an SSLv2 server with various client options"""
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002519 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002520 sys.stdout.write("\n")
Antoine Pitrou480a1242010-04-28 21:37:09 +00002521 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True)
2522 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL)
2523 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED)
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002524 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False)
Victor Stinner648b8622014-12-12 12:23:59 +01002525 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2526 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002527 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False)
Antoine Pitroub5218772010-05-21 09:56:06 +00002528 # SSLv23 client with specific SSL options
2529 if no_sslv2_implies_sslv3_hello():
2530 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs
2531 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False,
2532 client_options=ssl.OP_NO_SSLv2)
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002533 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False,
Antoine Pitroub5218772010-05-21 09:56:06 +00002534 client_options=ssl.OP_NO_SSLv3)
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002535 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False,
Antoine Pitroub5218772010-05-21 09:56:06 +00002536 client_options=ssl.OP_NO_TLSv1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002537
Antoine Pitrou23df4832010-08-04 17:14:06 +00002538 @skip_if_broken_ubuntu_ssl
Antoine Pitrou480a1242010-04-28 21:37:09 +00002539 def test_protocol_sslv23(self):
2540 """Connecting to an SSLv23 server with various client options"""
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002541 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002542 sys.stdout.write("\n")
Victor Stinner3de49192011-05-09 00:42:58 +02002543 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2544 try:
2545 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002546 except OSError as x:
Victor Stinner3de49192011-05-09 00:42:58 +02002547 # this fails on some older versions of OpenSSL (0.9.7l, for instance)
2548 if support.verbose:
2549 sys.stdout.write(
2550 " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n"
2551 % str(x))
Benjamin Petersone32467c2014-12-05 21:59:35 -05002552 if hasattr(ssl, 'PROTOCOL_SSLv3'):
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002553 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002554 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True)
Antoine Pitrou47e40422014-09-04 21:00:10 +02002555 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002556
Benjamin Petersone32467c2014-12-05 21:59:35 -05002557 if hasattr(ssl, 'PROTOCOL_SSLv3'):
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002558 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002559 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL)
Antoine Pitrou47e40422014-09-04 21:00:10 +02002560 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002561
Benjamin Petersone32467c2014-12-05 21:59:35 -05002562 if hasattr(ssl, 'PROTOCOL_SSLv3'):
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002563 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002564 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED)
Antoine Pitrou47e40422014-09-04 21:00:10 +02002565 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002566
Antoine Pitroub5218772010-05-21 09:56:06 +00002567 # Server with specific SSL options
Benjamin Petersone32467c2014-12-05 21:59:35 -05002568 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2569 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False,
Antoine Pitroub5218772010-05-21 09:56:06 +00002570 server_options=ssl.OP_NO_SSLv3)
2571 # Will choose TLSv1
2572 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True,
2573 server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
2574 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False,
2575 server_options=ssl.OP_NO_TLSv1)
2576
2577
Antoine Pitrou23df4832010-08-04 17:14:06 +00002578 @skip_if_broken_ubuntu_ssl
Benjamin Petersone32467c2014-12-05 21:59:35 -05002579 @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv3'),
2580 "OpenSSL is compiled without SSLv3 support")
Antoine Pitrou480a1242010-04-28 21:37:09 +00002581 def test_protocol_sslv3(self):
2582 """Connecting to an SSLv3 server with various client options"""
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002583 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002584 sys.stdout.write("\n")
Antoine Pitrou47e40422014-09-04 21:00:10 +02002585 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3')
2586 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL)
2587 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED)
Victor Stinner3de49192011-05-09 00:42:58 +02002588 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2589 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
Barry Warsaw46ae0ef2011-10-28 16:52:17 -04002590 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False,
2591 client_options=ssl.OP_NO_SSLv3)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002592 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
Antoine Pitroub5218772010-05-21 09:56:06 +00002593 if no_sslv2_implies_sslv3_hello():
2594 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002595 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23,
2596 False, client_options=ssl.OP_NO_SSLv2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002597
Antoine Pitrou23df4832010-08-04 17:14:06 +00002598 @skip_if_broken_ubuntu_ssl
Antoine Pitrou480a1242010-04-28 21:37:09 +00002599 def test_protocol_tlsv1(self):
2600 """Connecting to a TLSv1 server with various client options"""
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002601 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002602 sys.stdout.write("\n")
Antoine Pitrou47e40422014-09-04 21:00:10 +02002603 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1')
2604 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)
2605 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)
Victor Stinner3de49192011-05-09 00:42:58 +02002606 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2607 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
Benjamin Petersone32467c2014-12-05 21:59:35 -05002608 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2609 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False)
Barry Warsaw46ae0ef2011-10-28 16:52:17 -04002610 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False,
2611 client_options=ssl.OP_NO_TLSv1)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002612
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002613 @skip_if_broken_ubuntu_ssl
2614 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_1"),
2615 "TLS version 1.1 not supported.")
2616 def test_protocol_tlsv1_1(self):
2617 """Connecting to a TLSv1.1 server with various client options.
2618 Testing against older TLS versions."""
2619 if support.verbose:
2620 sys.stdout.write("\n")
Antoine Pitrou47e40422014-09-04 21:00:10 +02002621 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1')
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002622 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2623 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, False)
Benjamin Petersone32467c2014-12-05 21:59:35 -05002624 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2625 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False)
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002626 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv23, False,
2627 client_options=ssl.OP_NO_TLSv1_1)
2628
Antoine Pitrou47e40422014-09-04 21:00:10 +02002629 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1')
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002630 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False)
2631 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False)
2632
2633
2634 @skip_if_broken_ubuntu_ssl
2635 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_2"),
2636 "TLS version 1.2 not supported.")
2637 def test_protocol_tlsv1_2(self):
2638 """Connecting to a TLSv1.2 server with various client options.
2639 Testing against older TLS versions."""
2640 if support.verbose:
2641 sys.stdout.write("\n")
Antoine Pitrou47e40422014-09-04 21:00:10 +02002642 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2',
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002643 server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,
2644 client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,)
2645 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2646 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, False)
Benjamin Petersone32467c2014-12-05 21:59:35 -05002647 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2648 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False)
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002649 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv23, False,
2650 client_options=ssl.OP_NO_TLSv1_2)
2651
Antoine Pitrou47e40422014-09-04 21:00:10 +02002652 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2')
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002653 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False)
2654 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False)
2655 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False)
2656 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False)
2657
Antoine Pitrou480a1242010-04-28 21:37:09 +00002658 def test_starttls(self):
2659 """Switching from clear text to encrypted and back again."""
2660 msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002661
Trent Nelson78520002008-04-10 20:54:35 +00002662 server = ThreadedEchoServer(CERTFILE,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002663 ssl_version=ssl.PROTOCOL_TLSv1,
2664 starttls_server=True,
2665 chatty=True,
2666 connectionchatty=True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002667 wrapped = False
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002668 with server:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002669 s = socket.socket()
2670 s.setblocking(1)
2671 s.connect((HOST, server.port))
2672 if support.verbose:
2673 sys.stdout.write("\n")
2674 for indata in msgs:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002675 if support.verbose:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002676 sys.stdout.write(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002677 " client: sending %r...\n" % indata)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002678 if wrapped:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002679 conn.write(indata)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002680 outdata = conn.read()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002681 else:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002682 s.send(indata)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002683 outdata = s.recv(1024)
Antoine Pitrou480a1242010-04-28 21:37:09 +00002684 msg = outdata.strip().lower()
2685 if indata == b"STARTTLS" and msg.startswith(b"ok"):
2686 # STARTTLS ok, switch to secure mode
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002687 if support.verbose:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002688 sys.stdout.write(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002689 " client: read %r from server, starting TLS...\n"
2690 % msg)
Christian Heimesd0486372016-09-10 23:23:33 +02002691 conn = test_wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002692 wrapped = True
Antoine Pitrou480a1242010-04-28 21:37:09 +00002693 elif indata == b"ENDTLS" and msg.startswith(b"ok"):
2694 # ENDTLS ok, switch back to clear text
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002695 if support.verbose:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002696 sys.stdout.write(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002697 " client: read %r from server, ending TLS...\n"
2698 % msg)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002699 s = conn.unwrap()
2700 wrapped = False
2701 else:
2702 if support.verbose:
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002703 sys.stdout.write(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002704 " client: read %r from server\n" % msg)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002705 if support.verbose:
2706 sys.stdout.write(" client: closing connection.\n")
2707 if wrapped:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002708 conn.write(b"over\n")
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002709 else:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002710 s.send(b"over\n")
Bill Janssen6e027db2007-11-15 22:23:56 +00002711 if wrapped:
2712 conn.close()
2713 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002714 s.close()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002715
Antoine Pitrou480a1242010-04-28 21:37:09 +00002716 def test_socketserver(self):
2717 """Using a SocketServer to create and manage SSL connections."""
Antoine Pitrouda232592013-02-05 21:20:51 +01002718 server = make_https_server(self, certfile=CERTFILE)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002719 # try to connect
Antoine Pitrou803e6d62010-10-13 10:36:15 +00002720 if support.verbose:
2721 sys.stdout.write('\n')
2722 with open(CERTFILE, 'rb') as f:
2723 d1 = f.read()
2724 d2 = ''
2725 # now fetch the same data from the HTTPS server
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05002726 url = 'https://localhost:%d/%s' % (
2727 server.port, os.path.split(CERTFILE)[1])
2728 context = ssl.create_default_context(cafile=CERTFILE)
2729 f = urllib.request.urlopen(url, context=context)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002730 try:
Barry Warsaw820c1202008-06-12 04:06:45 +00002731 dlen = f.info().get("content-length")
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002732 if dlen and (int(dlen) > 0):
2733 d2 = f.read(int(dlen))
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002734 if support.verbose:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002735 sys.stdout.write(
2736 " client: read %d bytes from remote server '%s'\n"
2737 % (len(d2), server))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002738 finally:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00002739 f.close()
2740 self.assertEqual(d1, d2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002741
Antoine Pitrou480a1242010-04-28 21:37:09 +00002742 def test_asyncore_server(self):
2743 """Check the example asyncore integration."""
2744 indata = "TEST MESSAGE of mixed case\n"
Trent Nelson6b240cd2008-04-10 20:12:06 +00002745
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002746 if support.verbose:
Trent Nelson6b240cd2008-04-10 20:12:06 +00002747 sys.stdout.write("\n")
2748
Antoine Pitrou480a1242010-04-28 21:37:09 +00002749 indata = b"FOO\n"
Trent Nelson78520002008-04-10 20:54:35 +00002750 server = AsyncoreEchoServer(CERTFILE)
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002751 with server:
Christian Heimesd0486372016-09-10 23:23:33 +02002752 s = test_wrap_socket(socket.socket())
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002753 s.connect(('127.0.0.1', server.port))
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002754 if support.verbose:
Trent Nelson6b240cd2008-04-10 20:12:06 +00002755 sys.stdout.write(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002756 " client: sending %r...\n" % indata)
2757 s.write(indata)
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002758 outdata = s.read()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002759 if support.verbose:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002760 sys.stdout.write(" client: read %r\n" % outdata)
Trent Nelson6b240cd2008-04-10 20:12:06 +00002761 if outdata != indata.lower():
Antoine Pitrou18c913e2010-04-27 10:59:39 +00002762 self.fail(
Antoine Pitrou480a1242010-04-28 21:37:09 +00002763 "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n"
2764 % (outdata[:20], len(outdata),
2765 indata[:20].lower(), len(indata)))
2766 s.write(b"over\n")
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002767 if support.verbose:
Trent Nelson6b240cd2008-04-10 20:12:06 +00002768 sys.stdout.write(" client: closing connection.\n")
2769 s.close()
Antoine Pitroued986362010-08-15 23:28:10 +00002770 if support.verbose:
2771 sys.stdout.write(" client: connection closed.\n")
Trent Nelson6b240cd2008-04-10 20:12:06 +00002772
Antoine Pitrou480a1242010-04-28 21:37:09 +00002773 def test_recv_send(self):
2774 """Test recv(), send() and friends."""
Bill Janssen58afe4c2008-09-08 16:45:19 +00002775 if support.verbose:
2776 sys.stdout.write("\n")
2777
2778 server = ThreadedEchoServer(CERTFILE,
2779 certreqs=ssl.CERT_NONE,
2780 ssl_version=ssl.PROTOCOL_TLSv1,
2781 cacerts=CERTFILE,
2782 chatty=True,
2783 connectionchatty=False)
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002784 with server:
Christian Heimesd0486372016-09-10 23:23:33 +02002785 s = test_wrap_socket(socket.socket(),
Antoine Pitrou65a3f4b2011-12-21 16:52:40 +01002786 server_side=False,
2787 certfile=CERTFILE,
2788 ca_certs=CERTFILE,
2789 cert_reqs=ssl.CERT_NONE,
2790 ssl_version=ssl.PROTOCOL_TLSv1)
2791 s.connect((HOST, server.port))
Bill Janssen58afe4c2008-09-08 16:45:19 +00002792 # helper methods for standardising recv* method signatures
2793 def _recv_into():
2794 b = bytearray(b"\0"*100)
2795 count = s.recv_into(b)
2796 return b[:count]
2797
2798 def _recvfrom_into():
2799 b = bytearray(b"\0"*100)
2800 count, addr = s.recvfrom_into(b)
2801 return b[:count]
2802
Martin Panter519f9122016-04-03 02:12:54 +00002803 # (name, method, expect success?, *args, return value func)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002804 send_methods = [
Martin Panter519f9122016-04-03 02:12:54 +00002805 ('send', s.send, True, [], len),
2806 ('sendto', s.sendto, False, ["some.address"], len),
2807 ('sendall', s.sendall, True, [], lambda x: None),
Bill Janssen58afe4c2008-09-08 16:45:19 +00002808 ]
Martin Panter519f9122016-04-03 02:12:54 +00002809 # (name, method, whether to expect success, *args)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002810 recv_methods = [
2811 ('recv', s.recv, True, []),
2812 ('recvfrom', s.recvfrom, False, ["some.address"]),
2813 ('recv_into', _recv_into, True, []),
2814 ('recvfrom_into', _recvfrom_into, False, []),
2815 ]
2816 data_prefix = "PREFIX_"
2817
Martin Panter519f9122016-04-03 02:12:54 +00002818 for (meth_name, send_meth, expect_success, args,
2819 ret_val_meth) in send_methods:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002820 indata = (data_prefix + meth_name).encode('ascii')
Bill Janssen58afe4c2008-09-08 16:45:19 +00002821 try:
Martin Panter519f9122016-04-03 02:12:54 +00002822 ret = send_meth(indata, *args)
2823 msg = "sending with {}".format(meth_name)
2824 self.assertEqual(ret, ret_val_meth(indata), msg=msg)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002825 outdata = s.read()
Bill Janssen58afe4c2008-09-08 16:45:19 +00002826 if outdata != indata.lower():
Georg Brandl89fad142010-03-14 10:23:39 +00002827 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002828 "While sending with <<{name:s}>> bad data "
Antoine Pitrou480a1242010-04-28 21:37:09 +00002829 "<<{outdata:r}>> ({nout:d}) received; "
2830 "expected <<{indata:r}>> ({nin:d})\n".format(
2831 name=meth_name, outdata=outdata[:20],
Bill Janssen58afe4c2008-09-08 16:45:19 +00002832 nout=len(outdata),
Antoine Pitrou480a1242010-04-28 21:37:09 +00002833 indata=indata[:20], nin=len(indata)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002834 )
2835 )
2836 except ValueError as e:
2837 if expect_success:
Georg Brandl89fad142010-03-14 10:23:39 +00002838 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002839 "Failed to send with method <<{name:s}>>; "
2840 "expected to succeed.\n".format(name=meth_name)
2841 )
2842 if not str(e).startswith(meth_name):
Georg Brandl89fad142010-03-14 10:23:39 +00002843 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002844 "Method <<{name:s}>> failed with unexpected "
2845 "exception message: {exp:s}\n".format(
2846 name=meth_name, exp=e
2847 )
2848 )
2849
2850 for meth_name, recv_meth, expect_success, args in recv_methods:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002851 indata = (data_prefix + meth_name).encode('ascii')
Bill Janssen58afe4c2008-09-08 16:45:19 +00002852 try:
Antoine Pitrou480a1242010-04-28 21:37:09 +00002853 s.send(indata)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002854 outdata = recv_meth(*args)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002855 if outdata != indata.lower():
Georg Brandl89fad142010-03-14 10:23:39 +00002856 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002857 "While receiving with <<{name:s}>> bad data "
Antoine Pitrou480a1242010-04-28 21:37:09 +00002858 "<<{outdata:r}>> ({nout:d}) received; "
2859 "expected <<{indata:r}>> ({nin:d})\n".format(
2860 name=meth_name, outdata=outdata[:20],
Bill Janssen58afe4c2008-09-08 16:45:19 +00002861 nout=len(outdata),
Antoine Pitrou480a1242010-04-28 21:37:09 +00002862 indata=indata[:20], nin=len(indata)
Bill Janssen58afe4c2008-09-08 16:45:19 +00002863 )
2864 )
2865 except ValueError as e:
2866 if expect_success:
Georg Brandl89fad142010-03-14 10:23:39 +00002867 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002868 "Failed to receive with method <<{name:s}>>; "
2869 "expected to succeed.\n".format(name=meth_name)
2870 )
2871 if not str(e).startswith(meth_name):
Georg Brandl89fad142010-03-14 10:23:39 +00002872 self.fail(
Bill Janssen58afe4c2008-09-08 16:45:19 +00002873 "Method <<{name:s}>> failed with unexpected "
2874 "exception message: {exp:s}\n".format(
2875 name=meth_name, exp=e
2876 )
2877 )
2878 # consume data
2879 s.read()
2880
Martin Panterf6b1d662016-03-28 00:22:09 +00002881 # read(-1, buffer) is supported, even though read(-1) is not
Martin Panterbed7f1a2016-07-11 00:17:13 +00002882 data = b"data"
Martin Panter5503d472016-03-27 05:35:19 +00002883 s.send(data)
2884 buffer = bytearray(len(data))
2885 self.assertEqual(s.read(-1, buffer), len(data))
2886 self.assertEqual(buffer, data)
2887
Nick Coghlan513886a2011-08-28 00:00:27 +10002888 # Make sure sendmsg et al are disallowed to avoid
2889 # inadvertent disclosure of data and/or corruption
2890 # of the encrypted data stream
2891 self.assertRaises(NotImplementedError, s.sendmsg, [b"data"])
2892 self.assertRaises(NotImplementedError, s.recvmsg, 100)
2893 self.assertRaises(NotImplementedError,
2894 s.recvmsg_into, bytearray(100))
2895
Antoine Pitrou480a1242010-04-28 21:37:09 +00002896 s.write(b"over\n")
Martin Panter5503d472016-03-27 05:35:19 +00002897
2898 self.assertRaises(ValueError, s.recv, -1)
2899 self.assertRaises(ValueError, s.read, -1)
2900
Bill Janssen58afe4c2008-09-08 16:45:19 +00002901 s.close()
Bill Janssen58afe4c2008-09-08 16:45:19 +00002902
Martin Panterbed7f1a2016-07-11 00:17:13 +00002903 def test_recv_zero(self):
2904 server = ThreadedEchoServer(CERTFILE)
2905 server.__enter__()
2906 self.addCleanup(server.__exit__, None, None)
2907 s = socket.create_connection((HOST, server.port))
2908 self.addCleanup(s.close)
Christian Heimesd0486372016-09-10 23:23:33 +02002909 s = test_wrap_socket(s, suppress_ragged_eofs=False)
Martin Panterbed7f1a2016-07-11 00:17:13 +00002910 self.addCleanup(s.close)
2911
2912 # recv/read(0) should return no data
2913 s.send(b"data")
2914 self.assertEqual(s.recv(0), b"")
2915 self.assertEqual(s.read(0), b"")
2916 self.assertEqual(s.read(), b"data")
2917
2918 # Should not block if the other end sends no data
2919 s.setblocking(False)
2920 self.assertEqual(s.recv(0), b"")
2921 self.assertEqual(s.recv_into(bytearray()), 0)
2922
Antoine Pitroub4bebda2014-04-29 10:03:28 +02002923 def test_nonblocking_send(self):
2924 server = ThreadedEchoServer(CERTFILE,
2925 certreqs=ssl.CERT_NONE,
2926 ssl_version=ssl.PROTOCOL_TLSv1,
2927 cacerts=CERTFILE,
2928 chatty=True,
2929 connectionchatty=False)
2930 with server:
Christian Heimesd0486372016-09-10 23:23:33 +02002931 s = test_wrap_socket(socket.socket(),
Antoine Pitroub4bebda2014-04-29 10:03:28 +02002932 server_side=False,
2933 certfile=CERTFILE,
2934 ca_certs=CERTFILE,
2935 cert_reqs=ssl.CERT_NONE,
2936 ssl_version=ssl.PROTOCOL_TLSv1)
2937 s.connect((HOST, server.port))
2938 s.setblocking(False)
2939
2940 # If we keep sending data, at some point the buffers
2941 # will be full and the call will block
2942 buf = bytearray(8192)
2943 def fill_buffer():
2944 while True:
2945 s.send(buf)
2946 self.assertRaises((ssl.SSLWantWriteError,
2947 ssl.SSLWantReadError), fill_buffer)
2948
2949 # Now read all the output and discard it
2950 s.setblocking(True)
2951 s.close()
2952
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002953 def test_handshake_timeout(self):
2954 # Issue #5103: SSL handshake must respect the socket timeout
2955 server = socket.socket(socket.AF_INET)
2956 host = "127.0.0.1"
2957 port = support.bind_port(server)
2958 started = threading.Event()
2959 finish = False
2960
2961 def serve():
Charles-François Natali6e204602014-07-23 19:28:13 +01002962 server.listen()
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002963 started.set()
2964 conns = []
2965 while not finish:
2966 r, w, e = select.select([server], [], [], 0.1)
2967 if server in r:
2968 # Let the socket hang around rather than having
2969 # it closed by garbage collection.
2970 conns.append(server.accept()[0])
Antoine Pitroud2eca372010-10-29 23:41:37 +00002971 for sock in conns:
2972 sock.close()
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002973
2974 t = threading.Thread(target=serve)
2975 t.start()
2976 started.wait()
2977
2978 try:
Antoine Pitrou40f08742010-04-24 22:04:40 +00002979 try:
2980 c = socket.socket(socket.AF_INET)
2981 c.settimeout(0.2)
2982 c.connect((host, port))
2983 # Will attempt handshake and time out
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002984 self.assertRaisesRegex(socket.timeout, "timed out",
Christian Heimesd0486372016-09-10 23:23:33 +02002985 test_wrap_socket, c)
Antoine Pitrou40f08742010-04-24 22:04:40 +00002986 finally:
2987 c.close()
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002988 try:
2989 c = socket.socket(socket.AF_INET)
Christian Heimesd0486372016-09-10 23:23:33 +02002990 c = test_wrap_socket(c)
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002991 c.settimeout(0.2)
2992 # Will attempt handshake and time out
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002993 self.assertRaisesRegex(socket.timeout, "timed out",
Ezio Melottied3a7d22010-12-01 02:32:32 +00002994 c.connect, (host, port))
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00002995 finally:
2996 c.close()
2997 finally:
2998 finish = True
2999 t.join()
3000 server.close()
3001
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01003002 def test_server_accept(self):
3003 # Issue #16357: accept() on a SSLSocket created through
3004 # SSLContext.wrap_socket().
3005 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3006 context.verify_mode = ssl.CERT_REQUIRED
3007 context.load_verify_locations(CERTFILE)
3008 context.load_cert_chain(CERTFILE)
3009 server = socket.socket(socket.AF_INET)
3010 host = "127.0.0.1"
3011 port = support.bind_port(server)
3012 server = context.wrap_socket(server, server_side=True)
3013
3014 evt = threading.Event()
3015 remote = None
3016 peer = None
3017 def serve():
3018 nonlocal remote, peer
Charles-François Natali6e204602014-07-23 19:28:13 +01003019 server.listen()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01003020 # Block on the accept and wait on the connection to close.
3021 evt.set()
3022 remote, peer = server.accept()
3023 remote.recv(1)
3024
3025 t = threading.Thread(target=serve)
3026 t.start()
3027 # Client wait until server setup and perform a connect.
3028 evt.wait()
3029 client = context.wrap_socket(socket.socket())
3030 client.connect((host, port))
3031 client_addr = client.getsockname()
3032 client.close()
3033 t.join()
Antoine Pitroue1ceb502013-01-12 21:54:44 +01003034 remote.close()
3035 server.close()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01003036 # Sanity checks.
3037 self.assertIsInstance(remote, ssl.SSLSocket)
3038 self.assertEqual(peer, client_addr)
3039
Antoine Pitrou242db722013-05-01 20:52:07 +02003040 def test_getpeercert_enotconn(self):
3041 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3042 with context.wrap_socket(socket.socket()) as sock:
3043 with self.assertRaises(OSError) as cm:
3044 sock.getpeercert()
3045 self.assertEqual(cm.exception.errno, errno.ENOTCONN)
3046
3047 def test_do_handshake_enotconn(self):
3048 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3049 with context.wrap_socket(socket.socket()) as sock:
3050 with self.assertRaises(OSError) as cm:
3051 sock.do_handshake()
3052 self.assertEqual(cm.exception.errno, errno.ENOTCONN)
3053
Antoine Pitrou8f85f902012-01-03 22:46:48 +01003054 def test_default_ciphers(self):
3055 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3056 try:
3057 # Force a set of weak ciphers on our client context
3058 context.set_ciphers("DES")
3059 except ssl.SSLError:
3060 self.skipTest("no DES cipher available")
3061 with ThreadedEchoServer(CERTFILE,
3062 ssl_version=ssl.PROTOCOL_SSLv23,
3063 chatty=False) as server:
Antoine Pitroue1ceb502013-01-12 21:54:44 +01003064 with context.wrap_socket(socket.socket()) as s:
Andrew Svetlov0832af62012-12-18 23:10:48 +02003065 with self.assertRaises(OSError):
Antoine Pitrou8f85f902012-01-03 22:46:48 +01003066 s.connect((HOST, server.port))
3067 self.assertIn("no shared cipher", str(server.conn_errors[0]))
3068
Antoine Pitrou47e40422014-09-04 21:00:10 +02003069 def test_version_basic(self):
3070 """
3071 Basic tests for SSLSocket.version().
3072 More tests are done in the test_protocol_*() methods.
3073 """
3074 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3075 with ThreadedEchoServer(CERTFILE,
3076 ssl_version=ssl.PROTOCOL_TLSv1,
3077 chatty=False) as server:
3078 with context.wrap_socket(socket.socket()) as s:
3079 self.assertIs(s.version(), None)
3080 s.connect((HOST, server.port))
Christian Heimes598894f2016-09-05 23:19:05 +02003081 self.assertEqual(s.version(), 'TLSv1')
Antoine Pitrou47e40422014-09-04 21:00:10 +02003082 self.assertIs(s.version(), None)
3083
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003084 @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL")
3085 def test_default_ecdh_curve(self):
3086 # Issue #21015: elliptic curve-based Diffie Hellman key exchange
3087 # should be enabled by default on SSL contexts.
3088 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3089 context.load_cert_chain(CERTFILE)
Antoine Pitrouc0430612014-04-16 18:33:39 +02003090 # Prior to OpenSSL 1.0.0, ECDH ciphers have to be enabled
3091 # explicitly using the 'ECCdraft' cipher alias. Otherwise,
3092 # our default cipher list should prefer ECDH-based ciphers
3093 # automatically.
3094 if ssl.OPENSSL_VERSION_INFO < (1, 0, 0):
3095 context.set_ciphers("ECCdraft:ECDH")
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003096 with ThreadedEchoServer(context=context) as server:
3097 with context.wrap_socket(socket.socket()) as s:
3098 s.connect((HOST, server.port))
3099 self.assertIn("ECDH", s.cipher()[0])
3100
Antoine Pitroud6494802011-07-21 01:11:30 +02003101 @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES,
3102 "'tls-unique' channel binding not available")
3103 def test_tls_unique_channel_binding(self):
3104 """Test tls-unique channel binding."""
3105 if support.verbose:
3106 sys.stdout.write("\n")
3107
3108 server = ThreadedEchoServer(CERTFILE,
3109 certreqs=ssl.CERT_NONE,
3110 ssl_version=ssl.PROTOCOL_TLSv1,
3111 cacerts=CERTFILE,
3112 chatty=True,
3113 connectionchatty=False)
Antoine Pitrou6b15c902011-12-21 16:54:45 +01003114 with server:
Christian Heimesd0486372016-09-10 23:23:33 +02003115 s = test_wrap_socket(socket.socket(),
Antoine Pitrou6b15c902011-12-21 16:54:45 +01003116 server_side=False,
3117 certfile=CERTFILE,
3118 ca_certs=CERTFILE,
3119 cert_reqs=ssl.CERT_NONE,
3120 ssl_version=ssl.PROTOCOL_TLSv1)
3121 s.connect((HOST, server.port))
Antoine Pitroud6494802011-07-21 01:11:30 +02003122 # get the data
3123 cb_data = s.get_channel_binding("tls-unique")
3124 if support.verbose:
3125 sys.stdout.write(" got channel binding data: {0!r}\n"
3126 .format(cb_data))
3127
3128 # check if it is sane
3129 self.assertIsNotNone(cb_data)
3130 self.assertEqual(len(cb_data), 12) # True for TLSv1
3131
3132 # and compare with the peers version
3133 s.write(b"CB tls-unique\n")
3134 peer_data_repr = s.read().strip()
3135 self.assertEqual(peer_data_repr,
3136 repr(cb_data).encode("us-ascii"))
3137 s.close()
3138
3139 # now, again
Christian Heimesd0486372016-09-10 23:23:33 +02003140 s = test_wrap_socket(socket.socket(),
Antoine Pitroud6494802011-07-21 01:11:30 +02003141 server_side=False,
3142 certfile=CERTFILE,
3143 ca_certs=CERTFILE,
3144 cert_reqs=ssl.CERT_NONE,
3145 ssl_version=ssl.PROTOCOL_TLSv1)
3146 s.connect((HOST, server.port))
3147 new_cb_data = s.get_channel_binding("tls-unique")
3148 if support.verbose:
3149 sys.stdout.write(" got another channel binding data: {0!r}\n"
3150 .format(new_cb_data))
3151 # is it really unique
3152 self.assertNotEqual(cb_data, new_cb_data)
3153 self.assertIsNotNone(cb_data)
3154 self.assertEqual(len(cb_data), 12) # True for TLSv1
3155 s.write(b"CB tls-unique\n")
3156 peer_data_repr = s.read().strip()
3157 self.assertEqual(peer_data_repr,
3158 repr(new_cb_data).encode("us-ascii"))
3159 s.close()
Bill Janssen58afe4c2008-09-08 16:45:19 +00003160
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003161 def test_compression(self):
3162 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3163 context.load_cert_chain(CERTFILE)
3164 stats = server_params_test(context, context,
3165 chatty=True, connectionchatty=True)
3166 if support.verbose:
3167 sys.stdout.write(" got compression: {!r}\n".format(stats['compression']))
3168 self.assertIn(stats['compression'], { None, 'ZLIB', 'RLE' })
3169
3170 @unittest.skipUnless(hasattr(ssl, 'OP_NO_COMPRESSION'),
3171 "ssl.OP_NO_COMPRESSION needed for this test")
3172 def test_compression_disabled(self):
3173 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3174 context.load_cert_chain(CERTFILE)
Antoine Pitrou8691bff2011-12-20 10:47:42 +01003175 context.options |= ssl.OP_NO_COMPRESSION
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003176 stats = server_params_test(context, context,
3177 chatty=True, connectionchatty=True)
3178 self.assertIs(stats['compression'], None)
3179
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003180 def test_dh_params(self):
3181 # Check we can get a connection with ephemeral Diffie-Hellman
3182 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3183 context.load_cert_chain(CERTFILE)
3184 context.load_dh_params(DHFILE)
3185 context.set_ciphers("kEDH")
3186 stats = server_params_test(context, context,
3187 chatty=True, connectionchatty=True)
3188 cipher = stats["cipher"][0]
3189 parts = cipher.split("-")
3190 if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts:
3191 self.fail("Non-DH cipher: " + cipher[0])
3192
Benjamin Petersoncca27322015-01-23 16:35:37 -05003193 def test_selected_alpn_protocol(self):
3194 # selected_alpn_protocol() is None unless ALPN is used.
3195 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3196 context.load_cert_chain(CERTFILE)
3197 stats = server_params_test(context, context,
3198 chatty=True, connectionchatty=True)
3199 self.assertIs(stats['client_alpn_protocol'], None)
3200
3201 @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required")
3202 def test_selected_alpn_protocol_if_server_uses_alpn(self):
3203 # selected_alpn_protocol() is None unless ALPN is used by the client.
3204 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3205 client_context.load_verify_locations(CERTFILE)
3206 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3207 server_context.load_cert_chain(CERTFILE)
3208 server_context.set_alpn_protocols(['foo', 'bar'])
3209 stats = server_params_test(client_context, server_context,
3210 chatty=True, connectionchatty=True)
3211 self.assertIs(stats['client_alpn_protocol'], None)
3212
3213 @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test")
3214 def test_alpn_protocols(self):
3215 server_protocols = ['foo', 'bar', 'milkshake']
3216 protocol_tests = [
3217 (['foo', 'bar'], 'foo'),
Benjamin Peterson88615022015-01-23 17:30:26 -05003218 (['bar', 'foo'], 'foo'),
Benjamin Petersoncca27322015-01-23 16:35:37 -05003219 (['milkshake'], 'milkshake'),
Benjamin Peterson88615022015-01-23 17:30:26 -05003220 (['http/3.0', 'http/4.0'], None)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003221 ]
3222 for client_protocols, expected in protocol_tests:
Christian Heimes598894f2016-09-05 23:19:05 +02003223 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003224 server_context.load_cert_chain(CERTFILE)
3225 server_context.set_alpn_protocols(server_protocols)
Christian Heimes598894f2016-09-05 23:19:05 +02003226 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003227 client_context.load_cert_chain(CERTFILE)
3228 client_context.set_alpn_protocols(client_protocols)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003229
Christian Heimes598894f2016-09-05 23:19:05 +02003230 try:
3231 stats = server_params_test(client_context,
3232 server_context,
3233 chatty=True,
3234 connectionchatty=True)
3235 except ssl.SSLError as e:
3236 stats = e
3237
3238 if expected is None and IS_OPENSSL_1_1:
3239 # OpenSSL 1.1.0 raises handshake error
3240 self.assertIsInstance(stats, ssl.SSLError)
3241 else:
3242 msg = "failed trying %s (s) and %s (c).\n" \
3243 "was expecting %s, but got %%s from the %%s" \
3244 % (str(server_protocols), str(client_protocols),
3245 str(expected))
3246 client_result = stats['client_alpn_protocol']
3247 self.assertEqual(client_result, expected,
3248 msg % (client_result, "client"))
3249 server_result = stats['server_alpn_protocols'][-1] \
3250 if len(stats['server_alpn_protocols']) else 'nothing'
3251 self.assertEqual(server_result, expected,
3252 msg % (server_result, "server"))
Benjamin Petersoncca27322015-01-23 16:35:37 -05003253
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003254 def test_selected_npn_protocol(self):
3255 # selected_npn_protocol() is None unless NPN is used
3256 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3257 context.load_cert_chain(CERTFILE)
3258 stats = server_params_test(context, context,
3259 chatty=True, connectionchatty=True)
3260 self.assertIs(stats['client_npn_protocol'], None)
3261
3262 @unittest.skipUnless(ssl.HAS_NPN, "NPN support needed for this test")
3263 def test_npn_protocols(self):
3264 server_protocols = ['http/1.1', 'spdy/2']
3265 protocol_tests = [
3266 (['http/1.1', 'spdy/2'], 'http/1.1'),
3267 (['spdy/2', 'http/1.1'], 'http/1.1'),
3268 (['spdy/2', 'test'], 'spdy/2'),
3269 (['abc', 'def'], 'abc')
3270 ]
3271 for client_protocols, expected in protocol_tests:
3272 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3273 server_context.load_cert_chain(CERTFILE)
3274 server_context.set_npn_protocols(server_protocols)
3275 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3276 client_context.load_cert_chain(CERTFILE)
3277 client_context.set_npn_protocols(client_protocols)
3278 stats = server_params_test(client_context, server_context,
3279 chatty=True, connectionchatty=True)
3280
3281 msg = "failed trying %s (s) and %s (c).\n" \
3282 "was expecting %s, but got %%s from the %%s" \
3283 % (str(server_protocols), str(client_protocols),
3284 str(expected))
3285 client_result = stats['client_npn_protocol']
3286 self.assertEqual(client_result, expected, msg % (client_result, "client"))
3287 server_result = stats['server_npn_protocols'][-1] \
3288 if len(stats['server_npn_protocols']) else 'nothing'
3289 self.assertEqual(server_result, expected, msg % (server_result, "server"))
3290
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003291 def sni_contexts(self):
3292 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3293 server_context.load_cert_chain(SIGNED_CERTFILE)
3294 other_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3295 other_context.load_cert_chain(SIGNED_CERTFILE2)
3296 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3297 client_context.verify_mode = ssl.CERT_REQUIRED
3298 client_context.load_verify_locations(SIGNING_CA)
3299 return server_context, other_context, client_context
3300
3301 def check_common_name(self, stats, name):
3302 cert = stats['peercert']
3303 self.assertIn((('commonName', name),), cert['subject'])
3304
3305 @needs_sni
3306 def test_sni_callback(self):
3307 calls = []
3308 server_context, other_context, client_context = self.sni_contexts()
3309
3310 def servername_cb(ssl_sock, server_name, initial_context):
3311 calls.append((server_name, initial_context))
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003312 if server_name is not None:
3313 ssl_sock.context = other_context
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003314 server_context.set_servername_callback(servername_cb)
3315
3316 stats = server_params_test(client_context, server_context,
3317 chatty=True,
3318 sni_name='supermessage')
3319 # The hostname was fetched properly, and the certificate was
3320 # changed for the connection.
3321 self.assertEqual(calls, [("supermessage", server_context)])
3322 # CERTFILE4 was selected
3323 self.check_common_name(stats, 'fakehostname')
3324
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003325 calls = []
3326 # The callback is called with server_name=None
3327 stats = server_params_test(client_context, server_context,
3328 chatty=True,
3329 sni_name=None)
3330 self.assertEqual(calls, [(None, server_context)])
3331 self.check_common_name(stats, 'localhost')
3332
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003333 # Check disabling the callback
3334 calls = []
3335 server_context.set_servername_callback(None)
3336
3337 stats = server_params_test(client_context, server_context,
3338 chatty=True,
3339 sni_name='notfunny')
3340 # Certificate didn't change
3341 self.check_common_name(stats, 'localhost')
3342 self.assertEqual(calls, [])
3343
3344 @needs_sni
3345 def test_sni_callback_alert(self):
3346 # Returning a TLS alert is reflected to the connecting client
3347 server_context, other_context, client_context = self.sni_contexts()
3348
3349 def cb_returning_alert(ssl_sock, server_name, initial_context):
3350 return ssl.ALERT_DESCRIPTION_ACCESS_DENIED
3351 server_context.set_servername_callback(cb_returning_alert)
3352
3353 with self.assertRaises(ssl.SSLError) as cm:
3354 stats = server_params_test(client_context, server_context,
3355 chatty=False,
3356 sni_name='supermessage')
3357 self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_ACCESS_DENIED')
3358
3359 @needs_sni
3360 def test_sni_callback_raising(self):
3361 # Raising fails the connection with a TLS handshake failure alert.
3362 server_context, other_context, client_context = self.sni_contexts()
3363
3364 def cb_raising(ssl_sock, server_name, initial_context):
3365 1/0
3366 server_context.set_servername_callback(cb_raising)
3367
3368 with self.assertRaises(ssl.SSLError) as cm, \
3369 support.captured_stderr() as stderr:
3370 stats = server_params_test(client_context, server_context,
3371 chatty=False,
3372 sni_name='supermessage')
3373 self.assertEqual(cm.exception.reason, 'SSLV3_ALERT_HANDSHAKE_FAILURE')
3374 self.assertIn("ZeroDivisionError", stderr.getvalue())
3375
3376 @needs_sni
3377 def test_sni_callback_wrong_return_type(self):
3378 # Returning the wrong return type terminates the TLS connection
3379 # with an internal error alert.
3380 server_context, other_context, client_context = self.sni_contexts()
3381
3382 def cb_wrong_return_type(ssl_sock, server_name, initial_context):
3383 return "foo"
3384 server_context.set_servername_callback(cb_wrong_return_type)
3385
3386 with self.assertRaises(ssl.SSLError) as cm, \
3387 support.captured_stderr() as stderr:
3388 stats = server_params_test(client_context, server_context,
3389 chatty=False,
3390 sni_name='supermessage')
3391 self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR')
3392 self.assertIn("TypeError", stderr.getvalue())
3393
Benjamin Peterson4cb17812015-01-07 11:14:26 -06003394 def test_shared_ciphers(self):
Benjamin Petersonaacd5242015-01-07 11:42:38 -06003395 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Benjamin Peterson15042922015-01-07 22:12:43 -06003396 server_context.load_cert_chain(SIGNED_CERTFILE)
3397 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3398 client_context.verify_mode = ssl.CERT_REQUIRED
3399 client_context.load_verify_locations(SIGNING_CA)
Christian Heimes598894f2016-09-05 23:19:05 +02003400 if ssl.OPENSSL_VERSION_INFO >= (1, 0, 2):
3401 client_context.set_ciphers("AES128:AES256")
3402 server_context.set_ciphers("AES256")
3403 alg1 = "AES256"
3404 alg2 = "AES-256"
3405 else:
3406 client_context.set_ciphers("AES:3DES")
3407 server_context.set_ciphers("3DES")
3408 alg1 = "3DES"
3409 alg2 = "DES-CBC3"
3410
Benjamin Peterson4cb17812015-01-07 11:14:26 -06003411 stats = server_params_test(client_context, server_context)
3412 ciphers = stats['server_shared_ciphers'][0]
3413 self.assertGreater(len(ciphers), 0)
3414 for name, tls_version, bits in ciphers:
Christian Heimes598894f2016-09-05 23:19:05 +02003415 if not alg1 in name.split("-") and alg2 not in name:
3416 self.fail(name)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06003417
Antoine Pitrou60a26e02013-07-20 19:35:16 +02003418 def test_read_write_after_close_raises_valuerror(self):
3419 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3420 context.verify_mode = ssl.CERT_REQUIRED
3421 context.load_verify_locations(CERTFILE)
3422 context.load_cert_chain(CERTFILE)
3423 server = ThreadedEchoServer(context=context, chatty=False)
3424
3425 with server:
3426 s = context.wrap_socket(socket.socket())
3427 s.connect((HOST, server.port))
3428 s.close()
3429
3430 self.assertRaises(ValueError, s.read, 1024)
Antoine Pitrou28940732013-07-20 19:36:15 +02003431 self.assertRaises(ValueError, s.write, b'hello')
Antoine Pitrou60a26e02013-07-20 19:35:16 +02003432
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02003433 def test_sendfile(self):
3434 TEST_DATA = b"x" * 512
3435 with open(support.TESTFN, 'wb') as f:
3436 f.write(TEST_DATA)
3437 self.addCleanup(support.unlink, support.TESTFN)
3438 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3439 context.verify_mode = ssl.CERT_REQUIRED
3440 context.load_verify_locations(CERTFILE)
3441 context.load_cert_chain(CERTFILE)
3442 server = ThreadedEchoServer(context=context, chatty=False)
3443 with server:
3444 with context.wrap_socket(socket.socket()) as s:
3445 s.connect((HOST, server.port))
3446 with open(support.TESTFN, 'rb') as file:
3447 s.sendfile(file)
3448 self.assertEqual(s.recv(1024), TEST_DATA)
3449
Christian Heimes99a65702016-09-10 23:44:53 +02003450 def test_session(self):
3451 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3452 server_context.load_cert_chain(SIGNED_CERTFILE)
3453 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3454 client_context.verify_mode = ssl.CERT_REQUIRED
3455 client_context.load_verify_locations(SIGNING_CA)
3456
3457 # first conncetion without session
3458 stats = server_params_test(client_context, server_context)
3459 session = stats['session']
3460 self.assertTrue(session.id)
3461 self.assertGreater(session.time, 0)
3462 self.assertGreater(session.timeout, 0)
3463 self.assertTrue(session.has_ticket)
3464 if ssl.OPENSSL_VERSION_INFO > (1, 0, 1):
3465 self.assertGreater(session.ticket_lifetime_hint, 0)
3466 self.assertFalse(stats['session_reused'])
3467 sess_stat = server_context.session_stats()
3468 self.assertEqual(sess_stat['accept'], 1)
3469 self.assertEqual(sess_stat['hits'], 0)
3470
3471 # reuse session
3472 stats = server_params_test(client_context, server_context, session=session)
3473 sess_stat = server_context.session_stats()
3474 self.assertEqual(sess_stat['accept'], 2)
3475 self.assertEqual(sess_stat['hits'], 1)
3476 self.assertTrue(stats['session_reused'])
3477 session2 = stats['session']
3478 self.assertEqual(session2.id, session.id)
3479 self.assertEqual(session2, session)
3480 self.assertIsNot(session2, session)
3481 self.assertGreaterEqual(session2.time, session.time)
3482 self.assertGreaterEqual(session2.timeout, session.timeout)
3483
3484 # another one without session
3485 stats = server_params_test(client_context, server_context)
3486 self.assertFalse(stats['session_reused'])
3487 session3 = stats['session']
3488 self.assertNotEqual(session3.id, session.id)
3489 self.assertNotEqual(session3, session)
3490 sess_stat = server_context.session_stats()
3491 self.assertEqual(sess_stat['accept'], 3)
3492 self.assertEqual(sess_stat['hits'], 1)
3493
3494 # reuse session again
3495 stats = server_params_test(client_context, server_context, session=session)
3496 self.assertTrue(stats['session_reused'])
3497 session4 = stats['session']
3498 self.assertEqual(session4.id, session.id)
3499 self.assertEqual(session4, session)
3500 self.assertGreaterEqual(session4.time, session.time)
3501 self.assertGreaterEqual(session4.timeout, session.timeout)
3502 sess_stat = server_context.session_stats()
3503 self.assertEqual(sess_stat['accept'], 4)
3504 self.assertEqual(sess_stat['hits'], 2)
3505
3506 def test_session_handling(self):
3507 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3508 context.verify_mode = ssl.CERT_REQUIRED
3509 context.load_verify_locations(CERTFILE)
3510 context.load_cert_chain(CERTFILE)
3511
3512 context2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3513 context2.verify_mode = ssl.CERT_REQUIRED
3514 context2.load_verify_locations(CERTFILE)
3515 context2.load_cert_chain(CERTFILE)
3516
3517 server = ThreadedEchoServer(context=context, chatty=False)
3518 with server:
3519 with context.wrap_socket(socket.socket()) as s:
3520 # session is None before handshake
3521 self.assertEqual(s.session, None)
3522 self.assertEqual(s.session_reused, None)
3523 s.connect((HOST, server.port))
3524 session = s.session
3525 self.assertTrue(session)
3526 with self.assertRaises(TypeError) as e:
3527 s.session = object
3528 self.assertEqual(str(e.exception), 'Value is not a SSLSession.')
3529
3530 with context.wrap_socket(socket.socket()) as s:
3531 s.connect((HOST, server.port))
3532 # cannot set session after handshake
3533 with self.assertRaises(ValueError) as e:
3534 s.session = session
3535 self.assertEqual(str(e.exception),
3536 'Cannot set session after handshake.')
3537
3538 with context.wrap_socket(socket.socket()) as s:
3539 # can set session before handshake and before the
3540 # connection was established
3541 s.session = session
3542 s.connect((HOST, server.port))
3543 self.assertEqual(s.session.id, session.id)
3544 self.assertEqual(s.session, session)
3545 self.assertEqual(s.session_reused, True)
3546
3547 with context2.wrap_socket(socket.socket()) as s:
3548 # cannot re-use session with a different SSLContext
3549 with self.assertRaises(ValueError) as e:
3550 s.session = session
3551 s.connect((HOST, server.port))
3552 self.assertEqual(str(e.exception),
3553 'Session refers to a different SSLContext.')
3554
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003555
Thomas Woutersed03b412007-08-28 21:37:11 +00003556def test_main(verbose=False):
Antoine Pitrou15cee622010-08-04 16:45:21 +00003557 if support.verbose:
Berker Peksag9e7990a2015-05-16 23:21:26 +03003558 import warnings
Antoine Pitrou15cee622010-08-04 16:45:21 +00003559 plats = {
3560 'Linux': platform.linux_distribution,
3561 'Mac': platform.mac_ver,
3562 'Windows': platform.win32_ver,
3563 }
Berker Peksag9e7990a2015-05-16 23:21:26 +03003564 with warnings.catch_warnings():
3565 warnings.filterwarnings(
3566 'ignore',
R David Murray44b548d2016-09-08 13:59:53 -04003567 r'dist\(\) and linux_distribution\(\) '
Berker Peksag9e7990a2015-05-16 23:21:26 +03003568 'functions are deprecated .*',
3569 PendingDeprecationWarning,
3570 )
3571 for name, func in plats.items():
3572 plat = func()
3573 if plat and plat[0]:
3574 plat = '%s %r' % (name, plat)
3575 break
3576 else:
3577 plat = repr(platform.platform())
Antoine Pitrou15cee622010-08-04 16:45:21 +00003578 print("test_ssl: testing with %r %r" %
3579 (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO))
3580 print(" under %s" % plat)
Antoine Pitroud5323212010-10-22 18:19:07 +00003581 print(" HAS_SNI = %r" % ssl.HAS_SNI)
Antoine Pitrou609ef012013-03-29 18:09:06 +01003582 print(" OP_ALL = 0x%8x" % ssl.OP_ALL)
3583 try:
3584 print(" OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1)
3585 except AttributeError:
3586 pass
Antoine Pitrou15cee622010-08-04 16:45:21 +00003587
Antoine Pitrou152efa22010-05-16 18:19:27 +00003588 for filename in [
Martin Panter3840b2a2016-03-27 01:53:46 +00003589 CERTFILE, BYTES_CERTFILE,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003590 ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY,
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003591 SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003592 BADCERT, BADKEY, EMPTYCERT]:
3593 if not os.path.exists(filename):
3594 raise support.TestFailed("Can't read certificate file %r" % filename)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003595
Martin Panter3840b2a2016-03-27 01:53:46 +00003596 tests = [
3597 ContextTests, BasicSocketTests, SSLErrorTests, MemoryBIOTests,
3598 SimpleBackgroundTests,
3599 ]
Thomas Woutersed03b412007-08-28 21:37:11 +00003600
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003601 if support.is_resource_enabled('network'):
Bill Janssen6e027db2007-11-15 22:23:56 +00003602 tests.append(NetworkedTests)
Thomas Woutersed03b412007-08-28 21:37:11 +00003603
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003604 if _have_threads:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003605 thread_info = support.threading_setup()
Antoine Pitroudb5012a2013-01-12 22:00:09 +01003606 if thread_info:
Bill Janssen6e027db2007-11-15 22:23:56 +00003607 tests.append(ThreadedTests)
Thomas Woutersed03b412007-08-28 21:37:11 +00003608
Antoine Pitrou480a1242010-04-28 21:37:09 +00003609 try:
3610 support.run_unittest(*tests)
3611 finally:
3612 if _have_threads:
3613 support.threading_cleanup(*thread_info)
Thomas Woutersed03b412007-08-28 21:37:11 +00003614
3615if __name__ == "__main__":
3616 test_main()