blob: 9f134b4c62a9bea113f7d2ecff98fc8bad609977 [file] [log] [blame]
Jean-Paul Calderone8671c852011-03-02 19:26:20 -05001# Copyright (C) Jean-Paul Calderone
2# See LICENSE for details.
Jean-Paul Calderone8b63d452008-03-21 18:31:12 -04003
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -04004"""
Hynek Schlawackf90e3682016-03-11 11:21:13 +01005Unit tests for :mod:`OpenSSL.SSL`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -04006"""
7
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01008import datetime
Maximilian Hils868dc3c2017-02-10 14:56:55 +01009import sys
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +010010import uuid
11
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -050012from gc import collect, get_referrers
David Benjamin1fbe0642019-04-15 17:05:13 -050013from errno import (
Alex Gaynor03737182020-07-23 20:40:46 -040014 EAFNOSUPPORT,
15 ECONNREFUSED,
16 EINPROGRESS,
17 EWOULDBLOCK,
18 EPIPE,
19 ESHUTDOWN,
20)
Jeremy Lainé1ae7cb62018-03-21 14:49:42 +010021from sys import platform, getfilesystemencoding
David Benjamin1fbe0642019-04-15 17:05:13 -050022from socket import AF_INET, AF_INET6, MSG_PEEK, SHUT_RDWR, error, socket
Jean-Paul Calderonea65cf6c2009-07-19 10:26:52 -040023from os import makedirs
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040024from os.path import join
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -040025from weakref import ref
Alex Chanb7480992017-01-30 14:04:47 +000026from warnings import simplefilter
Jean-Paul Calderone460cc1f2009-03-07 11:31:12 -050027
Alex Gaynor963ae032019-07-06 17:38:32 -040028import flaky
29
Hynek Schlawack734d3022015-09-05 19:19:32 +020030import pytest
31
Paul Kehrer55fb3412017-06-29 18:44:08 -050032from pretend import raiser
33
Hugo van Kemenade60827f82019-08-30 00:39:35 +030034from six import PY2, text_type
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050035
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +010036from cryptography import x509
37from cryptography.hazmat.backends import default_backend
38from cryptography.hazmat.primitives import hashes
39from cryptography.hazmat.primitives import serialization
40from cryptography.hazmat.primitives.asymmetric import rsa
41from cryptography.x509.oid import NameOID
42
43
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040044from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080045from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040046from OpenSSL.crypto import dump_privatekey, load_privatekey
47from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040048from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040049
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040050from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
51from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040052from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040053from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -040054 SSLv2_METHOD,
55 SSLv3_METHOD,
56 SSLv23_METHOD,
57 TLSv1_METHOD,
58 TLSv1_1_METHOD,
59 TLSv1_2_METHOD,
60)
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040061from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040062from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -040063 VERIFY_PEER,
64 VERIFY_FAIL_IF_NO_PEER_CERT,
65 VERIFY_CLIENT_ONCE,
66 VERIFY_NONE,
67)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040068
Paul Kehrer55fb3412017-06-29 18:44:08 -050069from OpenSSL import SSL
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040070from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -040071 SESS_CACHE_OFF,
72 SESS_CACHE_CLIENT,
73 SESS_CACHE_SERVER,
74 SESS_CACHE_BOTH,
75 SESS_CACHE_NO_AUTO_CLEAR,
76 SESS_CACHE_NO_INTERNAL_LOOKUP,
77 SESS_CACHE_NO_INTERNAL_STORE,
78 SESS_CACHE_NO_INTERNAL,
79)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050080
81from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -040082 Error,
83 SysCallError,
84 WantReadError,
85 WantWriteError,
86 ZeroReturnError,
87)
88from OpenSSL.SSL import Context, Session, Connection, SSLeay_version
Cory Benfield0ba57ec2016-03-30 09:35:05 +010089from OpenSSL.SSL import _make_requires
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040090
Paul Kehrer55fb3412017-06-29 18:44:08 -050091from OpenSSL._util import ffi as _ffi, lib as _lib
Cory Benfieldba1820d2015-04-13 17:39:12 -040092
Alex Gaynord3b5d9b2016-07-31 10:54:24 -040093from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -040094 OP_NO_QUERY_MTU,
95 OP_COOKIE_EXCHANGE,
96 OP_NO_TICKET,
97 OP_NO_COMPRESSION,
98 MODE_RELEASE_BUFFERS,
99 NO_OVERLAPPING_PROTOCOLS,
100)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400101
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -0400102from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -0400103 SSL_ST_CONNECT,
104 SSL_ST_ACCEPT,
105 SSL_ST_MASK,
106 SSL_CB_LOOP,
107 SSL_CB_EXIT,
108 SSL_CB_READ,
109 SSL_CB_WRITE,
110 SSL_CB_ALERT,
111 SSL_CB_READ_ALERT,
112 SSL_CB_WRITE_ALERT,
113 SSL_CB_ACCEPT_LOOP,
114 SSL_CB_ACCEPT_EXIT,
115 SSL_CB_CONNECT_LOOP,
116 SSL_CB_CONNECT_EXIT,
117 SSL_CB_HANDSHAKE_START,
118 SSL_CB_HANDSHAKE_DONE,
119)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400120
Alex Gaynor5af32d02016-09-24 01:52:21 -0400121try:
122 from OpenSSL.SSL import (
Alex Gaynor03737182020-07-23 20:40:46 -0400123 SSL_ST_INIT,
124 SSL_ST_BEFORE,
125 SSL_ST_OK,
126 SSL_ST_RENEGOTIATE,
Alex Gaynor5af32d02016-09-24 01:52:21 -0400127 )
128except ImportError:
129 SSL_ST_INIT = SSL_ST_BEFORE = SSL_ST_OK = SSL_ST_RENEGOTIATE = None
130
Alex Chanb7480992017-01-30 14:04:47 +0000131from .util import WARNING_TYPE_EXPECTED, NON_ASCII, is_consistent_type
Hynek Schlawackf0e66852015-10-16 20:18:38 +0200132from .test_crypto import (
Alex Gaynor03737182020-07-23 20:40:46 -0400133 client_cert_pem,
134 client_key_pem,
135 server_cert_pem,
136 server_key_pem,
137 root_cert_pem,
Paul Kehrerbeaf9f52020-08-03 17:50:31 -0500138 root_key_pem,
Alex Gaynor03737182020-07-23 20:40:46 -0400139)
Hynek Schlawackf0e66852015-10-16 20:18:38 +0200140
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200141
Paul Kehrer41dc1362020-08-04 23:44:18 -0500142# openssl dhparam 2048 -out dh-2048.pem
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -0400143dhparam = """\
144-----BEGIN DH PARAMETERS-----
Paul Kehrer41dc1362020-08-04 23:44:18 -0500145MIIBCAKCAQEA2F5e976d/GjsaCdKv5RMWL/YV7fq1UUWpPAer5fDXflLMVUuYXxE
1463m3ayZob9lbpgEU0jlPAsXHfQPGxpKmvhv+xV26V/DEoukED8JeZUY/z4pigoptl
147+8+TYdNNE/rFSZQFXIp+v2D91IEgmHBnZlKFSbKR+p8i0KjExXGjU6ji3S5jkOku
148ogikc7df1Ui0hWNJCmTjExq07aXghk97PsdFSxjdawuG3+vos5bnNoUwPLYlFc/z
149ITYG0KXySiCLi4UDlXTZTz7u/+OYczPEgqa/JPUddbM/kfvaRAnjY38cfQ7qXf8Y
150i5s5yYK7a/0eWxxRr2qraYaUj8RwDpH9CwIBAg==
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -0400151-----END DH PARAMETERS-----
152"""
153
154
Hugo van Kemenade60827f82019-08-30 00:39:35 +0300155skip_if_py3 = pytest.mark.skipif(not PY2, reason="Python 2 only")
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200156
157
David Benjamin1fbe0642019-04-15 17:05:13 -0500158def socket_any_family():
159 try:
160 return socket(AF_INET)
161 except error as e:
162 if e.errno == EAFNOSUPPORT:
163 return socket(AF_INET6)
164 raise
165
166
167def loopback_address(socket):
168 if socket.family == AF_INET:
169 return "127.0.0.1"
170 else:
171 assert socket.family == AF_INET6
172 return "::1"
173
174
Jean-Paul Calderone05826732015-04-12 11:38:49 -0400175def join_bytes_or_unicode(prefix, suffix):
176 """
177 Join two path components of either ``bytes`` or ``unicode``.
178
179 The return type is the same as the type of ``prefix``.
180 """
181 # If the types are the same, nothing special is necessary.
182 if type(prefix) == type(suffix):
183 return join(prefix, suffix)
184
185 # Otherwise, coerce suffix to the type of prefix.
186 if isinstance(prefix, text_type):
187 return join(prefix, suffix.decode(getfilesystemencoding()))
188 else:
189 return join(prefix, suffix.encode(getfilesystemencoding()))
190
191
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400192def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400193 return ok
194
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400195
Rick Deanb1ccd562009-07-09 23:52:39 -0500196def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400197 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400198 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400199 """
200 # Connect a pair of sockets
David Benjamin1fbe0642019-04-15 17:05:13 -0500201 port = socket_any_family()
Alex Gaynor03737182020-07-23 20:40:46 -0400202 port.bind(("", 0))
Rick Deanb1ccd562009-07-09 23:52:39 -0500203 port.listen(1)
David Benjamin1fbe0642019-04-15 17:05:13 -0500204 client = socket(port.family)
Rick Deanb1ccd562009-07-09 23:52:39 -0500205 client.setblocking(False)
David Benjamin1fbe0642019-04-15 17:05:13 -0500206 client.connect_ex((loopback_address(port), port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400207 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500208 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500209
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400210 # Let's pass some unencrypted data to make sure our socket connection is
211 # fine. Just one byte, so we don't have to worry about buffers getting
212 # filled up or fragmentation.
Alex Gaynore7f51982016-09-11 11:48:14 -0400213 server.send(b"x")
214 assert client.recv(1024) == b"x"
215 client.send(b"y")
216 assert server.recv(1024) == b"y"
Rick Deanb1ccd562009-07-09 23:52:39 -0500217
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400218 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400219 server.setblocking(False)
220 client.setblocking(False)
Jim Shaver46f28912015-05-29 19:32:16 -0400221
Rick Deanb1ccd562009-07-09 23:52:39 -0500222 return (server, client)
223
224
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400225def handshake(client, server):
226 conns = [client, server]
227 while conns:
228 for conn in conns:
229 try:
230 conn.do_handshake()
231 except WantReadError:
232 pass
233 else:
234 conns.remove(conn)
235
236
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400237def _create_certificate_chain():
238 """
239 Construct and return a chain of certificates.
240
241 1. A new self-signed certificate authority certificate (cacert)
242 2. A new intermediate certificate signed by cacert (icert)
243 3. A new server certificate signed by icert (scert)
244 """
Alex Gaynor03737182020-07-23 20:40:46 -0400245 caext = X509Extension(b"basicConstraints", False, b"CA:true")
246 not_after_date = datetime.date.today() + datetime.timedelta(days=365)
Alex Gaynor675534c2020-01-12 11:59:49 -0600247 not_after = not_after_date.strftime("%Y%m%d%H%M%SZ").encode("ascii")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400248
249 # Step 1
250 cakey = PKey()
Alex Gaynor8cd336e2020-08-03 10:36:32 -0400251 cakey.generate_key(TYPE_RSA, 2048)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400252 cacert = X509()
David Benjamin6b799472020-06-24 17:14:16 -0400253 cacert.set_version(2)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400254 cacert.get_subject().commonName = "Authority Certificate"
255 cacert.set_issuer(cacert.get_subject())
256 cacert.set_pubkey(cakey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400257 cacert.set_notBefore(b"20000101000000Z")
Alex Gaynor675534c2020-01-12 11:59:49 -0600258 cacert.set_notAfter(not_after)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400259 cacert.add_extensions([caext])
260 cacert.set_serial_number(0)
Paul Kehrerd4b60462020-08-03 18:26:03 -0500261 cacert.sign(cakey, "sha256")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400262
263 # Step 2
264 ikey = PKey()
Alex Gaynor8cd336e2020-08-03 10:36:32 -0400265 ikey.generate_key(TYPE_RSA, 2048)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400266 icert = X509()
David Benjamin6b799472020-06-24 17:14:16 -0400267 icert.set_version(2)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400268 icert.get_subject().commonName = "Intermediate Certificate"
269 icert.set_issuer(cacert.get_subject())
270 icert.set_pubkey(ikey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400271 icert.set_notBefore(b"20000101000000Z")
Alex Gaynor675534c2020-01-12 11:59:49 -0600272 icert.set_notAfter(not_after)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400273 icert.add_extensions([caext])
274 icert.set_serial_number(0)
Paul Kehrerd4b60462020-08-03 18:26:03 -0500275 icert.sign(cakey, "sha256")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400276
277 # Step 3
278 skey = PKey()
Alex Gaynor8cd336e2020-08-03 10:36:32 -0400279 skey.generate_key(TYPE_RSA, 2048)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400280 scert = X509()
David Benjamin6b799472020-06-24 17:14:16 -0400281 scert.set_version(2)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400282 scert.get_subject().commonName = "Server Certificate"
283 scert.set_issuer(icert.get_subject())
284 scert.set_pubkey(skey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400285 scert.set_notBefore(b"20000101000000Z")
Alex Gaynor675534c2020-01-12 11:59:49 -0600286 scert.set_notAfter(not_after)
Alex Gaynor03737182020-07-23 20:40:46 -0400287 scert.add_extensions(
288 [X509Extension(b"basicConstraints", True, b"CA:false")]
289 )
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400290 scert.set_serial_number(0)
Paul Kehrerd4b60462020-08-03 18:26:03 -0500291 scert.sign(ikey, "sha256")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400292
293 return [(cakey, cacert), (ikey, icert), (skey, scert)]
294
295
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -0600296def loopback_client_factory(socket, version=SSLv23_METHOD):
297 client = Connection(Context(version), socket)
Alex Chan1c0cb662017-01-30 07:13:30 +0000298 client.set_connect_state()
299 return client
300
301
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -0600302def loopback_server_factory(socket, version=SSLv23_METHOD):
303 ctx = Context(version)
Alex Chan1c0cb662017-01-30 07:13:30 +0000304 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
305 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
306 server = Connection(ctx, socket)
307 server.set_accept_state()
308 return server
309
310
311def loopback(server_factory=None, client_factory=None):
312 """
313 Create a connected socket pair and force two connected SSL sockets
314 to talk to each other via memory BIOs.
315 """
316 if server_factory is None:
317 server_factory = loopback_server_factory
318 if client_factory is None:
319 client_factory = loopback_client_factory
320
321 (server, client) = socket_pair()
322 server = server_factory(server)
323 client = client_factory(client)
324
325 handshake(client, server)
326
327 server.setblocking(True)
328 client.setblocking(True)
329 return server, client
330
331
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000332def interact_in_memory(client_conn, server_conn):
333 """
334 Try to read application bytes from each of the two `Connection` objects.
335 Copy bytes back and forth between their send/receive buffers for as long
336 as there is anything to copy. When there is nothing more to copy,
337 return `None`. If one of them actually manages to deliver some application
338 bytes, return a two-tuple of the connection from which the bytes were read
339 and the bytes themselves.
340 """
341 wrote = True
342 while wrote:
343 # Loop until neither side has anything to say
344 wrote = False
345
346 # Copy stuff from each side's send buffer to the other side's
347 # receive buffer.
Alex Gaynor03737182020-07-23 20:40:46 -0400348 for (read, write) in [
349 (client_conn, server_conn),
350 (server_conn, client_conn),
351 ]:
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000352
353 # Give the side a chance to generate some more bytes, or succeed.
354 try:
355 data = read.recv(2 ** 16)
356 except WantReadError:
357 # It didn't succeed, so we'll hope it generated some output.
358 pass
359 else:
360 # It did succeed, so we'll stop now and let the caller deal
361 # with it.
362 return (read, data)
363
364 while True:
365 # Keep copying as long as there's more stuff there.
366 try:
367 dirty = read.bio_read(4096)
368 except WantReadError:
369 # Okay, nothing more waiting to be sent. Stop
370 # processing this send buffer.
371 break
372 else:
373 # Keep track of the fact that someone generated some
374 # output.
375 wrote = True
376 write.bio_write(dirty)
377
378
Alex Chan532b79e2017-01-24 15:14:52 +0000379def handshake_in_memory(client_conn, server_conn):
380 """
381 Perform the TLS handshake between two `Connection` instances connected to
382 each other via memory BIOs.
383 """
384 client_conn.set_connect_state()
385 server_conn.set_accept_state()
386
387 for conn in [client_conn, server_conn]:
388 try:
389 conn.do_handshake()
390 except WantReadError:
391 pass
392
393 interact_in_memory(client_conn, server_conn)
394
395
Alex Chanb7480992017-01-30 14:04:47 +0000396class TestVersion(object):
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400397 """
Alex Chanb7480992017-01-30 14:04:47 +0000398 Tests for version information exposed by `OpenSSL.SSL.SSLeay_version` and
399 `OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400400 """
Alex Gaynor03737182020-07-23 20:40:46 -0400401
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400402 def test_OPENSSL_VERSION_NUMBER(self):
403 """
Alex Chanb7480992017-01-30 14:04:47 +0000404 `OPENSSL_VERSION_NUMBER` is an integer with status in the low byte and
405 the patch, fix, minor, and major versions in the nibbles above that.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400406 """
Alex Chanb7480992017-01-30 14:04:47 +0000407 assert isinstance(OPENSSL_VERSION_NUMBER, int)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400408
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400409 def test_SSLeay_version(self):
410 """
Alex Chanb7480992017-01-30 14:04:47 +0000411 `SSLeay_version` takes a version type indicator and returns one of a
412 number of version strings based on that indicator.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400413 """
414 versions = {}
Alex Gaynor03737182020-07-23 20:40:46 -0400415 for t in [
416 SSLEAY_VERSION,
417 SSLEAY_CFLAGS,
418 SSLEAY_BUILT_ON,
419 SSLEAY_PLATFORM,
420 SSLEAY_DIR,
421 ]:
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400422 version = SSLeay_version(t)
423 versions[version] = t
Alex Chanb7480992017-01-30 14:04:47 +0000424 assert isinstance(version, bytes)
425 assert len(versions) == 5
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400426
427
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100428@pytest.fixture
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100429def ca_file(tmpdir):
430 """
431 Create a valid PEM file with CA certificates and return the path.
432 """
433 key = rsa.generate_private_key(
Alex Gaynor03737182020-07-23 20:40:46 -0400434 public_exponent=65537, key_size=2048, backend=default_backend()
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100435 )
436 public_key = key.public_key()
437
438 builder = x509.CertificateBuilder()
Alex Gaynor03737182020-07-23 20:40:46 -0400439 builder = builder.subject_name(
440 x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org")])
441 )
442 builder = builder.issuer_name(
443 x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org")])
444 )
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100445 one_day = datetime.timedelta(1, 0, 0)
446 builder = builder.not_valid_before(datetime.datetime.today() - one_day)
447 builder = builder.not_valid_after(datetime.datetime.today() + one_day)
448 builder = builder.serial_number(int(uuid.uuid4()))
449 builder = builder.public_key(public_key)
450 builder = builder.add_extension(
451 x509.BasicConstraints(ca=True, path_length=None), critical=True,
452 )
453
454 certificate = builder.sign(
Alex Gaynor03737182020-07-23 20:40:46 -0400455 private_key=key, algorithm=hashes.SHA256(), backend=default_backend()
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100456 )
457
458 ca_file = tmpdir.join("test.pem")
459 ca_file.write_binary(
Alex Gaynor03737182020-07-23 20:40:46 -0400460 certificate.public_bytes(encoding=serialization.Encoding.PEM,)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100461 )
462
463 return str(ca_file).encode("ascii")
464
465
466@pytest.fixture
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100467def context():
468 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500469 A simple "best TLS you can get" context. TLS 1.2+ in any reasonable OpenSSL
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100470 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500471 return Context(SSLv23_METHOD)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100472
473
474class TestContext(object):
Hynek Schlawackaa861212016-03-13 13:53:48 +0100475 """
Alex Chan532b79e2017-01-24 15:14:52 +0000476 Unit tests for `OpenSSL.SSL.Context`.
Hynek Schlawackaa861212016-03-13 13:53:48 +0100477 """
Alex Gaynor03737182020-07-23 20:40:46 -0400478
479 @pytest.mark.parametrize(
480 "cipher_string",
481 [b"hello world:AES128-SHA", u"hello world:AES128-SHA"],
482 )
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100483 def test_set_cipher_list(self, context, cipher_string):
484 """
Alex Chan532b79e2017-01-24 15:14:52 +0000485 `Context.set_cipher_list` accepts both byte and unicode strings
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100486 for naming the ciphers which connections created with the context
487 object will be able to choose from.
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100488 """
489 context.set_cipher_list(cipher_string)
490 conn = Connection(context, None)
491
492 assert "AES128-SHA" in conn.get_cipher_list()
493
Mark Williamsdf2480d2019-02-14 19:30:07 -0800494 def test_set_cipher_list_wrong_type(self, context):
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100495 """
Alex Chan532b79e2017-01-24 15:14:52 +0000496 `Context.set_cipher_list` raises `TypeError` when passed a non-string
Mark Williamsdf2480d2019-02-14 19:30:07 -0800497 argument.
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100498 """
Mark Williamsdf2480d2019-02-14 19:30:07 -0800499 with pytest.raises(TypeError):
500 context.set_cipher_list(object())
501
Alex Gaynor963ae032019-07-06 17:38:32 -0400502 @flaky.flaky
Mark Williamsdf2480d2019-02-14 19:30:07 -0800503 def test_set_cipher_list_no_cipher_match(self, context):
504 """
505 `Context.set_cipher_list` raises `OpenSSL.SSL.Error` with a
506 `"no cipher match"` reason string regardless of the TLS
507 version.
508 """
509 with pytest.raises(Error) as excinfo:
510 context.set_cipher_list(b"imaginary-cipher")
511 assert excinfo.value.args == (
Alex Gaynor03737182020-07-23 20:40:46 -0400512 [("SSL routines", "SSL_CTX_set_cipher_list", "no cipher match",)],
513 )
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100514
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100515 def test_load_client_ca(self, context, ca_file):
516 """
Alex Chan532b79e2017-01-24 15:14:52 +0000517 `Context.load_client_ca` works as far as we can tell.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100518 """
519 context.load_client_ca(ca_file)
520
521 def test_load_client_ca_invalid(self, context, tmpdir):
522 """
Alex Chan532b79e2017-01-24 15:14:52 +0000523 `Context.load_client_ca` raises an Error if the ca file is invalid.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100524 """
525 ca_file = tmpdir.join("test.pem")
526 ca_file.write("")
527
528 with pytest.raises(Error) as e:
529 context.load_client_ca(str(ca_file).encode("ascii"))
530
531 assert "PEM routines" == e.value.args[0][0][0]
532
533 def test_load_client_ca_unicode(self, context, ca_file):
534 """
535 Passing the path as unicode raises a warning but works.
536 """
Alex Gaynor03737182020-07-23 20:40:46 -0400537 pytest.deprecated_call(context.load_client_ca, ca_file.decode("ascii"))
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100538
539 def test_set_session_id(self, context):
540 """
Alex Chan532b79e2017-01-24 15:14:52 +0000541 `Context.set_session_id` works as far as we can tell.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100542 """
543 context.set_session_id(b"abc")
544
545 def test_set_session_id_fail(self, context):
546 """
Alex Chan532b79e2017-01-24 15:14:52 +0000547 `Context.set_session_id` errors are propagated.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100548 """
549 with pytest.raises(Error) as e:
550 context.set_session_id(b"abc" * 1000)
551
552 assert [
Alex Gaynor03737182020-07-23 20:40:46 -0400553 (
554 "SSL routines",
555 "SSL_CTX_set_session_id_context",
556 "ssl session id context too long",
557 )
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100558 ] == e.value.args[0]
559
560 def test_set_session_id_unicode(self, context):
561 """
Alex Chan532b79e2017-01-24 15:14:52 +0000562 `Context.set_session_id` raises a warning if a unicode string is
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100563 passed.
564 """
565 pytest.deprecated_call(context.set_session_id, u"abc")
566
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400567 def test_method(self):
568 """
Alex Chan532b79e2017-01-24 15:14:52 +0000569 `Context` can be instantiated with one of `SSLv2_METHOD`,
570 `SSLv3_METHOD`, `SSLv23_METHOD`, `TLSv1_METHOD`, `TLSv1_1_METHOD`,
571 or `TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400572 """
Alex Gaynor5af32d02016-09-24 01:52:21 -0400573 methods = [SSLv23_METHOD, TLSv1_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400574 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400575 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400576
Alex Gaynor5af32d02016-09-24 01:52:21 -0400577 maybe = [SSLv2_METHOD, SSLv3_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400578 for meth in maybe:
579 try:
580 Context(meth)
581 except (Error, ValueError):
582 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
583 # don't. Difficult to say in advance.
584 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400585
Alex Chan532b79e2017-01-24 15:14:52 +0000586 with pytest.raises(TypeError):
587 Context("")
588 with pytest.raises(ValueError):
589 Context(10)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400590
Rick Deane15b1472009-07-09 15:53:42 -0500591 def test_type(self):
592 """
Alex Gaynor01f90a12019-02-07 09:14:48 -0500593 `Context` can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500594 """
Alex Gaynor03737182020-07-23 20:40:46 -0400595 assert is_consistent_type(Context, "Context", TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500596
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400597 def test_use_privatekey(self):
598 """
Alex Chan532b79e2017-01-24 15:14:52 +0000599 `Context.use_privatekey` takes an `OpenSSL.crypto.PKey` instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400600 """
601 key = PKey()
Paul Kehrerc45a6ea2020-08-03 15:54:20 -0500602 key.generate_key(TYPE_RSA, 1024)
Paul Kehrer688538c2020-08-03 19:18:15 -0500603 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400604 ctx.use_privatekey(key)
Alex Chan532b79e2017-01-24 15:14:52 +0000605 with pytest.raises(TypeError):
606 ctx.use_privatekey("")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400607
Alex Chan532b79e2017-01-24 15:14:52 +0000608 def test_use_privatekey_file_missing(self, tmpfile):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800609 """
Alex Chan532b79e2017-01-24 15:14:52 +0000610 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` when passed
611 the name of a file which does not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800612 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500613 ctx = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000614 with pytest.raises(Error):
615 ctx.use_privatekey_file(tmpfile)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800616
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400617 def _use_privatekey_file_test(self, pemfile, filetype):
618 """
619 Verify that calling ``Context.use_privatekey_file`` with the given
620 arguments does not raise an exception.
621 """
622 key = PKey()
Paul Kehrerc45a6ea2020-08-03 15:54:20 -0500623 key.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400624
625 with open(pemfile, "wt") as pem:
Alex Gaynor03737182020-07-23 20:40:46 -0400626 pem.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400627
Paul Kehrer688538c2020-08-03 19:18:15 -0500628 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400629 ctx.use_privatekey_file(pemfile, filetype)
630
Alex Gaynor03737182020-07-23 20:40:46 -0400631 @pytest.mark.parametrize("filetype", [object(), "", None, 1.0])
Alex Chanfb078d82017-04-20 11:16:15 +0100632 def test_wrong_privatekey_file_wrong_args(self, tmpfile, filetype):
633 """
634 `Context.use_privatekey_file` raises `TypeError` when called with
635 a `filetype` which is not a valid file encoding.
636 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500637 ctx = Context(SSLv23_METHOD)
Alex Chanfb078d82017-04-20 11:16:15 +0100638 with pytest.raises(TypeError):
639 ctx.use_privatekey_file(tmpfile, filetype)
640
Alex Chan532b79e2017-01-24 15:14:52 +0000641 def test_use_privatekey_file_bytes(self, tmpfile):
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400642 """
643 A private key can be specified from a file by passing a ``bytes``
644 instance giving the file name to ``Context.use_privatekey_file``.
645 """
646 self._use_privatekey_file_test(
Alex Gaynor03737182020-07-23 20:40:46 -0400647 tmpfile + NON_ASCII.encode(getfilesystemencoding()), FILETYPE_PEM,
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400648 )
649
Alex Chan532b79e2017-01-24 15:14:52 +0000650 def test_use_privatekey_file_unicode(self, tmpfile):
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400651 """
652 A private key can be specified from a file by passing a ``unicode``
653 instance giving the file name to ``Context.use_privatekey_file``.
654 """
655 self._use_privatekey_file_test(
Alex Gaynor03737182020-07-23 20:40:46 -0400656 tmpfile.decode(getfilesystemencoding()) + NON_ASCII, FILETYPE_PEM,
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400657 )
658
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800659 def test_use_certificate_wrong_args(self):
660 """
Alex Chan532b79e2017-01-24 15:14:52 +0000661 `Context.use_certificate_wrong_args` raises `TypeError` when not passed
662 exactly one `OpenSSL.crypto.X509` instance as an argument.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800663 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500664 ctx = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000665 with pytest.raises(TypeError):
666 ctx.use_certificate("hello, world")
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800667
668 def test_use_certificate_uninitialized(self):
669 """
Alex Chan532b79e2017-01-24 15:14:52 +0000670 `Context.use_certificate` raises `OpenSSL.SSL.Error` when passed a
671 `OpenSSL.crypto.X509` instance which has not been initialized
672 (ie, which does not actually have any certificate data).
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800673 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500674 ctx = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000675 with pytest.raises(Error):
676 ctx.use_certificate(X509())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800677
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800678 def test_use_certificate(self):
679 """
Alex Chan532b79e2017-01-24 15:14:52 +0000680 `Context.use_certificate` sets the certificate which will be
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800681 used to identify connections created using the context.
682 """
683 # TODO
684 # Hard to assert anything. But we could set a privatekey then ask
685 # OpenSSL if the cert and key agree using check_privatekey. Then as
686 # long as check_privatekey works right we're good...
Paul Kehrer688538c2020-08-03 19:18:15 -0500687 ctx = Context(SSLv23_METHOD)
Paul Kehrerbeaf9f52020-08-03 17:50:31 -0500688 ctx.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800689
690 def test_use_certificate_file_wrong_args(self):
691 """
Alex Chan532b79e2017-01-24 15:14:52 +0000692 `Context.use_certificate_file` raises `TypeError` if the first
693 argument is not a byte string or the second argument is not an integer.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800694 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500695 ctx = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000696 with pytest.raises(TypeError):
697 ctx.use_certificate_file(object(), FILETYPE_PEM)
698 with pytest.raises(TypeError):
699 ctx.use_certificate_file(b"somefile", object())
700 with pytest.raises(TypeError):
701 ctx.use_certificate_file(object(), FILETYPE_PEM)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800702
Alex Chan532b79e2017-01-24 15:14:52 +0000703 def test_use_certificate_file_missing(self, tmpfile):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800704 """
Alex Chan532b79e2017-01-24 15:14:52 +0000705 `Context.use_certificate_file` raises `OpenSSL.SSL.Error` if passed
706 the name of a file which does not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800707 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500708 ctx = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000709 with pytest.raises(Error):
710 ctx.use_certificate_file(tmpfile)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800711
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400712 def _use_certificate_file_test(self, certificate_file):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800713 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400714 Verify that calling ``Context.use_certificate_file`` with the given
715 filename doesn't raise an exception.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800716 """
717 # TODO
718 # Hard to assert anything. But we could set a privatekey then ask
719 # OpenSSL if the cert and key agree using check_privatekey. Then as
720 # long as check_privatekey works right we're good...
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400721 with open(certificate_file, "wb") as pem_file:
Paul Kehrerbeaf9f52020-08-03 17:50:31 -0500722 pem_file.write(root_cert_pem)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800723
Paul Kehrer688538c2020-08-03 19:18:15 -0500724 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400725 ctx.use_certificate_file(certificate_file)
726
Alex Chan532b79e2017-01-24 15:14:52 +0000727 def test_use_certificate_file_bytes(self, tmpfile):
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400728 """
Alex Chan532b79e2017-01-24 15:14:52 +0000729 `Context.use_certificate_file` sets the certificate (given as a
730 `bytes` filename) which will be used to identify connections created
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400731 using the context.
732 """
Alex Chan532b79e2017-01-24 15:14:52 +0000733 filename = tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400734 self._use_certificate_file_test(filename)
735
Alex Chan532b79e2017-01-24 15:14:52 +0000736 def test_use_certificate_file_unicode(self, tmpfile):
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400737 """
Alex Chan532b79e2017-01-24 15:14:52 +0000738 `Context.use_certificate_file` sets the certificate (given as a
739 `bytes` filename) which will be used to identify connections created
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400740 using the context.
741 """
Alex Chan532b79e2017-01-24 15:14:52 +0000742 filename = tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400743 self._use_certificate_file_test(filename)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800744
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500745 def test_check_privatekey_valid(self):
746 """
Alex Chan532b79e2017-01-24 15:14:52 +0000747 `Context.check_privatekey` returns `None` if the `Context` instance
748 has been configured to use a matched key and certificate pair.
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500749 """
750 key = load_privatekey(FILETYPE_PEM, client_key_pem)
751 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
Paul Kehrer688538c2020-08-03 19:18:15 -0500752 context = Context(SSLv23_METHOD)
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500753 context.use_privatekey(key)
754 context.use_certificate(cert)
Alex Chan532b79e2017-01-24 15:14:52 +0000755 assert None is context.check_privatekey()
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500756
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500757 def test_check_privatekey_invalid(self):
758 """
Alex Chan532b79e2017-01-24 15:14:52 +0000759 `Context.check_privatekey` raises `Error` if the `Context` instance
760 has been configured to use a key and certificate pair which don't
761 relate to each other.
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500762 """
763 key = load_privatekey(FILETYPE_PEM, client_key_pem)
764 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Paul Kehrer688538c2020-08-03 19:18:15 -0500765 context = Context(SSLv23_METHOD)
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500766 context.use_privatekey(key)
767 context.use_certificate(cert)
Alex Chan532b79e2017-01-24 15:14:52 +0000768 with pytest.raises(Error):
769 context.check_privatekey()
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400770
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400771 def test_app_data(self):
772 """
Alex Chan532b79e2017-01-24 15:14:52 +0000773 `Context.set_app_data` stores an object for later retrieval
774 using `Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400775 """
776 app_data = object()
Paul Kehrer688538c2020-08-03 19:18:15 -0500777 context = Context(SSLv23_METHOD)
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400778 context.set_app_data(app_data)
Alex Chan532b79e2017-01-24 15:14:52 +0000779 assert context.get_app_data() is app_data
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400780
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400781 def test_set_options_wrong_args(self):
782 """
Alex Chan532b79e2017-01-24 15:14:52 +0000783 `Context.set_options` raises `TypeError` if called with
784 a non-`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400785 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500786 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000787 with pytest.raises(TypeError):
788 context.set_options(None)
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400789
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500790 def test_set_options(self):
791 """
Alex Chan532b79e2017-01-24 15:14:52 +0000792 `Context.set_options` returns the new options value.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500793 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500794 context = Context(SSLv23_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500795 options = context.set_options(OP_NO_SSLv2)
Alex Gaynor2310f8b2016-09-10 14:39:32 -0400796 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500797
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300798 def test_set_mode_wrong_args(self):
799 """
Alex Chan532b79e2017-01-24 15:14:52 +0000800 `Context.set_mode` raises `TypeError` if called with
801 a non-`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300802 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500803 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000804 with pytest.raises(TypeError):
805 context.set_mode(None)
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300806
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400807 def test_set_mode(self):
808 """
Alex Chan532b79e2017-01-24 15:14:52 +0000809 `Context.set_mode` accepts a mode bitvector and returns the
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400810 newly set mode.
811 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500812 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000813 assert MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500814
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400815 def test_set_timeout_wrong_args(self):
816 """
Alex Chan532b79e2017-01-24 15:14:52 +0000817 `Context.set_timeout` raises `TypeError` if called with
818 a non-`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400819 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500820 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000821 with pytest.raises(TypeError):
822 context.set_timeout(None)
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400823
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400824 def test_timeout(self):
825 """
Alex Chan532b79e2017-01-24 15:14:52 +0000826 `Context.set_timeout` sets the session timeout for all connections
827 created using the context object. `Context.get_timeout` retrieves
828 this value.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400829 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500830 context = Context(SSLv23_METHOD)
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400831 context.set_timeout(1234)
Alex Chan532b79e2017-01-24 15:14:52 +0000832 assert context.get_timeout() == 1234
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400833
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400834 def test_set_verify_depth_wrong_args(self):
835 """
Alex Chan532b79e2017-01-24 15:14:52 +0000836 `Context.set_verify_depth` raises `TypeError` if called with a
837 non-`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400838 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500839 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000840 with pytest.raises(TypeError):
841 context.set_verify_depth(None)
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400842
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400843 def test_verify_depth(self):
844 """
Alex Chan532b79e2017-01-24 15:14:52 +0000845 `Context.set_verify_depth` sets the number of certificates in
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200846 a chain to follow before giving up. The value can be retrieved with
Alex Chan532b79e2017-01-24 15:14:52 +0000847 `Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400848 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500849 context = Context(SSLv23_METHOD)
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400850 context.set_verify_depth(11)
Alex Chan532b79e2017-01-24 15:14:52 +0000851 assert context.get_verify_depth() == 11
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400852
Alex Chan532b79e2017-01-24 15:14:52 +0000853 def _write_encrypted_pem(self, passphrase, tmpfile):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400854 """
855 Write a new private key out to a new file, encrypted using the given
856 passphrase. Return the path to the new file.
857 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400858 key = PKey()
Paul Kehrerc45a6ea2020-08-03 15:54:20 -0500859 key.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400860 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
Alex Gaynor03737182020-07-23 20:40:46 -0400861 with open(tmpfile, "w") as fObj:
862 fObj.write(pem.decode("ascii"))
Alex Chan532b79e2017-01-24 15:14:52 +0000863 return tmpfile
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400864
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400865 def test_set_passwd_cb_wrong_args(self):
866 """
Alex Chan532b79e2017-01-24 15:14:52 +0000867 `Context.set_passwd_cb` raises `TypeError` if called with a
868 non-callable first argument.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400869 """
Paul Kehrer688538c2020-08-03 19:18:15 -0500870 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000871 with pytest.raises(TypeError):
872 context.set_passwd_cb(None)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400873
Alex Chan532b79e2017-01-24 15:14:52 +0000874 def test_set_passwd_cb(self, tmpfile):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400875 """
Alex Chan532b79e2017-01-24 15:14:52 +0000876 `Context.set_passwd_cb` accepts a callable which will be invoked when
877 a private key is loaded from an encrypted PEM.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400878 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400879 passphrase = b"foobar"
Alex Chan532b79e2017-01-24 15:14:52 +0000880 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400881 calledWith = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200882
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400883 def passphraseCallback(maxlen, verify, extra):
884 calledWith.append((maxlen, verify, extra))
885 return passphrase
Alex Gaynor03737182020-07-23 20:40:46 -0400886
Paul Kehrer688538c2020-08-03 19:18:15 -0500887 context = Context(SSLv23_METHOD)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400888 context.set_passwd_cb(passphraseCallback)
889 context.use_privatekey_file(pemFile)
Alex Chan532b79e2017-01-24 15:14:52 +0000890 assert len(calledWith) == 1
891 assert isinstance(calledWith[0][0], int)
892 assert isinstance(calledWith[0][1], int)
893 assert calledWith[0][2] is None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400894
Alex Chan532b79e2017-01-24 15:14:52 +0000895 def test_passwd_callback_exception(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400896 """
Alex Chan532b79e2017-01-24 15:14:52 +0000897 `Context.use_privatekey_file` propagates any exception raised
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200898 by the passphrase callback.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400899 """
Alex Chan532b79e2017-01-24 15:14:52 +0000900 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200901
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400902 def passphraseCallback(maxlen, verify, extra):
903 raise RuntimeError("Sorry, I am a fail.")
904
Paul Kehrer688538c2020-08-03 19:18:15 -0500905 context = Context(SSLv23_METHOD)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400906 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000907 with pytest.raises(RuntimeError):
908 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400909
Alex Chan532b79e2017-01-24 15:14:52 +0000910 def test_passwd_callback_false(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400911 """
Alex Chan532b79e2017-01-24 15:14:52 +0000912 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
913 passphrase callback returns a false value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400914 """
Alex Chan532b79e2017-01-24 15:14:52 +0000915 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200916
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400917 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500918 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400919
Paul Kehrer688538c2020-08-03 19:18:15 -0500920 context = Context(SSLv23_METHOD)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400921 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000922 with pytest.raises(Error):
923 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400924
Alex Chan532b79e2017-01-24 15:14:52 +0000925 def test_passwd_callback_non_string(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400926 """
Alex Chan532b79e2017-01-24 15:14:52 +0000927 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
928 passphrase callback returns a true non-string value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400929 """
Alex Chan532b79e2017-01-24 15:14:52 +0000930 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200931
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400932 def passphraseCallback(maxlen, verify, extra):
933 return 10
934
Paul Kehrer688538c2020-08-03 19:18:15 -0500935 context = Context(SSLv23_METHOD)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400936 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000937 # TODO: Surely this is the wrong error?
938 with pytest.raises(ValueError):
939 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400940
Alex Chan532b79e2017-01-24 15:14:52 +0000941 def test_passwd_callback_too_long(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400942 """
943 If the passphrase returned by the passphrase callback returns a string
944 longer than the indicated maximum length, it is truncated.
945 """
946 # A priori knowledge!
Alex Gaynore7f51982016-09-11 11:48:14 -0400947 passphrase = b"x" * 1024
Alex Chan532b79e2017-01-24 15:14:52 +0000948 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200949
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400950 def passphraseCallback(maxlen, verify, extra):
951 assert maxlen == 1024
Alex Gaynore7f51982016-09-11 11:48:14 -0400952 return passphrase + b"y"
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400953
Paul Kehrer688538c2020-08-03 19:18:15 -0500954 context = Context(SSLv23_METHOD)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400955 context.set_passwd_cb(passphraseCallback)
956 # This shall succeed because the truncated result is the correct
957 # passphrase.
958 context.use_privatekey_file(pemFile)
959
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400960 def test_set_info_callback(self):
961 """
Alex Chan532b79e2017-01-24 15:14:52 +0000962 `Context.set_info_callback` accepts a callable which will be
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200963 invoked when certain information about an SSL connection is available.
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400964 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500965 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400966
Paul Kehrer688538c2020-08-03 19:18:15 -0500967 clientSSL = Connection(Context(SSLv23_METHOD), client)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400968 clientSSL.set_connect_state()
969
970 called = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200971
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400972 def info(conn, where, ret):
973 called.append((conn, where, ret))
Alex Gaynor03737182020-07-23 20:40:46 -0400974
Paul Kehrer688538c2020-08-03 19:18:15 -0500975 context = Context(SSLv23_METHOD)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400976 context.set_info_callback(info)
Paul Kehrerbeaf9f52020-08-03 17:50:31 -0500977 context.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
978 context.use_privatekey(load_privatekey(FILETYPE_PEM, root_key_pem))
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400979
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400980 serverSSL = Connection(context, server)
981 serverSSL.set_accept_state()
982
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500983 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400984
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500985 # The callback must always be called with a Connection instance as the
986 # first argument. It would probably be better to split this into
987 # separate tests for client and server side info callbacks so we could
988 # assert it is called with the right Connection instance. It would
989 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500990 notConnections = [
Alex Gaynor03737182020-07-23 20:40:46 -0400991 conn
992 for (conn, where, ret) in called
993 if not isinstance(conn, Connection)
994 ]
995 assert (
996 [] == notConnections
997 ), "Some info callback arguments were not Connection instances."
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400998
Maximilian Hilsb2bca412020-07-28 16:31:22 +0200999 @pytest.mark.skipif(
1000 not getattr(_lib, "Cryptography_HAS_KEYLOG", None),
1001 reason="SSL_CTX_set_keylog_callback unavailable",
1002 )
1003 def test_set_keylog_callback(self):
1004 """
1005 `Context.set_keylog_callback` accepts a callable which will be
1006 invoked when key material is generated or received.
1007 """
1008 called = []
1009
1010 def keylog(conn, line):
1011 called.append((conn, line))
1012
Paul Kehrer688538c2020-08-03 19:18:15 -05001013 server_context = Context(TLSv1_2_METHOD)
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001014 server_context.set_keylog_callback(keylog)
1015 server_context.use_certificate(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001016 load_certificate(FILETYPE_PEM, root_cert_pem)
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001017 )
1018 server_context.use_privatekey(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001019 load_privatekey(FILETYPE_PEM, root_key_pem)
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001020 )
1021
Paul Kehrer688538c2020-08-03 19:18:15 -05001022 client_context = Context(SSLv23_METHOD)
Maximilian Hilsb2bca412020-07-28 16:31:22 +02001023
1024 self._handshake_test(server_context, client_context)
1025
1026 assert called
1027 assert all(isinstance(conn, Connection) for conn, line in called)
1028 assert all(b"CLIENT_RANDOM" in line for conn, line in called)
1029
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001030 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04001031 """
1032 Create a client context which will verify the peer certificate and call
Alex Chan532b79e2017-01-24 15:14:52 +00001033 its `load_verify_locations` method with the given arguments.
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04001034 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04001035 """
Rick Deanb1ccd562009-07-09 23:52:39 -05001036 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001037
Paul Kehrer688538c2020-08-03 19:18:15 -05001038 clientContext = Context(SSLv23_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001039 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001040 # Require that the server certificate verify properly or the
1041 # connection will fail.
1042 clientContext.set_verify(
1043 VERIFY_PEER,
Alex Gaynor03737182020-07-23 20:40:46 -04001044 lambda conn, cert, errno, depth, preverify_ok: preverify_ok,
1045 )
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001046
1047 clientSSL = Connection(clientContext, client)
1048 clientSSL.set_connect_state()
1049
Paul Kehrer688538c2020-08-03 19:18:15 -05001050 serverContext = Context(SSLv23_METHOD)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001051 serverContext.use_certificate(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001052 load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001053 )
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001054 serverContext.use_privatekey(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001055 load_privatekey(FILETYPE_PEM, root_key_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001056 )
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001057
1058 serverSSL = Connection(serverContext, server)
1059 serverSSL.set_accept_state()
1060
Jean-Paul Calderonef8742032010-09-25 00:00:32 -04001061 # Without load_verify_locations above, the handshake
1062 # will fail:
1063 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
1064 # 'certificate verify failed')]
1065 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001066
1067 cert = clientSSL.get_peer_certificate()
Alex Gaynor03737182020-07-23 20:40:46 -04001068 assert cert.get_subject().CN == "Testing Root CA"
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001069
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001070 def _load_verify_cafile(self, cafile):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001071 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001072 Verify that if path to a file containing a certificate is passed to
Alex Chan532b79e2017-01-24 15:14:52 +00001073 `Context.load_verify_locations` for the ``cafile`` parameter, that
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001074 certificate is used as a trust root for the purposes of verifying
Alex Chan532b79e2017-01-24 15:14:52 +00001075 connections created using that `Context`.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001076 """
Alex Gaynor03737182020-07-23 20:40:46 -04001077 with open(cafile, "w") as fObj:
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001078 fObj.write(root_cert_pem.decode("ascii"))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001079
1080 self._load_verify_locations_test(cafile)
1081
Alex Chan532b79e2017-01-24 15:14:52 +00001082 def test_load_verify_bytes_cafile(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001083 """
Alex Chan532b79e2017-01-24 15:14:52 +00001084 `Context.load_verify_locations` accepts a file name as a `bytes`
1085 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001086 """
Alex Chan532b79e2017-01-24 15:14:52 +00001087 cafile = tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001088 self._load_verify_cafile(cafile)
1089
Alex Chan532b79e2017-01-24 15:14:52 +00001090 def test_load_verify_unicode_cafile(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001091 """
Alex Chan532b79e2017-01-24 15:14:52 +00001092 `Context.load_verify_locations` accepts a file name as a `unicode`
1093 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001094 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001095 self._load_verify_cafile(
Alex Chan532b79e2017-01-24 15:14:52 +00001096 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001097 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001098
Alex Chan532b79e2017-01-24 15:14:52 +00001099 def test_load_verify_invalid_file(self, tmpfile):
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001100 """
Alex Chan532b79e2017-01-24 15:14:52 +00001101 `Context.load_verify_locations` raises `Error` when passed a
1102 non-existent cafile.
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001103 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001104 clientContext = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001105 with pytest.raises(Error):
1106 clientContext.load_verify_locations(tmpfile)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001107
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001108 def _load_verify_directory_locations_capath(self, capath):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001109 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001110 Verify that if path to a directory containing certificate files is
1111 passed to ``Context.load_verify_locations`` for the ``capath``
1112 parameter, those certificates are used as trust roots for the purposes
1113 of verifying connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001114 """
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001115 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -04001116 # Hash values computed manually with c_rehash to avoid depending on
1117 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
1118 # from OpenSSL 1.0.0.
Alex Gaynor03737182020-07-23 20:40:46 -04001119 for name in [b"c7adac82.0", b"c3705638.0"]:
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001120 cafile = join_bytes_or_unicode(capath, name)
Alex Gaynor03737182020-07-23 20:40:46 -04001121 with open(cafile, "w") as fObj:
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001122 fObj.write(root_cert_pem.decode("ascii"))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001123
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001124 self._load_verify_locations_test(None, capath)
1125
Alex Chan532b79e2017-01-24 15:14:52 +00001126 def test_load_verify_directory_bytes_capath(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001127 """
Alex Chan532b79e2017-01-24 15:14:52 +00001128 `Context.load_verify_locations` accepts a directory name as a `bytes`
1129 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001130 """
1131 self._load_verify_directory_locations_capath(
Alex Chan532b79e2017-01-24 15:14:52 +00001132 tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001133 )
1134
Alex Chan532b79e2017-01-24 15:14:52 +00001135 def test_load_verify_directory_unicode_capath(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001136 """
Alex Chan532b79e2017-01-24 15:14:52 +00001137 `Context.load_verify_locations` accepts a directory name as a `unicode`
1138 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001139 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001140 self._load_verify_directory_locations_capath(
Alex Chan532b79e2017-01-24 15:14:52 +00001141 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001142 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001143
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001144 def test_load_verify_locations_wrong_args(self):
1145 """
Alex Chan532b79e2017-01-24 15:14:52 +00001146 `Context.load_verify_locations` raises `TypeError` if with non-`str`
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001147 arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001148 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001149 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001150 with pytest.raises(TypeError):
1151 context.load_verify_locations(object())
1152 with pytest.raises(TypeError):
1153 context.load_verify_locations(object(), object())
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001154
Hynek Schlawack734d3022015-09-05 19:19:32 +02001155 @pytest.mark.skipif(
Paul Kehrer55fb3412017-06-29 18:44:08 -05001156 not platform.startswith("linux"),
1157 reason="Loading fallback paths is a linux-specific behavior to "
Alex Gaynor03737182020-07-23 20:40:46 -04001158 "accommodate pyca/cryptography manylinux1 wheels",
Paul Kehrer55fb3412017-06-29 18:44:08 -05001159 )
1160 def test_fallback_default_verify_paths(self, monkeypatch):
1161 """
1162 Test that we load certificates successfully on linux from the fallback
1163 path. To do this we set the _CRYPTOGRAPHY_MANYLINUX1_CA_FILE and
1164 _CRYPTOGRAPHY_MANYLINUX1_CA_DIR vars to be equal to whatever the
1165 current OpenSSL default is and we disable
1166 SSL_CTX_SET_default_verify_paths so that it can't find certs unless
1167 it loads via fallback.
1168 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001169 context = Context(SSLv23_METHOD)
Paul Kehrer55fb3412017-06-29 18:44:08 -05001170 monkeypatch.setattr(
1171 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1172 )
1173 monkeypatch.setattr(
1174 SSL,
1175 "_CRYPTOGRAPHY_MANYLINUX1_CA_FILE",
Alex Gaynor03737182020-07-23 20:40:46 -04001176 _ffi.string(_lib.X509_get_default_cert_file()),
Paul Kehrer55fb3412017-06-29 18:44:08 -05001177 )
1178 monkeypatch.setattr(
1179 SSL,
1180 "_CRYPTOGRAPHY_MANYLINUX1_CA_DIR",
Alex Gaynor03737182020-07-23 20:40:46 -04001181 _ffi.string(_lib.X509_get_default_cert_dir()),
Paul Kehrer55fb3412017-06-29 18:44:08 -05001182 )
1183 context.set_default_verify_paths()
1184 store = context.get_cert_store()
1185 sk_obj = _lib.X509_STORE_get0_objects(store._store)
1186 assert sk_obj != _ffi.NULL
1187 num = _lib.sk_X509_OBJECT_num(sk_obj)
1188 assert num != 0
1189
1190 def test_check_env_vars(self, monkeypatch):
1191 """
1192 Test that we return True/False appropriately if the env vars are set.
1193 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001194 context = Context(SSLv23_METHOD)
Paul Kehrer55fb3412017-06-29 18:44:08 -05001195 dir_var = "CUSTOM_DIR_VAR"
1196 file_var = "CUSTOM_FILE_VAR"
1197 assert context._check_env_vars_set(dir_var, file_var) is False
1198 monkeypatch.setenv(dir_var, "value")
1199 monkeypatch.setenv(file_var, "value")
1200 assert context._check_env_vars_set(dir_var, file_var) is True
1201 assert context._check_env_vars_set(dir_var, file_var) is True
1202
1203 def test_verify_no_fallback_if_env_vars_set(self, monkeypatch):
1204 """
1205 Test that we don't use the fallback path if env vars are set.
1206 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001207 context = Context(SSLv23_METHOD)
Paul Kehrer55fb3412017-06-29 18:44:08 -05001208 monkeypatch.setattr(
1209 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1210 )
Alex Gaynor03737182020-07-23 20:40:46 -04001211 dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
1212 "ascii"
1213 )
Paul Kehrer55fb3412017-06-29 18:44:08 -05001214 file_env_var = _ffi.string(
1215 _lib.X509_get_default_cert_file_env()
1216 ).decode("ascii")
1217 monkeypatch.setenv(dir_env_var, "value")
1218 monkeypatch.setenv(file_env_var, "value")
1219 context.set_default_verify_paths()
1220
1221 monkeypatch.setattr(
Alex Gaynor03737182020-07-23 20:40:46 -04001222 context, "_fallback_default_verify_paths", raiser(SystemError)
Paul Kehrer55fb3412017-06-29 18:44:08 -05001223 )
1224 context.set_default_verify_paths()
1225
1226 @pytest.mark.skipif(
Hynek Schlawack734d3022015-09-05 19:19:32 +02001227 platform == "win32",
1228 reason="set_default_verify_paths appears not to work on Windows. "
Alex Gaynor03737182020-07-23 20:40:46 -04001229 "See LP#404343 and LP#404344.",
Hynek Schlawack734d3022015-09-05 19:19:32 +02001230 )
1231 def test_set_default_verify_paths(self):
1232 """
Alex Chan532b79e2017-01-24 15:14:52 +00001233 `Context.set_default_verify_paths` causes the platform-specific CA
1234 certificate locations to be used for verification purposes.
Hynek Schlawack734d3022015-09-05 19:19:32 +02001235 """
1236 # Testing this requires a server with a certificate signed by one
1237 # of the CAs in the platform CA location. Getting one of those
1238 # costs money. Fortunately (or unfortunately, depending on your
1239 # perspective), it's easy to think of a public server on the
1240 # internet which has such a certificate. Connecting to the network
1241 # in a unit test is bad, but it's the only way I can think of to
1242 # really test this. -exarkun
Hynek Schlawackbf887932015-10-21 17:13:47 +02001243 context = Context(SSLv23_METHOD)
Hynek Schlawack734d3022015-09-05 19:19:32 +02001244 context.set_default_verify_paths()
1245 context.set_verify(
1246 VERIFY_PEER,
Alex Gaynor03737182020-07-23 20:40:46 -04001247 lambda conn, cert, errno, depth, preverify_ok: preverify_ok,
1248 )
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001249
David Benjamin1fbe0642019-04-15 17:05:13 -05001250 client = socket_any_family()
Hynek Schlawackbf887932015-10-21 17:13:47 +02001251 client.connect(("encrypted.google.com", 443))
Hynek Schlawack734d3022015-09-05 19:19:32 +02001252 clientSSL = Connection(context, client)
1253 clientSSL.set_connect_state()
Alex Gaynor373926c2018-05-12 07:43:07 -04001254 clientSSL.set_tlsext_host_name(b"encrypted.google.com")
Hynek Schlawack734d3022015-09-05 19:19:32 +02001255 clientSSL.do_handshake()
1256 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Alex Chan532b79e2017-01-24 15:14:52 +00001257 assert clientSSL.recv(1024)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001258
Paul Kehrer55fb3412017-06-29 18:44:08 -05001259 def test_fallback_path_is_not_file_or_dir(self):
1260 """
1261 Test that when passed empty arrays or paths that do not exist no
1262 errors are raised.
1263 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001264 context = Context(SSLv23_METHOD)
Paul Kehrer55fb3412017-06-29 18:44:08 -05001265 context._fallback_default_verify_paths([], [])
Alex Gaynor03737182020-07-23 20:40:46 -04001266 context._fallback_default_verify_paths(["/not/a/file"], ["/not/a/dir"])
Paul Kehrer55fb3412017-06-29 18:44:08 -05001267
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001268 def test_add_extra_chain_cert_invalid_cert(self):
1269 """
Alex Chan532b79e2017-01-24 15:14:52 +00001270 `Context.add_extra_chain_cert` raises `TypeError` if called with an
1271 object which is not an instance of `X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001272 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001273 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001274 with pytest.raises(TypeError):
1275 context.add_extra_chain_cert(object())
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001276
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001277 def _handshake_test(self, serverContext, clientContext):
1278 """
1279 Verify that a client and server created with the given contexts can
1280 successfully handshake and communicate.
1281 """
1282 serverSocket, clientSocket = socket_pair()
1283
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001284 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001285 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001286
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001287 client = Connection(clientContext, clientSocket)
1288 client.set_connect_state()
1289
1290 # Make them talk to each other.
Alex Chan532b79e2017-01-24 15:14:52 +00001291 # interact_in_memory(client, server)
1292 for _ in range(3):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001293 for s in [client, server]:
1294 try:
1295 s.do_handshake()
1296 except WantReadError:
1297 pass
1298
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001299 def test_set_verify_callback_connection_argument(self):
1300 """
1301 The first argument passed to the verify callback is the
Alex Chan532b79e2017-01-24 15:14:52 +00001302 `Connection` instance for which verification is taking place.
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001303 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001304 serverContext = Context(SSLv23_METHOD)
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001305 serverContext.use_privatekey(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001306 load_privatekey(FILETYPE_PEM, root_key_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001307 )
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001308 serverContext.use_certificate(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001309 load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001310 )
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001311 serverConnection = Connection(serverContext, None)
1312
1313 class VerifyCallback(object):
1314 def callback(self, connection, *args):
1315 self.connection = connection
1316 return 1
1317
1318 verify = VerifyCallback()
Paul Kehrer688538c2020-08-03 19:18:15 -05001319 clientContext = Context(SSLv23_METHOD)
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001320 clientContext.set_verify(VERIFY_PEER, verify.callback)
1321 clientConnection = Connection(clientContext, None)
1322 clientConnection.set_connect_state()
1323
Alex Chan532b79e2017-01-24 15:14:52 +00001324 handshake_in_memory(clientConnection, serverConnection)
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001325
Alex Chan532b79e2017-01-24 15:14:52 +00001326 assert verify.connection is clientConnection
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001327
Paul Kehrere7381862017-11-30 20:55:25 +08001328 def test_x509_in_verify_works(self):
1329 """
1330 We had a bug where the X509 cert instantiated in the callback wrapper
1331 didn't __init__ so it was missing objects needed when calling
1332 get_subject. This test sets up a handshake where we call get_subject
1333 on the cert provided to the verify callback.
1334 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001335 serverContext = Context(SSLv23_METHOD)
Paul Kehrere7381862017-11-30 20:55:25 +08001336 serverContext.use_privatekey(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001337 load_privatekey(FILETYPE_PEM, root_key_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001338 )
Paul Kehrere7381862017-11-30 20:55:25 +08001339 serverContext.use_certificate(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001340 load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001341 )
Paul Kehrere7381862017-11-30 20:55:25 +08001342 serverConnection = Connection(serverContext, None)
1343
1344 def verify_cb_get_subject(conn, cert, errnum, depth, ok):
1345 assert cert.get_subject()
1346 return 1
1347
Paul Kehrer688538c2020-08-03 19:18:15 -05001348 clientContext = Context(SSLv23_METHOD)
Paul Kehrere7381862017-11-30 20:55:25 +08001349 clientContext.set_verify(VERIFY_PEER, verify_cb_get_subject)
1350 clientConnection = Connection(clientContext, None)
1351 clientConnection.set_connect_state()
1352
1353 handshake_in_memory(clientConnection, serverConnection)
1354
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001355 def test_set_verify_callback_exception(self):
1356 """
Alex Chan532b79e2017-01-24 15:14:52 +00001357 If the verify callback passed to `Context.set_verify` raises an
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001358 exception, verification fails and the exception is propagated to the
Alex Chan532b79e2017-01-24 15:14:52 +00001359 caller of `Connection.do_handshake`.
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001360 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001361 serverContext = Context(TLSv1_2_METHOD)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001362 serverContext.use_privatekey(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001363 load_privatekey(FILETYPE_PEM, root_key_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001364 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001365 serverContext.use_certificate(
Paul Kehrerbeaf9f52020-08-03 17:50:31 -05001366 load_certificate(FILETYPE_PEM, root_cert_pem)
Alex Gaynor03737182020-07-23 20:40:46 -04001367 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001368
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06001369 clientContext = Context(TLSv1_2_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001370
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001371 def verify_callback(*args):
1372 raise Exception("silly verify failure")
Alex Gaynor03737182020-07-23 20:40:46 -04001373
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001374 clientContext.set_verify(VERIFY_PEER, verify_callback)
1375
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001376 with pytest.raises(Exception) as exc:
1377 self._handshake_test(serverContext, clientContext)
1378
Alex Chan532b79e2017-01-24 15:14:52 +00001379 assert "silly verify failure" == str(exc.value)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001380
Alex Chan532b79e2017-01-24 15:14:52 +00001381 def test_add_extra_chain_cert(self, tmpdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001382 """
Alex Chan532b79e2017-01-24 15:14:52 +00001383 `Context.add_extra_chain_cert` accepts an `X509`
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001384 instance to add to the certificate chain.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001385
Alex Chan532b79e2017-01-24 15:14:52 +00001386 See `_create_certificate_chain` for the details of the
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001387 certificate chain tested.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001388
1389 The chain is tested by starting a server with scert and connecting
1390 to it with a client which trusts cacert and requires verification to
1391 succeed.
1392 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001393 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001394 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1395
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001396 # Dump the CA certificate to a file because that's the only way to load
1397 # it as a trusted CA in the client context.
Alex Gaynor03737182020-07-23 20:40:46 -04001398 for cert, name in [
1399 (cacert, "ca.pem"),
1400 (icert, "i.pem"),
1401 (scert, "s.pem"),
1402 ]:
1403 with tmpdir.join(name).open("w") as f:
1404 f.write(dump_certificate(FILETYPE_PEM, cert).decode("ascii"))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001405
Alex Gaynor03737182020-07-23 20:40:46 -04001406 for key, name in [(cakey, "ca.key"), (ikey, "i.key"), (skey, "s.key")]:
1407 with tmpdir.join(name).open("w") as f:
1408 f.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001409
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001410 # Create the server context
Paul Kehrer688538c2020-08-03 19:18:15 -05001411 serverContext = Context(SSLv23_METHOD)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001412 serverContext.use_privatekey(skey)
1413 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001414 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001415 serverContext.add_extra_chain_cert(icert)
1416
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001417 # Create the client
Paul Kehrer688538c2020-08-03 19:18:15 -05001418 clientContext = Context(SSLv23_METHOD)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001419 clientContext.set_verify(
Alex Gaynor03737182020-07-23 20:40:46 -04001420 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
1421 )
Alex Chan532b79e2017-01-24 15:14:52 +00001422 clientContext.load_verify_locations(str(tmpdir.join("ca.pem")))
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001423
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001424 # Try it out.
1425 self._handshake_test(serverContext, clientContext)
1426
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001427 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001428 """
Alex Chan532b79e2017-01-24 15:14:52 +00001429 Verify that `Context.use_certificate_chain_file` reads a
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001430 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001431
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001432 The chain is tested by starting a server with scert and connecting to
1433 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001434 succeed.
1435 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001436 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001437 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1438
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001439 makedirs(certdir)
1440
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001441 chainFile = join_bytes_or_unicode(certdir, "chain.pem")
1442 caFile = join_bytes_or_unicode(certdir, "ca.pem")
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001443
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001444 # Write out the chain file.
Alex Gaynor03737182020-07-23 20:40:46 -04001445 with open(chainFile, "wb") as fObj:
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001446 # Most specific to least general.
1447 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1448 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1449 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1450
Alex Gaynor03737182020-07-23 20:40:46 -04001451 with open(caFile, "w") as fObj:
1452 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode("ascii"))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001453
Paul Kehrer688538c2020-08-03 19:18:15 -05001454 serverContext = Context(SSLv23_METHOD)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001455 serverContext.use_certificate_chain_file(chainFile)
1456 serverContext.use_privatekey(skey)
1457
Paul Kehrer688538c2020-08-03 19:18:15 -05001458 clientContext = Context(SSLv23_METHOD)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001459 clientContext.set_verify(
Alex Gaynor03737182020-07-23 20:40:46 -04001460 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
1461 )
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001462 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001463
1464 self._handshake_test(serverContext, clientContext)
1465
Alex Chan532b79e2017-01-24 15:14:52 +00001466 def test_use_certificate_chain_file_bytes(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001467 """
1468 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1469 an instance of ``bytes``) to specify additional certificates to use to
1470 construct and verify a trust chain.
1471 """
1472 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001473 tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001474 )
1475
Alex Chan532b79e2017-01-24 15:14:52 +00001476 def test_use_certificate_chain_file_unicode(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001477 """
1478 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1479 an instance of ``unicode``) to specify additional certificates to use
1480 to construct and verify a trust chain.
1481 """
1482 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001483 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001484 )
1485
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001486 def test_use_certificate_chain_file_wrong_args(self):
1487 """
Alex Chan532b79e2017-01-24 15:14:52 +00001488 `Context.use_certificate_chain_file` raises `TypeError` if passed a
1489 non-byte string single argument.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001490 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001491 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001492 with pytest.raises(TypeError):
1493 context.use_certificate_chain_file(object())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494
Alex Chan532b79e2017-01-24 15:14:52 +00001495 def test_use_certificate_chain_file_missing_file(self, tmpfile):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001496 """
Alex Chan532b79e2017-01-24 15:14:52 +00001497 `Context.use_certificate_chain_file` raises `OpenSSL.SSL.Error` when
1498 passed a bad chain file name (for example, the name of a file which
1499 does not exist).
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001500 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001501 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001502 with pytest.raises(Error):
1503 context.use_certificate_chain_file(tmpfile)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001504
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001505 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001506 """
Alex Chan532b79e2017-01-24 15:14:52 +00001507 `Context.get_verify_mode` returns the verify mode flags previously
1508 passed to `Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001509 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001510 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001511 assert context.get_verify_mode() == 0
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001512 context.set_verify(
Alex Gaynor03737182020-07-23 20:40:46 -04001513 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None
1514 )
Alex Chan532b79e2017-01-24 15:14:52 +00001515 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001516
Alex Gaynor03737182020-07-23 20:40:46 -04001517 @pytest.mark.parametrize("mode", [None, 1.0, object(), "mode"])
Alex Chanfb078d82017-04-20 11:16:15 +01001518 def test_set_verify_wrong_mode_arg(self, mode):
1519 """
1520 `Context.set_verify` raises `TypeError` if the first argument is
1521 not an integer.
1522 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001523 context = Context(SSLv23_METHOD)
Alex Chanfb078d82017-04-20 11:16:15 +01001524 with pytest.raises(TypeError):
1525 context.set_verify(mode=mode, callback=lambda *args: None)
1526
Alex Gaynor03737182020-07-23 20:40:46 -04001527 @pytest.mark.parametrize("callback", [None, 1.0, "mode", ("foo", "bar")])
Alex Chanfb078d82017-04-20 11:16:15 +01001528 def test_set_verify_wrong_callable_arg(self, callback):
1529 """
Alex Gaynor40bc0f12018-05-14 14:06:16 -04001530 `Context.set_verify` raises `TypeError` if the second argument
Alex Chanfb078d82017-04-20 11:16:15 +01001531 is not callable.
1532 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001533 context = Context(SSLv23_METHOD)
Alex Chanfb078d82017-04-20 11:16:15 +01001534 with pytest.raises(TypeError):
1535 context.set_verify(mode=VERIFY_PEER, callback=callback)
1536
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001537 def test_load_tmp_dh_wrong_args(self):
1538 """
Alex Chan532b79e2017-01-24 15:14:52 +00001539 `Context.load_tmp_dh` raises `TypeError` if called with a
1540 non-`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001541 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001542 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001543 with pytest.raises(TypeError):
1544 context.load_tmp_dh(object())
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001545
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001546 def test_load_tmp_dh_missing_file(self):
1547 """
Alex Chan532b79e2017-01-24 15:14:52 +00001548 `Context.load_tmp_dh` raises `OpenSSL.SSL.Error` if the
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001549 specified file does not exist.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001550 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001551 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001552 with pytest.raises(Error):
1553 context.load_tmp_dh(b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001554
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001555 def _load_tmp_dh_test(self, dhfilename):
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001556 """
1557 Verify that calling ``Context.load_tmp_dh`` with the given filename
1558 does not raise an exception.
1559 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001560 context = Context(SSLv23_METHOD)
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001561 with open(dhfilename, "w") as dhfile:
1562 dhfile.write(dhparam)
1563
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001564 context.load_tmp_dh(dhfilename)
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001565
Alex Chan532b79e2017-01-24 15:14:52 +00001566 def test_load_tmp_dh_bytes(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001567 """
Alex Chan532b79e2017-01-24 15:14:52 +00001568 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001569 specified file (given as ``bytes``).
1570 """
1571 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001572 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001573 )
1574
Alex Chan532b79e2017-01-24 15:14:52 +00001575 def test_load_tmp_dh_unicode(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001576 """
Alex Chan532b79e2017-01-24 15:14:52 +00001577 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001578 specified file (given as ``unicode``).
1579 """
1580 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001581 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001582 )
1583
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001584 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001585 """
Alex Chan532b79e2017-01-24 15:14:52 +00001586 `Context.set_tmp_ecdh` sets the elliptic curve for Diffie-Hellman to
1587 the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001588 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001589 context = Context(SSLv23_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001590 for curve in get_elliptic_curves():
Hynek Schlawacka07fa8c2015-10-17 10:15:28 +02001591 if curve.name.startswith(u"Oakley-"):
Hynek Schlawack7408aff2015-10-17 09:51:16 +02001592 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1593 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1594 # error queue on OpenSSL 1.0.2.
1595 continue
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001596 # The only easily "assertable" thing is that it does not raise an
1597 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001598 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001599
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001600 def test_set_session_cache_mode_wrong_args(self):
1601 """
Alex Chan532b79e2017-01-24 15:14:52 +00001602 `Context.set_session_cache_mode` raises `TypeError` if called with
1603 a non-integer argument.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001604 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001605 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001606 context = Context(SSLv23_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001607 with pytest.raises(TypeError):
1608 context.set_session_cache_mode(object())
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001609
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001610 def test_session_cache_mode(self):
1611 """
Alex Chan532b79e2017-01-24 15:14:52 +00001612 `Context.set_session_cache_mode` specifies how sessions are cached.
1613 The setting can be retrieved via `Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001614 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001615 context = Context(SSLv23_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001616 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001617 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
Alex Chan532b79e2017-01-24 15:14:52 +00001618 assert SESS_CACHE_OFF == off
1619 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001620
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001621 def test_get_cert_store(self):
1622 """
Alex Chan532b79e2017-01-24 15:14:52 +00001623 `Context.get_cert_store` returns a `X509Store` instance.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001624 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001625 context = Context(SSLv23_METHOD)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001626 store = context.get_cert_store()
Alex Chan532b79e2017-01-24 15:14:52 +00001627 assert isinstance(store, X509Store)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001628
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001629 def test_set_tlsext_use_srtp_not_bytes(self):
1630 """
1631 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1632
1633 It raises a TypeError if the list of profiles is not a byte string.
1634 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001635 context = Context(SSLv23_METHOD)
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001636 with pytest.raises(TypeError):
Alex Gaynor03737182020-07-23 20:40:46 -04001637 context.set_tlsext_use_srtp(text_type("SRTP_AES128_CM_SHA1_80"))
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001638
1639 def test_set_tlsext_use_srtp_invalid_profile(self):
1640 """
1641 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1642
1643 It raises an Error if the call to OpenSSL fails.
1644 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001645 context = Context(SSLv23_METHOD)
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001646 with pytest.raises(Error):
Alex Gaynor03737182020-07-23 20:40:46 -04001647 context.set_tlsext_use_srtp(b"SRTP_BOGUS")
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001648
1649 def test_set_tlsext_use_srtp_valid(self):
1650 """
1651 `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
1652
1653 It does not return anything.
1654 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001655 context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001656 assert context.set_tlsext_use_srtp(b"SRTP_AES128_CM_SHA1_80") is None
Jeremy Lainé02261ad2018-05-16 18:33:25 +02001657
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001659class TestServerNameCallback(object):
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001660 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001661 Tests for `Context.set_tlsext_servername_callback` and its
1662 interaction with `Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001663 """
Alex Gaynor03737182020-07-23 20:40:46 -04001664
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001665 def test_old_callback_forgotten(self):
1666 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001667 If `Context.set_tlsext_servername_callback` is used to specify
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001668 a new callback, the one it replaces is dereferenced.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001669 """
Alex Gaynor03737182020-07-23 20:40:46 -04001670
Alex Chanfb078d82017-04-20 11:16:15 +01001671 def callback(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001672 pass
1673
Alex Chanfb078d82017-04-20 11:16:15 +01001674 def replacement(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001675 pass
1676
Paul Kehrer688538c2020-08-03 19:18:15 -05001677 context = Context(SSLv23_METHOD)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001678 context.set_tlsext_servername_callback(callback)
1679
1680 tracker = ref(callback)
1681 del callback
1682
1683 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001684
1685 # One run of the garbage collector happens to work on CPython. PyPy
1686 # doesn't collect the underlying object until a second run for whatever
1687 # reason. That's fine, it still demonstrates our code has properly
1688 # dropped the reference.
1689 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001690 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001691
1692 callback = tracker()
1693 if callback is not None:
1694 referrers = get_referrers(callback)
Alex Chanfb078d82017-04-20 11:16:15 +01001695 if len(referrers) > 1: # pragma: nocover
1696 pytest.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001697
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001698 def test_no_servername(self):
1699 """
1700 When a client specifies no server name, the callback passed to
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001701 `Context.set_tlsext_servername_callback` is invoked and the
1702 result of `Connection.get_servername` is `None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001703 """
1704 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001705
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001706 def servername(conn):
1707 args.append((conn, conn.get_servername()))
Alex Gaynor03737182020-07-23 20:40:46 -04001708
Paul Kehrer688538c2020-08-03 19:18:15 -05001709 context = Context(SSLv23_METHOD)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001710 context.set_tlsext_servername_callback(servername)
1711
1712 # Lose our reference to it. The Context is responsible for keeping it
1713 # alive now.
1714 del servername
1715 collect()
1716
1717 # Necessary to actually accept the connection
1718 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001719 context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001720 load_certificate(FILETYPE_PEM, server_cert_pem)
1721 )
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001722
1723 # Do a little connection to trigger the logic
1724 server = Connection(context, None)
1725 server.set_accept_state()
1726
Paul Kehrer688538c2020-08-03 19:18:15 -05001727 client = Connection(Context(SSLv23_METHOD), None)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001728 client.set_connect_state()
1729
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001730 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001731
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001732 assert args == [(server, None)]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001733
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001734 def test_servername(self):
1735 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001736 When a client specifies a server name in its hello message, the
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001737 callback passed to `Contexts.set_tlsext_servername_callback` is
1738 invoked and the result of `Connection.get_servername` is that
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001739 server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001740 """
1741 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001742
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001743 def servername(conn):
1744 args.append((conn, conn.get_servername()))
Alex Gaynor03737182020-07-23 20:40:46 -04001745
Paul Kehrer688538c2020-08-03 19:18:15 -05001746 context = Context(SSLv23_METHOD)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001747 context.set_tlsext_servername_callback(servername)
1748
1749 # Necessary to actually accept the connection
1750 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001751 context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001752 load_certificate(FILETYPE_PEM, server_cert_pem)
1753 )
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001754
1755 # Do a little connection to trigger the logic
1756 server = Connection(context, None)
1757 server.set_accept_state()
1758
Paul Kehrer688538c2020-08-03 19:18:15 -05001759 client = Connection(Context(SSLv23_METHOD), None)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001760 client.set_connect_state()
Alex Gaynore7f51982016-09-11 11:48:14 -04001761 client.set_tlsext_host_name(b"foo1.example.com")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001762
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001763 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001764
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001765 assert args == [(server, b"foo1.example.com")]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001766
1767
Alex Chanec1e32d2016-11-10 14:11:45 +00001768class TestApplicationLayerProtoNegotiation(object):
Cory Benfield12eae892014-06-07 15:42:56 +01001769 """
1770 Tests for ALPN in PyOpenSSL.
1771 """
Alex Gaynor03737182020-07-23 20:40:46 -04001772
Alex Gaynor77debda2020-04-07 13:40:59 -04001773 def test_alpn_success(self):
1774 """
1775 Clients and servers that agree on the negotiated ALPN protocol can
1776 correct establish a connection, and the agreed protocol is reported
1777 by the connections.
1778 """
1779 select_args = []
Cory Benfield12eae892014-06-07 15:42:56 +01001780
Alex Gaynor77debda2020-04-07 13:40:59 -04001781 def select(conn, options):
1782 select_args.append((conn, options))
Alex Gaynor03737182020-07-23 20:40:46 -04001783 return b"spdy/2"
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001784
Paul Kehrer688538c2020-08-03 19:18:15 -05001785 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001786 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Cory Benfield12eae892014-06-07 15:42:56 +01001787
Paul Kehrer688538c2020-08-03 19:18:15 -05001788 server_context = Context(SSLv23_METHOD)
Alex Gaynor77debda2020-04-07 13:40:59 -04001789 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001790
Alex Gaynor77debda2020-04-07 13:40:59 -04001791 # Necessary to actually accept the connection
1792 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001793 load_privatekey(FILETYPE_PEM, server_key_pem)
1794 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001795 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001796 load_certificate(FILETYPE_PEM, server_cert_pem)
1797 )
Cory Benfield12eae892014-06-07 15:42:56 +01001798
Alex Gaynor77debda2020-04-07 13:40:59 -04001799 # Do a little connection to trigger the logic
1800 server = Connection(server_context, None)
1801 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001802
Alex Gaynor77debda2020-04-07 13:40:59 -04001803 client = Connection(client_context, None)
1804 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001805
Alex Gaynor77debda2020-04-07 13:40:59 -04001806 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001807
Alex Gaynor03737182020-07-23 20:40:46 -04001808 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
Alex Gaynor77debda2020-04-07 13:40:59 -04001809
Alex Gaynor03737182020-07-23 20:40:46 -04001810 assert server.get_alpn_proto_negotiated() == b"spdy/2"
1811 assert client.get_alpn_proto_negotiated() == b"spdy/2"
Alex Gaynor77debda2020-04-07 13:40:59 -04001812
1813 def test_alpn_set_on_connection(self):
1814 """
1815 The same as test_alpn_success, but setting the ALPN protocols on
1816 the connection rather than the context.
1817 """
1818 select_args = []
1819
1820 def select(conn, options):
1821 select_args.append((conn, options))
Alex Gaynor03737182020-07-23 20:40:46 -04001822 return b"spdy/2"
Alex Gaynor77debda2020-04-07 13:40:59 -04001823
1824 # Setup the client context but don't set any ALPN protocols.
Paul Kehrer688538c2020-08-03 19:18:15 -05001825 client_context = Context(SSLv23_METHOD)
Alex Gaynor77debda2020-04-07 13:40:59 -04001826
Paul Kehrer688538c2020-08-03 19:18:15 -05001827 server_context = Context(SSLv23_METHOD)
Alex Gaynor77debda2020-04-07 13:40:59 -04001828 server_context.set_alpn_select_callback(select)
1829
1830 # Necessary to actually accept the connection
1831 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001832 load_privatekey(FILETYPE_PEM, server_key_pem)
1833 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001834 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001835 load_certificate(FILETYPE_PEM, server_cert_pem)
1836 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001837
1838 # Do a little connection to trigger the logic
1839 server = Connection(server_context, None)
1840 server.set_accept_state()
1841
1842 # Set the ALPN protocols on the client connection.
1843 client = Connection(client_context, None)
Alex Gaynor03737182020-07-23 20:40:46 -04001844 client.set_alpn_protos([b"http/1.1", b"spdy/2"])
Alex Gaynor77debda2020-04-07 13:40:59 -04001845 client.set_connect_state()
1846
1847 interact_in_memory(server, client)
1848
Alex Gaynor03737182020-07-23 20:40:46 -04001849 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
Alex Gaynor77debda2020-04-07 13:40:59 -04001850
Alex Gaynor03737182020-07-23 20:40:46 -04001851 assert server.get_alpn_proto_negotiated() == b"spdy/2"
1852 assert client.get_alpn_proto_negotiated() == b"spdy/2"
Alex Gaynor77debda2020-04-07 13:40:59 -04001853
1854 def test_alpn_server_fail(self):
1855 """
1856 When clients and servers cannot agree on what protocol to use next
1857 the TLS connection does not get established.
1858 """
1859 select_args = []
1860
1861 def select(conn, options):
1862 select_args.append((conn, options))
Alex Gaynor03737182020-07-23 20:40:46 -04001863 return b""
Alex Gaynor77debda2020-04-07 13:40:59 -04001864
Paul Kehrer688538c2020-08-03 19:18:15 -05001865 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001866 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Alex Gaynor77debda2020-04-07 13:40:59 -04001867
Paul Kehrer688538c2020-08-03 19:18:15 -05001868 server_context = Context(SSLv23_METHOD)
Alex Gaynor77debda2020-04-07 13:40:59 -04001869 server_context.set_alpn_select_callback(select)
1870
1871 # Necessary to actually accept the connection
1872 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001873 load_privatekey(FILETYPE_PEM, server_key_pem)
1874 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001875 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001876 load_certificate(FILETYPE_PEM, server_cert_pem)
1877 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001878
1879 # Do a little connection to trigger the logic
1880 server = Connection(server_context, None)
1881 server.set_accept_state()
1882
1883 client = Connection(client_context, None)
1884 client.set_connect_state()
1885
1886 # If the client doesn't return anything, the connection will fail.
1887 with pytest.raises(Error):
Alex Chanec1e32d2016-11-10 14:11:45 +00001888 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001889
Alex Gaynor03737182020-07-23 20:40:46 -04001890 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
Cory Benfielde46fa842015-04-13 16:50:49 -04001891
Alex Gaynor77debda2020-04-07 13:40:59 -04001892 def test_alpn_no_server_overlap(self):
1893 """
1894 A server can allow a TLS handshake to complete without
1895 agreeing to an application protocol by returning
1896 ``NO_OVERLAPPING_PROTOCOLS``.
1897 """
1898 refusal_args = []
Cory Benfield12eae892014-06-07 15:42:56 +01001899
Alex Gaynor77debda2020-04-07 13:40:59 -04001900 def refusal(conn, options):
1901 refusal_args.append((conn, options))
1902 return NO_OVERLAPPING_PROTOCOLS
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001903
Alex Gaynor77debda2020-04-07 13:40:59 -04001904 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001905 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Cory Benfield12eae892014-06-07 15:42:56 +01001906
Alex Gaynor77debda2020-04-07 13:40:59 -04001907 server_context = Context(SSLv23_METHOD)
1908 server_context.set_alpn_select_callback(refusal)
Cory Benfield12eae892014-06-07 15:42:56 +01001909
Alex Gaynor77debda2020-04-07 13:40:59 -04001910 # Necessary to actually accept the connection
1911 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001912 load_privatekey(FILETYPE_PEM, server_key_pem)
1913 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001914 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001915 load_certificate(FILETYPE_PEM, server_cert_pem)
1916 )
Cory Benfield12eae892014-06-07 15:42:56 +01001917
Alex Gaynor77debda2020-04-07 13:40:59 -04001918 # Do a little connection to trigger the logic
1919 server = Connection(server_context, None)
1920 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001921
Alex Gaynor77debda2020-04-07 13:40:59 -04001922 client = Connection(client_context, None)
1923 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001924
Alex Gaynor77debda2020-04-07 13:40:59 -04001925 # Do the dance.
1926 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001927
Alex Gaynor03737182020-07-23 20:40:46 -04001928 assert refusal_args == [(server, [b"http/1.1", b"spdy/2"])]
Alex Gaynor77debda2020-04-07 13:40:59 -04001929
Alex Gaynor03737182020-07-23 20:40:46 -04001930 assert client.get_alpn_proto_negotiated() == b""
Alex Gaynor77debda2020-04-07 13:40:59 -04001931
1932 def test_alpn_select_cb_returns_invalid_value(self):
1933 """
1934 If the ALPN selection callback returns anything other than
1935 a bytestring or ``NO_OVERLAPPING_PROTOCOLS``, a
1936 :py:exc:`TypeError` is raised.
1937 """
1938 invalid_cb_args = []
1939
1940 def invalid_cb(conn, options):
1941 invalid_cb_args.append((conn, options))
1942 return u"can't return unicode"
1943
1944 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001945 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Alex Gaynor77debda2020-04-07 13:40:59 -04001946
1947 server_context = Context(SSLv23_METHOD)
1948 server_context.set_alpn_select_callback(invalid_cb)
1949
1950 # Necessary to actually accept the connection
1951 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001952 load_privatekey(FILETYPE_PEM, server_key_pem)
1953 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001954 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001955 load_certificate(FILETYPE_PEM, server_cert_pem)
1956 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001957
1958 # Do a little connection to trigger the logic
1959 server = Connection(server_context, None)
1960 server.set_accept_state()
1961
1962 client = Connection(client_context, None)
1963 client.set_connect_state()
1964
1965 # Do the dance.
1966 with pytest.raises(TypeError):
Alex Chanec1e32d2016-11-10 14:11:45 +00001967 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001968
Alex Gaynor03737182020-07-23 20:40:46 -04001969 assert invalid_cb_args == [(server, [b"http/1.1", b"spdy/2"])]
Cory Benfield12eae892014-06-07 15:42:56 +01001970
Alex Gaynor03737182020-07-23 20:40:46 -04001971 assert client.get_alpn_proto_negotiated() == b""
Cory Benfield12eae892014-06-07 15:42:56 +01001972
Alex Gaynor77debda2020-04-07 13:40:59 -04001973 def test_alpn_no_server(self):
1974 """
1975 When clients and servers cannot agree on what protocol to use next
1976 because the server doesn't offer ALPN, no protocol is negotiated.
1977 """
Paul Kehrer688538c2020-08-03 19:18:15 -05001978 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04001979 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001980
Paul Kehrer688538c2020-08-03 19:18:15 -05001981 server_context = Context(SSLv23_METHOD)
Cory Benfield12eae892014-06-07 15:42:56 +01001982
Alex Gaynor77debda2020-04-07 13:40:59 -04001983 # Necessary to actually accept the connection
1984 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04001985 load_privatekey(FILETYPE_PEM, server_key_pem)
1986 )
Alex Gaynor77debda2020-04-07 13:40:59 -04001987 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04001988 load_certificate(FILETYPE_PEM, server_cert_pem)
1989 )
Cory Benfield12eae892014-06-07 15:42:56 +01001990
Alex Gaynor77debda2020-04-07 13:40:59 -04001991 # Do a little connection to trigger the logic
1992 server = Connection(server_context, None)
1993 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001994
Alex Gaynor77debda2020-04-07 13:40:59 -04001995 client = Connection(client_context, None)
1996 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001997
Alex Gaynor77debda2020-04-07 13:40:59 -04001998 # Do the dance.
1999 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01002000
Alex Gaynor03737182020-07-23 20:40:46 -04002001 assert client.get_alpn_proto_negotiated() == b""
Cory Benfield12eae892014-06-07 15:42:56 +01002002
Alex Gaynor77debda2020-04-07 13:40:59 -04002003 def test_alpn_callback_exception(self):
2004 """
2005 We can handle exceptions in the ALPN select callback.
2006 """
2007 select_args = []
Cory Benfield12eae892014-06-07 15:42:56 +01002008
Alex Gaynor77debda2020-04-07 13:40:59 -04002009 def select(conn, options):
2010 select_args.append((conn, options))
2011 raise TypeError()
Cory Benfield12eae892014-06-07 15:42:56 +01002012
Paul Kehrer688538c2020-08-03 19:18:15 -05002013 client_context = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04002014 client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
Mark Williams5d890a02019-11-17 19:56:26 -08002015
Paul Kehrer688538c2020-08-03 19:18:15 -05002016 server_context = Context(SSLv23_METHOD)
Alex Gaynor77debda2020-04-07 13:40:59 -04002017 server_context.set_alpn_select_callback(select)
Mark Williams5d890a02019-11-17 19:56:26 -08002018
Alex Gaynor77debda2020-04-07 13:40:59 -04002019 # Necessary to actually accept the connection
2020 server_context.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04002021 load_privatekey(FILETYPE_PEM, server_key_pem)
2022 )
Alex Gaynor77debda2020-04-07 13:40:59 -04002023 server_context.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04002024 load_certificate(FILETYPE_PEM, server_cert_pem)
2025 )
Mark Williams5d890a02019-11-17 19:56:26 -08002026
Alex Gaynor77debda2020-04-07 13:40:59 -04002027 # Do a little connection to trigger the logic
2028 server = Connection(server_context, None)
2029 server.set_accept_state()
Mark Williams5d890a02019-11-17 19:56:26 -08002030
Alex Gaynor77debda2020-04-07 13:40:59 -04002031 client = Connection(client_context, None)
2032 client.set_connect_state()
Mark Williams5d890a02019-11-17 19:56:26 -08002033
Alex Gaynor77debda2020-04-07 13:40:59 -04002034 with pytest.raises(TypeError):
Mark Williams5d890a02019-11-17 19:56:26 -08002035 interact_in_memory(server, client)
Alex Gaynor03737182020-07-23 20:40:46 -04002036 assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002037
Cory Benfieldf1177e72015-04-12 09:11:49 -04002038
Alex Chanec1e32d2016-11-10 14:11:45 +00002039class TestSession(object):
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002040 """
2041 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2042 """
Alex Gaynor03737182020-07-23 20:40:46 -04002043
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002044 def test_construction(self):
2045 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002046 :py:class:`Session` can be constructed with no arguments, creating
2047 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002048 """
2049 new_session = Session()
Alex Chanec1e32d2016-11-10 14:11:45 +00002050 assert isinstance(new_session, Session)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002051
2052
Alex Chan1c0cb662017-01-30 07:13:30 +00002053class TestConnection(object):
Rick Deane15b1472009-07-09 15:53:42 -05002054 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002055 Unit tests for `OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002056 """
Alex Gaynor03737182020-07-23 20:40:46 -04002057
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002058 # XXX get_peer_certificate -> None
2059 # XXX sock_shutdown
2060 # XXX master_key -> TypeError
2061 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002062 # XXX connect -> TypeError
2063 # XXX connect_ex -> TypeError
2064 # XXX set_connect_state -> TypeError
2065 # XXX set_accept_state -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002066 # XXX do_handshake -> TypeError
2067 # XXX bio_read -> TypeError
2068 # XXX recv -> TypeError
2069 # XXX send -> TypeError
2070 # XXX bio_write -> TypeError
2071
Rick Deane15b1472009-07-09 15:53:42 -05002072 def test_type(self):
2073 """
Alex Gaynor01f90a12019-02-07 09:14:48 -05002074 `Connection` can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002075 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002076 ctx = Context(SSLv23_METHOD)
Alex Gaynor03737182020-07-23 20:40:46 -04002077 assert is_consistent_type(Connection, "Connection", ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002078
Alex Gaynor03737182020-07-23 20:40:46 -04002079 @pytest.mark.parametrize("bad_context", [object(), "context", None, 1])
Alex Chanfb078d82017-04-20 11:16:15 +01002080 def test_wrong_args(self, bad_context):
2081 """
2082 `Connection.__init__` raises `TypeError` if called with a non-`Context`
2083 instance argument.
2084 """
2085 with pytest.raises(TypeError):
2086 Connection(bad_context)
2087
Alex Gaynor03737182020-07-23 20:40:46 -04002088 @pytest.mark.parametrize("bad_bio", [object(), None, 1, [1, 2, 3]])
Daniel Holth079c9632019-11-17 22:45:52 -05002089 def test_bio_write_wrong_args(self, bad_bio):
2090 """
2091 `Connection.bio_write` raises `TypeError` if called with a non-bytes
2092 (or text) argument.
2093 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002094 context = Context(SSLv23_METHOD)
Daniel Holth079c9632019-11-17 22:45:52 -05002095 connection = Connection(context, None)
2096 with pytest.raises(TypeError):
2097 connection.bio_write(bad_bio)
2098
2099 def test_bio_write(self):
2100 """
2101 `Connection.bio_write` does not raise if called with bytes or
2102 bytearray, warns if called with text.
2103 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002104 context = Context(SSLv23_METHOD)
Daniel Holth079c9632019-11-17 22:45:52 -05002105 connection = Connection(context, None)
Alex Gaynor03737182020-07-23 20:40:46 -04002106 connection.bio_write(b"xy")
2107 connection.bio_write(bytearray(b"za"))
Daniel Holth079c9632019-11-17 22:45:52 -05002108 with pytest.warns(DeprecationWarning):
Alex Gaynor03737182020-07-23 20:40:46 -04002109 connection.bio_write(u"deprecated")
Daniel Holth079c9632019-11-17 22:45:52 -05002110
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002111 def test_get_context(self):
2112 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002113 `Connection.get_context` returns the `Context` instance used to
2114 construct the `Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002115 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002116 context = Context(SSLv23_METHOD)
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002117 connection = Connection(context, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002118 assert connection.get_context() is context
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002119
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002120 def test_set_context_wrong_args(self):
2121 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002122 `Connection.set_context` raises `TypeError` if called with a
Alex Chanfb078d82017-04-20 11:16:15 +01002123 non-`Context` instance argument.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002124 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002125 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002126 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002127 with pytest.raises(TypeError):
2128 connection.set_context(object())
2129 with pytest.raises(TypeError):
2130 connection.set_context("hello")
2131 with pytest.raises(TypeError):
2132 connection.set_context(1)
2133 assert ctx is connection.get_context()
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002134
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002135 def test_set_context(self):
2136 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002137 `Connection.set_context` specifies a new `Context` instance to be
2138 used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002139 """
2140 original = Context(SSLv23_METHOD)
Paul Kehrer688538c2020-08-03 19:18:15 -05002141 replacement = Context(SSLv23_METHOD)
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002142 connection = Connection(original, None)
2143 connection.set_context(replacement)
Alex Chan1c0cb662017-01-30 07:13:30 +00002144 assert replacement is connection.get_context()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002145 # Lose our references to the contexts, just in case the Connection
2146 # isn't properly managing its own contributions to their reference
2147 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002148 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002149 collect()
2150
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002151 def test_set_tlsext_host_name_wrong_args(self):
2152 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002153 If `Connection.set_tlsext_host_name` is called with a non-byte string
2154 argument or a byte string with an embedded NUL, `TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002155 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002156 conn = Connection(Context(SSLv23_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002157 with pytest.raises(TypeError):
2158 conn.set_tlsext_host_name(object())
2159 with pytest.raises(TypeError):
2160 conn.set_tlsext_host_name(b"with\0null")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002161
Hugo van Kemenade60827f82019-08-30 00:39:35 +03002162 if not PY2:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002163 # On Python 3.x, don't accidentally implicitly convert from text.
Alex Chan1c0cb662017-01-30 07:13:30 +00002164 with pytest.raises(TypeError):
2165 conn.set_tlsext_host_name(b"example.com".decode("ascii"))
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002166
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002167 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002168 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002169 `Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002170 immediate read.
2171 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002172 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002173 assert connection.pending() == 0
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002174
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002175 def test_peek(self):
2176 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002177 `Connection.recv` peeks into the connection if `socket.MSG_PEEK` is
2178 passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002179 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002180 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002181 server.send(b"xy")
2182 assert client.recv(2, MSG_PEEK) == b"xy"
2183 assert client.recv(2, MSG_PEEK) == b"xy"
2184 assert client.recv(2) == b"xy"
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002185
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002186 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002187 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002188 `Connection.connect` raises `TypeError` if called with a non-address
2189 argument.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002190 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002191 connection = Connection(Context(SSLv23_METHOD), socket_any_family())
Alex Chan1c0cb662017-01-30 07:13:30 +00002192 with pytest.raises(TypeError):
2193 connection.connect(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002194
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002195 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002196 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002197 `Connection.connect` raises `socket.error` if the underlying socket
2198 connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002199 """
David Benjamin1fbe0642019-04-15 17:05:13 -05002200 client = socket_any_family()
Paul Kehrer688538c2020-08-03 19:18:15 -05002201 context = Context(SSLv23_METHOD)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002202 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002203 # pytest.raises here doesn't work because of a bug in py.test on Python
2204 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002205 try:
David Benjamin1fbe0642019-04-15 17:05:13 -05002206 clientSSL.connect((loopback_address(client), 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002207 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002208 exc = e
2209 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002210
2211 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002212 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002213 `Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002214 """
David Benjamin1fbe0642019-04-15 17:05:13 -05002215 port = socket_any_family()
Alex Gaynor03737182020-07-23 20:40:46 -04002216 port.bind(("", 0))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002217 port.listen(3)
2218
Paul Kehrer688538c2020-08-03 19:18:15 -05002219 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
David Benjamin1fbe0642019-04-15 17:05:13 -05002220 clientSSL.connect((loopback_address(port), port.getsockname()[1]))
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002221 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002222
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002223 @pytest.mark.skipif(
2224 platform == "darwin",
Alex Gaynor03737182020-07-23 20:40:46 -04002225 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4",
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002226 )
2227 def test_connect_ex(self):
2228 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002229 If there is a connection error, `Connection.connect_ex` returns the
2230 errno instead of raising an exception.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002231 """
David Benjamin1fbe0642019-04-15 17:05:13 -05002232 port = socket_any_family()
Alex Gaynor03737182020-07-23 20:40:46 -04002233 port.bind(("", 0))
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002234 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002235
Paul Kehrer688538c2020-08-03 19:18:15 -05002236 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002237 clientSSL.setblocking(False)
2238 result = clientSSL.connect_ex(port.getsockname())
2239 expected = (EINPROGRESS, EWOULDBLOCK)
Alex Chan1c0cb662017-01-30 07:13:30 +00002240 assert result in expected
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002241
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002242 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002243 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002244 `Connection.accept` accepts a pending connection attempt and returns a
2245 tuple of a new `Connection` (the accepted client) and the address the
2246 connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002247 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002248 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002249 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2250 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
David Benjamin1fbe0642019-04-15 17:05:13 -05002251 port = socket_any_family()
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002252 portSSL = Connection(ctx, port)
Alex Gaynor03737182020-07-23 20:40:46 -04002253 portSSL.bind(("", 0))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002254 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002255
Paul Kehrer688538c2020-08-03 19:18:15 -05002256 clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002257
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002258 # Calling portSSL.getsockname() here to get the server IP address
2259 # sounds great, but frequently fails on Windows.
David Benjamin1fbe0642019-04-15 17:05:13 -05002260 clientSSL.connect((loopback_address(port), portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002261
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002262 serverSSL, address = portSSL.accept()
2263
Alex Chan1c0cb662017-01-30 07:13:30 +00002264 assert isinstance(serverSSL, Connection)
2265 assert serverSSL.get_context() is ctx
2266 assert address == clientSSL.getsockname()
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002267
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002268 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002269 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002270 `Connection.set_shutdown` raises `TypeError` if called with arguments
2271 other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002272 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002273 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002274 with pytest.raises(TypeError):
2275 connection.set_shutdown(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002276
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002277 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002278 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002279 `Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002280 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002281 server, client = loopback()
2282 assert not server.shutdown()
2283 assert server.get_shutdown() == SENT_SHUTDOWN
2284 with pytest.raises(ZeroReturnError):
2285 client.recv(1024)
2286 assert client.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002287 client.shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002288 assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
2289 with pytest.raises(ZeroReturnError):
2290 server.recv(1024)
2291 assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002292
Paul Aurichc85e0862015-01-08 08:34:33 -08002293 def test_shutdown_closed(self):
2294 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002295 If the underlying socket is closed, `Connection.shutdown` propagates
2296 the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002297 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002298 server, client = loopback()
Paul Aurichc85e0862015-01-08 08:34:33 -08002299 server.sock_shutdown(2)
Alex Chan1c0cb662017-01-30 07:13:30 +00002300 with pytest.raises(SysCallError) as exc:
2301 server.shutdown()
Alex Chanfb078d82017-04-20 11:16:15 +01002302 if platform == "win32":
2303 assert exc.value.args[0] == ESHUTDOWN
2304 else:
2305 assert exc.value.args[0] == EPIPE
Paul Aurichc85e0862015-01-08 08:34:33 -08002306
Glyph89389472015-04-14 17:29:26 -04002307 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002308 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002309 If the underlying connection is truncated, `Connection.shutdown`
2310 raises an `Error`.
Glyph6064ec32015-04-14 16:38:22 -04002311 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002312 server_ctx = Context(SSLv23_METHOD)
2313 client_ctx = Context(SSLv23_METHOD)
Glyph89389472015-04-14 17:29:26 -04002314 server_ctx.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04002315 load_privatekey(FILETYPE_PEM, server_key_pem)
2316 )
Glyph89389472015-04-14 17:29:26 -04002317 server_ctx.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04002318 load_certificate(FILETYPE_PEM, server_cert_pem)
2319 )
Glyph89389472015-04-14 17:29:26 -04002320 server = Connection(server_ctx, None)
2321 client = Connection(client_ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002322 handshake_in_memory(client, server)
2323 assert not server.shutdown()
2324 with pytest.raises(WantReadError):
2325 server.shutdown()
Glyph89389472015-04-14 17:29:26 -04002326 server.bio_shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002327 with pytest.raises(Error):
2328 server.shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002329
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002330 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002331 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002332 `Connection.set_shutdown` sets the state of the SSL connection
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002333 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002334 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002335 connection = Connection(Context(SSLv23_METHOD), socket_any_family())
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002336 connection.set_shutdown(RECEIVED_SHUTDOWN)
Alex Chan1c0cb662017-01-30 07:13:30 +00002337 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002338
kjavaf248592015-09-07 12:14:01 +01002339 def test_state_string(self):
2340 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002341 `Connection.state_string` verbosely describes the current state of
2342 the `Connection`.
kjavaf248592015-09-07 12:14:01 +01002343 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002344 server, client = socket_pair()
Alex Chan1c0cb662017-01-30 07:13:30 +00002345 server = loopback_server_factory(server)
2346 client = loopback_client_factory(client)
kjavaf248592015-09-07 12:14:01 +01002347
Alex Gaynor5af32d02016-09-24 01:52:21 -04002348 assert server.get_state_string() in [
Alex Gaynor03737182020-07-23 20:40:46 -04002349 b"before/accept initialization",
2350 b"before SSL initialization",
Alex Gaynor5af32d02016-09-24 01:52:21 -04002351 ]
2352 assert client.get_state_string() in [
Alex Gaynor03737182020-07-23 20:40:46 -04002353 b"before/connect initialization",
2354 b"before SSL initialization",
Alex Gaynor5af32d02016-09-24 01:52:21 -04002355 ]
kjavaf248592015-09-07 12:14:01 +01002356
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002357 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002358 """
2359 Any object can be set as app data by passing it to
Alex Chan1c0cb662017-01-30 07:13:30 +00002360 `Connection.set_app_data` and later retrieved with
2361 `Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002362 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002363 conn = Connection(Context(SSLv23_METHOD), None)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002364 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002365 app_data = object()
2366 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002367 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002368
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002369 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002370 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002371 `Connection.makefile` is not implemented and calling that
2372 method raises `NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002373 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002374 conn = Connection(Context(SSLv23_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002375 with pytest.raises(NotImplementedError):
2376 conn.makefile()
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002377
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002378 def test_get_certificate(self):
2379 """
2380 `Connection.get_certificate` returns the local certificate.
2381 """
2382 chain = _create_certificate_chain()
2383 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2384
Paul Kehrer688538c2020-08-03 19:18:15 -05002385 context = Context(SSLv23_METHOD)
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002386 context.use_certificate(scert)
2387 client = Connection(context, None)
2388 cert = client.get_certificate()
2389 assert cert is not None
2390 assert "Server Certificate" == cert.get_subject().CN
2391
2392 def test_get_certificate_none(self):
2393 """
2394 `Connection.get_certificate` returns the local certificate.
2395
2396 If there is no certificate, it returns None.
2397 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002398 context = Context(SSLv23_METHOD)
Jeremy Lainé460a19d2018-05-16 19:44:19 +02002399 client = Connection(context, None)
2400 cert = client.get_certificate()
2401 assert cert is None
2402
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002403 def test_get_peer_cert_chain(self):
2404 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002405 `Connection.get_peer_cert_chain` returns a list of certificates
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002406 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002407 """
2408 chain = _create_certificate_chain()
2409 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2410
Paul Kehrer688538c2020-08-03 19:18:15 -05002411 serverContext = Context(SSLv23_METHOD)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002412 serverContext.use_privatekey(skey)
2413 serverContext.use_certificate(scert)
2414 serverContext.add_extra_chain_cert(icert)
2415 serverContext.add_extra_chain_cert(cacert)
2416 server = Connection(serverContext, None)
2417 server.set_accept_state()
2418
2419 # Create the client
Paul Kehrer688538c2020-08-03 19:18:15 -05002420 clientContext = Context(SSLv23_METHOD)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002421 clientContext.set_verify(VERIFY_NONE, verify_cb)
2422 client = Connection(clientContext, None)
2423 client.set_connect_state()
2424
Alex Chan1c0cb662017-01-30 07:13:30 +00002425 interact_in_memory(client, server)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002426
2427 chain = client.get_peer_cert_chain()
Alex Chan1c0cb662017-01-30 07:13:30 +00002428 assert len(chain) == 3
2429 assert "Server Certificate" == chain[0].get_subject().CN
2430 assert "Intermediate Certificate" == chain[1].get_subject().CN
2431 assert "Authority Certificate" == chain[2].get_subject().CN
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002432
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002433 def test_get_peer_cert_chain_none(self):
2434 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002435 `Connection.get_peer_cert_chain` returns `None` if the peer sends
2436 no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002437 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002438 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002439 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2440 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2441 server = Connection(ctx, None)
2442 server.set_accept_state()
Paul Kehrer688538c2020-08-03 19:18:15 -05002443 client = Connection(Context(SSLv23_METHOD), None)
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002444 client.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002445 interact_in_memory(client, server)
2446 assert None is server.get_peer_cert_chain()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002447
Shane Harvey33c54992020-08-05 16:48:51 -07002448 def test_get_verified_chain(self):
2449 """
2450 `Connection.get_verified_chain` returns a list of certificates
2451 which the connected server returned for the certification verification.
2452 """
2453 chain = _create_certificate_chain()
2454 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2455
2456 serverContext = Context(SSLv23_METHOD)
2457 serverContext.use_privatekey(skey)
2458 serverContext.use_certificate(scert)
2459 serverContext.add_extra_chain_cert(icert)
2460 serverContext.add_extra_chain_cert(cacert)
2461 server = Connection(serverContext, None)
2462 server.set_accept_state()
2463
2464 # Create the client
2465 clientContext = Context(SSLv23_METHOD)
2466 # cacert is self-signed so the client must trust it for verification
2467 # to succeed.
2468 clientContext.get_cert_store().add_cert(cacert)
2469 clientContext.set_verify(VERIFY_PEER, verify_cb)
2470 client = Connection(clientContext, None)
2471 client.set_connect_state()
2472
2473 interact_in_memory(client, server)
2474
2475 chain = client.get_verified_chain()
2476 assert len(chain) == 3
2477 assert "Server Certificate" == chain[0].get_subject().CN
2478 assert "Intermediate Certificate" == chain[1].get_subject().CN
2479 assert "Authority Certificate" == chain[2].get_subject().CN
2480
2481 def test_get_verified_chain_none(self):
2482 """
2483 `Connection.get_verified_chain` returns `None` if the peer sends
2484 no certificate chain.
2485 """
2486 ctx = Context(SSLv23_METHOD)
2487 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2488 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2489 server = Connection(ctx, None)
2490 server.set_accept_state()
2491 client = Connection(Context(SSLv23_METHOD), None)
2492 client.set_connect_state()
2493 interact_in_memory(client, server)
2494 assert None is server.get_verified_chain()
2495
2496 def test_get_verified_chain_unconnected(self):
2497 """
2498 `Connection.get_verified_chain` returns `None` when used with an object
2499 which has not been connected.
2500 """
2501 ctx = Context(SSLv23_METHOD)
2502 server = Connection(ctx, None)
2503 assert None is server.get_verified_chain()
2504
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002505 def test_get_session_unconnected(self):
2506 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002507 `Connection.get_session` returns `None` when used with an object
2508 which has not been connected.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002509 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002510 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002511 server = Connection(ctx, None)
2512 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002513 assert None is session
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002514
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002515 def test_server_get_session(self):
2516 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002517 On the server side of a connection, `Connection.get_session` returns a
2518 `Session` instance representing the SSL session for that connection.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002519 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002520 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002521 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002522 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002523
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002524 def test_client_get_session(self):
2525 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002526 On the client side of a connection, `Connection.get_session`
2527 returns a `Session` instance representing the SSL session for
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002528 that connection.
2529 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002530 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002531 session = client.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002532 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002533
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002534 def test_set_session_wrong_args(self):
2535 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002536 `Connection.set_session` raises `TypeError` if called with an object
2537 that is not an instance of `Session`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002538 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002539 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002540 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002541 with pytest.raises(TypeError):
2542 connection.set_session(123)
2543 with pytest.raises(TypeError):
2544 connection.set_session("hello")
2545 with pytest.raises(TypeError):
2546 connection.set_session(object())
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002547
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002548 def test_client_set_session(self):
2549 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002550 `Connection.set_session`, when used prior to a connection being
2551 established, accepts a `Session` instance and causes an attempt to
2552 re-use the session it represents when the SSL handshake is performed.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002553 """
2554 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2555 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06002556 ctx = Context(TLSv1_2_METHOD)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002557 ctx.use_privatekey(key)
2558 ctx.use_certificate(cert)
2559 ctx.set_session_id("unity-test")
2560
2561 def makeServer(socket):
2562 server = Connection(ctx, socket)
2563 server.set_accept_state()
2564 return server
2565
Alex Gaynor03737182020-07-23 20:40:46 -04002566 originalServer, originalClient = loopback(server_factory=makeServer)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002567 originalSession = originalClient.get_session()
2568
2569 def makeClient(socket):
Alex Chan1c0cb662017-01-30 07:13:30 +00002570 client = loopback_client_factory(socket)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002571 client.set_session(originalSession)
2572 return client
Alex Gaynor03737182020-07-23 20:40:46 -04002573
Alex Chan1c0cb662017-01-30 07:13:30 +00002574 resumedServer, resumedClient = loopback(
Alex Gaynor03737182020-07-23 20:40:46 -04002575 server_factory=makeServer, client_factory=makeClient
2576 )
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002577
2578 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002579 # identifier for the session (new enough versions of OpenSSL expose
2580 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002581 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002582 # session is re-used. As long as the master key for the two
2583 # connections is the same, the session was re-used!
Alex Chan1c0cb662017-01-30 07:13:30 +00002584 assert originalServer.master_key() == resumedServer.master_key()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002585
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002586 def test_set_session_wrong_method(self):
2587 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002588 If `Connection.set_session` is passed a `Session` instance associated
2589 with a context using a different SSL method than the `Connection`
2590 is using, a `OpenSSL.SSL.Error` is raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002591 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002592 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2593 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2594 # is a way to check for 1.1.0)
Alex Gaynoraa32e712017-06-29 20:56:12 -07002595 if SSL_ST_INIT is None:
2596 v1 = TLSv1_2_METHOD
2597 v2 = TLSv1_METHOD
2598 elif hasattr(_lib, "SSLv3_method"):
Alex Gaynor5af32d02016-09-24 01:52:21 -04002599 v1 = TLSv1_METHOD
2600 v2 = SSLv3_METHOD
2601 else:
Alex Gaynoraa32e712017-06-29 20:56:12 -07002602 pytest.skip("Test requires either OpenSSL 1.1.0 or SSLv3")
Alex Gaynor5af32d02016-09-24 01:52:21 -04002603
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002604 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2605 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002606 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002607 ctx.use_privatekey(key)
2608 ctx.use_certificate(cert)
Paul Kehrerc45a6ea2020-08-03 15:54:20 -05002609 ctx.set_session_id(b"unity-test")
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002610
2611 def makeServer(socket):
2612 server = Connection(ctx, socket)
2613 server.set_accept_state()
2614 return server
2615
Alex Gaynor5af32d02016-09-24 01:52:21 -04002616 def makeOriginalClient(socket):
2617 client = Connection(Context(v1), socket)
2618 client.set_connect_state()
2619 return client
2620
Alex Chan1c0cb662017-01-30 07:13:30 +00002621 originalServer, originalClient = loopback(
Alex Gaynor03737182020-07-23 20:40:46 -04002622 server_factory=makeServer, client_factory=makeOriginalClient
2623 )
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002624 originalSession = originalClient.get_session()
2625
2626 def makeClient(socket):
2627 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002628 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002629 client.set_connect_state()
2630 client.set_session(originalSession)
2631 return client
2632
Alex Chan1c0cb662017-01-30 07:13:30 +00002633 with pytest.raises(Error):
2634 loopback(client_factory=makeClient, server_factory=makeServer)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002635
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002636 def test_wantWriteError(self):
2637 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002638 `Connection` methods which generate output raise
2639 `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002640 fail indicating a should-write state.
2641 """
2642 client_socket, server_socket = socket_pair()
2643 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002644 # anything. Only write a single byte at a time so we can be sure we
2645 # completely fill the buffer. Even though the socket API is allowed to
2646 # signal a short write via its return value it seems this doesn't
2647 # always happen on all platforms (FreeBSD and OS X particular) for the
2648 # very last bit of available buffer space.
2649 msg = b"x"
caternb2777a42018-08-09 15:38:13 -04002650 for i in range(1024 * 1024 * 64):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002651 try:
2652 client_socket.send(msg)
2653 except error as e:
2654 if e.errno == EWOULDBLOCK:
2655 break
2656 raise
2657 else:
Alex Chan1c0cb662017-01-30 07:13:30 +00002658 pytest.fail(
Alex Gaynor03737182020-07-23 20:40:46 -04002659 "Failed to fill socket buffer, cannot test BIO want write"
2660 )
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002661
Paul Kehrer688538c2020-08-03 19:18:15 -05002662 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002663 conn = Connection(ctx, client_socket)
2664 # Client's speak first, so make it an SSL client
2665 conn.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002666 with pytest.raises(WantWriteError):
2667 conn.do_handshake()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002668
2669 # XXX want_read
2670
Fedor Brunner416f4a12014-03-28 13:18:38 +01002671 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002672 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002673 `Connection.get_finished` returns `None` before TLS handshake
2674 is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002675 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002676 ctx = Context(SSLv23_METHOD)
Fedor Brunner5747b932014-03-05 14:22:34 +01002677 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002678 assert connection.get_finished() is None
Fedor Brunner416f4a12014-03-28 13:18:38 +01002679
2680 def test_get_peer_finished_before_connect(self):
2681 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002682 `Connection.get_peer_finished` returns `None` before TLS handshake
2683 is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002684 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002685 ctx = Context(SSLv23_METHOD)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002686 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002687 assert connection.get_peer_finished() is None
Fedor Brunner5747b932014-03-05 14:22:34 +01002688
Fedor Brunner416f4a12014-03-28 13:18:38 +01002689 def test_get_finished(self):
2690 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002691 `Connection.get_finished` method returns the TLS Finished message send
2692 from client, or server. Finished messages are send during
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002693 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002694 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002695 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002696
Alex Chan1c0cb662017-01-30 07:13:30 +00002697 assert server.get_finished() is not None
2698 assert len(server.get_finished()) > 0
Fedor Brunner416f4a12014-03-28 13:18:38 +01002699
2700 def test_get_peer_finished(self):
2701 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002702 `Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002703 message received from client, or server. Finished messages are send
2704 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002705 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002706 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002707
Alex Chan1c0cb662017-01-30 07:13:30 +00002708 assert server.get_peer_finished() is not None
2709 assert len(server.get_peer_finished()) > 0
Fedor Brunner5747b932014-03-05 14:22:34 +01002710
Fedor Brunner416f4a12014-03-28 13:18:38 +01002711 def test_tls_finished_message_symmetry(self):
2712 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002713 The TLS Finished message send by server must be the TLS Finished
2714 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002715
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002716 The TLS Finished message send by client must be the TLS Finished
2717 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002718 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002719 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002720
Alex Chan1c0cb662017-01-30 07:13:30 +00002721 assert server.get_finished() == client.get_peer_finished()
2722 assert client.get_finished() == server.get_peer_finished()
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002723
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002724 def test_get_cipher_name_before_connect(self):
2725 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002726 `Connection.get_cipher_name` returns `None` if no connection
2727 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002728 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002729 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002730 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002731 assert conn.get_cipher_name() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002732
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002733 def test_get_cipher_name(self):
2734 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002735 `Connection.get_cipher_name` returns a `unicode` string giving the
2736 name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002737 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002738 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002739 server_cipher_name, client_cipher_name = (
2740 server.get_cipher_name(),
2741 client.get_cipher_name(),
2742 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002743
Alex Chan1c0cb662017-01-30 07:13:30 +00002744 assert isinstance(server_cipher_name, text_type)
2745 assert isinstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002746
Alex Chan1c0cb662017-01-30 07:13:30 +00002747 assert server_cipher_name == client_cipher_name
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002748
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002749 def test_get_cipher_version_before_connect(self):
2750 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002751 `Connection.get_cipher_version` returns `None` if no connection
2752 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002753 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002754 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002755 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002756 assert conn.get_cipher_version() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002757
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002758 def test_get_cipher_version(self):
2759 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002760 `Connection.get_cipher_version` returns a `unicode` string giving
2761 the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002762 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002763 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002764 server_cipher_version, client_cipher_version = (
2765 server.get_cipher_version(),
2766 client.get_cipher_version(),
2767 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002768
Alex Chan1c0cb662017-01-30 07:13:30 +00002769 assert isinstance(server_cipher_version, text_type)
2770 assert isinstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002771
Alex Chan1c0cb662017-01-30 07:13:30 +00002772 assert server_cipher_version == client_cipher_version
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002773
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002774 def test_get_cipher_bits_before_connect(self):
2775 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002776 `Connection.get_cipher_bits` returns `None` if no connection has
2777 been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002778 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002779 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002780 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002781 assert conn.get_cipher_bits() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002782
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002783 def test_get_cipher_bits(self):
2784 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002785 `Connection.get_cipher_bits` returns the number of secret bits
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002786 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002787 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002788 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002789 server_cipher_bits, client_cipher_bits = (
2790 server.get_cipher_bits(),
2791 client.get_cipher_bits(),
2792 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002793
Alex Chan1c0cb662017-01-30 07:13:30 +00002794 assert isinstance(server_cipher_bits, int)
2795 assert isinstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002796
Alex Chan1c0cb662017-01-30 07:13:30 +00002797 assert server_cipher_bits == client_cipher_bits
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002798
Jim Shaverabff1882015-05-27 09:15:55 -04002799 def test_get_protocol_version_name(self):
2800 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002801 `Connection.get_protocol_version_name()` returns a string giving the
2802 protocol version of the current connection.
Jim Shaverabff1882015-05-27 09:15:55 -04002803 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002804 server, client = loopback()
Jim Shaverabff1882015-05-27 09:15:55 -04002805 client_protocol_version_name = client.get_protocol_version_name()
2806 server_protocol_version_name = server.get_protocol_version_name()
2807
Alex Chan1c0cb662017-01-30 07:13:30 +00002808 assert isinstance(server_protocol_version_name, text_type)
2809 assert isinstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002810
Alex Chan1c0cb662017-01-30 07:13:30 +00002811 assert server_protocol_version_name == client_protocol_version_name
Jim Shaverabff1882015-05-27 09:15:55 -04002812
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002813 def test_get_protocol_version(self):
2814 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002815 `Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002816 giving the protocol version of the current connection.
2817 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002818 server, client = loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002819 client_protocol_version = client.get_protocol_version()
2820 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002821
Alex Chan1c0cb662017-01-30 07:13:30 +00002822 assert isinstance(server_protocol_version, int)
2823 assert isinstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002824
Alex Chan1c0cb662017-01-30 07:13:30 +00002825 assert server_protocol_version == client_protocol_version
2826
2827 def test_wantReadError(self):
2828 """
2829 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
2830 no bytes available to be read from the BIO.
2831 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002832 ctx = Context(SSLv23_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002833 conn = Connection(ctx, None)
2834 with pytest.raises(WantReadError):
2835 conn.bio_read(1024)
2836
Alex Gaynor03737182020-07-23 20:40:46 -04002837 @pytest.mark.parametrize("bufsize", [1.0, None, object(), "bufsize"])
Alex Chanfb078d82017-04-20 11:16:15 +01002838 def test_bio_read_wrong_args(self, bufsize):
2839 """
2840 `Connection.bio_read` raises `TypeError` if passed a non-integer
2841 argument.
2842 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002843 ctx = Context(SSLv23_METHOD)
Alex Chanfb078d82017-04-20 11:16:15 +01002844 conn = Connection(ctx, None)
2845 with pytest.raises(TypeError):
2846 conn.bio_read(bufsize)
2847
Alex Chan1c0cb662017-01-30 07:13:30 +00002848 def test_buffer_size(self):
2849 """
2850 `Connection.bio_read` accepts an integer giving the maximum number
2851 of bytes to read and return.
2852 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002853 ctx = Context(SSLv23_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002854 conn = Connection(ctx, None)
2855 conn.set_connect_state()
2856 try:
2857 conn.do_handshake()
2858 except WantReadError:
2859 pass
2860 data = conn.bio_read(2)
2861 assert 2 == len(data)
2862
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002863
Alex Chanb7480992017-01-30 14:04:47 +00002864class TestConnectionGetCipherList(object):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002865 """
Alex Chanb7480992017-01-30 14:04:47 +00002866 Tests for `Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002867 """
Alex Gaynor03737182020-07-23 20:40:46 -04002868
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002869 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002870 """
Alex Chanb7480992017-01-30 14:04:47 +00002871 `Connection.get_cipher_list` returns a list of `bytes` giving the
2872 names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002873 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002874 connection = Connection(Context(SSLv23_METHOD), None)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002875 ciphers = connection.get_cipher_list()
Alex Chanb7480992017-01-30 14:04:47 +00002876 assert isinstance(ciphers, list)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002877 for cipher in ciphers:
Alex Chanb7480992017-01-30 14:04:47 +00002878 assert isinstance(cipher, str)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002879
2880
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002881class VeryLarge(bytes):
2882 """
2883 Mock object so that we don't have to allocate 2**31 bytes
2884 """
Alex Gaynor03737182020-07-23 20:40:46 -04002885
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002886 def __len__(self):
Alex Gaynor03737182020-07-23 20:40:46 -04002887 return 2 ** 31
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002888
2889
Alex Chanb7480992017-01-30 14:04:47 +00002890class TestConnectionSend(object):
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002891 """
Alex Chanb7480992017-01-30 14:04:47 +00002892 Tests for `Connection.send`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002893 """
Alex Gaynor03737182020-07-23 20:40:46 -04002894
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002895 def test_wrong_args(self):
2896 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002897 When called with arguments other than string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00002898 parameter, `Connection.send` raises `TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002899 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002900 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00002901 with pytest.raises(TypeError):
2902 connection.send(object())
Daniel Holth079c9632019-11-17 22:45:52 -05002903 with pytest.raises(TypeError):
2904 connection.send([1, 2, 3])
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002905
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002906 def test_short_bytes(self):
2907 """
Alex Chanb7480992017-01-30 14:04:47 +00002908 When passed a short byte string, `Connection.send` transmits all of it
2909 and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002910 """
Alex Chanb7480992017-01-30 14:04:47 +00002911 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002912 count = server.send(b"xy")
Alex Chanb7480992017-01-30 14:04:47 +00002913 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002914 assert client.recv(2) == b"xy"
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002915
Abraham Martinef063482015-03-25 14:06:24 +00002916 def test_text(self):
2917 """
Alex Chanb7480992017-01-30 14:04:47 +00002918 When passed a text, `Connection.send` transmits all of it and
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002919 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002920 """
Alex Chanb7480992017-01-30 14:04:47 +00002921 server, client = loopback()
2922 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00002923 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002924 count = server.send(b"xy".decode("ascii"))
Alex Gaynor03737182020-07-23 20:40:46 -04002925 assert "{0} for buf is no longer accepted, use bytes".format(
2926 WARNING_TYPE_EXPECTED
2927 ) == str(w[-1].message)
Alex Chanb7480992017-01-30 14:04:47 +00002928 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002929 assert client.recv(2) == b"xy"
Abraham Martinef063482015-03-25 14:06:24 +00002930
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002931 def test_short_memoryview(self):
2932 """
2933 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002934 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002935 of bytes sent.
2936 """
Alex Chanb7480992017-01-30 14:04:47 +00002937 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002938 count = server.send(memoryview(b"xy"))
Alex Chanb7480992017-01-30 14:04:47 +00002939 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002940 assert client.recv(2) == b"xy"
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002941
Daniel Holth079c9632019-11-17 22:45:52 -05002942 def test_short_bytearray(self):
2943 """
2944 When passed a short bytearray, `Connection.send` transmits all of
2945 it and returns the number of bytes sent.
2946 """
2947 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002948 count = server.send(bytearray(b"xy"))
Daniel Holth079c9632019-11-17 22:45:52 -05002949 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002950 assert client.recv(2) == b"xy"
Daniel Holth079c9632019-11-17 22:45:52 -05002951
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002952 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002953 def test_short_buffer(self):
2954 """
2955 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002956 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002957 of bytes sent.
2958 """
Alex Chanb7480992017-01-30 14:04:47 +00002959 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002960 count = server.send(buffer(b"xy")) # noqa: F821
Alex Chanb7480992017-01-30 14:04:47 +00002961 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002962 assert client.recv(2) == b"xy"
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002963
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002964 @pytest.mark.skipif(
Alex Gaynor03737182020-07-23 20:40:46 -04002965 sys.maxsize < 2 ** 31,
2966 reason="sys.maxsize < 2**31 - test requires 64 bit",
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002967 )
2968 def test_buf_too_large(self):
2969 """
2970 When passed a buffer containing >= 2**31 bytes,
2971 `Connection.send` bails out as SSL_write only
2972 accepts an int for the buffer length.
2973 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002974 connection = Connection(Context(SSLv23_METHOD), None)
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002975 with pytest.raises(ValueError) as exc_info:
2976 connection.send(VeryLarge())
2977 exc_info.match(r"Cannot send more than .+ bytes at once")
2978
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002979
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002980def _make_memoryview(size):
2981 """
2982 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2983 size.
2984 """
2985 return memoryview(bytearray(size))
2986
2987
Alex Chanb7480992017-01-30 14:04:47 +00002988class TestConnectionRecvInto(object):
Cory Benfield62d10332014-06-15 10:03:41 +01002989 """
Alex Chanb7480992017-01-30 14:04:47 +00002990 Tests for `Connection.recv_into`.
Cory Benfield62d10332014-06-15 10:03:41 +01002991 """
Alex Gaynor03737182020-07-23 20:40:46 -04002992
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002993 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002994 """
Alex Chanb7480992017-01-30 14:04:47 +00002995 Assert that when the given buffer is passed to `Connection.recv_into`,
2996 whatever bytes are available to be received that fit into that buffer
2997 are written into that buffer.
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002998 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002999 output_buffer = factory(5)
3000
Alex Chanb7480992017-01-30 14:04:47 +00003001 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003002 server.send(b"xy")
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04003003
Alex Chanb7480992017-01-30 14:04:47 +00003004 assert client.recv_into(output_buffer) == 2
Alex Gaynor03737182020-07-23 20:40:46 -04003005 assert output_buffer == bytearray(b"xy\x00\x00\x00")
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04003006
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003007 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01003008 """
Alex Chanb7480992017-01-30 14:04:47 +00003009 `Connection.recv_into` can be passed a `bytearray` instance and data
3010 in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01003011 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003012 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003013
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003014 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01003015 """
Alex Chanb7480992017-01-30 14:04:47 +00003016 Assert that when the given buffer is passed to `Connection.recv_into`
3017 along with a value for `nbytes` that is less than the size of that
3018 buffer, only `nbytes` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01003019 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003020 output_buffer = factory(10)
3021
Alex Chanb7480992017-01-30 14:04:47 +00003022 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003023 server.send(b"abcdefghij")
Cory Benfield62d10332014-06-15 10:03:41 +01003024
Alex Chanb7480992017-01-30 14:04:47 +00003025 assert client.recv_into(output_buffer, 5) == 5
Alex Gaynor03737182020-07-23 20:40:46 -04003026 assert output_buffer == bytearray(b"abcde\x00\x00\x00\x00\x00")
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04003027
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003028 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04003029 """
Alex Chanb7480992017-01-30 14:04:47 +00003030 When called with a `bytearray` instance, `Connection.recv_into`
3031 respects the `nbytes` parameter and doesn't copy in more than that
3032 number of bytes.
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04003033 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003034 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003035
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003036 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01003037 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003038 Assert that if there are more bytes available to be read from the
3039 receive buffer than would fit into the buffer passed to
Alex Chanb7480992017-01-30 14:04:47 +00003040 `Connection.recv_into`, only as many as fit are written into it.
Cory Benfield62d10332014-06-15 10:03:41 +01003041 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003042 output_buffer = factory(5)
3043
Alex Chanb7480992017-01-30 14:04:47 +00003044 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003045 server.send(b"abcdefghij")
Cory Benfield62d10332014-06-15 10:03:41 +01003046
Alex Chanb7480992017-01-30 14:04:47 +00003047 assert client.recv_into(output_buffer) == 5
Alex Gaynor03737182020-07-23 20:40:46 -04003048 assert output_buffer == bytearray(b"abcde")
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003049 rest = client.recv(5)
Alex Gaynor03737182020-07-23 20:40:46 -04003050 assert b"fghij" == rest
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003051
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003052 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003053 """
Alex Chanb7480992017-01-30 14:04:47 +00003054 When called with a `bytearray` instance, `Connection.recv_into`
3055 respects the size of the array and doesn't write more bytes into it
3056 than will fit.
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003057 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003058 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003059
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003060 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003061 """
Alex Chanb7480992017-01-30 14:04:47 +00003062 When called with a `bytearray` instance and an `nbytes` value that is
3063 too large, `Connection.recv_into` respects the size of the array and
3064 not the `nbytes` value and doesn't write more bytes into the buffer
3065 than will fit.
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003066 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003067 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003068
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003069 def test_peek(self):
Alex Chanb7480992017-01-30 14:04:47 +00003070 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003071 server.send(b"xy")
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003072
3073 for _ in range(2):
3074 output_buffer = bytearray(5)
Alex Chanb7480992017-01-30 14:04:47 +00003075 assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
Alex Gaynor03737182020-07-23 20:40:46 -04003076 assert output_buffer == bytearray(b"xy\x00\x00\x00")
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003077
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003078 def test_memoryview_no_length(self):
3079 """
Alex Chanb7480992017-01-30 14:04:47 +00003080 `Connection.recv_into` can be passed a `memoryview` instance and data
3081 in the receive buffer is written to it.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003082 """
3083 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003084
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003085 def test_memoryview_respects_length(self):
3086 """
Alex Chanb7480992017-01-30 14:04:47 +00003087 When called with a `memoryview` instance, `Connection.recv_into`
3088 respects the ``nbytes`` parameter and doesn't copy more than that
3089 number of bytes in.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003090 """
3091 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003092
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003093 def test_memoryview_doesnt_overfill(self):
3094 """
Alex Chanb7480992017-01-30 14:04:47 +00003095 When called with a `memoryview` instance, `Connection.recv_into`
3096 respects the size of the array and doesn't write more bytes into it
3097 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003098 """
3099 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003100
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003101 def test_memoryview_really_doesnt_overfill(self):
3102 """
Alex Chanb7480992017-01-30 14:04:47 +00003103 When called with a `memoryview` instance and an `nbytes` value that is
3104 too large, `Connection.recv_into` respects the size of the array and
3105 not the `nbytes` value and doesn't write more bytes into the buffer
3106 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003107 """
3108 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003109
Cory Benfield62d10332014-06-15 10:03:41 +01003110
Alex Chanb7480992017-01-30 14:04:47 +00003111class TestConnectionSendall(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003112 """
Alex Chanb7480992017-01-30 14:04:47 +00003113 Tests for `Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003114 """
Alex Gaynor03737182020-07-23 20:40:46 -04003115
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003116 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003117 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003118 When called with arguments other than a string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00003119 parameter, `Connection.sendall` raises `TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003120 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003121 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003122 with pytest.raises(TypeError):
3123 connection.sendall(object())
Daniel Holth079c9632019-11-17 22:45:52 -05003124 with pytest.raises(TypeError):
3125 connection.sendall([1, 2, 3])
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003126
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003127 def test_short(self):
3128 """
Alex Chanb7480992017-01-30 14:04:47 +00003129 `Connection.sendall` transmits all of the bytes in the string
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003130 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003131 """
Alex Chanb7480992017-01-30 14:04:47 +00003132 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003133 server.sendall(b"x")
3134 assert client.recv(1) == b"x"
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003135
Abraham Martinef063482015-03-25 14:06:24 +00003136 def test_text(self):
3137 """
Alex Chanb7480992017-01-30 14:04:47 +00003138 `Connection.sendall` transmits all the content in the string passed
3139 to it, raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003140 """
Alex Chanb7480992017-01-30 14:04:47 +00003141 server, client = loopback()
3142 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00003143 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003144 server.sendall(b"x".decode("ascii"))
Alex Gaynor03737182020-07-23 20:40:46 -04003145 assert "{0} for buf is no longer accepted, use bytes".format(
3146 WARNING_TYPE_EXPECTED
3147 ) == str(w[-1].message)
Alex Chanb7480992017-01-30 14:04:47 +00003148 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003149
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003150 def test_short_memoryview(self):
3151 """
3152 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003153 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003154 """
Alex Chanb7480992017-01-30 14:04:47 +00003155 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003156 server.sendall(memoryview(b"x"))
3157 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003158
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003159 @skip_if_py3
3160 def test_short_buffers(self):
3161 """
3162 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003163 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003164 """
Alex Chanb7480992017-01-30 14:04:47 +00003165 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003166 count = server.sendall(buffer(b"xy")) # noqa: F821
Daniel Holth079c9632019-11-17 22:45:52 -05003167 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04003168 assert client.recv(2) == b"xy"
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003169
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003170 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003171 """
Alex Chanb7480992017-01-30 14:04:47 +00003172 `Connection.sendall` transmits all the bytes in the string passed to it
3173 even if this requires multiple calls of an underlying write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003174 """
Alex Chanb7480992017-01-30 14:04:47 +00003175 server, client = loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003176 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003177 # On Windows, after 32k of bytes the write will block (forever
3178 # - because no one is yet reading).
Alex Gaynor03737182020-07-23 20:40:46 -04003179 message = b"x" * (1024 * 32 - 1) + b"y"
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003180 server.sendall(message)
3181 accum = []
3182 received = 0
3183 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003184 data = client.recv(1024)
3185 accum.append(data)
3186 received += len(data)
Alex Gaynor03737182020-07-23 20:40:46 -04003187 assert message == b"".join(accum)
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003188
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003189 def test_closed(self):
3190 """
Alex Chanb7480992017-01-30 14:04:47 +00003191 If the underlying socket is closed, `Connection.sendall` propagates the
3192 write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003193 """
Alex Chanb7480992017-01-30 14:04:47 +00003194 server, client = loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003195 server.sock_shutdown(2)
Alex Chanb7480992017-01-30 14:04:47 +00003196 with pytest.raises(SysCallError) as err:
3197 server.sendall(b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003198 if platform == "win32":
Alex Chanb7480992017-01-30 14:04:47 +00003199 assert err.value.args[0] == ESHUTDOWN
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003200 else:
Alex Chanb7480992017-01-30 14:04:47 +00003201 assert err.value.args[0] == EPIPE
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003202
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003203
Alex Chanb7480992017-01-30 14:04:47 +00003204class TestConnectionRenegotiate(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003205 """
3206 Tests for SSL renegotiation APIs.
3207 """
Alex Gaynor03737182020-07-23 20:40:46 -04003208
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003209 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003210 """
Alex Chanb7480992017-01-30 14:04:47 +00003211 `Connection.total_renegotiations` returns `0` before any renegotiations
3212 have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003213 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003214 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003215 assert connection.total_renegotiations() == 0
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003216
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003217 def test_renegotiate(self):
3218 """
3219 Go through a complete renegotiation cycle.
3220 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003221 server, client = loopback(
3222 lambda s: loopback_server_factory(s, TLSv1_2_METHOD),
3223 lambda s: loopback_client_factory(s, TLSv1_2_METHOD),
3224 )
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003225
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003226 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003227
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003228 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003229
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003230 assert 0 == server.total_renegotiations()
3231 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003232
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003233 assert True is server.renegotiate()
3234
3235 assert True is server.renegotiate_pending()
3236
3237 server.setblocking(False)
3238 client.setblocking(False)
3239
3240 client.do_handshake()
3241 server.do_handshake()
3242
3243 assert 1 == server.total_renegotiations()
3244 while False is server.renegotiate_pending():
3245 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003246
3247
Alex Chanb7480992017-01-30 14:04:47 +00003248class TestError(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003249 """
Alex Chanb7480992017-01-30 14:04:47 +00003250 Unit tests for `OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003251 """
Alex Gaynor03737182020-07-23 20:40:46 -04003252
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003253 def test_type(self):
3254 """
Alex Chanb7480992017-01-30 14:04:47 +00003255 `Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003256 """
Alex Chanb7480992017-01-30 14:04:47 +00003257 assert issubclass(Error, Exception)
Alex Gaynor03737182020-07-23 20:40:46 -04003258 assert Error.__name__ == "Error"
Rick Deane15b1472009-07-09 15:53:42 -05003259
3260
Alex Chanb7480992017-01-30 14:04:47 +00003261class TestConstants(object):
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003262 """
Alex Chanb7480992017-01-30 14:04:47 +00003263 Tests for the values of constants exposed in `OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003264
3265 These are values defined by OpenSSL intended only to be used as flags to
3266 OpenSSL APIs. The only assertions it seems can be made about them is
3267 their values.
3268 """
Alex Gaynor03737182020-07-23 20:40:46 -04003269
Hynek Schlawack35618382015-09-05 21:54:25 +02003270 @pytest.mark.skipif(
3271 OP_NO_QUERY_MTU is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003272 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003273 )
3274 def test_op_no_query_mtu(self):
3275 """
Alex Chanb7480992017-01-30 14:04:47 +00003276 The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3277 of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003278 """
Alex Chanb7480992017-01-30 14:04:47 +00003279 assert OP_NO_QUERY_MTU == 0x1000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003280
Hynek Schlawack35618382015-09-05 21:54:25 +02003281 @pytest.mark.skipif(
3282 OP_COOKIE_EXCHANGE is None,
3283 reason="OP_COOKIE_EXCHANGE unavailable - "
Alex Gaynor03737182020-07-23 20:40:46 -04003284 "OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003285 )
3286 def test_op_cookie_exchange(self):
3287 """
Alex Chanb7480992017-01-30 14:04:47 +00003288 The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3289 value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003290 """
Alex Chanb7480992017-01-30 14:04:47 +00003291 assert OP_COOKIE_EXCHANGE == 0x2000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003292
Hynek Schlawack35618382015-09-05 21:54:25 +02003293 @pytest.mark.skipif(
3294 OP_NO_TICKET is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003295 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003296 )
3297 def test_op_no_ticket(self):
3298 """
Alex Chanb7480992017-01-30 14:04:47 +00003299 The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3300 `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003301 """
Alex Chanb7480992017-01-30 14:04:47 +00003302 assert OP_NO_TICKET == 0x4000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003303
Hynek Schlawack35618382015-09-05 21:54:25 +02003304 @pytest.mark.skipif(
3305 OP_NO_COMPRESSION is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003306 reason=(
3307 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3308 ),
Hynek Schlawack35618382015-09-05 21:54:25 +02003309 )
3310 def test_op_no_compression(self):
3311 """
Alex Chanb7480992017-01-30 14:04:47 +00003312 The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3313 value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003314 """
Alex Chanb7480992017-01-30 14:04:47 +00003315 assert OP_NO_COMPRESSION == 0x20000
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003316
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003317 def test_sess_cache_off(self):
3318 """
Alex Chanb7480992017-01-30 14:04:47 +00003319 The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3320 `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003321 """
Alex Chanb7480992017-01-30 14:04:47 +00003322 assert 0x0 == SESS_CACHE_OFF
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003323
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003324 def test_sess_cache_client(self):
3325 """
Alex Chanb7480992017-01-30 14:04:47 +00003326 The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3327 `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003328 """
Alex Chanb7480992017-01-30 14:04:47 +00003329 assert 0x1 == SESS_CACHE_CLIENT
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003330
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003331 def test_sess_cache_server(self):
3332 """
Alex Chanb7480992017-01-30 14:04:47 +00003333 The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3334 `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003335 """
Alex Chanb7480992017-01-30 14:04:47 +00003336 assert 0x2 == SESS_CACHE_SERVER
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003337
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003338 def test_sess_cache_both(self):
3339 """
Alex Chanb7480992017-01-30 14:04:47 +00003340 The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3341 `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003342 """
Alex Chanb7480992017-01-30 14:04:47 +00003343 assert 0x3 == SESS_CACHE_BOTH
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003344
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003345 def test_sess_cache_no_auto_clear(self):
3346 """
Alex Chanb7480992017-01-30 14:04:47 +00003347 The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3348 value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3349 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003350 """
Alex Chanb7480992017-01-30 14:04:47 +00003351 assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003352
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003353 def test_sess_cache_no_internal_lookup(self):
3354 """
Alex Chanb7480992017-01-30 14:04:47 +00003355 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3356 the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3357 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003358 """
Alex Chanb7480992017-01-30 14:04:47 +00003359 assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003360
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003361 def test_sess_cache_no_internal_store(self):
3362 """
Alex Chanb7480992017-01-30 14:04:47 +00003363 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3364 the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3365 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003366 """
Alex Chanb7480992017-01-30 14:04:47 +00003367 assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003368
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003369 def test_sess_cache_no_internal(self):
3370 """
Alex Chanb7480992017-01-30 14:04:47 +00003371 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3372 value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
3373 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003374 """
Alex Chanb7480992017-01-30 14:04:47 +00003375 assert 0x300 == SESS_CACHE_NO_INTERNAL
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003376
3377
Alex Chanb7480992017-01-30 14:04:47 +00003378class TestMemoryBIO(object):
Rick Deanb71c0d22009-04-01 14:09:23 -05003379 """
Alex Chanb7480992017-01-30 14:04:47 +00003380 Tests for `OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003381 """
Alex Gaynor03737182020-07-23 20:40:46 -04003382
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003383 def _server(self, sock):
3384 """
Alex Chanb7480992017-01-30 14:04:47 +00003385 Create a new server-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003386 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003387 # Create the server side Connection. This is mostly setup boilerplate
3388 # - use TLSv1, use a particular certificate, etc.
Paul Kehrer688538c2020-08-03 19:18:15 -05003389 server_ctx = Context(SSLv23_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003390 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003391 server_ctx.set_verify(
3392 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
Alex Gaynor03737182020-07-23 20:40:46 -04003393 verify_cb,
Hynek Schlawack35618382015-09-05 21:54:25 +02003394 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003395 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003396 server_ctx.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04003397 load_privatekey(FILETYPE_PEM, server_key_pem)
3398 )
Hynek Schlawack35618382015-09-05 21:54:25 +02003399 server_ctx.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04003400 load_certificate(FILETYPE_PEM, server_cert_pem)
3401 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003402 server_ctx.check_privatekey()
3403 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003404 # Here the Connection is actually created. If None is passed as the
3405 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003406 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003407 server_conn.set_accept_state()
3408 return server_conn
3409
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003410 def _client(self, sock):
3411 """
Alex Chanb7480992017-01-30 14:04:47 +00003412 Create a new client-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003413 """
3414 # Now create the client side Connection. Similar boilerplate to the
3415 # above.
Paul Kehrer688538c2020-08-03 19:18:15 -05003416 client_ctx = Context(SSLv23_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003417 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003418 client_ctx.set_verify(
3419 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
Alex Gaynor03737182020-07-23 20:40:46 -04003420 verify_cb,
Hynek Schlawack35618382015-09-05 21:54:25 +02003421 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003422 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003423 client_ctx.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04003424 load_privatekey(FILETYPE_PEM, client_key_pem)
3425 )
Hynek Schlawack35618382015-09-05 21:54:25 +02003426 client_ctx.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04003427 load_certificate(FILETYPE_PEM, client_cert_pem)
3428 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003429 client_ctx.check_privatekey()
3430 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003431 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003432 client_conn.set_connect_state()
3433 return client_conn
3434
Alex Chanb7480992017-01-30 14:04:47 +00003435 def test_memory_connect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003436 """
Alex Chanb7480992017-01-30 14:04:47 +00003437 Two `Connection`s which use memory BIOs can be manually connected by
3438 reading from the output of each and writing those bytes to the input of
3439 the other and in this way establish a connection and exchange
3440 application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003441 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003442 server_conn = self._server(None)
3443 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003444
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003445 # There should be no key or nonces yet.
Alex Chanb7480992017-01-30 14:04:47 +00003446 assert server_conn.master_key() is None
3447 assert server_conn.client_random() is None
3448 assert server_conn.server_random() is None
Rick Deanb71c0d22009-04-01 14:09:23 -05003449
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003450 # First, the handshake needs to happen. We'll deliver bytes back and
3451 # forth between the client and server until neither of them feels like
3452 # speaking any more.
Alex Chanb7480992017-01-30 14:04:47 +00003453 assert interact_in_memory(client_conn, server_conn) is None
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003454
3455 # Now that the handshake is done, there should be a key and nonces.
Alex Chanb7480992017-01-30 14:04:47 +00003456 assert server_conn.master_key() is not None
3457 assert server_conn.client_random() is not None
3458 assert server_conn.server_random() is not None
3459 assert server_conn.client_random() == client_conn.client_random()
3460 assert server_conn.server_random() == client_conn.server_random()
3461 assert server_conn.client_random() != server_conn.server_random()
3462 assert client_conn.client_random() != client_conn.server_random()
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003463
Paul Kehrerbdb76392017-12-01 04:54:32 +08003464 # Export key material for other uses.
Alex Gaynor03737182020-07-23 20:40:46 -04003465 cekm = client_conn.export_keying_material(b"LABEL", 32)
3466 sekm = server_conn.export_keying_material(b"LABEL", 32)
Paul Kehrerbdb76392017-12-01 04:54:32 +08003467 assert cekm is not None
3468 assert sekm is not None
3469 assert cekm == sekm
3470 assert len(sekm) == 32
3471
3472 # Export key material for other uses with additional context.
Alex Gaynor03737182020-07-23 20:40:46 -04003473 cekmc = client_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
3474 sekmc = server_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
Paul Kehrerbdb76392017-12-01 04:54:32 +08003475 assert cekmc is not None
3476 assert sekmc is not None
3477 assert cekmc == sekmc
3478 assert cekmc != cekm
3479 assert sekmc != sekm
3480 # Export with alternate label
Alex Gaynor03737182020-07-23 20:40:46 -04003481 cekmt = client_conn.export_keying_material(b"test", 32, b"CONTEXT")
3482 sekmt = server_conn.export_keying_material(b"test", 32, b"CONTEXT")
Paul Kehrerbdb76392017-12-01 04:54:32 +08003483 assert cekmc != cekmt
3484 assert sekmc != sekmt
3485
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003486 # Here are the bytes we'll try to send.
Alex Gaynor03737182020-07-23 20:40:46 -04003487 important_message = b"One if by land, two if by sea."
Rick Deanb71c0d22009-04-01 14:09:23 -05003488
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003489 server_conn.write(important_message)
Alex Gaynor03737182020-07-23 20:40:46 -04003490 assert interact_in_memory(client_conn, server_conn) == (
3491 client_conn,
3492 important_message,
3493 )
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003494
3495 client_conn.write(important_message[::-1])
Alex Gaynor03737182020-07-23 20:40:46 -04003496 assert interact_in_memory(client_conn, server_conn) == (
3497 server_conn,
3498 important_message[::-1],
3499 )
Rick Deanb71c0d22009-04-01 14:09:23 -05003500
Alex Chanb7480992017-01-30 14:04:47 +00003501 def test_socket_connect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003502 """
Alex Chanb7480992017-01-30 14:04:47 +00003503 Just like `test_memory_connect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003504
Hynek Schlawack35618382015-09-05 21:54:25 +02003505 This is primarily to rule out the memory BIO code as the source of any
Alex Chanb7480992017-01-30 14:04:47 +00003506 problems encountered while passing data over a `Connection` (if
Hynek Schlawack35618382015-09-05 21:54:25 +02003507 this test fails, there must be a problem outside the memory BIO code,
3508 as no memory BIO is involved here). Even though this isn't a memory
3509 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003510 """
Alex Chanb7480992017-01-30 14:04:47 +00003511 server_conn, client_conn = loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003512
Alex Gaynore7f51982016-09-11 11:48:14 -04003513 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003514 client_conn.send(important_message)
3515 msg = server_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003516 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003517
3518 # Again in the other direction, just for fun.
3519 important_message = important_message[::-1]
3520 server_conn.send(important_message)
3521 msg = client_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003522 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003523
Alex Chanb7480992017-01-30 14:04:47 +00003524 def test_socket_overrides_memory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003525 """
Alex Chanb7480992017-01-30 14:04:47 +00003526 Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
3527 work on `OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003528 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003529 context = Context(SSLv23_METHOD)
David Benjamin1fbe0642019-04-15 17:05:13 -05003530 client = socket_any_family()
Rick Deanb71c0d22009-04-01 14:09:23 -05003531 clientSSL = Connection(context, client)
Alex Chanb7480992017-01-30 14:04:47 +00003532 with pytest.raises(TypeError):
3533 clientSSL.bio_read(100)
3534 with pytest.raises(TypeError):
Paul Kehrerc45a6ea2020-08-03 15:54:20 -05003535 clientSSL.bio_write(b"foo")
Alex Chanb7480992017-01-30 14:04:47 +00003536 with pytest.raises(TypeError):
3537 clientSSL.bio_shutdown()
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003538
Alex Chanb7480992017-01-30 14:04:47 +00003539 def test_outgoing_overflow(self):
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003540 """
3541 If more bytes than can be written to the memory BIO are passed to
Alex Chanb7480992017-01-30 14:04:47 +00003542 `Connection.send` at once, the number of bytes which were written is
3543 returned and that many bytes from the beginning of the input can be
3544 read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003545 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003546 server = self._server(None)
3547 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003548
Alex Chanb7480992017-01-30 14:04:47 +00003549 interact_in_memory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003550
3551 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003552 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003553 # Sanity check. We're trying to test what happens when the entire
3554 # input can't be sent. If the entire input was sent, this test is
3555 # meaningless.
Alex Chanb7480992017-01-30 14:04:47 +00003556 assert sent < size
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003557
Alex Chanb7480992017-01-30 14:04:47 +00003558 receiver, received = interact_in_memory(client, server)
3559 assert receiver is server
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003560
3561 # We can rely on all of these bytes being received at once because
Alex Chanb7480992017-01-30 14:04:47 +00003562 # loopback passes 2 ** 16 to recv - more than 2 ** 15.
3563 assert len(received) == sent
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003564
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003565 def test_shutdown(self):
3566 """
Alex Chanb7480992017-01-30 14:04:47 +00003567 `Connection.bio_shutdown` signals the end of the data stream
3568 from which the `Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003569 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003570 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003571 server.bio_shutdown()
Alex Chanb7480992017-01-30 14:04:47 +00003572 with pytest.raises(Error) as err:
3573 server.recv(1024)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003574 # We don't want WantReadError or ZeroReturnError or anything - it's a
3575 # handshake failure.
Alex Chanb7480992017-01-30 14:04:47 +00003576 assert type(err.value) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003577
Alex Chanb7480992017-01-30 14:04:47 +00003578 def test_unexpected_EOF(self):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003579 """
3580 If the connection is lost before an orderly SSL shutdown occurs,
Alex Chanb7480992017-01-30 14:04:47 +00003581 `OpenSSL.SSL.SysCallError` is raised with a message of
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003582 "Unexpected EOF".
3583 """
Alex Chanb7480992017-01-30 14:04:47 +00003584 server_conn, client_conn = loopback()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003585 client_conn.sock_shutdown(SHUT_RDWR)
Alex Chanb7480992017-01-30 14:04:47 +00003586 with pytest.raises(SysCallError) as err:
3587 server_conn.recv(1024)
3588 assert err.value.args == (-1, "Unexpected EOF")
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003589
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003590 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003591 """
Alex Chanb7480992017-01-30 14:04:47 +00003592 Verify the return value of the `get_client_ca_list` method for
Hynek Schlawack35618382015-09-05 21:54:25 +02003593 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003594
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003595 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003596 before the client and server are connected to each other. This
3597 function should specify a list of CAs for the server to send to the
3598 client and return that same list. The list will be used to verify
Alex Chanb7480992017-01-30 14:04:47 +00003599 that `get_client_ca_list` returns the proper value at
Hynek Schlawack35618382015-09-05 21:54:25 +02003600 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003601 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003602 server = self._server(None)
3603 client = self._client(None)
Alex Chanb7480992017-01-30 14:04:47 +00003604 assert client.get_client_ca_list() == []
3605 assert server.get_client_ca_list() == []
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003606 ctx = server.get_context()
3607 expected = func(ctx)
Alex Chanb7480992017-01-30 14:04:47 +00003608 assert client.get_client_ca_list() == []
3609 assert server.get_client_ca_list() == expected
3610 interact_in_memory(client, server)
3611 assert client.get_client_ca_list() == expected
3612 assert server.get_client_ca_list() == expected
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003613
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003614 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003615 """
Alex Chanb7480992017-01-30 14:04:47 +00003616 `Context.set_client_ca_list` raises a `TypeError` if called with a
3617 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003618 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003619 ctx = Context(SSLv23_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003620 with pytest.raises(TypeError):
3621 ctx.set_client_ca_list("spam")
3622 with pytest.raises(TypeError):
3623 ctx.set_client_ca_list(["spam"])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003624
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003625 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003626 """
Alex Chanb7480992017-01-30 14:04:47 +00003627 If passed an empty list, `Context.set_client_ca_list` configures the
3628 context to send no CA names to the client and, on both the server and
3629 client sides, `Connection.get_client_ca_list` returns an empty list
3630 after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003631 """
Alex Gaynor03737182020-07-23 20:40:46 -04003632
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003633 def no_ca(ctx):
3634 ctx.set_client_ca_list([])
3635 return []
Alex Gaynor03737182020-07-23 20:40:46 -04003636
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003637 self._check_client_ca_list(no_ca)
3638
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003639 def test_set_one_ca_list(self):
3640 """
3641 If passed a list containing a single X509Name,
Alex Chanb7480992017-01-30 14:04:47 +00003642 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003643 that CA name to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003644 `Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003645 X509Name after the connection is set up.
3646 """
3647 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3648 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003649
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003650 def single_ca(ctx):
3651 ctx.set_client_ca_list([cadesc])
3652 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003653
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003654 self._check_client_ca_list(single_ca)
3655
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003656 def test_set_multiple_ca_list(self):
3657 """
3658 If passed a list containing multiple X509Name objects,
Alex Chanb7480992017-01-30 14:04:47 +00003659 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003660 those CA names to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003661 `Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003662 X509Names after the connection is set up.
3663 """
3664 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3665 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3666
3667 sedesc = secert.get_subject()
3668 cldesc = clcert.get_subject()
3669
3670 def multiple_ca(ctx):
3671 L = [sedesc, cldesc]
3672 ctx.set_client_ca_list(L)
3673 return L
Alex Gaynor03737182020-07-23 20:40:46 -04003674
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003675 self._check_client_ca_list(multiple_ca)
3676
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003677 def test_reset_ca_list(self):
3678 """
3679 If called multiple times, only the X509Names passed to the final call
Alex Chanb7480992017-01-30 14:04:47 +00003680 of `Context.set_client_ca_list` are used to configure the CA
Hynek Schlawack35618382015-09-05 21:54:25 +02003681 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003682 """
3683 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3684 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3685 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3686
3687 cadesc = cacert.get_subject()
3688 sedesc = secert.get_subject()
3689 cldesc = clcert.get_subject()
3690
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003691 def changed_ca(ctx):
3692 ctx.set_client_ca_list([sedesc, cldesc])
3693 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003694 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003695
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003696 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003697
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003698 def test_mutated_ca_list(self):
3699 """
Alex Chanb7480992017-01-30 14:04:47 +00003700 If the list passed to `Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003701 afterwards, this does not affect the list of CA names sent to the
3702 client.
3703 """
3704 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3705 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3706
3707 cadesc = cacert.get_subject()
3708 sedesc = secert.get_subject()
3709
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003710 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003711 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003712 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003713 L.append(sedesc)
3714 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003715
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003716 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003717
Alex Chanb7480992017-01-30 14:04:47 +00003718 def test_add_client_ca_wrong_args(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003719 """
Alex Chanb7480992017-01-30 14:04:47 +00003720 `Context.add_client_ca` raises `TypeError` if called with
3721 a non-X509 object.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003722 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003723 ctx = Context(SSLv23_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003724 with pytest.raises(TypeError):
3725 ctx.add_client_ca("spam")
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003726
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003727 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003728 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003729 A certificate's subject can be added as a CA to be sent to the client
Alex Chanb7480992017-01-30 14:04:47 +00003730 with `Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003731 """
3732 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3733 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003734
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003735 def single_ca(ctx):
3736 ctx.add_client_ca(cacert)
3737 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003738
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003739 self._check_client_ca_list(single_ca)
3740
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003741 def test_multiple_add_client_ca(self):
3742 """
3743 Multiple CA names can be sent to the client by calling
Alex Chanb7480992017-01-30 14:04:47 +00003744 `Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003745 """
3746 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3747 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3748
3749 cadesc = cacert.get_subject()
3750 sedesc = secert.get_subject()
3751
3752 def multiple_ca(ctx):
3753 ctx.add_client_ca(cacert)
3754 ctx.add_client_ca(secert)
3755 return [cadesc, sedesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003756
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003757 self._check_client_ca_list(multiple_ca)
3758
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003759 def test_set_and_add_client_ca(self):
3760 """
Alex Chanb7480992017-01-30 14:04:47 +00003761 A call to `Context.set_client_ca_list` followed by a call to
3762 `Context.add_client_ca` results in using the CA names from the
Hynek Schlawack35618382015-09-05 21:54:25 +02003763 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003764 """
3765 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3766 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3767 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3768
3769 cadesc = cacert.get_subject()
3770 sedesc = secert.get_subject()
3771 cldesc = clcert.get_subject()
3772
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003773 def mixed_set_add_ca(ctx):
3774 ctx.set_client_ca_list([cadesc, sedesc])
3775 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003776 return [cadesc, sedesc, cldesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003777
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003778 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003779
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003780 def test_set_after_add_client_ca(self):
3781 """
Alex Chanb7480992017-01-30 14:04:47 +00003782 A call to `Context.set_client_ca_list` after a call to
3783 `Context.add_client_ca` replaces the CA name specified by the
Hynek Schlawack35618382015-09-05 21:54:25 +02003784 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003785 """
3786 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3787 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3788 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3789
3790 cadesc = cacert.get_subject()
3791 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003792
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003793 def set_replaces_add_ca(ctx):
3794 ctx.add_client_ca(clcert)
3795 ctx.set_client_ca_list([cadesc])
3796 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003797 return [cadesc, sedesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003798
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003799 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003800
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003801
Alex Chanb7480992017-01-30 14:04:47 +00003802class TestInfoConstants(object):
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003803 """
3804 Tests for assorted constants exposed for use in info callbacks.
3805 """
Alex Gaynor03737182020-07-23 20:40:46 -04003806
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003807 def test_integers(self):
3808 """
3809 All of the info constants are integers.
3810
3811 This is a very weak test. It would be nice to have one that actually
3812 verifies that as certain info events happen, the value passed to the
3813 info callback matches up with the constant exposed by OpenSSL.SSL.
3814 """
3815 for const in [
Alex Gaynor03737182020-07-23 20:40:46 -04003816 SSL_ST_CONNECT,
3817 SSL_ST_ACCEPT,
3818 SSL_ST_MASK,
3819 SSL_CB_LOOP,
3820 SSL_CB_EXIT,
3821 SSL_CB_READ,
3822 SSL_CB_WRITE,
3823 SSL_CB_ALERT,
3824 SSL_CB_READ_ALERT,
3825 SSL_CB_WRITE_ALERT,
3826 SSL_CB_ACCEPT_LOOP,
3827 SSL_CB_ACCEPT_EXIT,
3828 SSL_CB_CONNECT_LOOP,
3829 SSL_CB_CONNECT_EXIT,
3830 SSL_CB_HANDSHAKE_START,
3831 SSL_CB_HANDSHAKE_DONE,
Hynek Schlawack35618382015-09-05 21:54:25 +02003832 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003833 assert isinstance(const, int)
3834
3835 # These constants don't exist on OpenSSL 1.1.0
3836 for const in [
Alex Gaynor03737182020-07-23 20:40:46 -04003837 SSL_ST_INIT,
3838 SSL_ST_BEFORE,
3839 SSL_ST_OK,
3840 SSL_ST_RENEGOTIATE,
Alex Gaynor5af32d02016-09-24 01:52:21 -04003841 ]:
3842 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003843
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003844
Cory Benfield1d142142016-03-30 11:51:45 +01003845class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003846 """
3847 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003848 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003849 """
Alex Gaynor03737182020-07-23 20:40:46 -04003850
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003851 def test_available(self):
3852 """
3853 When the OpenSSL functionality is available the decorated functions
3854 work appropriately.
3855 """
3856 feature_guard = _make_requires(True, "Error text")
3857 results = []
3858
3859 @feature_guard
3860 def inner():
3861 results.append(True)
3862 return True
3863
Cory Benfield2333e5e2016-03-30 14:24:16 +01003864 assert inner() is True
3865 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003866
3867 def test_unavailable(self):
3868 """
3869 When the OpenSSL functionality is not available the decorated function
3870 does not execute and NotImplementedError is raised.
3871 """
3872 feature_guard = _make_requires(False, "Error text")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003873
3874 @feature_guard
Alex Chanfb078d82017-04-20 11:16:15 +01003875 def inner(): # pragma: nocover
3876 pytest.fail("Should not be called")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003877
Cory Benfield1d142142016-03-30 11:51:45 +01003878 with pytest.raises(NotImplementedError) as e:
3879 inner()
3880
3881 assert "Error text" in str(e.value)
Cory Benfield496652a2017-01-24 11:42:56 +00003882
3883
Alex Chanb7480992017-01-30 14:04:47 +00003884class TestOCSP(object):
Cory Benfield496652a2017-01-24 11:42:56 +00003885 """
3886 Tests for PyOpenSSL's OCSP stapling support.
3887 """
Alex Gaynor03737182020-07-23 20:40:46 -04003888
Cory Benfield496652a2017-01-24 11:42:56 +00003889 sample_ocsp_data = b"this is totally ocsp data"
3890
3891 def _client_connection(self, callback, data, request_ocsp=True):
3892 """
3893 Builds a client connection suitable for using OCSP.
3894
3895 :param callback: The callback to register for OCSP.
3896 :param data: The opaque data object that will be handed to the
3897 OCSP callback.
3898 :param request_ocsp: Whether the client will actually ask for OCSP
3899 stapling. Useful for testing only.
3900 """
3901 ctx = Context(SSLv23_METHOD)
3902 ctx.set_ocsp_client_callback(callback, data)
3903 client = Connection(ctx)
3904
3905 if request_ocsp:
3906 client.request_ocsp()
3907
3908 client.set_connect_state()
3909 return client
3910
3911 def _server_connection(self, callback, data):
3912 """
3913 Builds a server connection suitable for using OCSP.
3914
3915 :param callback: The callback to register for OCSP.
3916 :param data: The opaque data object that will be handed to the
3917 OCSP callback.
3918 """
3919 ctx = Context(SSLv23_METHOD)
3920 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
3921 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
3922 ctx.set_ocsp_server_callback(callback, data)
3923 server = Connection(ctx)
3924 server.set_accept_state()
3925 return server
3926
3927 def test_callbacks_arent_called_by_default(self):
3928 """
3929 If both the client and the server have registered OCSP callbacks, but
3930 the client does not send the OCSP request, neither callback gets
3931 called.
3932 """
Alex Gaynor03737182020-07-23 20:40:46 -04003933
Alex Chanfb078d82017-04-20 11:16:15 +01003934 def ocsp_callback(*args, **kwargs): # pragma: nocover
3935 pytest.fail("Should not be called")
Cory Benfield496652a2017-01-24 11:42:56 +00003936
3937 client = self._client_connection(
3938 callback=ocsp_callback, data=None, request_ocsp=False
3939 )
3940 server = self._server_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003941 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003942
Cory Benfield496652a2017-01-24 11:42:56 +00003943 def test_client_negotiates_without_server(self):
3944 """
3945 If the client wants to do OCSP but the server does not, the handshake
3946 succeeds, and the client callback fires with an empty byte string.
3947 """
3948 called = []
3949
3950 def ocsp_callback(conn, ocsp_data, ignored):
3951 called.append(ocsp_data)
3952 return True
3953
3954 client = self._client_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003955 server = loopback_server_factory(socket=None)
3956 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003957
3958 assert len(called) == 1
Alex Gaynor03737182020-07-23 20:40:46 -04003959 assert called[0] == b""
Cory Benfield496652a2017-01-24 11:42:56 +00003960
3961 def test_client_receives_servers_data(self):
3962 """
3963 The data the server sends in its callback is received by the client.
3964 """
3965 calls = []
3966
3967 def server_callback(*args, **kwargs):
3968 return self.sample_ocsp_data
3969
3970 def client_callback(conn, ocsp_data, ignored):
3971 calls.append(ocsp_data)
3972 return True
3973
3974 client = self._client_connection(callback=client_callback, data=None)
3975 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003976 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003977
3978 assert len(calls) == 1
3979 assert calls[0] == self.sample_ocsp_data
3980
3981 def test_callbacks_are_invoked_with_connections(self):
3982 """
3983 The first arguments to both callbacks are their respective connections.
3984 """
3985 client_calls = []
3986 server_calls = []
3987
3988 def client_callback(conn, *args, **kwargs):
3989 client_calls.append(conn)
3990 return True
3991
3992 def server_callback(conn, *args, **kwargs):
3993 server_calls.append(conn)
3994 return self.sample_ocsp_data
3995
3996 client = self._client_connection(callback=client_callback, data=None)
3997 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003998 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003999
4000 assert len(client_calls) == 1
4001 assert len(server_calls) == 1
4002 assert client_calls[0] is client
4003 assert server_calls[0] is server
4004
4005 def test_opaque_data_is_passed_through(self):
4006 """
4007 Both callbacks receive an opaque, user-provided piece of data in their
4008 callbacks as the final argument.
4009 """
4010 calls = []
4011
4012 def server_callback(*args):
4013 calls.append(args)
4014 return self.sample_ocsp_data
4015
4016 def client_callback(*args):
4017 calls.append(args)
4018 return True
4019
4020 sentinel = object()
4021
4022 client = self._client_connection(
4023 callback=client_callback, data=sentinel
4024 )
4025 server = self._server_connection(
4026 callback=server_callback, data=sentinel
4027 )
Alex Chanb7480992017-01-30 14:04:47 +00004028 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004029
4030 assert len(calls) == 2
4031 assert calls[0][-1] is sentinel
4032 assert calls[1][-1] is sentinel
4033
4034 def test_server_returns_empty_string(self):
4035 """
4036 If the server returns an empty bytestring from its callback, the
4037 client callback is called with the empty bytestring.
4038 """
4039 client_calls = []
4040
4041 def server_callback(*args):
Alex Gaynor03737182020-07-23 20:40:46 -04004042 return b""
Cory Benfield496652a2017-01-24 11:42:56 +00004043
4044 def client_callback(conn, ocsp_data, ignored):
4045 client_calls.append(ocsp_data)
4046 return True
4047
4048 client = self._client_connection(callback=client_callback, data=None)
4049 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00004050 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004051
4052 assert len(client_calls) == 1
Alex Gaynor03737182020-07-23 20:40:46 -04004053 assert client_calls[0] == b""
Cory Benfield496652a2017-01-24 11:42:56 +00004054
4055 def test_client_returns_false_terminates_handshake(self):
4056 """
4057 If the client returns False from its callback, the handshake fails.
4058 """
Alex Gaynor03737182020-07-23 20:40:46 -04004059
Cory Benfield496652a2017-01-24 11:42:56 +00004060 def server_callback(*args):
4061 return self.sample_ocsp_data
4062
4063 def client_callback(*args):
4064 return False
4065
4066 client = self._client_connection(callback=client_callback, data=None)
4067 server = self._server_connection(callback=server_callback, data=None)
4068
4069 with pytest.raises(Error):
Alex Chanb7480992017-01-30 14:04:47 +00004070 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004071
4072 def test_exceptions_in_client_bubble_up(self):
4073 """
4074 The callbacks thrown in the client callback bubble up to the caller.
4075 """
Alex Gaynor03737182020-07-23 20:40:46 -04004076
Cory Benfield496652a2017-01-24 11:42:56 +00004077 class SentinelException(Exception):
4078 pass
4079
4080 def server_callback(*args):
4081 return self.sample_ocsp_data
4082
4083 def client_callback(*args):
4084 raise SentinelException()
4085
4086 client = self._client_connection(callback=client_callback, data=None)
4087 server = self._server_connection(callback=server_callback, data=None)
4088
4089 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00004090 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004091
4092 def test_exceptions_in_server_bubble_up(self):
4093 """
4094 The callbacks thrown in the server callback bubble up to the caller.
4095 """
Alex Gaynor03737182020-07-23 20:40:46 -04004096
Cory Benfield496652a2017-01-24 11:42:56 +00004097 class SentinelException(Exception):
4098 pass
4099
4100 def server_callback(*args):
4101 raise SentinelException()
4102
Alex Chanfb078d82017-04-20 11:16:15 +01004103 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00004104 pytest.fail("Should not be called")
4105
4106 client = self._client_connection(callback=client_callback, data=None)
4107 server = self._server_connection(callback=server_callback, data=None)
4108
4109 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00004110 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004111
4112 def test_server_must_return_bytes(self):
4113 """
4114 The server callback must return a bytestring, or a TypeError is thrown.
4115 """
Alex Gaynor03737182020-07-23 20:40:46 -04004116
Cory Benfield496652a2017-01-24 11:42:56 +00004117 def server_callback(*args):
Alex Gaynor03737182020-07-23 20:40:46 -04004118 return self.sample_ocsp_data.decode("ascii")
Cory Benfield496652a2017-01-24 11:42:56 +00004119
Alex Chanfb078d82017-04-20 11:16:15 +01004120 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00004121 pytest.fail("Should not be called")
4122
4123 client = self._client_connection(callback=client_callback, data=None)
4124 server = self._server_connection(callback=server_callback, data=None)
4125
4126 with pytest.raises(TypeError):
Alex Chanb7480992017-01-30 14:04:47 +00004127 handshake_in_memory(client, server)