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 | 3de4919 | 2011-05-09 00:42:58 +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 | 3de4919 | 2011-05-09 00:42:58 +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 | 3de4919 | 2011-05-09 00:42:58 +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 | 3de4919 | 2011-05-09 00:42:58 +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 | 3de4919 | 2011-05-09 00:42:58 +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 | e93bf7a | 2011-02-26 23:24:06 +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 | 8a14a0c | 2011-02-27 15:44:12 +0000 | [diff] [blame] | 501 | # EWOULDBLOCK under Windows, EINPROGRESS elsewhere |
| 502 | self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +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 | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 522 | def test_connect_with_context(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 523 | with support.transient_internet("svn.python.org"): |
| 524 | # Same as test_connect, but with a separately created context |
| 525 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 526 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 527 | s.connect(("svn.python.org", 443)) |
| 528 | try: |
| 529 | self.assertEqual({}, s.getpeercert()) |
| 530 | finally: |
| 531 | s.close() |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 532 | # Same with a server hostname |
| 533 | s = ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 534 | server_hostname="svn.python.org") |
| 535 | if ssl.HAS_SNI: |
| 536 | s.connect(("svn.python.org", 443)) |
| 537 | s.close() |
| 538 | else: |
| 539 | self.assertRaises(ValueError, s.connect, ("svn.python.org", 443)) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 540 | # This should fail because we have no verification certs |
| 541 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 542 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 543 | self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 544 | s.connect, ("svn.python.org", 443)) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 545 | s.close() |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 546 | # This should succeed because we specify the root cert |
| 547 | ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) |
| 548 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 549 | s.connect(("svn.python.org", 443)) |
| 550 | try: |
| 551 | cert = s.getpeercert() |
| 552 | self.assertTrue(cert) |
| 553 | finally: |
| 554 | s.close() |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 555 | |
| 556 | def test_connect_capath(self): |
| 557 | # Verify server certificates using the `capath` argument |
Antoine Pitrou | 467f28d | 2010-05-16 19:22:44 +0000 | [diff] [blame] | 558 | # NOTE: the subject hashing algorithm has been changed between |
| 559 | # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must |
| 560 | # contain both versions of each certificate (same content, different |
Antoine Pitrou | d7e4c1c | 2010-05-17 14:13:10 +0000 | [diff] [blame] | 561 | # filename) for this test to be portable across OpenSSL releases. |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 562 | with support.transient_internet("svn.python.org"): |
| 563 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 564 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 565 | ctx.load_verify_locations(capath=CAPATH) |
| 566 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 567 | s.connect(("svn.python.org", 443)) |
| 568 | try: |
| 569 | cert = s.getpeercert() |
| 570 | self.assertTrue(cert) |
| 571 | finally: |
| 572 | s.close() |
| 573 | # Same with a bytes `capath` argument |
| 574 | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 575 | ctx.verify_mode = ssl.CERT_REQUIRED |
| 576 | ctx.load_verify_locations(capath=BYTES_CAPATH) |
| 577 | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
| 578 | s.connect(("svn.python.org", 443)) |
| 579 | try: |
| 580 | cert = s.getpeercert() |
| 581 | self.assertTrue(cert) |
| 582 | finally: |
| 583 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 584 | |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 585 | @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") |
| 586 | def test_makefile_close(self): |
| 587 | # Issue #5238: creating a file-like object with makefile() shouldn't |
| 588 | # delay closing the underlying "real socket" (here tested with its |
| 589 | # file descriptor, hence skipping the test under Windows). |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 590 | with support.transient_internet("svn.python.org"): |
| 591 | ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) |
| 592 | ss.connect(("svn.python.org", 443)) |
| 593 | fd = ss.fileno() |
| 594 | f = ss.makefile() |
| 595 | f.close() |
| 596 | # The fd is still open |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 597 | os.read(fd, 0) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 598 | # Closing the SSL socket should close the fd too |
| 599 | ss.close() |
| 600 | gc.collect() |
| 601 | with self.assertRaises(OSError) as e: |
| 602 | os.read(fd, 0) |
| 603 | self.assertEqual(e.exception.errno, errno.EBADF) |
Antoine Pitrou | e322024 | 2010-04-24 11:13:53 +0000 | [diff] [blame] | 604 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 605 | def test_non_blocking_handshake(self): |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 606 | with support.transient_internet("svn.python.org"): |
| 607 | s = socket.socket(socket.AF_INET) |
| 608 | s.connect(("svn.python.org", 443)) |
| 609 | s.setblocking(False) |
| 610 | s = ssl.wrap_socket(s, |
| 611 | cert_reqs=ssl.CERT_NONE, |
| 612 | do_handshake_on_connect=False) |
| 613 | count = 0 |
| 614 | while True: |
| 615 | try: |
| 616 | count += 1 |
| 617 | s.do_handshake() |
| 618 | break |
| 619 | except ssl.SSLError as err: |
| 620 | if err.args[0] == ssl.SSL_ERROR_WANT_READ: |
| 621 | select.select([s], [], []) |
| 622 | elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: |
| 623 | select.select([], [s], []) |
| 624 | else: |
| 625 | raise |
| 626 | s.close() |
| 627 | if support.verbose: |
| 628 | 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] | 629 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 630 | def test_get_server_certificate(self): |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 631 | def _test_get_server_certificate(host, port, cert=None): |
| 632 | with support.transient_internet(host): |
| 633 | pem = ssl.get_server_certificate((host, port)) |
| 634 | if not pem: |
| 635 | self.fail("No server certificate on %s:%s!" % (host, port)) |
Antoine Pitrou | 5aefa66 | 2011-04-28 19:24:46 +0200 | [diff] [blame] | 636 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 637 | try: |
| 638 | pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE) |
| 639 | except ssl.SSLError as x: |
| 640 | #should fail |
| 641 | if support.verbose: |
| 642 | sys.stdout.write("%s\n" % x) |
| 643 | else: |
Antoine Pitrou | 5aefa66 | 2011-04-28 19:24:46 +0200 | [diff] [blame] | 644 | self.fail("Got server certificate %s for %s:%s!" % (pem, host, port)) |
| 645 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 646 | pem = ssl.get_server_certificate((host, port), ca_certs=cert) |
| 647 | if not pem: |
Antoine Pitrou | 5aefa66 | 2011-04-28 19:24:46 +0200 | [diff] [blame] | 648 | self.fail("No server certificate on %s:%s!" % (host, port)) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 649 | if support.verbose: |
Antoine Pitrou | 5aefa66 | 2011-04-28 19:24:46 +0200 | [diff] [blame] | 650 | sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem)) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 651 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 652 | _test_get_server_certificate('svn.python.org', 443, SVN_PYTHON_ORG_ROOT_CERT) |
| 653 | if support.IPV6_ENABLED: |
| 654 | _test_get_server_certificate('ipv6.google.com', 443) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 655 | |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 656 | def test_ciphers(self): |
| 657 | remote = ("svn.python.org", 443) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 658 | with support.transient_internet(remote[0]): |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 659 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 660 | cert_reqs=ssl.CERT_NONE, ciphers="ALL") |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 661 | s.connect(remote) |
Antoine Pitrou | 350c722 | 2010-09-09 13:31:46 +0000 | [diff] [blame] | 662 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 663 | cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") |
| 664 | s.connect(remote) |
| 665 | # Error checking can happen at instantiation or when connecting |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 666 | with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 667 | with socket.socket(socket.AF_INET) as sock: |
| 668 | s = ssl.wrap_socket(sock, |
| 669 | cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") |
| 670 | s.connect(remote) |
Antoine Pitrou | f4c7bad | 2010-08-15 23:02:22 +0000 | [diff] [blame] | 671 | |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 672 | def test_algorithms(self): |
| 673 | # Issue #8484: all algorithms should be available when verifying a |
| 674 | # certificate. |
Antoine Pitrou | 29619b2 | 2010-04-22 18:43:31 +0000 | [diff] [blame] | 675 | # SHA256 was added in OpenSSL 0.9.8 |
| 676 | if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15): |
| 677 | self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION) |
Victor Stinner | f332abb | 2011-01-08 03:16:05 +0000 | [diff] [blame] | 678 | # https://sha2.hboeck.de/ was used until 2011-01-08 (no route to host) |
| 679 | remote = ("sha256.tbs-internet.com", 443) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 680 | sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem") |
Antoine Pitrou | 160fd93 | 2011-01-08 10:23:29 +0000 | [diff] [blame] | 681 | with support.transient_internet("sha256.tbs-internet.com"): |
Antoine Pitrou | a88c83c | 2010-09-07 20:42:19 +0000 | [diff] [blame] | 682 | s = ssl.wrap_socket(socket.socket(socket.AF_INET), |
| 683 | cert_reqs=ssl.CERT_REQUIRED, |
| 684 | ca_certs=sha256_cert,) |
Antoine Pitrou | fec12ff | 2010-04-21 19:46:23 +0000 | [diff] [blame] | 685 | try: |
| 686 | s.connect(remote) |
| 687 | if support.verbose: |
| 688 | sys.stdout.write("\nCipher with %r is %r\n" % |
| 689 | (remote, s.cipher())) |
| 690 | sys.stdout.write("Certificate is:\n%s\n" % |
| 691 | pprint.pformat(s.getpeercert())) |
| 692 | finally: |
| 693 | s.close() |
| 694 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 695 | |
| 696 | try: |
| 697 | import threading |
| 698 | except ImportError: |
| 699 | _have_threads = False |
| 700 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 701 | _have_threads = True |
| 702 | |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 703 | from test.ssl_servers import make_https_server |
| 704 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 705 | class ThreadedEchoServer(threading.Thread): |
| 706 | |
| 707 | class ConnectionHandler(threading.Thread): |
| 708 | |
| 709 | """A mildly complicated class, because we want it to work both |
| 710 | with and without the SSL wrapper around the socket connection, so |
| 711 | that we can test the STARTTLS functionality.""" |
| 712 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 713 | def __init__(self, server, connsock, addr): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 714 | self.server = server |
| 715 | self.running = False |
| 716 | self.sock = connsock |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 717 | self.addr = addr |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 718 | self.sock.setblocking(1) |
| 719 | self.sslconn = None |
| 720 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 721 | self.daemon = True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 722 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 723 | def wrap_conn(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 724 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 725 | self.sslconn = self.server.context.wrap_socket( |
| 726 | self.sock, server_side=True) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 727 | except ssl.SSLError: |
| 728 | # XXX Various errors can have happened here, for example |
| 729 | # a mismatching protocol version, an invalid certificate, |
| 730 | # or a low-level bug. This should be made more discriminating. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 731 | if self.server.chatty: |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 732 | handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 733 | self.running = False |
| 734 | self.server.stop() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 735 | self.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 736 | return False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 737 | else: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 738 | if self.server.context.verify_mode == ssl.CERT_REQUIRED: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 739 | cert = self.sslconn.getpeercert() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 740 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 741 | sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") |
| 742 | cert_binary = self.sslconn.getpeercert(True) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 743 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 744 | sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") |
| 745 | cipher = self.sslconn.cipher() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 746 | if support.verbose and self.server.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 747 | sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") |
| 748 | return True |
| 749 | |
| 750 | def read(self): |
| 751 | if self.sslconn: |
| 752 | return self.sslconn.read() |
| 753 | else: |
| 754 | return self.sock.recv(1024) |
| 755 | |
| 756 | def write(self, bytes): |
| 757 | if self.sslconn: |
| 758 | return self.sslconn.write(bytes) |
| 759 | else: |
| 760 | return self.sock.send(bytes) |
| 761 | |
| 762 | def close(self): |
| 763 | if self.sslconn: |
| 764 | self.sslconn.close() |
| 765 | else: |
| 766 | self.sock.close() |
| 767 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 768 | def run(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 769 | self.running = True |
| 770 | if not self.server.starttls_server: |
| 771 | if not self.wrap_conn(): |
| 772 | return |
| 773 | while self.running: |
| 774 | try: |
| 775 | msg = self.read() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 776 | stripped = msg.strip() |
| 777 | if not stripped: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 778 | # eof, so quit this handler |
| 779 | self.running = False |
| 780 | self.close() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 781 | elif stripped == b'over': |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 782 | if support.verbose and self.server.connectionchatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 783 | sys.stdout.write(" server: client closed connection\n") |
| 784 | self.close() |
| 785 | return |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 786 | elif (self.server.starttls_server and |
Antoine Pitrou | 764b878 | 2010-04-28 22:57:15 +0000 | [diff] [blame] | 787 | stripped == b'STARTTLS'): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 788 | if support.verbose and self.server.connectionchatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 789 | sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 790 | self.write(b"OK\n") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 791 | if not self.wrap_conn(): |
| 792 | return |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 793 | elif (self.server.starttls_server and self.sslconn |
Antoine Pitrou | 764b878 | 2010-04-28 22:57:15 +0000 | [diff] [blame] | 794 | and stripped == b'ENDTLS'): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 795 | if support.verbose and self.server.connectionchatty: |
| 796 | sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 797 | self.write(b"OK\n") |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 798 | self.sock = self.sslconn.unwrap() |
| 799 | self.sslconn = None |
| 800 | if support.verbose and self.server.connectionchatty: |
| 801 | sys.stdout.write(" server: connection is now unencrypted...\n") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 802 | else: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 803 | if (support.verbose and |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 804 | self.server.connectionchatty): |
| 805 | ctype = (self.sslconn and "encrypted") or "unencrypted" |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 806 | sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" |
| 807 | % (msg, ctype, msg.lower(), ctype)) |
| 808 | self.write(msg.lower()) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 809 | except socket.error: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 810 | if self.server.chatty: |
| 811 | handle_error("Test server failure:\n") |
| 812 | self.close() |
| 813 | self.running = False |
| 814 | # normally, we'd just stop here, but for the test |
| 815 | # harness, we want to stop the server |
| 816 | self.server.stop() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 817 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 818 | def __init__(self, certificate=None, ssl_version=None, |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 819 | certreqs=None, cacerts=None, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 820 | chatty=True, connectionchatty=False, starttls_server=False, |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 821 | ciphers=None, context=None): |
| 822 | if context: |
| 823 | self.context = context |
| 824 | else: |
| 825 | self.context = ssl.SSLContext(ssl_version |
| 826 | if ssl_version is not None |
| 827 | else ssl.PROTOCOL_TLSv1) |
| 828 | self.context.verify_mode = (certreqs if certreqs is not None |
| 829 | else ssl.CERT_NONE) |
| 830 | if cacerts: |
| 831 | self.context.load_verify_locations(cacerts) |
| 832 | if certificate: |
| 833 | self.context.load_cert_chain(certificate) |
| 834 | if ciphers: |
| 835 | self.context.set_ciphers(ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 836 | self.chatty = chatty |
| 837 | self.connectionchatty = connectionchatty |
| 838 | self.starttls_server = starttls_server |
| 839 | self.sock = socket.socket() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 840 | self.port = support.bind_port(self.sock) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 841 | self.flag = None |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 842 | self.active = False |
| 843 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 844 | self.daemon = True |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 845 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 846 | def start(self, flag=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 847 | self.flag = flag |
| 848 | threading.Thread.start(self) |
| 849 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 850 | def run(self): |
Antoine Pitrou | af7c602 | 2010-04-27 09:56:02 +0000 | [diff] [blame] | 851 | self.sock.settimeout(0.05) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 852 | self.sock.listen(5) |
| 853 | self.active = True |
| 854 | if self.flag: |
| 855 | # signal an event |
| 856 | self.flag.set() |
| 857 | while self.active: |
| 858 | try: |
| 859 | newconn, connaddr = self.sock.accept() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 860 | if support.verbose and self.chatty: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 861 | sys.stdout.write(' server: new connection from ' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 862 | + repr(connaddr) + '\n') |
| 863 | handler = self.ConnectionHandler(self, newconn, connaddr) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 864 | handler.start() |
| 865 | except socket.timeout: |
| 866 | pass |
| 867 | except KeyboardInterrupt: |
| 868 | self.stop() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 869 | self.sock.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 870 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 871 | def stop(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 872 | self.active = False |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 873 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 874 | class AsyncoreEchoServer(threading.Thread): |
| 875 | |
| 876 | # this one's based on asyncore.dispatcher |
| 877 | |
| 878 | class EchoServer (asyncore.dispatcher): |
| 879 | |
| 880 | class ConnectionHandler (asyncore.dispatcher_with_send): |
| 881 | |
| 882 | def __init__(self, conn, certfile): |
| 883 | self.socket = ssl.wrap_socket(conn, server_side=True, |
| 884 | certfile=certfile, |
| 885 | do_handshake_on_connect=False) |
| 886 | asyncore.dispatcher_with_send.__init__(self, self.socket) |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 887 | self._ssl_accepting = True |
| 888 | self._do_ssl_handshake() |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 889 | |
| 890 | def readable(self): |
| 891 | if isinstance(self.socket, ssl.SSLSocket): |
| 892 | while self.socket.pending() > 0: |
| 893 | self.handle_read_event() |
| 894 | return True |
| 895 | |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 896 | def _do_ssl_handshake(self): |
| 897 | try: |
| 898 | self.socket.do_handshake() |
| 899 | except ssl.SSLError as err: |
| 900 | if err.args[0] in (ssl.SSL_ERROR_WANT_READ, |
| 901 | ssl.SSL_ERROR_WANT_WRITE): |
| 902 | return |
| 903 | elif err.args[0] == ssl.SSL_ERROR_EOF: |
| 904 | return self.handle_close() |
| 905 | raise |
| 906 | except socket.error as err: |
| 907 | if err.args[0] == errno.ECONNABORTED: |
| 908 | return self.handle_close() |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 909 | else: |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 910 | self._ssl_accepting = False |
| 911 | |
| 912 | def handle_read(self): |
| 913 | if self._ssl_accepting: |
| 914 | self._do_ssl_handshake() |
| 915 | else: |
| 916 | data = self.recv(1024) |
| 917 | if support.verbose: |
| 918 | sys.stdout.write(" server: read %s from client\n" % repr(data)) |
| 919 | if not data: |
| 920 | self.close() |
| 921 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 922 | self.send(data.lower()) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 923 | |
| 924 | def handle_close(self): |
Bill Janssen | 2f5799b | 2008-06-29 00:08:12 +0000 | [diff] [blame] | 925 | self.close() |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 926 | if support.verbose: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 927 | sys.stdout.write(" server: closed connection %s\n" % self.socket) |
| 928 | |
| 929 | def handle_error(self): |
| 930 | raise |
| 931 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 932 | def __init__(self, certfile): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 933 | self.certfile = certfile |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 934 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 935 | self.port = support.bind_port(sock, '') |
| 936 | asyncore.dispatcher.__init__(self, sock) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 937 | self.listen(5) |
| 938 | |
Giampaolo Rodolà | 977c707 | 2010-10-04 21:08:36 +0000 | [diff] [blame] | 939 | def handle_accepted(self, sock_obj, addr): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 940 | if support.verbose: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 941 | sys.stdout.write(" server: new connection from %s:%s\n" %addr) |
| 942 | self.ConnectionHandler(sock_obj, self.certfile) |
| 943 | |
| 944 | def handle_error(self): |
| 945 | raise |
| 946 | |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 947 | def __init__(self, certfile): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 948 | self.flag = None |
| 949 | self.active = False |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 950 | self.server = self.EchoServer(certfile) |
| 951 | self.port = self.server.port |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 952 | threading.Thread.__init__(self) |
Benjamin Peterson | 4171da5 | 2008-08-18 21:11:09 +0000 | [diff] [blame] | 953 | self.daemon = True |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 954 | |
| 955 | def __str__(self): |
| 956 | return "<%s %s>" % (self.__class__.__name__, self.server) |
| 957 | |
| 958 | def start (self, flag=None): |
| 959 | self.flag = flag |
| 960 | threading.Thread.start(self) |
| 961 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 962 | def run(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 963 | self.active = True |
| 964 | if self.flag: |
| 965 | self.flag.set() |
| 966 | while self.active: |
| 967 | try: |
| 968 | asyncore.loop(1) |
| 969 | except: |
| 970 | pass |
| 971 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 972 | def stop(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 973 | self.active = False |
| 974 | self.server.close() |
| 975 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 976 | def bad_cert_test(certfile): |
| 977 | """ |
| 978 | Launch a server with CERT_REQUIRED, and check that trying to |
| 979 | connect to it with the given client certificate fails. |
| 980 | """ |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 981 | server = ThreadedEchoServer(CERTFILE, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 982 | certreqs=ssl.CERT_REQUIRED, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 983 | cacerts=CERTFILE, chatty=False, |
| 984 | connectionchatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 985 | flag = threading.Event() |
| 986 | server.start(flag) |
| 987 | # wait for it to start |
| 988 | flag.wait() |
| 989 | # try to connect |
| 990 | try: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 991 | try: |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 992 | with socket.socket() as sock: |
| 993 | s = ssl.wrap_socket(sock, |
| 994 | certfile=certfile, |
| 995 | ssl_version=ssl.PROTOCOL_TLSv1) |
| 996 | s.connect((HOST, server.port)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 997 | except ssl.SSLError as x: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 998 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 999 | sys.stdout.write("\nSSLError is %s\n" % x.args[1]) |
Antoine Pitrou | 05830aa | 2010-04-27 13:15:18 +0000 | [diff] [blame] | 1000 | except socket.error as x: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1001 | if support.verbose: |
Georg Brandl | b75b639 | 2010-10-24 14:20:22 +0000 | [diff] [blame] | 1002 | sys.stdout.write("\nsocket.error is %s\n" % x.args[1]) |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 1003 | except IOError as x: |
Giampaolo Rodolà | cd9dfb9 | 2010-08-29 20:56:56 +0000 | [diff] [blame] | 1004 | if x.errno != errno.ENOENT: |
| 1005 | raise |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 1006 | if support.verbose: |
Giampaolo Rodolà | cd9dfb9 | 2010-08-29 20:56:56 +0000 | [diff] [blame] | 1007 | sys.stdout.write("\IOError is %s\n" % str(x)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1008 | else: |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1009 | raise AssertionError("Use of invalid cert should have failed!") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1010 | finally: |
| 1011 | server.stop() |
| 1012 | server.join() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1013 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1014 | def server_params_test(client_context, server_context, indata=b"FOO\n", |
| 1015 | chatty=True, connectionchatty=False): |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1016 | """ |
| 1017 | Launch a server, connect a client to it and try various reads |
| 1018 | and writes. |
| 1019 | """ |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1020 | server = ThreadedEchoServer(context=server_context, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1021 | chatty=chatty, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1022 | connectionchatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1023 | flag = threading.Event() |
| 1024 | server.start(flag) |
| 1025 | # wait for it to start |
| 1026 | flag.wait() |
| 1027 | # try to connect |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1028 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1029 | s = client_context.wrap_socket(socket.socket()) |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1030 | s.connect((HOST, server.port)) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1031 | for arg in [indata, bytearray(indata), memoryview(indata)]: |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1032 | if connectionchatty: |
| 1033 | if support.verbose: |
| 1034 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1035 | " client: sending %r...\n" % indata) |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1036 | s.write(arg) |
| 1037 | outdata = s.read() |
| 1038 | if connectionchatty: |
| 1039 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1040 | sys.stdout.write(" client: read %r\n" % outdata) |
Antoine Pitrou | 7d7aede | 2009-11-25 18:55:32 +0000 | [diff] [blame] | 1041 | if outdata != indata.lower(): |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1042 | raise AssertionError( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1043 | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 1044 | % (outdata[:20], len(outdata), |
| 1045 | indata[:20].lower(), len(indata))) |
| 1046 | s.write(b"over\n") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1047 | if connectionchatty: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1048 | if support.verbose: |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1049 | sys.stdout.write(" client: closing connection.\n") |
| 1050 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1051 | finally: |
| 1052 | server.stop() |
| 1053 | server.join() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1054 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1055 | def try_protocol_combo(server_protocol, client_protocol, expect_success, |
| 1056 | certsreqs=None, server_options=0, client_options=0): |
Benjamin Peterson | 2a691a8 | 2008-03-31 01:51:45 +0000 | [diff] [blame] | 1057 | if certsreqs is None: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1058 | certsreqs = ssl.CERT_NONE |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1059 | certtype = { |
| 1060 | ssl.CERT_NONE: "CERT_NONE", |
| 1061 | ssl.CERT_OPTIONAL: "CERT_OPTIONAL", |
| 1062 | ssl.CERT_REQUIRED: "CERT_REQUIRED", |
| 1063 | }[certsreqs] |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1064 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1065 | 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] | 1066 | sys.stdout.write(formatstr % |
| 1067 | (ssl.get_protocol_name(client_protocol), |
| 1068 | ssl.get_protocol_name(server_protocol), |
| 1069 | certtype)) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1070 | client_context = ssl.SSLContext(client_protocol) |
| 1071 | client_context.options = ssl.OP_ALL | client_options |
| 1072 | server_context = ssl.SSLContext(server_protocol) |
| 1073 | server_context.options = ssl.OP_ALL | server_options |
| 1074 | for ctx in (client_context, server_context): |
| 1075 | ctx.verify_mode = certsreqs |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 1076 | # NOTE: we must enable "ALL" ciphers, otherwise an SSLv23 client |
| 1077 | # will send an SSLv3 hello (rather than SSLv2) starting from |
| 1078 | # OpenSSL 1.0.0 (see issue #8322). |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1079 | ctx.set_ciphers("ALL") |
| 1080 | ctx.load_cert_chain(CERTFILE) |
| 1081 | ctx.load_verify_locations(CERTFILE) |
| 1082 | try: |
| 1083 | server_params_test(client_context, server_context, |
| 1084 | chatty=False, connectionchatty=False) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1085 | # Protocol mismatch can result in either an SSLError, or a |
| 1086 | # "Connection reset by peer" error. |
| 1087 | except ssl.SSLError: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1088 | if expect_success: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1089 | raise |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1090 | except socket.error as e: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1091 | if expect_success or e.errno != errno.ECONNRESET: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1092 | raise |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1093 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1094 | if not expect_success: |
Antoine Pitrou | d75b2a9 | 2010-05-06 14:15:10 +0000 | [diff] [blame] | 1095 | raise AssertionError( |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1096 | "Client protocol %s succeeded with server protocol %s!" |
| 1097 | % (ssl.get_protocol_name(client_protocol), |
| 1098 | ssl.get_protocol_name(server_protocol))) |
| 1099 | |
| 1100 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1101 | class ThreadedTests(unittest.TestCase): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1102 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1103 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1104 | def test_echo(self): |
| 1105 | """Basic test of an SSL client connecting to a server""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1106 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1107 | sys.stdout.write("\n") |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1108 | for protocol in PROTOCOLS: |
| 1109 | context = ssl.SSLContext(protocol) |
| 1110 | context.load_cert_chain(CERTFILE) |
| 1111 | server_params_test(context, context, |
| 1112 | chatty=True, connectionchatty=True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1113 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1114 | def test_getpeercert(self): |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1115 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1116 | sys.stdout.write("\n") |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1117 | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 1118 | context.verify_mode = ssl.CERT_REQUIRED |
| 1119 | context.load_verify_locations(CERTFILE) |
| 1120 | context.load_cert_chain(CERTFILE) |
| 1121 | server = ThreadedEchoServer(context=context, chatty=False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1122 | flag = threading.Event() |
| 1123 | server.start(flag) |
| 1124 | # wait for it to start |
| 1125 | flag.wait() |
| 1126 | # try to connect |
| 1127 | try: |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1128 | s = context.wrap_socket(socket.socket()) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1129 | s.connect((HOST, server.port)) |
| 1130 | cert = s.getpeercert() |
| 1131 | self.assertTrue(cert, "Can't get peer certificate.") |
| 1132 | cipher = s.cipher() |
| 1133 | if support.verbose: |
| 1134 | sys.stdout.write(pprint.pformat(cert) + '\n') |
| 1135 | sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') |
| 1136 | if 'subject' not in cert: |
| 1137 | self.fail("No subject field in certificate: %s." % |
| 1138 | pprint.pformat(cert)) |
| 1139 | if ((('organizationName', 'Python Software Foundation'),) |
| 1140 | not in cert['subject']): |
| 1141 | self.fail( |
| 1142 | "Missing or invalid 'organizationName' field in certificate subject; " |
| 1143 | "should be 'Python Software Foundation'.") |
Antoine Pitrou | fb04691 | 2010-11-09 20:21:19 +0000 | [diff] [blame] | 1144 | self.assertIn('notBefore', cert) |
| 1145 | self.assertIn('notAfter', cert) |
| 1146 | before = ssl.cert_time_to_seconds(cert['notBefore']) |
| 1147 | after = ssl.cert_time_to_seconds(cert['notAfter']) |
| 1148 | self.assertLess(before, after) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1149 | s.close() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1150 | finally: |
| 1151 | server.stop() |
| 1152 | server.join() |
| 1153 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1154 | def test_empty_cert(self): |
| 1155 | """Connecting with an empty cert file""" |
| 1156 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1157 | "nullcert.pem")) |
| 1158 | def test_malformed_cert(self): |
| 1159 | """Connecting with a badly formatted certificate (syntax error)""" |
| 1160 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1161 | "badcert.pem")) |
| 1162 | def test_nonexisting_cert(self): |
| 1163 | """Connecting with a non-existing cert file""" |
| 1164 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1165 | "wrongcert.pem")) |
| 1166 | def test_malformed_key(self): |
| 1167 | """Connecting with a badly formatted key (syntax error)""" |
| 1168 | bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, |
| 1169 | "badkey.pem")) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1170 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1171 | def test_rude_shutdown(self): |
| 1172 | """A brutal shutdown of an SSL server should raise an IOError |
| 1173 | in the client when attempting handshake. |
| 1174 | """ |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1175 | listener_ready = threading.Event() |
| 1176 | listener_gone = threading.Event() |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1177 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1178 | s = socket.socket() |
| 1179 | port = support.bind_port(s, HOST) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1180 | |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1181 | # `listener` runs in a thread. It sits in an accept() until |
| 1182 | # the main thread connects. Then it rudely closes the socket, |
| 1183 | # and sets Event `listener_gone` to let the main thread know |
| 1184 | # the socket is gone. |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1185 | def listener(): |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1186 | s.listen(5) |
| 1187 | listener_ready.set() |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1188 | newsock, addr = s.accept() |
| 1189 | newsock.close() |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1190 | s.close() |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1191 | listener_gone.set() |
| 1192 | |
| 1193 | def connector(): |
| 1194 | listener_ready.wait() |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1195 | with socket.socket() as c: |
| 1196 | c.connect((HOST, port)) |
| 1197 | listener_gone.wait() |
| 1198 | try: |
| 1199 | ssl_sock = ssl.wrap_socket(c) |
| 1200 | except IOError: |
| 1201 | pass |
| 1202 | else: |
| 1203 | self.fail('connecting to closed SSL socket should have failed') |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1204 | |
| 1205 | t = threading.Thread(target=listener) |
| 1206 | t.start() |
Antoine Pitrou | 773b5db | 2010-04-27 08:53:36 +0000 | [diff] [blame] | 1207 | try: |
| 1208 | connector() |
| 1209 | finally: |
| 1210 | t.join() |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1211 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1212 | @skip_if_broken_ubuntu_ssl |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame^] | 1213 | @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'), |
| 1214 | "OpenSSL is compiled without SSLv2 support") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1215 | def test_protocol_sslv2(self): |
| 1216 | """Connecting to an SSLv2 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1217 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1218 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1219 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) |
| 1220 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) |
| 1221 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) |
| 1222 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) |
| 1223 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) |
| 1224 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1225 | # SSLv23 client with specific SSL options |
| 1226 | if no_sslv2_implies_sslv3_hello(): |
| 1227 | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
| 1228 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, |
| 1229 | client_options=ssl.OP_NO_SSLv2) |
| 1230 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, |
| 1231 | client_options=ssl.OP_NO_SSLv3) |
| 1232 | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True, |
| 1233 | client_options=ssl.OP_NO_TLSv1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1234 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1235 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1236 | def test_protocol_sslv23(self): |
| 1237 | """Connecting to an SSLv23 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1238 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1239 | sys.stdout.write("\n") |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame^] | 1240 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1241 | try: |
| 1242 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) |
| 1243 | except (ssl.SSLError, socket.error) as x: |
| 1244 | # this fails on some older versions of OpenSSL (0.9.7l, for instance) |
| 1245 | if support.verbose: |
| 1246 | sys.stdout.write( |
| 1247 | " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" |
| 1248 | % str(x)) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1249 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) |
| 1250 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) |
| 1251 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1252 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1253 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) |
| 1254 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) |
| 1255 | 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] | 1256 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1257 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) |
| 1258 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) |
| 1259 | 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] | 1260 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1261 | # Server with specific SSL options |
| 1262 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, |
| 1263 | server_options=ssl.OP_NO_SSLv3) |
| 1264 | # Will choose TLSv1 |
| 1265 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, |
| 1266 | server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
| 1267 | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, |
| 1268 | server_options=ssl.OP_NO_TLSv1) |
| 1269 | |
| 1270 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1271 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1272 | def test_protocol_sslv3(self): |
| 1273 | """Connecting to an SSLv3 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1274 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1275 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1276 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) |
| 1277 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) |
| 1278 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame^] | 1279 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1280 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1281 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) |
| 1282 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1283 | if no_sslv2_implies_sslv3_hello(): |
| 1284 | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
| 1285 | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, True, |
| 1286 | client_options=ssl.OP_NO_SSLv2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1287 | |
Antoine Pitrou | 23df483 | 2010-08-04 17:14:06 +0000 | [diff] [blame] | 1288 | @skip_if_broken_ubuntu_ssl |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1289 | def test_protocol_tlsv1(self): |
| 1290 | """Connecting to a TLSv1 server with various client options""" |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1291 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1292 | sys.stdout.write("\n") |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1293 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) |
| 1294 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) |
| 1295 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame^] | 1296 | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
| 1297 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1298 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) |
| 1299 | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1300 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1301 | def test_starttls(self): |
| 1302 | """Switching from clear text to encrypted and back again.""" |
| 1303 | 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] | 1304 | |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1305 | server = ThreadedEchoServer(CERTFILE, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1306 | ssl_version=ssl.PROTOCOL_TLSv1, |
| 1307 | starttls_server=True, |
| 1308 | chatty=True, |
| 1309 | connectionchatty=True) |
| 1310 | flag = threading.Event() |
| 1311 | server.start(flag) |
| 1312 | # wait for it to start |
| 1313 | flag.wait() |
| 1314 | # try to connect |
| 1315 | wrapped = False |
| 1316 | try: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1317 | s = socket.socket() |
| 1318 | s.setblocking(1) |
| 1319 | s.connect((HOST, server.port)) |
| 1320 | if support.verbose: |
| 1321 | sys.stdout.write("\n") |
| 1322 | for indata in msgs: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1323 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1324 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1325 | " client: sending %r...\n" % indata) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1326 | if wrapped: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1327 | conn.write(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1328 | outdata = conn.read() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1329 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1330 | s.send(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1331 | outdata = s.recv(1024) |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1332 | msg = outdata.strip().lower() |
| 1333 | if indata == b"STARTTLS" and msg.startswith(b"ok"): |
| 1334 | # STARTTLS ok, switch to secure mode |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1335 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1336 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1337 | " client: read %r from server, starting TLS...\n" |
| 1338 | % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1339 | conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) |
| 1340 | wrapped = True |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1341 | elif indata == b"ENDTLS" and msg.startswith(b"ok"): |
| 1342 | # ENDTLS ok, switch back to clear text |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1343 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1344 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1345 | " client: read %r from server, ending TLS...\n" |
| 1346 | % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1347 | s = conn.unwrap() |
| 1348 | wrapped = False |
| 1349 | else: |
| 1350 | if support.verbose: |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1351 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1352 | " client: read %r from server\n" % msg) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1353 | if support.verbose: |
| 1354 | sys.stdout.write(" client: closing connection.\n") |
| 1355 | if wrapped: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1356 | conn.write(b"over\n") |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1357 | else: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1358 | s.send(b"over\n") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1359 | if wrapped: |
| 1360 | conn.close() |
| 1361 | else: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1362 | s.close() |
| 1363 | finally: |
| 1364 | server.stop() |
| 1365 | server.join() |
| 1366 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1367 | def test_socketserver(self): |
| 1368 | """Using a SocketServer to create and manage SSL connections.""" |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1369 | server = make_https_server(self, CERTFILE) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1370 | # try to connect |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1371 | if support.verbose: |
| 1372 | sys.stdout.write('\n') |
| 1373 | with open(CERTFILE, 'rb') as f: |
| 1374 | d1 = f.read() |
| 1375 | d2 = '' |
| 1376 | # now fetch the same data from the HTTPS server |
| 1377 | url = 'https://%s:%d/%s' % ( |
| 1378 | HOST, server.port, os.path.split(CERTFILE)[1]) |
| 1379 | f = urllib.request.urlopen(url) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1380 | try: |
Barry Warsaw | 820c120 | 2008-06-12 04:06:45 +0000 | [diff] [blame] | 1381 | dlen = f.info().get("content-length") |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1382 | if dlen and (int(dlen) > 0): |
| 1383 | d2 = f.read(int(dlen)) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1384 | if support.verbose: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1385 | sys.stdout.write( |
| 1386 | " client: read %d bytes from remote server '%s'\n" |
| 1387 | % (len(d2), server)) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1388 | finally: |
Antoine Pitrou | 803e6d6 | 2010-10-13 10:36:15 +0000 | [diff] [blame] | 1389 | f.close() |
| 1390 | self.assertEqual(d1, d2) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1391 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1392 | def test_asyncore_server(self): |
| 1393 | """Check the example asyncore integration.""" |
| 1394 | indata = "TEST MESSAGE of mixed case\n" |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1395 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1396 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1397 | sys.stdout.write("\n") |
| 1398 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1399 | indata = b"FOO\n" |
Trent Nelson | 7852000 | 2008-04-10 20:54:35 +0000 | [diff] [blame] | 1400 | server = AsyncoreEchoServer(CERTFILE) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1401 | flag = threading.Event() |
| 1402 | server.start(flag) |
| 1403 | # wait for it to start |
| 1404 | flag.wait() |
| 1405 | # try to connect |
| 1406 | try: |
| 1407 | s = ssl.wrap_socket(socket.socket()) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1408 | s.connect(('127.0.0.1', server.port)) |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1409 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1410 | sys.stdout.write( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1411 | " client: sending %r...\n" % indata) |
| 1412 | s.write(indata) |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1413 | outdata = s.read() |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1414 | if support.verbose: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1415 | sys.stdout.write(" client: read %r\n" % outdata) |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1416 | if outdata != indata.lower(): |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1417 | self.fail( |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1418 | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 1419 | % (outdata[:20], len(outdata), |
| 1420 | indata[:20].lower(), len(indata))) |
| 1421 | s.write(b"over\n") |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1422 | if support.verbose: |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1423 | sys.stdout.write(" client: closing connection.\n") |
| 1424 | s.close() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1425 | if support.verbose: |
| 1426 | sys.stdout.write(" client: connection closed.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1427 | finally: |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1428 | if support.verbose: |
| 1429 | sys.stdout.write(" cleanup: stopping server.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1430 | server.stop() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1431 | if support.verbose: |
| 1432 | sys.stdout.write(" cleanup: joining server thread.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1433 | server.join() |
Antoine Pitrou | ed98636 | 2010-08-15 23:28:10 +0000 | [diff] [blame] | 1434 | if support.verbose: |
| 1435 | sys.stdout.write(" cleanup: successfully joined.\n") |
Trent Nelson | 6b240cd | 2008-04-10 20:12:06 +0000 | [diff] [blame] | 1436 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1437 | def test_recv_send(self): |
| 1438 | """Test recv(), send() and friends.""" |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1439 | if support.verbose: |
| 1440 | sys.stdout.write("\n") |
| 1441 | |
| 1442 | server = ThreadedEchoServer(CERTFILE, |
| 1443 | certreqs=ssl.CERT_NONE, |
| 1444 | ssl_version=ssl.PROTOCOL_TLSv1, |
| 1445 | cacerts=CERTFILE, |
| 1446 | chatty=True, |
| 1447 | connectionchatty=False) |
| 1448 | flag = threading.Event() |
| 1449 | server.start(flag) |
| 1450 | # wait for it to start |
| 1451 | flag.wait() |
| 1452 | # try to connect |
Antoine Pitrou | 18c913e | 2010-04-27 10:59:39 +0000 | [diff] [blame] | 1453 | s = ssl.wrap_socket(socket.socket(), |
| 1454 | server_side=False, |
| 1455 | certfile=CERTFILE, |
| 1456 | ca_certs=CERTFILE, |
| 1457 | cert_reqs=ssl.CERT_NONE, |
| 1458 | ssl_version=ssl.PROTOCOL_TLSv1) |
| 1459 | s.connect((HOST, server.port)) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1460 | try: |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1461 | # helper methods for standardising recv* method signatures |
| 1462 | def _recv_into(): |
| 1463 | b = bytearray(b"\0"*100) |
| 1464 | count = s.recv_into(b) |
| 1465 | return b[:count] |
| 1466 | |
| 1467 | def _recvfrom_into(): |
| 1468 | b = bytearray(b"\0"*100) |
| 1469 | count, addr = s.recvfrom_into(b) |
| 1470 | return b[:count] |
| 1471 | |
| 1472 | # (name, method, whether to expect success, *args) |
| 1473 | send_methods = [ |
| 1474 | ('send', s.send, True, []), |
| 1475 | ('sendto', s.sendto, False, ["some.address"]), |
| 1476 | ('sendall', s.sendall, True, []), |
| 1477 | ] |
| 1478 | recv_methods = [ |
| 1479 | ('recv', s.recv, True, []), |
| 1480 | ('recvfrom', s.recvfrom, False, ["some.address"]), |
| 1481 | ('recv_into', _recv_into, True, []), |
| 1482 | ('recvfrom_into', _recvfrom_into, False, []), |
| 1483 | ] |
| 1484 | data_prefix = "PREFIX_" |
| 1485 | |
| 1486 | for meth_name, send_meth, expect_success, args in send_methods: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1487 | indata = (data_prefix + meth_name).encode('ascii') |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1488 | try: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1489 | send_meth(indata, *args) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1490 | outdata = s.read() |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1491 | if outdata != indata.lower(): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1492 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1493 | "While sending with <<{name:s}>> bad data " |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1494 | "<<{outdata:r}>> ({nout:d}) received; " |
| 1495 | "expected <<{indata:r}>> ({nin:d})\n".format( |
| 1496 | name=meth_name, outdata=outdata[:20], |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1497 | nout=len(outdata), |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1498 | indata=indata[:20], nin=len(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1499 | ) |
| 1500 | ) |
| 1501 | except ValueError as e: |
| 1502 | if expect_success: |
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 | "Failed to send with method <<{name:s}>>; " |
| 1505 | "expected to succeed.\n".format(name=meth_name) |
| 1506 | ) |
| 1507 | if not str(e).startswith(meth_name): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1508 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1509 | "Method <<{name:s}>> failed with unexpected " |
| 1510 | "exception message: {exp:s}\n".format( |
| 1511 | name=meth_name, exp=e |
| 1512 | ) |
| 1513 | ) |
| 1514 | |
| 1515 | for meth_name, recv_meth, expect_success, args in recv_methods: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1516 | indata = (data_prefix + meth_name).encode('ascii') |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1517 | try: |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1518 | s.send(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1519 | outdata = recv_meth(*args) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1520 | if outdata != indata.lower(): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1521 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1522 | "While receiving with <<{name:s}>> bad data " |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1523 | "<<{outdata:r}>> ({nout:d}) received; " |
| 1524 | "expected <<{indata:r}>> ({nin:d})\n".format( |
| 1525 | name=meth_name, outdata=outdata[:20], |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1526 | nout=len(outdata), |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1527 | indata=indata[:20], nin=len(indata) |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1528 | ) |
| 1529 | ) |
| 1530 | except ValueError as e: |
| 1531 | if expect_success: |
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 | "Failed to receive with method <<{name:s}>>; " |
| 1534 | "expected to succeed.\n".format(name=meth_name) |
| 1535 | ) |
| 1536 | if not str(e).startswith(meth_name): |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 1537 | self.fail( |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1538 | "Method <<{name:s}>> failed with unexpected " |
| 1539 | "exception message: {exp:s}\n".format( |
| 1540 | name=meth_name, exp=e |
| 1541 | ) |
| 1542 | ) |
| 1543 | # consume data |
| 1544 | s.read() |
| 1545 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1546 | s.write(b"over\n") |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1547 | s.close() |
| 1548 | finally: |
| 1549 | server.stop() |
| 1550 | server.join() |
| 1551 | |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1552 | def test_handshake_timeout(self): |
| 1553 | # Issue #5103: SSL handshake must respect the socket timeout |
| 1554 | server = socket.socket(socket.AF_INET) |
| 1555 | host = "127.0.0.1" |
| 1556 | port = support.bind_port(server) |
| 1557 | started = threading.Event() |
| 1558 | finish = False |
| 1559 | |
| 1560 | def serve(): |
| 1561 | server.listen(5) |
| 1562 | started.set() |
| 1563 | conns = [] |
| 1564 | while not finish: |
| 1565 | r, w, e = select.select([server], [], [], 0.1) |
| 1566 | if server in r: |
| 1567 | # Let the socket hang around rather than having |
| 1568 | # it closed by garbage collection. |
| 1569 | conns.append(server.accept()[0]) |
Antoine Pitrou | d2eca37 | 2010-10-29 23:41:37 +0000 | [diff] [blame] | 1570 | for sock in conns: |
| 1571 | sock.close() |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1572 | |
| 1573 | t = threading.Thread(target=serve) |
| 1574 | t.start() |
| 1575 | started.wait() |
| 1576 | |
| 1577 | try: |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 1578 | try: |
| 1579 | c = socket.socket(socket.AF_INET) |
| 1580 | c.settimeout(0.2) |
| 1581 | c.connect((host, port)) |
| 1582 | # Will attempt handshake and time out |
Antoine Pitrou | c4df784 | 2010-12-03 19:59:41 +0000 | [diff] [blame] | 1583 | self.assertRaisesRegex(socket.timeout, "timed out", |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1584 | ssl.wrap_socket, c) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 1585 | finally: |
| 1586 | c.close() |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1587 | try: |
| 1588 | c = socket.socket(socket.AF_INET) |
| 1589 | c = ssl.wrap_socket(c) |
| 1590 | c.settimeout(0.2) |
| 1591 | # Will attempt handshake and time out |
Antoine Pitrou | c4df784 | 2010-12-03 19:59:41 +0000 | [diff] [blame] | 1592 | self.assertRaisesRegex(socket.timeout, "timed out", |
Ezio Melotti | ed3a7d2 | 2010-12-01 02:32:32 +0000 | [diff] [blame] | 1593 | c.connect, (host, port)) |
Antoine Pitrou | d3f8ab8 | 2010-04-24 21:26:44 +0000 | [diff] [blame] | 1594 | finally: |
| 1595 | c.close() |
| 1596 | finally: |
| 1597 | finish = True |
| 1598 | t.join() |
| 1599 | server.close() |
| 1600 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 1601 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1602 | def test_main(verbose=False): |
Antoine Pitrou | 15cee62 | 2010-08-04 16:45:21 +0000 | [diff] [blame] | 1603 | if support.verbose: |
| 1604 | plats = { |
| 1605 | 'Linux': platform.linux_distribution, |
| 1606 | 'Mac': platform.mac_ver, |
| 1607 | 'Windows': platform.win32_ver, |
| 1608 | } |
| 1609 | for name, func in plats.items(): |
| 1610 | plat = func() |
| 1611 | if plat and plat[0]: |
| 1612 | plat = '%s %r' % (name, plat) |
| 1613 | break |
| 1614 | else: |
| 1615 | plat = repr(platform.platform()) |
| 1616 | print("test_ssl: testing with %r %r" % |
| 1617 | (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO)) |
| 1618 | print(" under %s" % plat) |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 1619 | print(" HAS_SNI = %r" % ssl.HAS_SNI) |
Antoine Pitrou | 15cee62 | 2010-08-04 16:45:21 +0000 | [diff] [blame] | 1620 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1621 | for filename in [ |
| 1622 | CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, |
| 1623 | ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, |
| 1624 | BADCERT, BADKEY, EMPTYCERT]: |
| 1625 | if not os.path.exists(filename): |
| 1626 | raise support.TestFailed("Can't read certificate file %r" % filename) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1627 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1628 | tests = [ContextTests, BasicSocketTests] |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1629 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1630 | if support.is_resource_enabled('network'): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1631 | tests.append(NetworkedTests) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1632 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1633 | if _have_threads: |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 1634 | thread_info = support.threading_setup() |
| 1635 | if thread_info and support.is_resource_enabled('network'): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 1636 | tests.append(ThreadedTests) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1637 | |
Antoine Pitrou | 480a124 | 2010-04-28 21:37:09 +0000 | [diff] [blame] | 1638 | try: |
| 1639 | support.run_unittest(*tests) |
| 1640 | finally: |
| 1641 | if _have_threads: |
| 1642 | support.threading_cleanup(*thread_info) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1643 | |
| 1644 | if __name__ == "__main__": |
| 1645 | test_main() |