blob: 7e28ab743d96b2022cbc40666b52bcc65d465369 [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
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002448 def test_get_session_unconnected(self):
2449 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002450 `Connection.get_session` returns `None` when used with an object
2451 which has not been connected.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002452 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002453 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002454 server = Connection(ctx, None)
2455 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002456 assert None is session
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002457
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002458 def test_server_get_session(self):
2459 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002460 On the server side of a connection, `Connection.get_session` returns a
2461 `Session` instance representing the SSL session for that connection.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002462 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002463 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002464 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002465 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002466
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002467 def test_client_get_session(self):
2468 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002469 On the client side of a connection, `Connection.get_session`
2470 returns a `Session` instance representing the SSL session for
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002471 that connection.
2472 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002473 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002474 session = client.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002475 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002476
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002477 def test_set_session_wrong_args(self):
2478 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002479 `Connection.set_session` raises `TypeError` if called with an object
2480 that is not an instance of `Session`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002481 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002482 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002483 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002484 with pytest.raises(TypeError):
2485 connection.set_session(123)
2486 with pytest.raises(TypeError):
2487 connection.set_session("hello")
2488 with pytest.raises(TypeError):
2489 connection.set_session(object())
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002490
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002491 def test_client_set_session(self):
2492 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002493 `Connection.set_session`, when used prior to a connection being
2494 established, accepts a `Session` instance and causes an attempt to
2495 re-use the session it represents when the SSL handshake is performed.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002496 """
2497 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2498 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06002499 ctx = Context(TLSv1_2_METHOD)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002500 ctx.use_privatekey(key)
2501 ctx.use_certificate(cert)
2502 ctx.set_session_id("unity-test")
2503
2504 def makeServer(socket):
2505 server = Connection(ctx, socket)
2506 server.set_accept_state()
2507 return server
2508
Alex Gaynor03737182020-07-23 20:40:46 -04002509 originalServer, originalClient = loopback(server_factory=makeServer)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002510 originalSession = originalClient.get_session()
2511
2512 def makeClient(socket):
Alex Chan1c0cb662017-01-30 07:13:30 +00002513 client = loopback_client_factory(socket)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002514 client.set_session(originalSession)
2515 return client
Alex Gaynor03737182020-07-23 20:40:46 -04002516
Alex Chan1c0cb662017-01-30 07:13:30 +00002517 resumedServer, resumedClient = loopback(
Alex Gaynor03737182020-07-23 20:40:46 -04002518 server_factory=makeServer, client_factory=makeClient
2519 )
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002520
2521 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002522 # identifier for the session (new enough versions of OpenSSL expose
2523 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002524 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002525 # session is re-used. As long as the master key for the two
2526 # connections is the same, the session was re-used!
Alex Chan1c0cb662017-01-30 07:13:30 +00002527 assert originalServer.master_key() == resumedServer.master_key()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002528
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002529 def test_set_session_wrong_method(self):
2530 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002531 If `Connection.set_session` is passed a `Session` instance associated
2532 with a context using a different SSL method than the `Connection`
2533 is using, a `OpenSSL.SSL.Error` is raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002534 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002535 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2536 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2537 # is a way to check for 1.1.0)
Alex Gaynoraa32e712017-06-29 20:56:12 -07002538 if SSL_ST_INIT is None:
2539 v1 = TLSv1_2_METHOD
2540 v2 = TLSv1_METHOD
2541 elif hasattr(_lib, "SSLv3_method"):
Alex Gaynor5af32d02016-09-24 01:52:21 -04002542 v1 = TLSv1_METHOD
2543 v2 = SSLv3_METHOD
2544 else:
Alex Gaynoraa32e712017-06-29 20:56:12 -07002545 pytest.skip("Test requires either OpenSSL 1.1.0 or SSLv3")
Alex Gaynor5af32d02016-09-24 01:52:21 -04002546
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002547 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2548 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002549 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002550 ctx.use_privatekey(key)
2551 ctx.use_certificate(cert)
Paul Kehrerc45a6ea2020-08-03 15:54:20 -05002552 ctx.set_session_id(b"unity-test")
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002553
2554 def makeServer(socket):
2555 server = Connection(ctx, socket)
2556 server.set_accept_state()
2557 return server
2558
Alex Gaynor5af32d02016-09-24 01:52:21 -04002559 def makeOriginalClient(socket):
2560 client = Connection(Context(v1), socket)
2561 client.set_connect_state()
2562 return client
2563
Alex Chan1c0cb662017-01-30 07:13:30 +00002564 originalServer, originalClient = loopback(
Alex Gaynor03737182020-07-23 20:40:46 -04002565 server_factory=makeServer, client_factory=makeOriginalClient
2566 )
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002567 originalSession = originalClient.get_session()
2568
2569 def makeClient(socket):
2570 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002571 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002572 client.set_connect_state()
2573 client.set_session(originalSession)
2574 return client
2575
Alex Chan1c0cb662017-01-30 07:13:30 +00002576 with pytest.raises(Error):
2577 loopback(client_factory=makeClient, server_factory=makeServer)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002578
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002579 def test_wantWriteError(self):
2580 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002581 `Connection` methods which generate output raise
2582 `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002583 fail indicating a should-write state.
2584 """
2585 client_socket, server_socket = socket_pair()
2586 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002587 # anything. Only write a single byte at a time so we can be sure we
2588 # completely fill the buffer. Even though the socket API is allowed to
2589 # signal a short write via its return value it seems this doesn't
2590 # always happen on all platforms (FreeBSD and OS X particular) for the
2591 # very last bit of available buffer space.
2592 msg = b"x"
caternb2777a42018-08-09 15:38:13 -04002593 for i in range(1024 * 1024 * 64):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002594 try:
2595 client_socket.send(msg)
2596 except error as e:
2597 if e.errno == EWOULDBLOCK:
2598 break
2599 raise
2600 else:
Alex Chan1c0cb662017-01-30 07:13:30 +00002601 pytest.fail(
Alex Gaynor03737182020-07-23 20:40:46 -04002602 "Failed to fill socket buffer, cannot test BIO want write"
2603 )
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002604
Paul Kehrer688538c2020-08-03 19:18:15 -05002605 ctx = Context(SSLv23_METHOD)
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002606 conn = Connection(ctx, client_socket)
2607 # Client's speak first, so make it an SSL client
2608 conn.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002609 with pytest.raises(WantWriteError):
2610 conn.do_handshake()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002611
2612 # XXX want_read
2613
Fedor Brunner416f4a12014-03-28 13:18:38 +01002614 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002615 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002616 `Connection.get_finished` returns `None` before TLS handshake
2617 is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002618 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002619 ctx = Context(SSLv23_METHOD)
Fedor Brunner5747b932014-03-05 14:22:34 +01002620 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002621 assert connection.get_finished() is None
Fedor Brunner416f4a12014-03-28 13:18:38 +01002622
2623 def test_get_peer_finished_before_connect(self):
2624 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002625 `Connection.get_peer_finished` returns `None` before TLS handshake
2626 is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002627 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002628 ctx = Context(SSLv23_METHOD)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002629 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002630 assert connection.get_peer_finished() is None
Fedor Brunner5747b932014-03-05 14:22:34 +01002631
Fedor Brunner416f4a12014-03-28 13:18:38 +01002632 def test_get_finished(self):
2633 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002634 `Connection.get_finished` method returns the TLS Finished message send
2635 from client, or server. Finished messages are send during
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002636 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002637 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002638 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002639
Alex Chan1c0cb662017-01-30 07:13:30 +00002640 assert server.get_finished() is not None
2641 assert len(server.get_finished()) > 0
Fedor Brunner416f4a12014-03-28 13:18:38 +01002642
2643 def test_get_peer_finished(self):
2644 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002645 `Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002646 message received from client, or server. Finished messages are send
2647 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002648 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002649 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002650
Alex Chan1c0cb662017-01-30 07:13:30 +00002651 assert server.get_peer_finished() is not None
2652 assert len(server.get_peer_finished()) > 0
Fedor Brunner5747b932014-03-05 14:22:34 +01002653
Fedor Brunner416f4a12014-03-28 13:18:38 +01002654 def test_tls_finished_message_symmetry(self):
2655 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002656 The TLS Finished message send by server must be the TLS Finished
2657 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002658
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002659 The TLS Finished message send by client must be the TLS Finished
2660 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002661 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002662 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002663
Alex Chan1c0cb662017-01-30 07:13:30 +00002664 assert server.get_finished() == client.get_peer_finished()
2665 assert client.get_finished() == server.get_peer_finished()
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002666
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002667 def test_get_cipher_name_before_connect(self):
2668 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002669 `Connection.get_cipher_name` returns `None` if no connection
2670 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002671 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002672 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002673 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002674 assert conn.get_cipher_name() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002675
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002676 def test_get_cipher_name(self):
2677 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002678 `Connection.get_cipher_name` returns a `unicode` string giving the
2679 name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002680 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002681 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002682 server_cipher_name, client_cipher_name = (
2683 server.get_cipher_name(),
2684 client.get_cipher_name(),
2685 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002686
Alex Chan1c0cb662017-01-30 07:13:30 +00002687 assert isinstance(server_cipher_name, text_type)
2688 assert isinstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002689
Alex Chan1c0cb662017-01-30 07:13:30 +00002690 assert server_cipher_name == client_cipher_name
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002691
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002692 def test_get_cipher_version_before_connect(self):
2693 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002694 `Connection.get_cipher_version` returns `None` if no connection
2695 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002696 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002697 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002698 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002699 assert conn.get_cipher_version() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002700
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002701 def test_get_cipher_version(self):
2702 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002703 `Connection.get_cipher_version` returns a `unicode` string giving
2704 the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002705 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002706 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002707 server_cipher_version, client_cipher_version = (
2708 server.get_cipher_version(),
2709 client.get_cipher_version(),
2710 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002711
Alex Chan1c0cb662017-01-30 07:13:30 +00002712 assert isinstance(server_cipher_version, text_type)
2713 assert isinstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002714
Alex Chan1c0cb662017-01-30 07:13:30 +00002715 assert server_cipher_version == client_cipher_version
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002716
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002717 def test_get_cipher_bits_before_connect(self):
2718 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002719 `Connection.get_cipher_bits` returns `None` if no connection has
2720 been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002721 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002722 ctx = Context(SSLv23_METHOD)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002723 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002724 assert conn.get_cipher_bits() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002725
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002726 def test_get_cipher_bits(self):
2727 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002728 `Connection.get_cipher_bits` returns the number of secret bits
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002729 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002730 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002731 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002732 server_cipher_bits, client_cipher_bits = (
2733 server.get_cipher_bits(),
2734 client.get_cipher_bits(),
2735 )
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002736
Alex Chan1c0cb662017-01-30 07:13:30 +00002737 assert isinstance(server_cipher_bits, int)
2738 assert isinstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002739
Alex Chan1c0cb662017-01-30 07:13:30 +00002740 assert server_cipher_bits == client_cipher_bits
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002741
Jim Shaverabff1882015-05-27 09:15:55 -04002742 def test_get_protocol_version_name(self):
2743 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002744 `Connection.get_protocol_version_name()` returns a string giving the
2745 protocol version of the current connection.
Jim Shaverabff1882015-05-27 09:15:55 -04002746 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002747 server, client = loopback()
Jim Shaverabff1882015-05-27 09:15:55 -04002748 client_protocol_version_name = client.get_protocol_version_name()
2749 server_protocol_version_name = server.get_protocol_version_name()
2750
Alex Chan1c0cb662017-01-30 07:13:30 +00002751 assert isinstance(server_protocol_version_name, text_type)
2752 assert isinstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002753
Alex Chan1c0cb662017-01-30 07:13:30 +00002754 assert server_protocol_version_name == client_protocol_version_name
Jim Shaverabff1882015-05-27 09:15:55 -04002755
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002756 def test_get_protocol_version(self):
2757 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002758 `Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002759 giving the protocol version of the current connection.
2760 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002761 server, client = loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002762 client_protocol_version = client.get_protocol_version()
2763 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002764
Alex Chan1c0cb662017-01-30 07:13:30 +00002765 assert isinstance(server_protocol_version, int)
2766 assert isinstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002767
Alex Chan1c0cb662017-01-30 07:13:30 +00002768 assert server_protocol_version == client_protocol_version
2769
2770 def test_wantReadError(self):
2771 """
2772 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
2773 no bytes available to be read from the BIO.
2774 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002775 ctx = Context(SSLv23_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002776 conn = Connection(ctx, None)
2777 with pytest.raises(WantReadError):
2778 conn.bio_read(1024)
2779
Alex Gaynor03737182020-07-23 20:40:46 -04002780 @pytest.mark.parametrize("bufsize", [1.0, None, object(), "bufsize"])
Alex Chanfb078d82017-04-20 11:16:15 +01002781 def test_bio_read_wrong_args(self, bufsize):
2782 """
2783 `Connection.bio_read` raises `TypeError` if passed a non-integer
2784 argument.
2785 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002786 ctx = Context(SSLv23_METHOD)
Alex Chanfb078d82017-04-20 11:16:15 +01002787 conn = Connection(ctx, None)
2788 with pytest.raises(TypeError):
2789 conn.bio_read(bufsize)
2790
Alex Chan1c0cb662017-01-30 07:13:30 +00002791 def test_buffer_size(self):
2792 """
2793 `Connection.bio_read` accepts an integer giving the maximum number
2794 of bytes to read and return.
2795 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002796 ctx = Context(SSLv23_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002797 conn = Connection(ctx, None)
2798 conn.set_connect_state()
2799 try:
2800 conn.do_handshake()
2801 except WantReadError:
2802 pass
2803 data = conn.bio_read(2)
2804 assert 2 == len(data)
2805
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002806
Alex Chanb7480992017-01-30 14:04:47 +00002807class TestConnectionGetCipherList(object):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002808 """
Alex Chanb7480992017-01-30 14:04:47 +00002809 Tests for `Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002810 """
Alex Gaynor03737182020-07-23 20:40:46 -04002811
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002812 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002813 """
Alex Chanb7480992017-01-30 14:04:47 +00002814 `Connection.get_cipher_list` returns a list of `bytes` giving the
2815 names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002816 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002817 connection = Connection(Context(SSLv23_METHOD), None)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002818 ciphers = connection.get_cipher_list()
Alex Chanb7480992017-01-30 14:04:47 +00002819 assert isinstance(ciphers, list)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002820 for cipher in ciphers:
Alex Chanb7480992017-01-30 14:04:47 +00002821 assert isinstance(cipher, str)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002822
2823
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002824class VeryLarge(bytes):
2825 """
2826 Mock object so that we don't have to allocate 2**31 bytes
2827 """
Alex Gaynor03737182020-07-23 20:40:46 -04002828
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002829 def __len__(self):
Alex Gaynor03737182020-07-23 20:40:46 -04002830 return 2 ** 31
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002831
2832
Alex Chanb7480992017-01-30 14:04:47 +00002833class TestConnectionSend(object):
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002834 """
Alex Chanb7480992017-01-30 14:04:47 +00002835 Tests for `Connection.send`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002836 """
Alex Gaynor03737182020-07-23 20:40:46 -04002837
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002838 def test_wrong_args(self):
2839 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002840 When called with arguments other than string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00002841 parameter, `Connection.send` raises `TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002842 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002843 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00002844 with pytest.raises(TypeError):
2845 connection.send(object())
Daniel Holth079c9632019-11-17 22:45:52 -05002846 with pytest.raises(TypeError):
2847 connection.send([1, 2, 3])
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002848
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002849 def test_short_bytes(self):
2850 """
Alex Chanb7480992017-01-30 14:04:47 +00002851 When passed a short byte string, `Connection.send` transmits all of it
2852 and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002853 """
Alex Chanb7480992017-01-30 14:04:47 +00002854 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002855 count = server.send(b"xy")
Alex Chanb7480992017-01-30 14:04:47 +00002856 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002857 assert client.recv(2) == b"xy"
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002858
Abraham Martinef063482015-03-25 14:06:24 +00002859 def test_text(self):
2860 """
Alex Chanb7480992017-01-30 14:04:47 +00002861 When passed a text, `Connection.send` transmits all of it and
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002862 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002863 """
Alex Chanb7480992017-01-30 14:04:47 +00002864 server, client = loopback()
2865 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00002866 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002867 count = server.send(b"xy".decode("ascii"))
Alex Gaynor03737182020-07-23 20:40:46 -04002868 assert "{0} for buf is no longer accepted, use bytes".format(
2869 WARNING_TYPE_EXPECTED
2870 ) == str(w[-1].message)
Alex Chanb7480992017-01-30 14:04:47 +00002871 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002872 assert client.recv(2) == b"xy"
Abraham Martinef063482015-03-25 14:06:24 +00002873
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002874 def test_short_memoryview(self):
2875 """
2876 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002877 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002878 of bytes sent.
2879 """
Alex Chanb7480992017-01-30 14:04:47 +00002880 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002881 count = server.send(memoryview(b"xy"))
Alex Chanb7480992017-01-30 14:04:47 +00002882 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002883 assert client.recv(2) == b"xy"
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002884
Daniel Holth079c9632019-11-17 22:45:52 -05002885 def test_short_bytearray(self):
2886 """
2887 When passed a short bytearray, `Connection.send` transmits all of
2888 it and returns the number of bytes sent.
2889 """
2890 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002891 count = server.send(bytearray(b"xy"))
Daniel Holth079c9632019-11-17 22:45:52 -05002892 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002893 assert client.recv(2) == b"xy"
Daniel Holth079c9632019-11-17 22:45:52 -05002894
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002895 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002896 def test_short_buffer(self):
2897 """
2898 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002899 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002900 of bytes sent.
2901 """
Alex Chanb7480992017-01-30 14:04:47 +00002902 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002903 count = server.send(buffer(b"xy")) # noqa: F821
Alex Chanb7480992017-01-30 14:04:47 +00002904 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002905 assert client.recv(2) == b"xy"
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002906
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002907 @pytest.mark.skipif(
Alex Gaynor03737182020-07-23 20:40:46 -04002908 sys.maxsize < 2 ** 31,
2909 reason="sys.maxsize < 2**31 - test requires 64 bit",
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002910 )
2911 def test_buf_too_large(self):
2912 """
2913 When passed a buffer containing >= 2**31 bytes,
2914 `Connection.send` bails out as SSL_write only
2915 accepts an int for the buffer length.
2916 """
Paul Kehrer688538c2020-08-03 19:18:15 -05002917 connection = Connection(Context(SSLv23_METHOD), None)
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002918 with pytest.raises(ValueError) as exc_info:
2919 connection.send(VeryLarge())
2920 exc_info.match(r"Cannot send more than .+ bytes at once")
2921
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002922
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002923def _make_memoryview(size):
2924 """
2925 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2926 size.
2927 """
2928 return memoryview(bytearray(size))
2929
2930
Alex Chanb7480992017-01-30 14:04:47 +00002931class TestConnectionRecvInto(object):
Cory Benfield62d10332014-06-15 10:03:41 +01002932 """
Alex Chanb7480992017-01-30 14:04:47 +00002933 Tests for `Connection.recv_into`.
Cory Benfield62d10332014-06-15 10:03:41 +01002934 """
Alex Gaynor03737182020-07-23 20:40:46 -04002935
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002936 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002937 """
Alex Chanb7480992017-01-30 14:04:47 +00002938 Assert that when the given buffer is passed to `Connection.recv_into`,
2939 whatever bytes are available to be received that fit into that buffer
2940 are written into that buffer.
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002941 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002942 output_buffer = factory(5)
2943
Alex Chanb7480992017-01-30 14:04:47 +00002944 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002945 server.send(b"xy")
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002946
Alex Chanb7480992017-01-30 14:04:47 +00002947 assert client.recv_into(output_buffer) == 2
Alex Gaynor03737182020-07-23 20:40:46 -04002948 assert output_buffer == bytearray(b"xy\x00\x00\x00")
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002949
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002950 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002951 """
Alex Chanb7480992017-01-30 14:04:47 +00002952 `Connection.recv_into` can be passed a `bytearray` instance and data
2953 in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002954 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002955 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002956
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002957 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002958 """
Alex Chanb7480992017-01-30 14:04:47 +00002959 Assert that when the given buffer is passed to `Connection.recv_into`
2960 along with a value for `nbytes` that is less than the size of that
2961 buffer, only `nbytes` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002962 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002963 output_buffer = factory(10)
2964
Alex Chanb7480992017-01-30 14:04:47 +00002965 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002966 server.send(b"abcdefghij")
Cory Benfield62d10332014-06-15 10:03:41 +01002967
Alex Chanb7480992017-01-30 14:04:47 +00002968 assert client.recv_into(output_buffer, 5) == 5
Alex Gaynor03737182020-07-23 20:40:46 -04002969 assert output_buffer == bytearray(b"abcde\x00\x00\x00\x00\x00")
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002970
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002971 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002972 """
Alex Chanb7480992017-01-30 14:04:47 +00002973 When called with a `bytearray` instance, `Connection.recv_into`
2974 respects the `nbytes` parameter and doesn't copy in more than that
2975 number of bytes.
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002976 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002977 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002978
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002979 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002980 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002981 Assert that if there are more bytes available to be read from the
2982 receive buffer than would fit into the buffer passed to
Alex Chanb7480992017-01-30 14:04:47 +00002983 `Connection.recv_into`, only as many as fit are written into it.
Cory Benfield62d10332014-06-15 10:03:41 +01002984 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002985 output_buffer = factory(5)
2986
Alex Chanb7480992017-01-30 14:04:47 +00002987 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04002988 server.send(b"abcdefghij")
Cory Benfield62d10332014-06-15 10:03:41 +01002989
Alex Chanb7480992017-01-30 14:04:47 +00002990 assert client.recv_into(output_buffer) == 5
Alex Gaynor03737182020-07-23 20:40:46 -04002991 assert output_buffer == bytearray(b"abcde")
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002992 rest = client.recv(5)
Alex Gaynor03737182020-07-23 20:40:46 -04002993 assert b"fghij" == rest
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002994
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002995 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002996 """
Alex Chanb7480992017-01-30 14:04:47 +00002997 When called with a `bytearray` instance, `Connection.recv_into`
2998 respects the size of the array and doesn't write more bytes into it
2999 than will fit.
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003000 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003001 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003002
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003003 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003004 """
Alex Chanb7480992017-01-30 14:04:47 +00003005 When called with a `bytearray` instance and an `nbytes` value that is
3006 too large, `Connection.recv_into` respects the size of the array and
3007 not the `nbytes` value and doesn't write more bytes into the buffer
3008 than will fit.
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003009 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003010 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003011
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003012 def test_peek(self):
Alex Chanb7480992017-01-30 14:04:47 +00003013 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003014 server.send(b"xy")
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003015
3016 for _ in range(2):
3017 output_buffer = bytearray(5)
Alex Chanb7480992017-01-30 14:04:47 +00003018 assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
Alex Gaynor03737182020-07-23 20:40:46 -04003019 assert output_buffer == bytearray(b"xy\x00\x00\x00")
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003020
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003021 def test_memoryview_no_length(self):
3022 """
Alex Chanb7480992017-01-30 14:04:47 +00003023 `Connection.recv_into` can be passed a `memoryview` instance and data
3024 in the receive buffer is written to it.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003025 """
3026 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003027
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003028 def test_memoryview_respects_length(self):
3029 """
Alex Chanb7480992017-01-30 14:04:47 +00003030 When called with a `memoryview` instance, `Connection.recv_into`
3031 respects the ``nbytes`` parameter and doesn't copy more than that
3032 number of bytes in.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003033 """
3034 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003035
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003036 def test_memoryview_doesnt_overfill(self):
3037 """
Alex Chanb7480992017-01-30 14:04:47 +00003038 When called with a `memoryview` instance, `Connection.recv_into`
3039 respects the size of the array and doesn't write more bytes into it
3040 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003041 """
3042 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003043
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003044 def test_memoryview_really_doesnt_overfill(self):
3045 """
Alex Chanb7480992017-01-30 14:04:47 +00003046 When called with a `memoryview` instance and an `nbytes` value that is
3047 too large, `Connection.recv_into` respects the size of the array and
3048 not the `nbytes` value and doesn't write more bytes into the buffer
3049 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003050 """
3051 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003052
Cory Benfield62d10332014-06-15 10:03:41 +01003053
Alex Chanb7480992017-01-30 14:04:47 +00003054class TestConnectionSendall(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003055 """
Alex Chanb7480992017-01-30 14:04:47 +00003056 Tests for `Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003057 """
Alex Gaynor03737182020-07-23 20:40:46 -04003058
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003059 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003060 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003061 When called with arguments other than a string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00003062 parameter, `Connection.sendall` raises `TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003063 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003064 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003065 with pytest.raises(TypeError):
3066 connection.sendall(object())
Daniel Holth079c9632019-11-17 22:45:52 -05003067 with pytest.raises(TypeError):
3068 connection.sendall([1, 2, 3])
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003069
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003070 def test_short(self):
3071 """
Alex Chanb7480992017-01-30 14:04:47 +00003072 `Connection.sendall` transmits all of the bytes in the string
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003073 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003074 """
Alex Chanb7480992017-01-30 14:04:47 +00003075 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003076 server.sendall(b"x")
3077 assert client.recv(1) == b"x"
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003078
Abraham Martinef063482015-03-25 14:06:24 +00003079 def test_text(self):
3080 """
Alex Chanb7480992017-01-30 14:04:47 +00003081 `Connection.sendall` transmits all the content in the string passed
3082 to it, raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003083 """
Alex Chanb7480992017-01-30 14:04:47 +00003084 server, client = loopback()
3085 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00003086 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003087 server.sendall(b"x".decode("ascii"))
Alex Gaynor03737182020-07-23 20:40:46 -04003088 assert "{0} for buf is no longer accepted, use bytes".format(
3089 WARNING_TYPE_EXPECTED
3090 ) == str(w[-1].message)
Alex Chanb7480992017-01-30 14:04:47 +00003091 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003092
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003093 def test_short_memoryview(self):
3094 """
3095 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003096 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003097 """
Alex Chanb7480992017-01-30 14:04:47 +00003098 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003099 server.sendall(memoryview(b"x"))
3100 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003101
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003102 @skip_if_py3
3103 def test_short_buffers(self):
3104 """
3105 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003106 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003107 """
Alex Chanb7480992017-01-30 14:04:47 +00003108 server, client = loopback()
Alex Gaynor03737182020-07-23 20:40:46 -04003109 count = server.sendall(buffer(b"xy")) # noqa: F821
Daniel Holth079c9632019-11-17 22:45:52 -05003110 assert count == 2
Alex Gaynor03737182020-07-23 20:40:46 -04003111 assert client.recv(2) == b"xy"
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003112
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003113 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003114 """
Alex Chanb7480992017-01-30 14:04:47 +00003115 `Connection.sendall` transmits all the bytes in the string passed to it
3116 even if this requires multiple calls of an underlying write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003117 """
Alex Chanb7480992017-01-30 14:04:47 +00003118 server, client = loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003119 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003120 # On Windows, after 32k of bytes the write will block (forever
3121 # - because no one is yet reading).
Alex Gaynor03737182020-07-23 20:40:46 -04003122 message = b"x" * (1024 * 32 - 1) + b"y"
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003123 server.sendall(message)
3124 accum = []
3125 received = 0
3126 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003127 data = client.recv(1024)
3128 accum.append(data)
3129 received += len(data)
Alex Gaynor03737182020-07-23 20:40:46 -04003130 assert message == b"".join(accum)
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003131
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003132 def test_closed(self):
3133 """
Alex Chanb7480992017-01-30 14:04:47 +00003134 If the underlying socket is closed, `Connection.sendall` propagates the
3135 write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003136 """
Alex Chanb7480992017-01-30 14:04:47 +00003137 server, client = loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003138 server.sock_shutdown(2)
Alex Chanb7480992017-01-30 14:04:47 +00003139 with pytest.raises(SysCallError) as err:
3140 server.sendall(b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003141 if platform == "win32":
Alex Chanb7480992017-01-30 14:04:47 +00003142 assert err.value.args[0] == ESHUTDOWN
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003143 else:
Alex Chanb7480992017-01-30 14:04:47 +00003144 assert err.value.args[0] == EPIPE
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003145
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003146
Alex Chanb7480992017-01-30 14:04:47 +00003147class TestConnectionRenegotiate(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003148 """
3149 Tests for SSL renegotiation APIs.
3150 """
Alex Gaynor03737182020-07-23 20:40:46 -04003151
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003152 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003153 """
Alex Chanb7480992017-01-30 14:04:47 +00003154 `Connection.total_renegotiations` returns `0` before any renegotiations
3155 have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003156 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003157 connection = Connection(Context(SSLv23_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003158 assert connection.total_renegotiations() == 0
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003159
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003160 def test_renegotiate(self):
3161 """
3162 Go through a complete renegotiation cycle.
3163 """
Paul Kehrer7d5a3bf2019-01-21 12:24:02 -06003164 server, client = loopback(
3165 lambda s: loopback_server_factory(s, TLSv1_2_METHOD),
3166 lambda s: loopback_client_factory(s, TLSv1_2_METHOD),
3167 )
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003168
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003169 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003170
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003171 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003172
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003173 assert 0 == server.total_renegotiations()
3174 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003175
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003176 assert True is server.renegotiate()
3177
3178 assert True is server.renegotiate_pending()
3179
3180 server.setblocking(False)
3181 client.setblocking(False)
3182
3183 client.do_handshake()
3184 server.do_handshake()
3185
3186 assert 1 == server.total_renegotiations()
3187 while False is server.renegotiate_pending():
3188 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003189
3190
Alex Chanb7480992017-01-30 14:04:47 +00003191class TestError(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003192 """
Alex Chanb7480992017-01-30 14:04:47 +00003193 Unit tests for `OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003194 """
Alex Gaynor03737182020-07-23 20:40:46 -04003195
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003196 def test_type(self):
3197 """
Alex Chanb7480992017-01-30 14:04:47 +00003198 `Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003199 """
Alex Chanb7480992017-01-30 14:04:47 +00003200 assert issubclass(Error, Exception)
Alex Gaynor03737182020-07-23 20:40:46 -04003201 assert Error.__name__ == "Error"
Rick Deane15b1472009-07-09 15:53:42 -05003202
3203
Alex Chanb7480992017-01-30 14:04:47 +00003204class TestConstants(object):
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003205 """
Alex Chanb7480992017-01-30 14:04:47 +00003206 Tests for the values of constants exposed in `OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003207
3208 These are values defined by OpenSSL intended only to be used as flags to
3209 OpenSSL APIs. The only assertions it seems can be made about them is
3210 their values.
3211 """
Alex Gaynor03737182020-07-23 20:40:46 -04003212
Hynek Schlawack35618382015-09-05 21:54:25 +02003213 @pytest.mark.skipif(
3214 OP_NO_QUERY_MTU is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003215 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003216 )
3217 def test_op_no_query_mtu(self):
3218 """
Alex Chanb7480992017-01-30 14:04:47 +00003219 The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3220 of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003221 """
Alex Chanb7480992017-01-30 14:04:47 +00003222 assert OP_NO_QUERY_MTU == 0x1000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003223
Hynek Schlawack35618382015-09-05 21:54:25 +02003224 @pytest.mark.skipif(
3225 OP_COOKIE_EXCHANGE is None,
3226 reason="OP_COOKIE_EXCHANGE unavailable - "
Alex Gaynor03737182020-07-23 20:40:46 -04003227 "OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003228 )
3229 def test_op_cookie_exchange(self):
3230 """
Alex Chanb7480992017-01-30 14:04:47 +00003231 The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3232 value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003233 """
Alex Chanb7480992017-01-30 14:04:47 +00003234 assert OP_COOKIE_EXCHANGE == 0x2000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003235
Hynek Schlawack35618382015-09-05 21:54:25 +02003236 @pytest.mark.skipif(
3237 OP_NO_TICKET is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003238 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old",
Hynek Schlawack35618382015-09-05 21:54:25 +02003239 )
3240 def test_op_no_ticket(self):
3241 """
Alex Chanb7480992017-01-30 14:04:47 +00003242 The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3243 `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003244 """
Alex Chanb7480992017-01-30 14:04:47 +00003245 assert OP_NO_TICKET == 0x4000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003246
Hynek Schlawack35618382015-09-05 21:54:25 +02003247 @pytest.mark.skipif(
3248 OP_NO_COMPRESSION is None,
Alex Gaynor03737182020-07-23 20:40:46 -04003249 reason=(
3250 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3251 ),
Hynek Schlawack35618382015-09-05 21:54:25 +02003252 )
3253 def test_op_no_compression(self):
3254 """
Alex Chanb7480992017-01-30 14:04:47 +00003255 The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3256 value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003257 """
Alex Chanb7480992017-01-30 14:04:47 +00003258 assert OP_NO_COMPRESSION == 0x20000
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003259
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003260 def test_sess_cache_off(self):
3261 """
Alex Chanb7480992017-01-30 14:04:47 +00003262 The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3263 `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003264 """
Alex Chanb7480992017-01-30 14:04:47 +00003265 assert 0x0 == SESS_CACHE_OFF
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003266
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003267 def test_sess_cache_client(self):
3268 """
Alex Chanb7480992017-01-30 14:04:47 +00003269 The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3270 `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003271 """
Alex Chanb7480992017-01-30 14:04:47 +00003272 assert 0x1 == SESS_CACHE_CLIENT
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003273
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003274 def test_sess_cache_server(self):
3275 """
Alex Chanb7480992017-01-30 14:04:47 +00003276 The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3277 `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003278 """
Alex Chanb7480992017-01-30 14:04:47 +00003279 assert 0x2 == SESS_CACHE_SERVER
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003280
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003281 def test_sess_cache_both(self):
3282 """
Alex Chanb7480992017-01-30 14:04:47 +00003283 The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3284 `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003285 """
Alex Chanb7480992017-01-30 14:04:47 +00003286 assert 0x3 == SESS_CACHE_BOTH
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003287
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003288 def test_sess_cache_no_auto_clear(self):
3289 """
Alex Chanb7480992017-01-30 14:04:47 +00003290 The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3291 value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3292 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003293 """
Alex Chanb7480992017-01-30 14:04:47 +00003294 assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003295
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003296 def test_sess_cache_no_internal_lookup(self):
3297 """
Alex Chanb7480992017-01-30 14:04:47 +00003298 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3299 the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3300 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003301 """
Alex Chanb7480992017-01-30 14:04:47 +00003302 assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003303
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003304 def test_sess_cache_no_internal_store(self):
3305 """
Alex Chanb7480992017-01-30 14:04:47 +00003306 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3307 the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3308 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003309 """
Alex Chanb7480992017-01-30 14:04:47 +00003310 assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003311
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003312 def test_sess_cache_no_internal(self):
3313 """
Alex Chanb7480992017-01-30 14:04:47 +00003314 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3315 value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
3316 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003317 """
Alex Chanb7480992017-01-30 14:04:47 +00003318 assert 0x300 == SESS_CACHE_NO_INTERNAL
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003319
3320
Alex Chanb7480992017-01-30 14:04:47 +00003321class TestMemoryBIO(object):
Rick Deanb71c0d22009-04-01 14:09:23 -05003322 """
Alex Chanb7480992017-01-30 14:04:47 +00003323 Tests for `OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003324 """
Alex Gaynor03737182020-07-23 20:40:46 -04003325
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003326 def _server(self, sock):
3327 """
Alex Chanb7480992017-01-30 14:04:47 +00003328 Create a new server-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003329 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003330 # Create the server side Connection. This is mostly setup boilerplate
3331 # - use TLSv1, use a particular certificate, etc.
Paul Kehrer688538c2020-08-03 19:18:15 -05003332 server_ctx = Context(SSLv23_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003333 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003334 server_ctx.set_verify(
3335 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
Alex Gaynor03737182020-07-23 20:40:46 -04003336 verify_cb,
Hynek Schlawack35618382015-09-05 21:54:25 +02003337 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003338 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003339 server_ctx.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04003340 load_privatekey(FILETYPE_PEM, server_key_pem)
3341 )
Hynek Schlawack35618382015-09-05 21:54:25 +02003342 server_ctx.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04003343 load_certificate(FILETYPE_PEM, server_cert_pem)
3344 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003345 server_ctx.check_privatekey()
3346 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003347 # Here the Connection is actually created. If None is passed as the
3348 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003349 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003350 server_conn.set_accept_state()
3351 return server_conn
3352
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003353 def _client(self, sock):
3354 """
Alex Chanb7480992017-01-30 14:04:47 +00003355 Create a new client-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003356 """
3357 # Now create the client side Connection. Similar boilerplate to the
3358 # above.
Paul Kehrer688538c2020-08-03 19:18:15 -05003359 client_ctx = Context(SSLv23_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003360 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003361 client_ctx.set_verify(
3362 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
Alex Gaynor03737182020-07-23 20:40:46 -04003363 verify_cb,
Hynek Schlawack35618382015-09-05 21:54:25 +02003364 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003365 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003366 client_ctx.use_privatekey(
Alex Gaynor03737182020-07-23 20:40:46 -04003367 load_privatekey(FILETYPE_PEM, client_key_pem)
3368 )
Hynek Schlawack35618382015-09-05 21:54:25 +02003369 client_ctx.use_certificate(
Alex Gaynor03737182020-07-23 20:40:46 -04003370 load_certificate(FILETYPE_PEM, client_cert_pem)
3371 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003372 client_ctx.check_privatekey()
3373 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003374 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003375 client_conn.set_connect_state()
3376 return client_conn
3377
Alex Chanb7480992017-01-30 14:04:47 +00003378 def test_memory_connect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003379 """
Alex Chanb7480992017-01-30 14:04:47 +00003380 Two `Connection`s which use memory BIOs can be manually connected by
3381 reading from the output of each and writing those bytes to the input of
3382 the other and in this way establish a connection and exchange
3383 application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003384 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003385 server_conn = self._server(None)
3386 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003387
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003388 # There should be no key or nonces yet.
Alex Chanb7480992017-01-30 14:04:47 +00003389 assert server_conn.master_key() is None
3390 assert server_conn.client_random() is None
3391 assert server_conn.server_random() is None
Rick Deanb71c0d22009-04-01 14:09:23 -05003392
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003393 # First, the handshake needs to happen. We'll deliver bytes back and
3394 # forth between the client and server until neither of them feels like
3395 # speaking any more.
Alex Chanb7480992017-01-30 14:04:47 +00003396 assert interact_in_memory(client_conn, server_conn) is None
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003397
3398 # Now that the handshake is done, there should be a key and nonces.
Alex Chanb7480992017-01-30 14:04:47 +00003399 assert server_conn.master_key() is not None
3400 assert server_conn.client_random() is not None
3401 assert server_conn.server_random() is not None
3402 assert server_conn.client_random() == client_conn.client_random()
3403 assert server_conn.server_random() == client_conn.server_random()
3404 assert server_conn.client_random() != server_conn.server_random()
3405 assert client_conn.client_random() != client_conn.server_random()
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003406
Paul Kehrerbdb76392017-12-01 04:54:32 +08003407 # Export key material for other uses.
Alex Gaynor03737182020-07-23 20:40:46 -04003408 cekm = client_conn.export_keying_material(b"LABEL", 32)
3409 sekm = server_conn.export_keying_material(b"LABEL", 32)
Paul Kehrerbdb76392017-12-01 04:54:32 +08003410 assert cekm is not None
3411 assert sekm is not None
3412 assert cekm == sekm
3413 assert len(sekm) == 32
3414
3415 # Export key material for other uses with additional context.
Alex Gaynor03737182020-07-23 20:40:46 -04003416 cekmc = client_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
3417 sekmc = server_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
Paul Kehrerbdb76392017-12-01 04:54:32 +08003418 assert cekmc is not None
3419 assert sekmc is not None
3420 assert cekmc == sekmc
3421 assert cekmc != cekm
3422 assert sekmc != sekm
3423 # Export with alternate label
Alex Gaynor03737182020-07-23 20:40:46 -04003424 cekmt = client_conn.export_keying_material(b"test", 32, b"CONTEXT")
3425 sekmt = server_conn.export_keying_material(b"test", 32, b"CONTEXT")
Paul Kehrerbdb76392017-12-01 04:54:32 +08003426 assert cekmc != cekmt
3427 assert sekmc != sekmt
3428
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003429 # Here are the bytes we'll try to send.
Alex Gaynor03737182020-07-23 20:40:46 -04003430 important_message = b"One if by land, two if by sea."
Rick Deanb71c0d22009-04-01 14:09:23 -05003431
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003432 server_conn.write(important_message)
Alex Gaynor03737182020-07-23 20:40:46 -04003433 assert interact_in_memory(client_conn, server_conn) == (
3434 client_conn,
3435 important_message,
3436 )
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003437
3438 client_conn.write(important_message[::-1])
Alex Gaynor03737182020-07-23 20:40:46 -04003439 assert interact_in_memory(client_conn, server_conn) == (
3440 server_conn,
3441 important_message[::-1],
3442 )
Rick Deanb71c0d22009-04-01 14:09:23 -05003443
Alex Chanb7480992017-01-30 14:04:47 +00003444 def test_socket_connect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003445 """
Alex Chanb7480992017-01-30 14:04:47 +00003446 Just like `test_memory_connect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003447
Hynek Schlawack35618382015-09-05 21:54:25 +02003448 This is primarily to rule out the memory BIO code as the source of any
Alex Chanb7480992017-01-30 14:04:47 +00003449 problems encountered while passing data over a `Connection` (if
Hynek Schlawack35618382015-09-05 21:54:25 +02003450 this test fails, there must be a problem outside the memory BIO code,
3451 as no memory BIO is involved here). Even though this isn't a memory
3452 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003453 """
Alex Chanb7480992017-01-30 14:04:47 +00003454 server_conn, client_conn = loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003455
Alex Gaynore7f51982016-09-11 11:48:14 -04003456 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003457 client_conn.send(important_message)
3458 msg = server_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003459 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003460
3461 # Again in the other direction, just for fun.
3462 important_message = important_message[::-1]
3463 server_conn.send(important_message)
3464 msg = client_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003465 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003466
Alex Chanb7480992017-01-30 14:04:47 +00003467 def test_socket_overrides_memory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003468 """
Alex Chanb7480992017-01-30 14:04:47 +00003469 Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
3470 work on `OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003471 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003472 context = Context(SSLv23_METHOD)
David Benjamin1fbe0642019-04-15 17:05:13 -05003473 client = socket_any_family()
Rick Deanb71c0d22009-04-01 14:09:23 -05003474 clientSSL = Connection(context, client)
Alex Chanb7480992017-01-30 14:04:47 +00003475 with pytest.raises(TypeError):
3476 clientSSL.bio_read(100)
3477 with pytest.raises(TypeError):
Paul Kehrerc45a6ea2020-08-03 15:54:20 -05003478 clientSSL.bio_write(b"foo")
Alex Chanb7480992017-01-30 14:04:47 +00003479 with pytest.raises(TypeError):
3480 clientSSL.bio_shutdown()
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003481
Alex Chanb7480992017-01-30 14:04:47 +00003482 def test_outgoing_overflow(self):
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003483 """
3484 If more bytes than can be written to the memory BIO are passed to
Alex Chanb7480992017-01-30 14:04:47 +00003485 `Connection.send` at once, the number of bytes which were written is
3486 returned and that many bytes from the beginning of the input can be
3487 read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003488 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003489 server = self._server(None)
3490 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003491
Alex Chanb7480992017-01-30 14:04:47 +00003492 interact_in_memory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003493
3494 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003495 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003496 # Sanity check. We're trying to test what happens when the entire
3497 # input can't be sent. If the entire input was sent, this test is
3498 # meaningless.
Alex Chanb7480992017-01-30 14:04:47 +00003499 assert sent < size
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003500
Alex Chanb7480992017-01-30 14:04:47 +00003501 receiver, received = interact_in_memory(client, server)
3502 assert receiver is server
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003503
3504 # We can rely on all of these bytes being received at once because
Alex Chanb7480992017-01-30 14:04:47 +00003505 # loopback passes 2 ** 16 to recv - more than 2 ** 15.
3506 assert len(received) == sent
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003507
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003508 def test_shutdown(self):
3509 """
Alex Chanb7480992017-01-30 14:04:47 +00003510 `Connection.bio_shutdown` signals the end of the data stream
3511 from which the `Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003512 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003513 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003514 server.bio_shutdown()
Alex Chanb7480992017-01-30 14:04:47 +00003515 with pytest.raises(Error) as err:
3516 server.recv(1024)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003517 # We don't want WantReadError or ZeroReturnError or anything - it's a
3518 # handshake failure.
Alex Chanb7480992017-01-30 14:04:47 +00003519 assert type(err.value) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003520
Alex Chanb7480992017-01-30 14:04:47 +00003521 def test_unexpected_EOF(self):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003522 """
3523 If the connection is lost before an orderly SSL shutdown occurs,
Alex Chanb7480992017-01-30 14:04:47 +00003524 `OpenSSL.SSL.SysCallError` is raised with a message of
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003525 "Unexpected EOF".
3526 """
Alex Chanb7480992017-01-30 14:04:47 +00003527 server_conn, client_conn = loopback()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003528 client_conn.sock_shutdown(SHUT_RDWR)
Alex Chanb7480992017-01-30 14:04:47 +00003529 with pytest.raises(SysCallError) as err:
3530 server_conn.recv(1024)
3531 assert err.value.args == (-1, "Unexpected EOF")
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003532
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003533 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003534 """
Alex Chanb7480992017-01-30 14:04:47 +00003535 Verify the return value of the `get_client_ca_list` method for
Hynek Schlawack35618382015-09-05 21:54:25 +02003536 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003537
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003538 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003539 before the client and server are connected to each other. This
3540 function should specify a list of CAs for the server to send to the
3541 client and return that same list. The list will be used to verify
Alex Chanb7480992017-01-30 14:04:47 +00003542 that `get_client_ca_list` returns the proper value at
Hynek Schlawack35618382015-09-05 21:54:25 +02003543 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003544 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003545 server = self._server(None)
3546 client = self._client(None)
Alex Chanb7480992017-01-30 14:04:47 +00003547 assert client.get_client_ca_list() == []
3548 assert server.get_client_ca_list() == []
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003549 ctx = server.get_context()
3550 expected = func(ctx)
Alex Chanb7480992017-01-30 14:04:47 +00003551 assert client.get_client_ca_list() == []
3552 assert server.get_client_ca_list() == expected
3553 interact_in_memory(client, server)
3554 assert client.get_client_ca_list() == expected
3555 assert server.get_client_ca_list() == expected
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003556
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003557 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003558 """
Alex Chanb7480992017-01-30 14:04:47 +00003559 `Context.set_client_ca_list` raises a `TypeError` if called with a
3560 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003561 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003562 ctx = Context(SSLv23_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003563 with pytest.raises(TypeError):
3564 ctx.set_client_ca_list("spam")
3565 with pytest.raises(TypeError):
3566 ctx.set_client_ca_list(["spam"])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003567
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003568 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003569 """
Alex Chanb7480992017-01-30 14:04:47 +00003570 If passed an empty list, `Context.set_client_ca_list` configures the
3571 context to send no CA names to the client and, on both the server and
3572 client sides, `Connection.get_client_ca_list` returns an empty list
3573 after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003574 """
Alex Gaynor03737182020-07-23 20:40:46 -04003575
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003576 def no_ca(ctx):
3577 ctx.set_client_ca_list([])
3578 return []
Alex Gaynor03737182020-07-23 20:40:46 -04003579
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003580 self._check_client_ca_list(no_ca)
3581
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003582 def test_set_one_ca_list(self):
3583 """
3584 If passed a list containing a single X509Name,
Alex Chanb7480992017-01-30 14:04:47 +00003585 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003586 that CA name to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003587 `Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003588 X509Name after the connection is set up.
3589 """
3590 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3591 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003592
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003593 def single_ca(ctx):
3594 ctx.set_client_ca_list([cadesc])
3595 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003596
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003597 self._check_client_ca_list(single_ca)
3598
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003599 def test_set_multiple_ca_list(self):
3600 """
3601 If passed a list containing multiple X509Name objects,
Alex Chanb7480992017-01-30 14:04:47 +00003602 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003603 those CA names to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003604 `Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003605 X509Names after the connection is set up.
3606 """
3607 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3608 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3609
3610 sedesc = secert.get_subject()
3611 cldesc = clcert.get_subject()
3612
3613 def multiple_ca(ctx):
3614 L = [sedesc, cldesc]
3615 ctx.set_client_ca_list(L)
3616 return L
Alex Gaynor03737182020-07-23 20:40:46 -04003617
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003618 self._check_client_ca_list(multiple_ca)
3619
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003620 def test_reset_ca_list(self):
3621 """
3622 If called multiple times, only the X509Names passed to the final call
Alex Chanb7480992017-01-30 14:04:47 +00003623 of `Context.set_client_ca_list` are used to configure the CA
Hynek Schlawack35618382015-09-05 21:54:25 +02003624 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003625 """
3626 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3627 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3628 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3629
3630 cadesc = cacert.get_subject()
3631 sedesc = secert.get_subject()
3632 cldesc = clcert.get_subject()
3633
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003634 def changed_ca(ctx):
3635 ctx.set_client_ca_list([sedesc, cldesc])
3636 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003637 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003638
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003639 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003640
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003641 def test_mutated_ca_list(self):
3642 """
Alex Chanb7480992017-01-30 14:04:47 +00003643 If the list passed to `Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003644 afterwards, this does not affect the list of CA names sent to the
3645 client.
3646 """
3647 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3648 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3649
3650 cadesc = cacert.get_subject()
3651 sedesc = secert.get_subject()
3652
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003653 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003654 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003655 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003656 L.append(sedesc)
3657 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003658
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003659 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003660
Alex Chanb7480992017-01-30 14:04:47 +00003661 def test_add_client_ca_wrong_args(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003662 """
Alex Chanb7480992017-01-30 14:04:47 +00003663 `Context.add_client_ca` raises `TypeError` if called with
3664 a non-X509 object.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003665 """
Paul Kehrer688538c2020-08-03 19:18:15 -05003666 ctx = Context(SSLv23_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003667 with pytest.raises(TypeError):
3668 ctx.add_client_ca("spam")
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003669
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003670 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003671 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003672 A certificate's subject can be added as a CA to be sent to the client
Alex Chanb7480992017-01-30 14:04:47 +00003673 with `Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003674 """
3675 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3676 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003677
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003678 def single_ca(ctx):
3679 ctx.add_client_ca(cacert)
3680 return [cadesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003681
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003682 self._check_client_ca_list(single_ca)
3683
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003684 def test_multiple_add_client_ca(self):
3685 """
3686 Multiple CA names can be sent to the client by calling
Alex Chanb7480992017-01-30 14:04:47 +00003687 `Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003688 """
3689 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3690 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3691
3692 cadesc = cacert.get_subject()
3693 sedesc = secert.get_subject()
3694
3695 def multiple_ca(ctx):
3696 ctx.add_client_ca(cacert)
3697 ctx.add_client_ca(secert)
3698 return [cadesc, sedesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003699
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003700 self._check_client_ca_list(multiple_ca)
3701
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003702 def test_set_and_add_client_ca(self):
3703 """
Alex Chanb7480992017-01-30 14:04:47 +00003704 A call to `Context.set_client_ca_list` followed by a call to
3705 `Context.add_client_ca` results in using the CA names from the
Hynek Schlawack35618382015-09-05 21:54:25 +02003706 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003707 """
3708 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3709 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3710 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3711
3712 cadesc = cacert.get_subject()
3713 sedesc = secert.get_subject()
3714 cldesc = clcert.get_subject()
3715
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003716 def mixed_set_add_ca(ctx):
3717 ctx.set_client_ca_list([cadesc, sedesc])
3718 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003719 return [cadesc, sedesc, cldesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003720
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003721 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003722
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003723 def test_set_after_add_client_ca(self):
3724 """
Alex Chanb7480992017-01-30 14:04:47 +00003725 A call to `Context.set_client_ca_list` after a call to
3726 `Context.add_client_ca` replaces the CA name specified by the
Hynek Schlawack35618382015-09-05 21:54:25 +02003727 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003728 """
3729 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3730 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3731 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3732
3733 cadesc = cacert.get_subject()
3734 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003735
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003736 def set_replaces_add_ca(ctx):
3737 ctx.add_client_ca(clcert)
3738 ctx.set_client_ca_list([cadesc])
3739 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003740 return [cadesc, sedesc]
Alex Gaynor03737182020-07-23 20:40:46 -04003741
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003742 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003743
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003744
Alex Chanb7480992017-01-30 14:04:47 +00003745class TestInfoConstants(object):
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003746 """
3747 Tests for assorted constants exposed for use in info callbacks.
3748 """
Alex Gaynor03737182020-07-23 20:40:46 -04003749
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003750 def test_integers(self):
3751 """
3752 All of the info constants are integers.
3753
3754 This is a very weak test. It would be nice to have one that actually
3755 verifies that as certain info events happen, the value passed to the
3756 info callback matches up with the constant exposed by OpenSSL.SSL.
3757 """
3758 for const in [
Alex Gaynor03737182020-07-23 20:40:46 -04003759 SSL_ST_CONNECT,
3760 SSL_ST_ACCEPT,
3761 SSL_ST_MASK,
3762 SSL_CB_LOOP,
3763 SSL_CB_EXIT,
3764 SSL_CB_READ,
3765 SSL_CB_WRITE,
3766 SSL_CB_ALERT,
3767 SSL_CB_READ_ALERT,
3768 SSL_CB_WRITE_ALERT,
3769 SSL_CB_ACCEPT_LOOP,
3770 SSL_CB_ACCEPT_EXIT,
3771 SSL_CB_CONNECT_LOOP,
3772 SSL_CB_CONNECT_EXIT,
3773 SSL_CB_HANDSHAKE_START,
3774 SSL_CB_HANDSHAKE_DONE,
Hynek Schlawack35618382015-09-05 21:54:25 +02003775 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003776 assert isinstance(const, int)
3777
3778 # These constants don't exist on OpenSSL 1.1.0
3779 for const in [
Alex Gaynor03737182020-07-23 20:40:46 -04003780 SSL_ST_INIT,
3781 SSL_ST_BEFORE,
3782 SSL_ST_OK,
3783 SSL_ST_RENEGOTIATE,
Alex Gaynor5af32d02016-09-24 01:52:21 -04003784 ]:
3785 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003786
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003787
Cory Benfield1d142142016-03-30 11:51:45 +01003788class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003789 """
3790 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003791 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003792 """
Alex Gaynor03737182020-07-23 20:40:46 -04003793
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003794 def test_available(self):
3795 """
3796 When the OpenSSL functionality is available the decorated functions
3797 work appropriately.
3798 """
3799 feature_guard = _make_requires(True, "Error text")
3800 results = []
3801
3802 @feature_guard
3803 def inner():
3804 results.append(True)
3805 return True
3806
Cory Benfield2333e5e2016-03-30 14:24:16 +01003807 assert inner() is True
3808 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003809
3810 def test_unavailable(self):
3811 """
3812 When the OpenSSL functionality is not available the decorated function
3813 does not execute and NotImplementedError is raised.
3814 """
3815 feature_guard = _make_requires(False, "Error text")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003816
3817 @feature_guard
Alex Chanfb078d82017-04-20 11:16:15 +01003818 def inner(): # pragma: nocover
3819 pytest.fail("Should not be called")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003820
Cory Benfield1d142142016-03-30 11:51:45 +01003821 with pytest.raises(NotImplementedError) as e:
3822 inner()
3823
3824 assert "Error text" in str(e.value)
Cory Benfield496652a2017-01-24 11:42:56 +00003825
3826
Alex Chanb7480992017-01-30 14:04:47 +00003827class TestOCSP(object):
Cory Benfield496652a2017-01-24 11:42:56 +00003828 """
3829 Tests for PyOpenSSL's OCSP stapling support.
3830 """
Alex Gaynor03737182020-07-23 20:40:46 -04003831
Cory Benfield496652a2017-01-24 11:42:56 +00003832 sample_ocsp_data = b"this is totally ocsp data"
3833
3834 def _client_connection(self, callback, data, request_ocsp=True):
3835 """
3836 Builds a client connection suitable for using OCSP.
3837
3838 :param callback: The callback to register for OCSP.
3839 :param data: The opaque data object that will be handed to the
3840 OCSP callback.
3841 :param request_ocsp: Whether the client will actually ask for OCSP
3842 stapling. Useful for testing only.
3843 """
3844 ctx = Context(SSLv23_METHOD)
3845 ctx.set_ocsp_client_callback(callback, data)
3846 client = Connection(ctx)
3847
3848 if request_ocsp:
3849 client.request_ocsp()
3850
3851 client.set_connect_state()
3852 return client
3853
3854 def _server_connection(self, callback, data):
3855 """
3856 Builds a server connection suitable for using OCSP.
3857
3858 :param callback: The callback to register for OCSP.
3859 :param data: The opaque data object that will be handed to the
3860 OCSP callback.
3861 """
3862 ctx = Context(SSLv23_METHOD)
3863 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
3864 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
3865 ctx.set_ocsp_server_callback(callback, data)
3866 server = Connection(ctx)
3867 server.set_accept_state()
3868 return server
3869
3870 def test_callbacks_arent_called_by_default(self):
3871 """
3872 If both the client and the server have registered OCSP callbacks, but
3873 the client does not send the OCSP request, neither callback gets
3874 called.
3875 """
Alex Gaynor03737182020-07-23 20:40:46 -04003876
Alex Chanfb078d82017-04-20 11:16:15 +01003877 def ocsp_callback(*args, **kwargs): # pragma: nocover
3878 pytest.fail("Should not be called")
Cory Benfield496652a2017-01-24 11:42:56 +00003879
3880 client = self._client_connection(
3881 callback=ocsp_callback, data=None, request_ocsp=False
3882 )
3883 server = self._server_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003884 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003885
Cory Benfield496652a2017-01-24 11:42:56 +00003886 def test_client_negotiates_without_server(self):
3887 """
3888 If the client wants to do OCSP but the server does not, the handshake
3889 succeeds, and the client callback fires with an empty byte string.
3890 """
3891 called = []
3892
3893 def ocsp_callback(conn, ocsp_data, ignored):
3894 called.append(ocsp_data)
3895 return True
3896
3897 client = self._client_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003898 server = loopback_server_factory(socket=None)
3899 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003900
3901 assert len(called) == 1
Alex Gaynor03737182020-07-23 20:40:46 -04003902 assert called[0] == b""
Cory Benfield496652a2017-01-24 11:42:56 +00003903
3904 def test_client_receives_servers_data(self):
3905 """
3906 The data the server sends in its callback is received by the client.
3907 """
3908 calls = []
3909
3910 def server_callback(*args, **kwargs):
3911 return self.sample_ocsp_data
3912
3913 def client_callback(conn, ocsp_data, ignored):
3914 calls.append(ocsp_data)
3915 return True
3916
3917 client = self._client_connection(callback=client_callback, data=None)
3918 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003919 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003920
3921 assert len(calls) == 1
3922 assert calls[0] == self.sample_ocsp_data
3923
3924 def test_callbacks_are_invoked_with_connections(self):
3925 """
3926 The first arguments to both callbacks are their respective connections.
3927 """
3928 client_calls = []
3929 server_calls = []
3930
3931 def client_callback(conn, *args, **kwargs):
3932 client_calls.append(conn)
3933 return True
3934
3935 def server_callback(conn, *args, **kwargs):
3936 server_calls.append(conn)
3937 return self.sample_ocsp_data
3938
3939 client = self._client_connection(callback=client_callback, data=None)
3940 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003941 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003942
3943 assert len(client_calls) == 1
3944 assert len(server_calls) == 1
3945 assert client_calls[0] is client
3946 assert server_calls[0] is server
3947
3948 def test_opaque_data_is_passed_through(self):
3949 """
3950 Both callbacks receive an opaque, user-provided piece of data in their
3951 callbacks as the final argument.
3952 """
3953 calls = []
3954
3955 def server_callback(*args):
3956 calls.append(args)
3957 return self.sample_ocsp_data
3958
3959 def client_callback(*args):
3960 calls.append(args)
3961 return True
3962
3963 sentinel = object()
3964
3965 client = self._client_connection(
3966 callback=client_callback, data=sentinel
3967 )
3968 server = self._server_connection(
3969 callback=server_callback, data=sentinel
3970 )
Alex Chanb7480992017-01-30 14:04:47 +00003971 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003972
3973 assert len(calls) == 2
3974 assert calls[0][-1] is sentinel
3975 assert calls[1][-1] is sentinel
3976
3977 def test_server_returns_empty_string(self):
3978 """
3979 If the server returns an empty bytestring from its callback, the
3980 client callback is called with the empty bytestring.
3981 """
3982 client_calls = []
3983
3984 def server_callback(*args):
Alex Gaynor03737182020-07-23 20:40:46 -04003985 return b""
Cory Benfield496652a2017-01-24 11:42:56 +00003986
3987 def client_callback(conn, ocsp_data, ignored):
3988 client_calls.append(ocsp_data)
3989 return True
3990
3991 client = self._client_connection(callback=client_callback, data=None)
3992 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003993 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003994
3995 assert len(client_calls) == 1
Alex Gaynor03737182020-07-23 20:40:46 -04003996 assert client_calls[0] == b""
Cory Benfield496652a2017-01-24 11:42:56 +00003997
3998 def test_client_returns_false_terminates_handshake(self):
3999 """
4000 If the client returns False from its callback, the handshake fails.
4001 """
Alex Gaynor03737182020-07-23 20:40:46 -04004002
Cory Benfield496652a2017-01-24 11:42:56 +00004003 def server_callback(*args):
4004 return self.sample_ocsp_data
4005
4006 def client_callback(*args):
4007 return False
4008
4009 client = self._client_connection(callback=client_callback, data=None)
4010 server = self._server_connection(callback=server_callback, data=None)
4011
4012 with pytest.raises(Error):
Alex Chanb7480992017-01-30 14:04:47 +00004013 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004014
4015 def test_exceptions_in_client_bubble_up(self):
4016 """
4017 The callbacks thrown in the client callback bubble up to the caller.
4018 """
Alex Gaynor03737182020-07-23 20:40:46 -04004019
Cory Benfield496652a2017-01-24 11:42:56 +00004020 class SentinelException(Exception):
4021 pass
4022
4023 def server_callback(*args):
4024 return self.sample_ocsp_data
4025
4026 def client_callback(*args):
4027 raise SentinelException()
4028
4029 client = self._client_connection(callback=client_callback, data=None)
4030 server = self._server_connection(callback=server_callback, data=None)
4031
4032 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00004033 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004034
4035 def test_exceptions_in_server_bubble_up(self):
4036 """
4037 The callbacks thrown in the server callback bubble up to the caller.
4038 """
Alex Gaynor03737182020-07-23 20:40:46 -04004039
Cory Benfield496652a2017-01-24 11:42:56 +00004040 class SentinelException(Exception):
4041 pass
4042
4043 def server_callback(*args):
4044 raise SentinelException()
4045
Alex Chanfb078d82017-04-20 11:16:15 +01004046 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00004047 pytest.fail("Should not be called")
4048
4049 client = self._client_connection(callback=client_callback, data=None)
4050 server = self._server_connection(callback=server_callback, data=None)
4051
4052 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00004053 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00004054
4055 def test_server_must_return_bytes(self):
4056 """
4057 The server callback must return a bytestring, or a TypeError is thrown.
4058 """
Alex Gaynor03737182020-07-23 20:40:46 -04004059
Cory Benfield496652a2017-01-24 11:42:56 +00004060 def server_callback(*args):
Alex Gaynor03737182020-07-23 20:40:46 -04004061 return self.sample_ocsp_data.decode("ascii")
Cory Benfield496652a2017-01-24 11:42:56 +00004062
Alex Chanfb078d82017-04-20 11:16:15 +01004063 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00004064 pytest.fail("Should not be called")
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(TypeError):
Alex Chanb7480992017-01-30 14:04:47 +00004070 handshake_in_memory(client, server)