Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1 | # Test the support for SSL and sockets |
| 2 | |
| 3 | import sys |
| 4 | import unittest |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 5 | from test import support |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 6 | import socket |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 7 | import select |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 8 | import time |
Antoine Pitrou | cfcd8ad | 2010-04-23 23:31:47 +0000 | [diff] [blame] | 9 | import gc |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 10 | import os |
Antoine Pitrou | cfcd8ad | 2010-04-23 23:31:47 +0000 | [diff] [blame] | 11 | import errno |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 12 | import pprint |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 13 | import tempfile |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 14 | import urllib.request |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 15 | import traceback |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 16 | import asyncore |
Antoine Pitrou | 9d54366 | 2010-04-23 23:10:32 +0000 | [diff] [blame] | 17 | import weakref |
Antoine Pitrou | 15cee62 | 2010-08-04 16:45:21 +0000 | [diff] [blame] | 18 | import platform |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 19 | import functools |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 20 | |
Antoine Pitrou | 05d936d | 2010-10-13 11:38:36 +0000 | [diff] [blame] | 21 | ssl = support.import_module("ssl") |
| 22 | |
| 23 | PROTOCOLS = [ |
Victor Stinner | 17ca323 | 2011-05-10 00:48:41 +0200 | [diff] [blame] | 24 | ssl.PROTOCOL_SSLv3, |
Antoine Pitrou | 05d936d | 2010-10-13 11:38:36 +0000 | [diff] [blame] | 25 | ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1 |
| 26 | ] |
Victor Stinner | 17ca323 | 2011-05-10 00:48:41 +0200 | [diff] [blame] | 27 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 28 | PROTOCOLS.append(ssl.PROTOCOL_SSLv2) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 29 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 30 | HOST = support.HOST |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 31 | |
| 32 | data_file = lambda name: os.path.join(os.path.dirname(__file__), name) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 33 | |
Antoine Pitrou | 8156409 | 2010-10-08 23:06:24 +0000 | [diff] [blame] | 34 | # The custom key and certificate files used in test_ssl are generated |
| 35 | # using Lib/test/make_ssl_certs.py. |
| 36 | # Other certificates are simply fetched from the Internet servers they |
| 37 | # are meant to authenticate. |
| 38 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 39 | CERTFILE = data_file("keycert.pem") |
Victor Stinner | 313a120 | 2010-06-11 23:56:51 +0000 | [diff] [blame] | 40 | BYTES_CERTFILE = os.fsencode(CERTFILE) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 41 | ONLYCERT = data_file("ssl_cert.pem") |
| 42 | ONLYKEY = data_file("ssl_key.pem") |
Victor Stinner | 313a120 | 2010-06-11 23:56:51 +0000 | [diff] [blame] | 43 | BYTES_ONLYCERT = os.fsencode(ONLYCERT) |
| 44 | BYTES_ONLYKEY = os.fsencode(ONLYKEY) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 45 | CAPATH = data_file("capath") |
Victor Stinner | 313a120 | 2010-06-11 23:56:51 +0000 | [diff] [blame] | 46 | BYTES_CAPATH = os.fsencode(CAPATH) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 47 | |
| 48 | SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem") |
| 49 | |
| 50 | EMPTYCERT = data_file("nullcert.pem") |
| 51 | BADCERT = data_file("badcert.pem") |
| 52 | WRONGCERT = data_file("XXXnonexisting.pem") |
| 53 | BADKEY = data_file("badkey.pem") |
| 54 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 55 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 56 | def handle_error(prefix): |
| 57 | exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 58 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 59 | sys.stdout.write(prefix + exc_format) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 60 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 61 | def can_clear_options(): |
| 62 | # 0.9.8m or higher |
| 63 | return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 13, 15) |
| 64 | |
| 65 | def no_sslv2_implies_sslv3_hello(): |
| 66 | # 0.9.7h or higher |
| 67 | return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) |
| 68 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 69 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 70 | # Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2 |
| 71 | def skip_if_broken_ubuntu_ssl(func): |
Victor Stinner | 17ca323 | 2011-05-10 00:48:41 +0200 | [diff] [blame] | 72 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 73 | @functools.wraps(func) |
| 74 | def f(*args, **kwargs): |
| 75 | try: |
| 76 | ssl.SSLContext(ssl.PROTOCOL_SSLv2) |
| 77 | except ssl.SSLError: |
| 78 | if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and |
| 79 | platform.linux_distribution() == ('debian', 'squeeze/sid', '')): |
| 80 | raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour") |
| 81 | return func(*args, **kwargs) |
| 82 | return f |
| 83 | else: |
| 84 | return func |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 85 | |
| 86 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 87 | class BasicSocketTests(unittest.TestCase): |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 88 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 89 | def test_constants(self): |
Victor Stinner | ee18b6f | 2011-05-10 00:38:00 +0200 | [diff] [blame] | 90 | #ssl.PROTOCOL_SSLv2 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 91 | ssl.PROTOCOL_SSLv23 |
| 92 | ssl.PROTOCOL_SSLv3 |
| 93 | ssl.PROTOCOL_TLSv1 |
| 94 | ssl.CERT_NONE |
| 95 | ssl.CERT_OPTIONAL |
| 96 | ssl.CERT_REQUIRED |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 97 | self.assertIn(ssl.HAS_SNI, {True, False}) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 98 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 99 | def test_random(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 100 | v = ssl.RAND_status() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 101 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 102 | sys.stdout.write("\n RAND_status is %d (%s)\n" |
| 103 | % (v, (v and "sufficient randomness") or |
| 104 | "insufficient randomness")) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 105 | try: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 106 | ssl.RAND_egd(1) |
| 107 | except TypeError: |
| 108 | pass |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 109 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 110 | print("didn't raise TypeError") |
| 111 | ssl.RAND_add("this is a random string", 75.0) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 112 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 113 | def test_parse_cert(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 114 | # note that this uses an 'unofficial' function in _ssl.c, |
| 115 | # provided solely for this test, to exercise the certificate |
| 116 | # parsing code |
Antoine Pitrou | fb04691 | 2010-11-09 20:21:19 +0000 | [diff] [blame] | 117 | p = ssl._ssl._test_decode_cert(CERTFILE) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 118 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 119 | sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 120 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 121 | def test_DER_to_PEM(self): |
| 122 | with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: |
| 123 | pem = f.read() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 124 | d1 = ssl.PEM_cert_to_DER_cert(pem) |
| 125 | p2 = ssl.DER_cert_to_PEM_cert(d1) |
| 126 | d2 = ssl.PEM_cert_to_DER_cert(p2) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 127 | self.assertEqual(d1, d2) |
Antoine Pitrou | 9bfbe61 | 2010-04-27 22:08:08 +0000 | [diff] [blame] | 128 | if not p2.startswith(ssl.PEM_HEADER + '\n'): |
| 129 | self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2) |
| 130 | if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'): |
| 131 | self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 132 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 133 | def test_openssl_version(self): |
| 134 | n = ssl.OPENSSL_VERSION_NUMBER |
| 135 | t = ssl.OPENSSL_VERSION_INFO |
| 136 | s = ssl.OPENSSL_VERSION |
| 137 | self.assertIsInstance(n, int) |
| 138 | self.assertIsInstance(t, tuple) |
| 139 | self.assertIsInstance(s, str) |
| 140 | # Some sanity checks follow |
| 141 | # >= 0.9 |
| 142 | self.assertGreaterEqual(n, 0x900000) |
| 143 | # < 2.0 |
| 144 | self.assertLess(n, 0x20000000) |
| 145 | major, minor, fix, patch, status = t |
| 146 | self.assertGreaterEqual(major, 0) |
| 147 | self.assertLess(major, 2) |
| 148 | self.assertGreaterEqual(minor, 0) |
| 149 | self.assertLess(minor, 256) |
| 150 | self.assertGreaterEqual(fix, 0) |
| 151 | self.assertLess(fix, 256) |
| 152 | self.assertGreaterEqual(patch, 0) |
| 153 | self.assertLessEqual(patch, 26) |
| 154 | self.assertGreaterEqual(status, 0) |
| 155 | self.assertLessEqual(status, 15) |
| 156 | # Version string as returned by OpenSSL, the format might change |
| 157 | self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)), |
| 158 | (s, t)) |
| 159 | |
Antoine Pitrou | 9d54366 | 2010-04-23 23:10:32 +0000 | [diff] [blame] | 160 | @support.cpython_only |
| 161 | def test_refcycle(self): |
| 162 | # Issue #7943: an SSL object doesn't create reference cycles with |
| 163 | # itself. |
| 164 | s = socket.socket(socket.AF_INET) |
| 165 | ss = ssl.wrap_socket(s) |
| 166 | wr = weakref.ref(ss) |
| 167 | del ss |
| 168 | self.assertEqual(wr(), None) |
| 169 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 170 | def test_wrapped_unconnected(self): |
| 171 | # Methods on an unconnected SSLSocket propagate the original |
| 172 | # socket.error raise by the underlying socket object. |
| 173 | s = socket.socket(socket.AF_INET) |
| 174 | ss = ssl.wrap_socket(s) |
| 175 | self.assertRaises(socket.error, ss.recv, 1) |
| 176 | self.assertRaises(socket.error, ss.recv_into, bytearray(b'x')) |
| 177 | self.assertRaises(socket.error, ss.recvfrom, 1) |
| 178 | self.assertRaises(socket.error, ss.recvfrom_into, bytearray(b'x'), 1) |
| 179 | self.assertRaises(socket.error, ss.send, b'x') |
| 180 | self.assertRaises(socket.error, ss.sendto, b'x', ('0.0.0.0', 0)) |
| 181 | |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 182 | def test_timeout(self): |
| 183 | # Issue #8524: when creating an SSL socket, the timeout of the |
| 184 | # original socket should be retained. |
| 185 | for timeout in (None, 0.0, 5.0): |
| 186 | s = socket.socket(socket.AF_INET) |
| 187 | s.settimeout(timeout) |
| 188 | ss = ssl.wrap_socket(s) |
| 189 | self.assertEqual(timeout, ss.gettimeout()) |
| 190 | |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 191 | def test_errors(self): |
| 192 | sock = socket.socket() |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 193 | self.assertRaisesRegex(ValueError, |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 194 | "certfile must be specified", |
| 195 | ssl.wrap_socket, sock, keyfile=CERTFILE) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 196 | self.assertRaisesRegex(ValueError, |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 197 | "certfile must be specified for server-side operations", |
| 198 | ssl.wrap_socket, sock, server_side=True) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 199 | self.assertRaisesRegex(ValueError, |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 200 | "certfile must be specified for server-side operations", |
| 201 | ssl.wrap_socket, sock, server_side=True, certfile="") |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 202 | s = ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 203 | self.assertRaisesRegex(ValueError, "can't connect in server-side mode", |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 204 | s.connect, (HOST, 8080)) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 205 | with self.assertRaises(IOError) as cm: |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 206 | with socket.socket() as sock: |
| 207 | ssl.wrap_socket(sock, certfile=WRONGCERT) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 208 | self.assertEqual(cm.exception.errno, errno.ENOENT) |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 209 | with self.assertRaises(IOError) as cm: |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 210 | with socket.socket() as sock: |
| 211 | ssl.wrap_socket(sock, certfile=CERTFILE, keyfile=WRONGCERT) |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 212 | self.assertEqual(cm.exception.errno, errno.ENOENT) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 213 | with self.assertRaises(IOError) as cm: |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 214 | with socket.socket() as sock: |
| 215 | ssl.wrap_socket(sock, certfile=WRONGCERT, keyfile=WRONGCERT) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 216 | self.assertEqual(cm.exception.errno, errno.ENOENT) |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 217 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 218 | def test_match_hostname(self): |
| 219 | def ok(cert, hostname): |
| 220 | ssl.match_hostname(cert, hostname) |
| 221 | def fail(cert, hostname): |
| 222 | self.assertRaises(ssl.CertificateError, |
| 223 | ssl.match_hostname, cert, hostname) |
| 224 | |
| 225 | cert = {'subject': ((('commonName', 'example.com'),),)} |
| 226 | ok(cert, 'example.com') |
| 227 | ok(cert, 'ExAmple.cOm') |
| 228 | fail(cert, 'www.example.com') |
| 229 | fail(cert, '.example.com') |
| 230 | fail(cert, 'example.org') |
| 231 | fail(cert, 'exampleXcom') |
| 232 | |
| 233 | cert = {'subject': ((('commonName', '*.a.com'),),)} |
| 234 | ok(cert, 'foo.a.com') |
| 235 | fail(cert, 'bar.foo.a.com') |
| 236 | fail(cert, 'a.com') |
| 237 | fail(cert, 'Xa.com') |
| 238 | fail(cert, '.a.com') |
| 239 | |
| 240 | cert = {'subject': ((('commonName', 'a.*.com'),),)} |
| 241 | ok(cert, 'a.foo.com') |
| 242 | fail(cert, 'a..com') |
| 243 | fail(cert, 'a.com') |
| 244 | |
| 245 | cert = {'subject': ((('commonName', 'f*.com'),),)} |
| 246 | ok(cert, 'foo.com') |
| 247 | ok(cert, 'f.com') |
| 248 | fail(cert, 'bar.com') |
| 249 | fail(cert, 'foo.a.com') |
| 250 | fail(cert, 'bar.foo.com') |
| 251 | |
| 252 | # Slightly fake real-world example |
| 253 | cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', |
| 254 | 'subject': ((('commonName', 'linuxfrz.org'),),), |
| 255 | 'subjectAltName': (('DNS', 'linuxfr.org'), |
| 256 | ('DNS', 'linuxfr.com'), |
| 257 | ('othername', '<unsupported>'))} |
| 258 | ok(cert, 'linuxfr.org') |
| 259 | ok(cert, 'linuxfr.com') |
| 260 | # Not a "DNS" entry |
| 261 | fail(cert, '<unsupported>') |
| 262 | # When there is a subjectAltName, commonName isn't used |
| 263 | fail(cert, 'linuxfrz.org') |
| 264 | |
| 265 | # A pristine real-world example |
| 266 | cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', |
| 267 | 'subject': ((('countryName', 'US'),), |
| 268 | (('stateOrProvinceName', 'California'),), |
| 269 | (('localityName', 'Mountain View'),), |
| 270 | (('organizationName', 'Google Inc'),), |
| 271 | (('commonName', 'mail.google.com'),))} |
| 272 | ok(cert, 'mail.google.com') |
| 273 | fail(cert, 'gmail.com') |
| 274 | # Only commonName is considered |
| 275 | fail(cert, 'California') |
| 276 | |
| 277 | # Neither commonName nor subjectAltName |
| 278 | cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', |
| 279 | 'subject': ((('countryName', 'US'),), |
| 280 | (('stateOrProvinceName', 'California'),), |
| 281 | (('localityName', 'Mountain View'),), |
| 282 | (('organizationName', 'Google Inc'),))} |
| 283 | fail(cert, 'mail.google.com') |
| 284 | |
Antoine Pitrou | 1c86b44 | 2011-05-06 15:19:49 +0200 | [diff] [blame] | 285 | # No DNS entry in subjectAltName but a commonName |
| 286 | cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', |
| 287 | 'subject': ((('countryName', 'US'),), |
| 288 | (('stateOrProvinceName', 'California'),), |
| 289 | (('localityName', 'Mountain View'),), |
| 290 | (('commonName', 'mail.google.com'),)), |
| 291 | 'subjectAltName': (('othername', 'blabla'), )} |
| 292 | ok(cert, 'mail.google.com') |
| 293 | |
| 294 | # No DNS entry subjectAltName and no commonName |
| 295 | cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', |
| 296 | 'subject': ((('countryName', 'US'),), |
| 297 | (('stateOrProvinceName', 'California'),), |
| 298 | (('localityName', 'Mountain View'),), |
| 299 | (('organizationName', 'Google Inc'),)), |
| 300 | 'subjectAltName': (('othername', 'blabla'),)} |
| 301 | fail(cert, 'google.com') |
| 302 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 303 | # Empty cert / no cert |
| 304 | self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com') |
| 305 | self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com') |
| 306 | |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 307 | def test_server_side(self): |
| 308 | # server_hostname doesn't work for server sockets |
| 309 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 310 | with socket.socket() as sock: |
| 311 | self.assertRaises(ValueError, ctx.wrap_socket, sock, True, |
| 312 | server_hostname="some.hostname") |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 313 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 314 | class ContextTests(unittest.TestCase): |
| 315 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 316 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 317 | def test_constructor(self): |
Victor Stinner | 17ca323 | 2011-05-10 00:48:41 +0200 | [diff] [blame] | 318 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 319 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv2) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 320 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 321 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv3) |
| 322 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 323 | self.assertRaises(TypeError, ssl.SSLContext) |
| 324 | self.assertRaises(ValueError, ssl.SSLContext, -1) |
| 325 | self.assertRaises(ValueError, ssl.SSLContext, 42) |
| 326 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 327 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 328 | def test_protocol(self): |
| 329 | for proto in PROTOCOLS: |
| 330 | ctx = ssl.SSLContext(proto) |
| 331 | self.assertEqual(ctx.protocol, proto) |
| 332 | |
| 333 | def test_ciphers(self): |
| 334 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 335 | ctx.set_ciphers("ALL") |
| 336 | ctx.set_ciphers("DEFAULT") |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 337 | with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
Antoine Pitrou | 3047406 | 2010-05-16 23:46:26 +0000 | [diff] [blame] | 338 | ctx.set_ciphers("^$:,;?*'dorothyx") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 339 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 340 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 341 | def test_options(self): |
| 342 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 343 | # OP_ALL is the default value |
| 344 | self.assertEqual(ssl.OP_ALL, ctx.options) |
| 345 | ctx.options |= ssl.OP_NO_SSLv2 |
| 346 | self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2, |
| 347 | ctx.options) |
| 348 | ctx.options |= ssl.OP_NO_SSLv3 |
| 349 | self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3, |
| 350 | ctx.options) |
| 351 | if can_clear_options(): |
| 352 | ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1 |
| 353 | self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, |
| 354 | ctx.options) |
| 355 | ctx.options = 0 |
| 356 | self.assertEqual(0, ctx.options) |
| 357 | else: |
| 358 | with self.assertRaises(ValueError): |
| 359 | ctx.options = 0 |
| 360 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 361 | def test_verify(self): |
| 362 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 363 | # Default value |
| 364 | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 365 | ctx.verify_mode = ssl.CERT_OPTIONAL |
| 366 | self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
| 367 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 368 | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 369 | ctx.verify_mode = ssl.CERT_NONE |
| 370 | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 371 | with self.assertRaises(TypeError): |
| 372 | ctx.verify_mode = None |
| 373 | with self.assertRaises(ValueError): |
| 374 | ctx.verify_mode = 42 |
| 375 | |
| 376 | def test_load_cert_chain(self): |
| 377 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 378 | # Combined key and cert in a single file |
| 379 | ctx.load_cert_chain(CERTFILE) |
| 380 | ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) |
| 381 | self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 382 | with self.assertRaises(IOError) as cm: |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 383 | ctx.load_cert_chain(WRONGCERT) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 384 | self.assertEqual(cm.exception.errno, errno.ENOENT) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 385 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 386 | ctx.load_cert_chain(BADCERT) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 387 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 388 | ctx.load_cert_chain(EMPTYCERT) |
| 389 | # Separate key and cert |
Antoine Pitrou | d091950 | 2010-05-17 10:30:00 +0000 | [diff] [blame] | 390 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 391 | ctx.load_cert_chain(ONLYCERT, ONLYKEY) |
| 392 | ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) |
| 393 | ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 394 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 395 | ctx.load_cert_chain(ONLYCERT) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 396 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 397 | ctx.load_cert_chain(ONLYKEY) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 398 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 399 | ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) |
| 400 | # Mismatching key and cert |
Antoine Pitrou | d091950 | 2010-05-17 10:30:00 +0000 | [diff] [blame] | 401 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 402 | with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"): |
Antoine Pitrou | 8156409 | 2010-10-08 23:06:24 +0000 | [diff] [blame] | 403 | ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 404 | |
| 405 | def test_load_verify_locations(self): |
| 406 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 407 | ctx.load_verify_locations(CERTFILE) |
| 408 | ctx.load_verify_locations(cafile=CERTFILE, capath=None) |
| 409 | ctx.load_verify_locations(BYTES_CERTFILE) |
| 410 | ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) |
| 411 | self.assertRaises(TypeError, ctx.load_verify_locations) |
| 412 | self.assertRaises(TypeError, ctx.load_verify_locations, None, None) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 413 | with self.assertRaises(IOError) as cm: |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 414 | ctx.load_verify_locations(WRONGCERT) |
Giampaolo Rodolà | 4a656eb | 2010-08-29 22:50:39 +0000 | [diff] [blame] | 415 | self.assertEqual(cm.exception.errno, errno.ENOENT) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 416 | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 417 | ctx.load_verify_locations(BADCERT) |
| 418 | ctx.load_verify_locations(CERTFILE, CAPATH) |
| 419 | ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) |
| 420 | |
Victor Stinner | 80f75e6 | 2011-01-29 11:31:20 +0000 | [diff] [blame] | 421 | # Issue #10989: crash if the second argument type is invalid |
| 422 | self.assertRaises(TypeError, ctx.load_verify_locations, None, True) |
| 423 | |
Antoine Pitrou | eb585ad | 2010-10-22 18:24:20 +0000 | [diff] [blame] | 424 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | b0182c8 | 2010-10-12 20:09:02 +0000 | [diff] [blame] | 425 | def test_session_stats(self): |
| 426 | for proto in PROTOCOLS: |
| 427 | ctx = ssl.SSLContext(proto) |
| 428 | self.assertEqual(ctx.session_stats(), { |
| 429 | 'number': 0, |
| 430 | 'connect': 0, |
| 431 | 'connect_good': 0, |
| 432 | 'connect_renegotiate': 0, |
| 433 | 'accept': 0, |
| 434 | 'accept_good': 0, |
| 435 | 'accept_renegotiate': 0, |
| 436 | 'hits': 0, |
| 437 | 'misses': 0, |
| 438 | 'timeouts': 0, |
| 439 | 'cache_full': 0, |
| 440 | }) |
| 441 | |
Antoine Pitrou | 664c2d1 | 2010-11-17 20:29:42 +0000 | [diff] [blame] | 442 | def test_set_default_verify_paths(self): |
| 443 | # There's not much we can do to test that it acts as expected, |
| 444 | # so just check it doesn't crash or raise an exception. |
| 445 | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 446 | ctx.set_default_verify_paths() |
| 447 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 448 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 449 | class NetworkedTests(unittest.TestCase): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 450 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 451 | def test_connect(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 452 | with support.transient_internet("svn.python.org"): |
| 453 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 454 | cert_reqs=ssl.CERT_NONE) |
| 455 | try: |
| 456 | s.connect(("svn.python.org", 443)) |
| 457 | self.assertEqual({}, s.getpeercert()) |
| 458 | finally: |
| 459 | s.close() |
| 460 | |
| 461 | # this should fail because we have no verification certs |
| 462 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 463 | cert_reqs=ssl.CERT_REQUIRED) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 464 | self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", |
| 465 | s.connect, ("svn.python.org", 443)) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 466 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 467 | |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 468 | # this should succeed because we specify the root cert |
| 469 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 470 | cert_reqs=ssl.CERT_REQUIRED, |
| 471 | ca_certs=SVN_PYTHON_ORG_ROOT_CERT) |
| 472 | try: |
| 473 | s.connect(("svn.python.org", 443)) |
| 474 | self.assertTrue(s.getpeercert()) |
| 475 | finally: |
| 476 | s.close() |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 477 | |
Antoine Pitrou | 86cbfec | 2011-02-26 23:25:34 +0000 | [diff] [blame] | 478 | def test_connect_ex(self): |
| 479 | # Issue #11326: check connect_ex() implementation |
| 480 | with support.transient_internet("svn.python.org"): |
| 481 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 482 | cert_reqs=ssl.CERT_REQUIRED, |
| 483 | ca_certs=SVN_PYTHON_ORG_ROOT_CERT) |
| 484 | try: |
| 485 | self.assertEqual(0, s.connect_ex(("svn.python.org", 443))) |
| 486 | self.assertTrue(s.getpeercert()) |
| 487 | finally: |
| 488 | s.close() |
| 489 | |
| 490 | def test_non_blocking_connect_ex(self): |
| 491 | # Issue #11326: non-blocking connect_ex() should allow handshake |
| 492 | # to proceed after the socket gets ready. |
| 493 | with support.transient_internet("svn.python.org"): |
| 494 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 495 | cert_reqs=ssl.CERT_REQUIRED, |
| 496 | ca_certs=SVN_PYTHON_ORG_ROOT_CERT, |
| 497 | do_handshake_on_connect=False) |
| 498 | try: |
| 499 | s.setblocking(False) |
| 500 | rc = s.connect_ex(('svn.python.org', 443)) |
Antoine Pitrou | d1c9845 | 2011-02-27 15:45:16 +0000 | [diff] [blame] | 501 | # EWOULDBLOCK under Windows, EINPROGRESS elsewhere |
| 502 | self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) |
Antoine Pitrou | 86cbfec | 2011-02-26 23:25:34 +0000 | [diff] [blame] | 503 | # Wait for connect to finish |
| 504 | select.select([], [s], [], 5.0) |
| 505 | # Non-blocking handshake |
| 506 | while True: |
| 507 | try: |
| 508 | s.do_handshake() |
| 509 | break |
| 510 | except ssl.SSLError as err: |
| 511 | if err.args[0] == ssl.SSL_ERROR_WANT_READ: |
| 512 | select.select([s], [], [], 5.0) |
| 513 | elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: |
| 514 | select.select([], [s], [], 5.0) |
| 515 | else: |
| 516 | raise |
| 517 | # SSL established |
| 518 | self.assertTrue(s.getpeercert()) |
| 519 | finally: |
| 520 | s.close() |
| 521 | |
Antoine Pitrou | b4410db | 2011-05-18 18:51:06 +0200 | [diff] [blame] | 522 | def test_timeout_connect_ex(self): |
| 523 | # Issue #12065: on a timeout, connect_ex() should return the original |
| 524 | # errno (mimicking the behaviour of non-SSL sockets). |
| 525 | with support.transient_internet("svn.python.org"): |
| 526 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 527 | cert_reqs=ssl.CERT_REQUIRED, |
| 528 | ca_certs=SVN_PYTHON_ORG_ROOT_CERT, |
| 529 | do_handshake_on_connect=False) |
| 530 | try: |
| 531 | s.settimeout(0.0000001) |
| 532 | rc = s.connect_ex(('svn.python.org', 443)) |
| 533 | if rc == 0: |
| 534 | self.skipTest("svn.python.org responded too quickly") |
| 535 | self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) |
| 536 | finally: |
| 537 | s.close() |
| 538 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 539 | def test_connect_with_context(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 540 | with support.transient_internet("svn.python.org"): |
| 541 | # Same as test_connect, but with a separately created context |
| 542 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 543 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 544 | s.connect(("svn.python.org", 443)) |
| 545 | try: |
| 546 | self.assertEqual({}, s.getpeercert()) |
| 547 | finally: |
| 548 | s.close() |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 549 | # Same with a server hostname |
| 550 | s = ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 551 | server_hostname="svn.python.org") |
| 552 | if ssl.HAS_SNI: |
| 553 | s.connect(("svn.python.org", 443)) |
| 554 | s.close() |
| 555 | else: |
| 556 | self.assertRaises(ValueError, s.connect, ("svn.python.org", 443)) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 557 | # This should fail because we have no verification certs |
| 558 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 559 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 560 | self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 561 | s.connect, ("svn.python.org", 443)) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 562 | s.close() |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 563 | # This should succeed because we specify the root cert |
| 564 | ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) |
| 565 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 566 | s.connect(("svn.python.org", 443)) |
| 567 | try: |
| 568 | cert = s.getpeercert() |
| 569 | self.assertTrue(cert) |
| 570 | finally: |
| 571 | s.close() |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 572 | |
| 573 | def test_connect_capath(self): |
| 574 | # Verify server certificates using the `capath` argument |
Antoine Pitrou | 467f28d | 2010-05-16 19:22:44 +0000 | [diff] [blame] | 575 | # NOTE: the subject hashing algorithm has been changed between |
| 576 | # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must |
| 577 | # contain both versions of each certificate (same content, different |
Antoine Pitrou | d7e4c1c | 2010-05-17 14:13:10 +0000 | [diff] [blame] | 578 | # filename) for this test to be portable across OpenSSL releases. |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 579 | with support.transient_internet("svn.python.org"): |
| 580 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 581 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 582 | ctx.load_verify_locations(capath=CAPATH) |
| 583 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 584 | s.connect(("svn.python.org", 443)) |
| 585 | try: |
| 586 | cert = s.getpeercert() |
| 587 | self.assertTrue(cert) |
| 588 | finally: |
| 589 | s.close() |
| 590 | # Same with a bytes `capath` argument |
| 591 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 592 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 593 | ctx.load_verify_locations(capath=BYTES_CAPATH) |
| 594 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 595 | s.connect(("svn.python.org", 443)) |
| 596 | try: |
| 597 | cert = s.getpeercert() |
| 598 | self.assertTrue(cert) |
| 599 | finally: |
| 600 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 601 | |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 602 | @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") |
| 603 | def test_makefile_close(self): |
| 604 | # Issue #5238: creating a file-like object with makefile() shouldn't |
| 605 | # delay closing the underlying "real socket" (here tested with its |
| 606 | # file descriptor, hence skipping the test under Windows). |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 607 | with support.transient_internet("svn.python.org"): |
| 608 | ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) |
| 609 | ss.connect(("svn.python.org", 443)) |
| 610 | fd = ss.fileno() |
| 611 | f = ss.makefile() |
| 612 | f.close() |
| 613 | # The fd is still open |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 614 | os.read(fd, 0) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 615 | # Closing the SSL socket should close the fd too |
| 616 | ss.close() |
| 617 | gc.collect() |
| 618 | with self.assertRaises(OSError) as e: |
| 619 | os.read(fd, 0) |
| 620 | self.assertEqual(e.exception.errno, errno.EBADF) |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 621 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 622 | def test_non_blocking_handshake(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 623 | with support.transient_internet("svn.python.org"): |
| 624 | s = socket.socket(socket.AF_INET) |
| 625 | s.connect(("svn.python.org", 443)) |
| 626 | s.setblocking(False) |
| 627 | s = ssl.wrap_socket(s, |
| 628 | cert_reqs=ssl.CERT_NONE, |
| 629 | do_handshake_on_connect=False) |
| 630 | count = 0 |
| 631 | while True: |
| 632 | try: |
| 633 | count += 1 |
| 634 | s.do_handshake() |
| 635 | break |
| 636 | except ssl.SSLError as err: |
| 637 | if err.args[0] == ssl.SSL_ERROR_WANT_READ: |
| 638 | select.select([s], [], []) |
| 639 | elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: |
| 640 | select.select([], [s], []) |
| 641 | else: |
| 642 | raise |
| 643 | s.close() |
| 644 | if support.verbose: |
| 645 | sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 646 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 647 | def test_get_server_certificate(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 648 | with support.transient_internet("svn.python.org"): |
| 649 | pem = ssl.get_server_certificate(("svn.python.org", 443)) |
| 650 | if not pem: |
| 651 | self.fail("No server certificate on svn.python.org:443!") |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 652 | |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 653 | try: |
| 654 | pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE) |
| 655 | except ssl.SSLError as x: |
| 656 | #should fail |
| 657 | if support.verbose: |
| 658 | sys.stdout.write("%s\n" % x) |
| 659 | else: |
| 660 | self.fail("Got server certificate %s for svn.python.org!" % pem) |
| 661 | |
| 662 | pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) |
| 663 | if not pem: |
| 664 | self.fail("No server certificate on svn.python.org:443!") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 665 | if support.verbose: |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 666 | sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 667 | |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 668 | def test_ciphers(self): |
| 669 | remote = ("svn.python.org", 443) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 670 | with support.transient_internet(remote[0]): |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 671 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 672 | cert_reqs=ssl.CERT_NONE, ciphers="ALL") |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 673 | s.connect(remote) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 674 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 675 | cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") |
| 676 | s.connect(remote) |
| 677 | # Error checking can happen at instantiation or when connecting |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 678 | with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 679 | with socket.socket(socket.AF_INET) as sock: |
| 680 | s = ssl.wrap_socket(sock, |
| 681 | cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") |
| 682 | s.connect(remote) |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 683 | |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 684 | def test_algorithms(self): |
| 685 | # Issue #8484: all algorithms should be available when verifying a |
| 686 | # certificate. |
Antoine Pitrou | 29619b2 | 2010-04-22 18:43:31 +0000 | [diff] [blame] | 687 | # SHA256 was added in OpenSSL 0.9.8 |
| 688 | if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15): |
| 689 | self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION) |
Victor Stinner | f332abb | 2011-01-08 03:16:05 +0000 | [diff] [blame] | 690 | # https://sha2.hboeck.de/ was used until 2011-01-08 (no route to host) |
| 691 | remote = ("sha256.tbs-internet.com", 443) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 692 | sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem") |
Antoine Pitrou | 160fd93 | 2011-01-08 10:23:29 +0000 | [diff] [blame] | 693 | with support.transient_internet("sha256.tbs-internet.com"): |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 694 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 695 | cert_reqs=ssl.CERT_REQUIRED, |
| 696 | ca_certs=sha256_cert,) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 697 | try: |
| 698 | s.connect(remote) |
| 699 | if support.verbose: |
| 700 | sys.stdout.write("\nCipher with %r is %r\n" % |
| 701 | (remote, s.cipher())) |
| 702 | sys.stdout.write("Certificate is:\n%s\n" % |
| 703 | pprint.pformat(s.getpeercert())) |
| 704 | finally: |
| 705 | s.close() |
| 706 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 707 | |
| 708 | try: |
| 709 | import threading |
| 710 | except ImportError: |
| 711 | _have_threads = False |
| 712 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 713 | _have_threads = True |
| 714 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 715 | from test.ssl_servers import make_https_server |
| 716 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 717 | class ThreadedEchoServer(threading.Thread): |
| 718 | |
| 719 | class ConnectionHandler(threading.Thread): |
| 720 | |
| 721 | """A mildly complicated class, because we want it to work both |
| 722 | with and without the SSL wrapper around the socket connection, so |
| 723 | that we can test the STARTTLS functionality.""" |
| 724 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 725 | def __init__(self, server, connsock, addr): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 726 | self.server = server |
| 727 | self.running = False |
| 728 | self.sock = connsock |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 729 | self.addr = addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 730 | self.sock.setblocking(1) |
| 731 | self.sslconn = None |
| 732 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 733 | self.daemon = True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 734 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 735 | def wrap_conn(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 736 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 737 | self.sslconn = self.server.context.wrap_socket( |
| 738 | self.sock, server_side=True) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 739 | except ssl.SSLError: |
| 740 | # XXX Various errors can have happened here, for example |
| 741 | # a mismatching protocol version, an invalid certificate, |
| 742 | # or a low-level bug. This should be made more discriminating. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 743 | if self.server.chatty: |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 744 | handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 745 | self.running = False |
| 746 | self.server.stop() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 747 | self.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 748 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 749 | else: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 750 | if self.server.context.verify_mode == ssl.CERT_REQUIRED: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 751 | cert = self.sslconn.getpeercert() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 752 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 753 | sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") |
| 754 | cert_binary = self.sslconn.getpeercert(True) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 755 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 756 | sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") |
| 757 | cipher = self.sslconn.cipher() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 758 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 759 | sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") |
| 760 | return True |
| 761 | |
| 762 | def read(self): |
| 763 | if self.sslconn: |
| 764 | return self.sslconn.read() |
| 765 | else: |
| 766 | return self.sock.recv(1024) |
| 767 | |
| 768 | def write(self, bytes): |
| 769 | if self.sslconn: |
| 770 | return self.sslconn.write(bytes) |
| 771 | else: |
| 772 | return self.sock.send(bytes) |
| 773 | |
| 774 | def close(self): |
| 775 | if self.sslconn: |
| 776 | self.sslconn.close() |
| 777 | else: |
| 778 | self.sock.close() |
| 779 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 780 | def run(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 781 | self.running = True |
| 782 | if not self.server.starttls_server: |
| 783 | if not self.wrap_conn(): |
| 784 | return |
| 785 | while self.running: |
| 786 | try: |
| 787 | msg = self.read() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 788 | stripped = msg.strip() |
| 789 | if not stripped: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 790 | # eof, so quit this handler |
| 791 | self.running = False |
| 792 | self.close() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 793 | elif stripped == b'over': |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 794 | if support.verbose and self.server.connectionchatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 795 | sys.stdout.write(" server: client closed connection\n") |
| 796 | self.close() |
| 797 | return |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 798 | elif (self.server.starttls_server and |
Antoine Pitrou | 764b878 | 2010-04-28 22:57:15 +0000 | [diff] [blame] | 799 | stripped == b'STARTTLS'): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 800 | if support.verbose and self.server.connectionchatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 801 | sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 802 | self.write(b"OK\n") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 803 | if not self.wrap_conn(): |
| 804 | return |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 805 | elif (self.server.starttls_server and self.sslconn |
Antoine Pitrou | 764b878 | 2010-04-28 22:57:15 +0000 | [diff] [blame] | 806 | and stripped == b'ENDTLS'): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 807 | if support.verbose and self.server.connectionchatty: |
| 808 | sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 809 | self.write(b"OK\n") |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 810 | self.sock = self.sslconn.unwrap() |
| 811 | self.sslconn = None |
| 812 | if support.verbose and self.server.connectionchatty: |
| 813 | sys.stdout.write(" server: connection is now unencrypted...\n") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 814 | else: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 815 | if (support.verbose and |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 816 | self.server.connectionchatty): |
| 817 | ctype = (self.sslconn and "encrypted") or "unencrypted" |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 818 | sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" |
| 819 | % (msg, ctype, msg.lower(), ctype)) |
| 820 | self.write(msg.lower()) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 821 | except socket.error: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 822 | if self.server.chatty: |
| 823 | handle_error("Test server failure:\n") |
| 824 | self.close() |
| 825 | self.running = False |
| 826 | # normally, we'd just stop here, but for the test |
| 827 | # harness, we want to stop the server |
| 828 | self.server.stop() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 829 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 830 | def __init__(self, certificate=None, ssl_version=None, |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 831 | certreqs=None, cacerts=None, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 832 | chatty=True, connectionchatty=False, starttls_server=False, |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 833 | ciphers=None, context=None): |
| 834 | if context: |
| 835 | self.context = context |
| 836 | else: |
| 837 | self.context = ssl.SSLContext(ssl_version |
| 838 | if ssl_version is not None |
| 839 | else ssl.PROTOCOL_TLSv1) |
| 840 | self.context.verify_mode = (certreqs if certreqs is not None |
| 841 | else ssl.CERT_NONE) |
| 842 | if cacerts: |
| 843 | self.context.load_verify_locations(cacerts) |
| 844 | if certificate: |
| 845 | self.context.load_cert_chain(certificate) |
| 846 | if ciphers: |
| 847 | self.context.set_ciphers(ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 848 | self.chatty = chatty |
| 849 | self.connectionchatty = connectionchatty |
| 850 | self.starttls_server = starttls_server |
| 851 | self.sock = socket.socket() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 852 | self.port = support.bind_port(self.sock) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 853 | self.flag = None |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 854 | self.active = False |
| 855 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 856 | self.daemon = True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 857 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 858 | def start(self, flag=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 859 | self.flag = flag |
| 860 | threading.Thread.start(self) |
| 861 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 862 | def run(self): |
Antoine Pitrou | af7c602 | 2010-04-27 09:56:02 +0000 | [diff] [blame] | 863 | self.sock.settimeout(0.05) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 864 | self.sock.listen(5) |
| 865 | self.active = True |
| 866 | if self.flag: |
| 867 | # signal an event |
| 868 | self.flag.set() |
| 869 | while self.active: |
| 870 | try: |
| 871 | newconn, connaddr = self.sock.accept() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 872 | if support.verbose and self.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 873 | sys.stdout.write(' server: new connection from ' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 874 | + repr(connaddr) + '\n') |
| 875 | handler = self.ConnectionHandler(self, newconn, connaddr) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 876 | handler.start() |
| 877 | except socket.timeout: |
| 878 | pass |
| 879 | except KeyboardInterrupt: |
| 880 | self.stop() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 881 | self.sock.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 882 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 883 | def stop(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 884 | self.active = False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 885 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 886 | class AsyncoreEchoServer(threading.Thread): |
| 887 | |
| 888 | # this one's based on asyncore.dispatcher |
| 889 | |
| 890 | class EchoServer (asyncore.dispatcher): |
| 891 | |
| 892 | class ConnectionHandler (asyncore.dispatcher_with_send): |
| 893 | |
| 894 | def __init__(self, conn, certfile): |
| 895 | self.socket = ssl.wrap_socket(conn, server_side=True, |
| 896 | certfile=certfile, |
| 897 | do_handshake_on_connect=False) |
| 898 | asyncore.dispatcher_with_send.__init__(self, self.socket) |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 899 | self._ssl_accepting = True |
| 900 | self._do_ssl_handshake() |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 901 | |
| 902 | def readable(self): |
| 903 | if isinstance(self.socket, ssl.SSLSocket): |
| 904 | while self.socket.pending() > 0: |
| 905 | self.handle_read_event() |
| 906 | return True |
| 907 | |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 908 | def _do_ssl_handshake(self): |
| 909 | try: |
| 910 | self.socket.do_handshake() |
| 911 | except ssl.SSLError as err: |
| 912 | if err.args[0] in (ssl.SSL_ERROR_WANT_READ, |
| 913 | ssl.SSL_ERROR_WANT_WRITE): |
| 914 | return |
| 915 | elif err.args[0] == ssl.SSL_ERROR_EOF: |
| 916 | return self.handle_close() |
| 917 | raise |
| 918 | except socket.error as err: |
| 919 | if err.args[0] == errno.ECONNABORTED: |
| 920 | return self.handle_close() |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 921 | else: |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 922 | self._ssl_accepting = False |
| 923 | |
| 924 | def handle_read(self): |
| 925 | if self._ssl_accepting: |
| 926 | self._do_ssl_handshake() |
| 927 | else: |
| 928 | data = self.recv(1024) |
| 929 | if support.verbose: |
| 930 | sys.stdout.write(" server: read %s from client\n" % repr(data)) |
| 931 | if not data: |
| 932 | self.close() |
| 933 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 934 | self.send(data.lower()) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 935 | |
| 936 | def handle_close(self): |
Bill Janssen | 2f5799b | 2008-06-29 00:08:12 +0000 | [diff] [blame] | 937 | self.close() |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 938 | if support.verbose: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 939 | sys.stdout.write(" server: closed connection %s\n" % self.socket) |
| 940 | |
| 941 | def handle_error(self): |
| 942 | raise |
| 943 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 944 | def __init__(self, certfile): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 945 | self.certfile = certfile |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 946 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 947 | self.port = support.bind_port(sock, '') |
| 948 | asyncore.dispatcher.__init__(self, sock) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 949 | self.listen(5) |
| 950 | |
Giampaolo Rodolà | 977c707 | 2010-10-04 21:08:36 +0000 | [diff] [blame] | 951 | def handle_accepted(self, sock_obj, addr): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 952 | if support.verbose: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 953 | sys.stdout.write(" server: new connection from %s:%s\n" %addr) |
| 954 | self.ConnectionHandler(sock_obj, self.certfile) |
| 955 | |
| 956 | def handle_error(self): |
| 957 | raise |
| 958 | |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 959 | def __init__(self, certfile): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 960 | self.flag = None |
| 961 | self.active = False |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 962 | self.server = self.EchoServer(certfile) |
| 963 | self.port = self.server.port |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 964 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 965 | self.daemon = True |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 966 | |
| 967 | def __str__(self): |
| 968 | return "<%s %s>" % (self.__class__.__name__, self.server) |
| 969 | |
| 970 | def start (self, flag=None): |
| 971 | self.flag = flag |
| 972 | threading.Thread.start(self) |
| 973 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 974 | def run(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 975 | self.active = True |
| 976 | if self.flag: |
| 977 | self.flag.set() |
| 978 | while self.active: |
| 979 | try: |
| 980 | asyncore.loop(1) |
| 981 | except: |
| 982 | pass |
| 983 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 984 | def stop(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 985 | self.active = False |
| 986 | self.server.close() |
| 987 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 988 | def bad_cert_test(certfile): |
| 989 | """ |
| 990 | Launch a server with CERT_REQUIRED, and check that trying to |
| 991 | connect to it with the given client certificate fails. |
| 992 | """ |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 993 | server = ThreadedEchoServer(CERTFILE, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 994 | certreqs=ssl.CERT_REQUIRED, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 995 | cacerts=CERTFILE, chatty=False, |
| 996 | connectionchatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 997 | flag = threading.Event() |
| 998 | server.start(flag) |
| 999 | # wait for it to start |
| 1000 | flag.wait() |
| 1001 | # try to connect |
| 1002 | try: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1003 | try: |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1004 | with socket.socket() as sock: |
| 1005 | s = ssl.wrap_socket(sock, |
| 1006 | certfile=certfile, |
| 1007 | ssl_version=ssl.PROTOCOL_TLSv1) |
| 1008 | s.connect((HOST, server.port)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1009 | except ssl.SSLError as x: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1010 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1011 | sys.stdout.write("\nSSLError is %s\n" % x.args[1]) |
Antoine Pitrou | 05830aa | 2010-04-27 13:15:18 +0000 | [diff] [blame] | 1012 | except socket.error as x: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1013 | if support.verbose: |
Georg Brandl | b75b639 | 2010-10-24 14:20:22 +0000 | [diff] [blame] | 1014 | sys.stdout.write("\nsocket.error is %s\n" % x.args[1]) |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 1015 | except IOError as x: |
Giampaolo Rodolà | cd9dfb9 | 2010-08-29 20:56:56 +0000 | [diff] [blame] | 1016 | if x.errno != errno.ENOENT: |
| 1017 | raise |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 1018 | if support.verbose: |
Giampaolo Rodolà | cd9dfb9 | 2010-08-29 20:56:56 +0000 | [diff] [blame] | 1019 | sys.stdout.write("\IOError is %s\n" % str(x)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1020 | else: |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1021 | raise AssertionError("Use of invalid cert should have failed!") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1022 | finally: |
| 1023 | server.stop() |
| 1024 | server.join() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1025 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1026 | def server_params_test(client_context, server_context, indata=b"FOO\n", |
| 1027 | chatty=True, connectionchatty=False): |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1028 | """ |
| 1029 | Launch a server, connect a client to it and try various reads |
| 1030 | and writes. |
| 1031 | """ |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1032 | server = ThreadedEchoServer(context=server_context, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1033 | chatty=chatty, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1034 | connectionchatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1035 | flag = threading.Event() |
| 1036 | server.start(flag) |
| 1037 | # wait for it to start |
| 1038 | flag.wait() |
| 1039 | # try to connect |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1040 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1041 | s = client_context.wrap_socket(socket.socket()) |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1042 | s.connect((HOST, server.port)) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1043 | for arg in [indata, bytearray(indata), memoryview(indata)]: |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1044 | if connectionchatty: |
| 1045 | if support.verbose: |
| 1046 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1047 | " client: sending %r...\n" % indata) |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1048 | s.write(arg) |
| 1049 | outdata = s.read() |
| 1050 | if connectionchatty: |
| 1051 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1052 | sys.stdout.write(" client: read %r\n" % outdata) |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1053 | if outdata != indata.lower(): |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1054 | raise AssertionError( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1055 | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 1056 | % (outdata[:20], len(outdata), |
| 1057 | indata[:20].lower(), len(indata))) |
| 1058 | s.write(b"over\n") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1059 | if connectionchatty: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1060 | if support.verbose: |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1061 | sys.stdout.write(" client: closing connection.\n") |
| 1062 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1063 | finally: |
| 1064 | server.stop() |
| 1065 | server.join() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1066 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1067 | def try_protocol_combo(server_protocol, client_protocol, expect_success, |
| 1068 | certsreqs=None, server_options=0, client_options=0): |
Benjamin Peterson | 2a691a8 | 2008-03-31 01:51:45 +0000 | [diff] [blame] | 1069 | if certsreqs is None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1070 | certsreqs = ssl.CERT_NONE |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1071 | certtype = { |
| 1072 | ssl.CERT_NONE: "CERT_NONE", |
| 1073 | ssl.CERT_OPTIONAL: "CERT_OPTIONAL", |
| 1074 | ssl.CERT_REQUIRED: "CERT_REQUIRED", |
| 1075 | }[certsreqs] |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1076 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1077 | formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n" |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1078 | sys.stdout.write(formatstr % |
| 1079 | (ssl.get_protocol_name(client_protocol), |
| 1080 | ssl.get_protocol_name(server_protocol), |
| 1081 | certtype)) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1082 | client_context = ssl.SSLContext(client_protocol) |
| 1083 | client_context.options = ssl.OP_ALL | client_options |
| 1084 | server_context = ssl.SSLContext(server_protocol) |
| 1085 | server_context.options = ssl.OP_ALL | server_options |
| 1086 | for ctx in (client_context, server_context): |
| 1087 | ctx.verify_mode = certsreqs |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 1088 | # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client |
| 1089 | # will send an SSLv3 hello (rather than SSLv2) starting from |
| 1090 | # OpenSSL 1.0.0 (see issue #8322). |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1091 | ctx.set_ciphers("ALL") |
| 1092 | ctx.load_cert_chain(CERTFILE) |
| 1093 | ctx.load_verify_locations(CERTFILE) |
| 1094 | try: |
| 1095 | server_params_test(client_context, server_context, |
| 1096 | chatty=False, connectionchatty=False) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1097 | # Protocol mismatch can result in either an SSLError, or a |
| 1098 | # "Connection reset by peer" error. |
| 1099 | except ssl.SSLError: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1100 | if expect_success: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1101 | raise |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1102 | except socket.error as e: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1103 | if expect_success or e.errno != errno.ECONNRESET: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1104 | raise |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1105 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1106 | if not expect_success: |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1107 | raise AssertionError( |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1108 | "Client protocol %s succeeded with server protocol %s!" |
| 1109 | % (ssl.get_protocol_name(client_protocol), |
| 1110 | ssl.get_protocol_name(server_protocol))) |
| 1111 | |
| 1112 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1113 | class ThreadedTests(unittest.TestCase): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1114 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1115 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1116 | def test_echo(self): |
| 1117 | """Basic test of an SSL client connecting to a server""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1118 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1119 | sys.stdout.write("\n") |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1120 | for protocol in PROTOCOLS: |
| 1121 | context = ssl.SSLContext(protocol) |
| 1122 | context.load_cert_chain(CERTFILE) |
| 1123 | server_params_test(context, context, |
| 1124 | chatty=True, connectionchatty=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1125 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1126 | def test_getpeercert(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1127 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1128 | sys.stdout.write("\n") |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1129 | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 1130 | context.verify_mode = ssl.CERT_REQUIRED |
| 1131 | context.load_verify_locations(CERTFILE) |
| 1132 | context.load_cert_chain(CERTFILE) |
| 1133 | server = ThreadedEchoServer(context=context, chatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1134 | flag = threading.Event() |
| 1135 | server.start(flag) |
| 1136 | # wait for it to start |
| 1137 | flag.wait() |
| 1138 | # try to connect |
| 1139 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1140 | s = context.wrap_socket(socket.socket()) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1141 | s.connect((HOST, server.port)) |
| 1142 | cert = s.getpeercert() |
| 1143 | self.assertTrue(cert, "Can't get peer certificate.") |
| 1144 | cipher = s.cipher() |
| 1145 | if support.verbose: |
| 1146 | sys.stdout.write(pprint.pformat(cert) + '\n') |
| 1147 | sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') |
| 1148 | if 'subject' not in cert: |
| 1149 | self.fail("No subject field in certificate: %s." % |
| 1150 | pprint.pformat(cert)) |
| 1151 | if ((('organizationName', 'Python Software Foundation'),) |
| 1152 | not in cert['subject']): |
| 1153 | self.fail( |
| 1154 | "Missing or invalid 'organizationName' field in certificate subject; " |
| 1155 | "should be 'Python Software Foundation'.") |
Antoine Pitrou | fb04691 | 2010-11-09 20:21:19 +0000 | [diff] [blame] | 1156 | self.assertIn('notBefore', cert) |
| 1157 | self.assertIn('notAfter', cert) |
| 1158 | before = ssl.cert_time_to_seconds(cert['notBefore']) |
| 1159 | after = ssl.cert_time_to_seconds(cert['notAfter']) |
| 1160 | self.assertLess(before, after) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1161 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1162 | finally: |
| 1163 | server.stop() |
| 1164 | server.join() |
| 1165 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1166 | def test_empty_cert(self): |
| 1167 | """Connecting with an empty cert file""" |
| 1168 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1169 | "nullcert.pem")) |
| 1170 | def test_malformed_cert(self): |
| 1171 | """Connecting with a badly formatted certificate (syntax error)""" |
| 1172 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1173 | "badcert.pem")) |
| 1174 | def test_nonexisting_cert(self): |
| 1175 | """Connecting with a non-existing cert file""" |
| 1176 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1177 | "wrongcert.pem")) |
| 1178 | def test_malformed_key(self): |
| 1179 | """Connecting with a badly formatted key (syntax error)""" |
| 1180 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1181 | "badkey.pem")) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1182 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1183 | def test_rude_shutdown(self): |
| 1184 | """A brutal shutdown of an SSL server should raise an IOError |
| 1185 | in the client when attempting handshake. |
| 1186 | """ |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1187 | listener_ready = threading.Event() |
| 1188 | listener_gone = threading.Event() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1189 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1190 | s = socket.socket() |
| 1191 | port = support.bind_port(s, HOST) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1192 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1193 | # `listener` runs in a thread. It sits in an accept() until |
| 1194 | # the main thread connects. Then it rudely closes the socket, |
| 1195 | # and sets Event `listener_gone` to let the main thread know |
| 1196 | # the socket is gone. |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1197 | def listener(): |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1198 | s.listen(5) |
| 1199 | listener_ready.set() |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1200 | newsock, addr = s.accept() |
| 1201 | newsock.close() |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1202 | s.close() |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1203 | listener_gone.set() |
| 1204 | |
| 1205 | def connector(): |
| 1206 | listener_ready.wait() |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1207 | with socket.socket() as c: |
| 1208 | c.connect((HOST, port)) |
| 1209 | listener_gone.wait() |
| 1210 | try: |
| 1211 | ssl_sock = ssl.wrap_socket(c) |
| 1212 | except IOError: |
| 1213 | pass |
| 1214 | else: |
| 1215 | self.fail('connecting to closed SSL socket should have failed') |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1216 | |
| 1217 | t = threading.Thread(target=listener) |
| 1218 | t.start() |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1219 | try: |
| 1220 | connector() |
| 1221 | finally: |
| 1222 | t.join() |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1223 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1224 | @skip_if_broken_ubuntu_ssl |
Victor Stinner | ee18b6f | 2011-05-10 00:38:00 +0200 | [diff] [blame] | 1225 | @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'), "need SSLv2") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1226 | def test_protocol_sslv2(self): |
| 1227 | """Connecting to an SSLv2 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1228 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1229 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1230 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) |
| 1231 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) |
| 1232 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) |
| 1233 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) |
| 1234 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) |
| 1235 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1236 | # SSLv23 client with specific SSL options |
| 1237 | if no_sslv2_implies_sslv3_hello(): |
| 1238 | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
| 1239 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, |
| 1240 | client_options=ssl.OP_NO_SSLv2) |
| 1241 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, |
| 1242 | client_options=ssl.OP_NO_SSLv3) |
| 1243 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, |
| 1244 | client_options=ssl.OP_NO_TLSv1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1245 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1246 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1247 | def test_protocol_sslv23(self): |
| 1248 | """Connecting to an SSLv23 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1249 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1250 | sys.stdout.write("\n") |
Victor Stinner | ee18b6f | 2011-05-10 00:38:00 +0200 | [diff] [blame] | 1251 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1252 | try: |
| 1253 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) |
| 1254 | except (ssl.SSLError, socket.error) as x: |
| 1255 | # this fails on some older versions of OpenSSL (0.9.7l, for instance) |
| 1256 | if support.verbose: |
| 1257 | sys.stdout.write( |
| 1258 | " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" |
| 1259 | % str(x)) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1260 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) |
| 1261 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) |
| 1262 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1263 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1264 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) |
| 1265 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) |
| 1266 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1267 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1268 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) |
| 1269 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) |
| 1270 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1271 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1272 | # Server with specific SSL options |
| 1273 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, |
| 1274 | server_options=ssl.OP_NO_SSLv3) |
| 1275 | # Will choose TLSv1 |
| 1276 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, |
| 1277 | server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
| 1278 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, |
| 1279 | server_options=ssl.OP_NO_TLSv1) |
| 1280 | |
| 1281 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1282 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1283 | def test_protocol_sslv3(self): |
| 1284 | """Connecting to an SSLv3 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1285 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1286 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1287 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) |
| 1288 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) |
| 1289 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) |
Victor Stinner | ee18b6f | 2011-05-10 00:38:00 +0200 | [diff] [blame] | 1290 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1291 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1292 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) |
| 1293 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1294 | if no_sslv2_implies_sslv3_hello(): |
| 1295 | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
| 1296 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, |
| 1297 | client_options=ssl.OP_NO_SSLv2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1298 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1299 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1300 | def test_protocol_tlsv1(self): |
| 1301 | """Connecting to a TLSv1 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1302 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1303 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1304 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) |
| 1305 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) |
| 1306 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) |
Victor Stinner | ee18b6f | 2011-05-10 00:38:00 +0200 | [diff] [blame] | 1307 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1308 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1309 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) |
| 1310 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1311 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1312 | def test_starttls(self): |
| 1313 | """Switching from clear text to encrypted and back again.""" |
| 1314 | msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1315 | |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1316 | server = ThreadedEchoServer(CERTFILE, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1317 | ssl_version=ssl.PROTOCOL_TLSv1, |
| 1318 | starttls_server=True, |
| 1319 | chatty=True, |
| 1320 | connectionchatty=True) |
| 1321 | flag = threading.Event() |
| 1322 | server.start(flag) |
| 1323 | # wait for it to start |
| 1324 | flag.wait() |
| 1325 | # try to connect |
| 1326 | wrapped = False |
| 1327 | try: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1328 | s = socket.socket() |
| 1329 | s.setblocking(1) |
| 1330 | s.connect((HOST, server.port)) |
| 1331 | if support.verbose: |
| 1332 | sys.stdout.write("\n") |
| 1333 | for indata in msgs: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1334 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1335 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1336 | " client: sending %r...\n" % indata) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1337 | if wrapped: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1338 | conn.write(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1339 | outdata = conn.read() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1340 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1341 | s.send(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1342 | outdata = s.recv(1024) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1343 | msg = outdata.strip().lower() |
| 1344 | if indata == b"STARTTLS" and msg.startswith(b"ok"): |
| 1345 | # STARTTLS ok, switch to secure mode |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1346 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1347 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1348 | " client: read %r from server, starting TLS...\n" |
| 1349 | % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1350 | conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) |
| 1351 | wrapped = True |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1352 | elif indata == b"ENDTLS" and msg.startswith(b"ok"): |
| 1353 | # ENDTLS ok, switch back to clear text |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1354 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1355 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1356 | " client: read %r from server, ending TLS...\n" |
| 1357 | % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1358 | s = conn.unwrap() |
| 1359 | wrapped = False |
| 1360 | else: |
| 1361 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1362 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1363 | " client: read %r from server\n" % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1364 | if support.verbose: |
| 1365 | sys.stdout.write(" client: closing connection.\n") |
| 1366 | if wrapped: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1367 | conn.write(b"over\n") |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1368 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1369 | s.send(b"over\n") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1370 | if wrapped: |
| 1371 | conn.close() |
| 1372 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1373 | s.close() |
| 1374 | finally: |
| 1375 | server.stop() |
| 1376 | server.join() |
| 1377 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1378 | def test_socketserver(self): |
| 1379 | """Using a SocketServer to create and manage SSL connections.""" |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1380 | server = make_https_server(self, CERTFILE) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1381 | # try to connect |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1382 | if support.verbose: |
| 1383 | sys.stdout.write('\n') |
| 1384 | with open(CERTFILE, 'rb') as f: |
| 1385 | d1 = f.read() |
| 1386 | d2 = '' |
| 1387 | # now fetch the same data from the HTTPS server |
| 1388 | url = 'https://%s:%d/%s' % ( |
| 1389 | HOST, server.port, os.path.split(CERTFILE)[1]) |
| 1390 | f = urllib.request.urlopen(url) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1391 | try: |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 1392 | dlen = f.info().get("content-length") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1393 | if dlen and (int(dlen) > 0): |
| 1394 | d2 = f.read(int(dlen)) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1395 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1396 | sys.stdout.write( |
| 1397 | " client: read %d bytes from remote server '%s'\n" |
| 1398 | % (len(d2), server)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1399 | finally: |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1400 | f.close() |
| 1401 | self.assertEqual(d1, d2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1402 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1403 | def test_asyncore_server(self): |
| 1404 | """Check the example asyncore integration.""" |
| 1405 | indata = "TEST MESSAGE of mixed case\n" |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1406 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1407 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1408 | sys.stdout.write("\n") |
| 1409 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1410 | indata = b"FOO\n" |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1411 | server = AsyncoreEchoServer(CERTFILE) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1412 | flag = threading.Event() |
| 1413 | server.start(flag) |
| 1414 | # wait for it to start |
| 1415 | flag.wait() |
| 1416 | # try to connect |
| 1417 | try: |
| 1418 | s = ssl.wrap_socket(socket.socket()) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1419 | s.connect(('127.0.0.1', server.port)) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1420 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1421 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1422 | " client: sending %r...\n" % indata) |
| 1423 | s.write(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1424 | outdata = s.read() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1425 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1426 | sys.stdout.write(" client: read %r\n" % outdata) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1427 | if outdata != indata.lower(): |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1428 | self.fail( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1429 | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 1430 | % (outdata[:20], len(outdata), |
| 1431 | indata[:20].lower(), len(indata))) |
| 1432 | s.write(b"over\n") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1433 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1434 | sys.stdout.write(" client: closing connection.\n") |
| 1435 | s.close() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1436 | if support.verbose: |
| 1437 | sys.stdout.write(" client: connection closed.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1438 | finally: |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1439 | if support.verbose: |
| 1440 | sys.stdout.write(" cleanup: stopping server.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1441 | server.stop() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1442 | if support.verbose: |
| 1443 | sys.stdout.write(" cleanup: joining server thread.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1444 | server.join() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1445 | if support.verbose: |
| 1446 | sys.stdout.write(" cleanup: successfully joined.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1447 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1448 | def test_recv_send(self): |
| 1449 | """Test recv(), send() and friends.""" |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1450 | if support.verbose: |
| 1451 | sys.stdout.write("\n") |
| 1452 | |
| 1453 | server = ThreadedEchoServer(CERTFILE, |
| 1454 | certreqs=ssl.CERT_NONE, |
| 1455 | ssl_version=ssl.PROTOCOL_TLSv1, |
| 1456 | cacerts=CERTFILE, |
| 1457 | chatty=True, |
| 1458 | connectionchatty=False) |
| 1459 | flag = threading.Event() |
| 1460 | server.start(flag) |
| 1461 | # wait for it to start |
| 1462 | flag.wait() |
| 1463 | # try to connect |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1464 | s = ssl.wrap_socket(socket.socket(), |
| 1465 | server_side=False, |
| 1466 | certfile=CERTFILE, |
| 1467 | ca_certs=CERTFILE, |
| 1468 | cert_reqs=ssl.CERT_NONE, |
| 1469 | ssl_version=ssl.PROTOCOL_TLSv1) |
| 1470 | s.connect((HOST, server.port)) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1471 | try: |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1472 | # helper methods for standardising recv* method signatures |
| 1473 | def _recv_into(): |
| 1474 | b = bytearray(b"\0"*100) |
| 1475 | count = s.recv_into(b) |
| 1476 | return b[:count] |
| 1477 | |
| 1478 | def _recvfrom_into(): |
| 1479 | b = bytearray(b"\0"*100) |
| 1480 | count, addr = s.recvfrom_into(b) |
| 1481 | return b[:count] |
| 1482 | |
| 1483 | # (name, method, whether to expect success, *args) |
| 1484 | send_methods = [ |
| 1485 | ('send', s.send, True, []), |
| 1486 | ('sendto', s.sendto, False, ["some.address"]), |
| 1487 | ('sendall', s.sendall, True, []), |
| 1488 | ] |
| 1489 | recv_methods = [ |
| 1490 | ('recv', s.recv, True, []), |
| 1491 | ('recvfrom', s.recvfrom, False, ["some.address"]), |
| 1492 | ('recv_into', _recv_into, True, []), |
| 1493 | ('recvfrom_into', _recvfrom_into, False, []), |
| 1494 | ] |
| 1495 | data_prefix = "PREFIX_" |
| 1496 | |
| 1497 | for meth_name, send_meth, expect_success, args in send_methods: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1498 | indata = (data_prefix + meth_name).encode('ascii') |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1499 | try: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1500 | send_meth(indata, *args) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1501 | outdata = s.read() |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1502 | if outdata != indata.lower(): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1503 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1504 | "While sending with <<{name:s}>> bad data " |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1505 | "<<{outdata:r}>> ({nout:d}) received; " |
| 1506 | "expected <<{indata:r}>> ({nin:d})\n".format( |
| 1507 | name=meth_name, outdata=outdata[:20], |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1508 | nout=len(outdata), |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1509 | indata=indata[:20], nin=len(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1510 | ) |
| 1511 | ) |
| 1512 | except ValueError as e: |
| 1513 | if expect_success: |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1514 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1515 | "Failed to send with method <<{name:s}>>; " |
| 1516 | "expected to succeed.\n".format(name=meth_name) |
| 1517 | ) |
| 1518 | if not str(e).startswith(meth_name): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1519 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1520 | "Method <<{name:s}>> failed with unexpected " |
| 1521 | "exception message: {exp:s}\n".format( |
| 1522 | name=meth_name, exp=e |
| 1523 | ) |
| 1524 | ) |
| 1525 | |
| 1526 | for meth_name, recv_meth, expect_success, args in recv_methods: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1527 | indata = (data_prefix + meth_name).encode('ascii') |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1528 | try: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1529 | s.send(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1530 | outdata = recv_meth(*args) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1531 | if outdata != indata.lower(): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1532 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1533 | "While receiving with <<{name:s}>> bad data " |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1534 | "<<{outdata:r}>> ({nout:d}) received; " |
| 1535 | "expected <<{indata:r}>> ({nin:d})\n".format( |
| 1536 | name=meth_name, outdata=outdata[:20], |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1537 | nout=len(outdata), |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1538 | indata=indata[:20], nin=len(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1539 | ) |
| 1540 | ) |
| 1541 | except ValueError as e: |
| 1542 | if expect_success: |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1543 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1544 | "Failed to receive with method <<{name:s}>>; " |
| 1545 | "expected to succeed.\n".format(name=meth_name) |
| 1546 | ) |
| 1547 | if not str(e).startswith(meth_name): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1548 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1549 | "Method <<{name:s}>> failed with unexpected " |
| 1550 | "exception message: {exp:s}\n".format( |
| 1551 | name=meth_name, exp=e |
| 1552 | ) |
| 1553 | ) |
| 1554 | # consume data |
| 1555 | s.read() |
| 1556 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1557 | s.write(b"over\n") |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1558 | s.close() |
| 1559 | finally: |
| 1560 | server.stop() |
| 1561 | server.join() |
| 1562 | |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1563 | def test_handshake_timeout(self): |
| 1564 | # Issue #5103: SSL handshake must respect the socket timeout |
| 1565 | server = socket.socket(socket.AF_INET) |
| 1566 | host = "127.0.0.1" |
| 1567 | port = support.bind_port(server) |
| 1568 | started = threading.Event() |
| 1569 | finish = False |
| 1570 | |
| 1571 | def serve(): |
| 1572 | server.listen(5) |
| 1573 | started.set() |
| 1574 | conns = [] |
| 1575 | while not finish: |
| 1576 | r, w, e = select.select([server], [], [], 0.1) |
| 1577 | if server in r: |
| 1578 | # Let the socket hang around rather than having |
| 1579 | # it closed by garbage collection. |
| 1580 | conns.append(server.accept()[0]) |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1581 | for sock in conns: |
| 1582 | sock.close() |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1583 | |
| 1584 | t = threading.Thread(target=serve) |
| 1585 | t.start() |
| 1586 | started.wait() |
| 1587 | |
| 1588 | try: |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 1589 | try: |
| 1590 | c = socket.socket(socket.AF_INET) |
| 1591 | c.settimeout(0.2) |
| 1592 | c.connect((host, port)) |
| 1593 | # Will attempt handshake and time out |
Antoine Pitrou | c4df784 | 2010-12-03 19:59:41 +0000 | [diff] [blame] | 1594 | self.assertRaisesRegex(socket.timeout, "timed out", |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1595 | ssl.wrap_socket, c) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 1596 | finally: |
| 1597 | c.close() |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1598 | try: |
| 1599 | c = socket.socket(socket.AF_INET) |
| 1600 | c = ssl.wrap_socket(c) |
| 1601 | c.settimeout(0.2) |
| 1602 | # Will attempt handshake and time out |
Antoine Pitrou | c4df784 | 2010-12-03 19:59:41 +0000 | [diff] [blame] | 1603 | self.assertRaisesRegex(socket.timeout, "timed out", |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1604 | c.connect, (host, port)) |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1605 | finally: |
| 1606 | c.close() |
| 1607 | finally: |
| 1608 | finish = True |
| 1609 | t.join() |
| 1610 | server.close() |
| 1611 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1612 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1613 | def test_main(verbose=False): |
Antoine Pitrou | 15cee62 | 2010-08-04 16:45:21 +0000 | [diff] [blame] | 1614 | if support.verbose: |
| 1615 | plats = { |
| 1616 | 'Linux': platform.linux_distribution, |
| 1617 | 'Mac': platform.mac_ver, |
| 1618 | 'Windows': platform.win32_ver, |
| 1619 | } |
| 1620 | for name, func in plats.items(): |
| 1621 | plat = func() |
| 1622 | if plat and plat[0]: |
| 1623 | plat = '%s %r' % (name, plat) |
| 1624 | break |
| 1625 | else: |
| 1626 | plat = repr(platform.platform()) |
| 1627 | print("test_ssl: testing with %r %r" % |
| 1628 | (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO)) |
| 1629 | print(" under %s" % plat) |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 1630 | print(" HAS_SNI = %r" % ssl.HAS_SNI) |
Antoine Pitrou | 15cee62 | 2010-08-04 16:45:21 +0000 | [diff] [blame] | 1631 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1632 | for filename in [ |
| 1633 | CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, |
| 1634 | ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, |
| 1635 | BADCERT, BADKEY, EMPTYCERT]: |
| 1636 | if not os.path.exists(filename): |
| 1637 | raise support.TestFailed("Can't read certificate file %r" % filename) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1638 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1639 | tests = [ContextTests, BasicSocketTests] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1640 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1641 | if support.is_resource_enabled('network'): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1642 | tests.append(NetworkedTests) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1643 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1644 | if _have_threads: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1645 | thread_info = support.threading_setup() |
| 1646 | if thread_info and support.is_resource_enabled('network'): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1647 | tests.append(ThreadedTests) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1648 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1649 | try: |
| 1650 | support.run_unittest(*tests) |
| 1651 | finally: |
| 1652 | if _have_threads: |
| 1653 | support.threading_cleanup(*thread_info) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1654 | |
| 1655 | if __name__ == "__main__": |
| 1656 | test_main() |