blob: e154811f1a29d85ee5124d4e8fcec9e45005a27d [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
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +020013from errno import ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN
Hynek Schlawackf8979a52015-09-05 21:25:25 +020014from sys import platform, getfilesystemencoding, version_info
Maximilian Hils1d95dea2015-08-17 19:27:20 +020015from socket import MSG_PEEK, SHUT_RDWR, error, socket
Jean-Paul Calderonea65cf6c2009-07-19 10:26:52 -040016from os import makedirs
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040017from os.path import join
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -040018from weakref import ref
Alex Chanb7480992017-01-30 14:04:47 +000019from warnings import simplefilter
Jean-Paul Calderone460cc1f2009-03-07 11:31:12 -050020
Hynek Schlawack734d3022015-09-05 19:19:32 +020021import pytest
22
Paul Kehrer55fb3412017-06-29 18:44:08 -050023from pretend import raiser
24
Hynek Schlawackf90e3682016-03-11 11:21:13 +010025from six import PY3, text_type
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050026
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +010027from cryptography import x509
28from cryptography.hazmat.backends import default_backend
29from cryptography.hazmat.primitives import hashes
30from cryptography.hazmat.primitives import serialization
31from cryptography.hazmat.primitives.asymmetric import rsa
32from cryptography.x509.oid import NameOID
33
34
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040035from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080036from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040037from OpenSSL.crypto import dump_privatekey, load_privatekey
38from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040039from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040040
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040041from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
42from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040043from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040044from OpenSSL.SSL import (
45 SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
46 TLSv1_1_METHOD, TLSv1_2_METHOD)
47from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040048from OpenSSL.SSL import (
49 VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040050
Paul Kehrer55fb3412017-06-29 18:44:08 -050051from OpenSSL import SSL
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040052from OpenSSL.SSL import (
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050053 SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
54 SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
55 SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
56
57from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070058 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050059from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070060 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Cory Benfield0ba57ec2016-03-30 09:35:05 +010061from OpenSSL.SSL import _make_requires
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040062
Paul Kehrer55fb3412017-06-29 18:44:08 -050063from OpenSSL._util import ffi as _ffi, lib as _lib
Cory Benfieldba1820d2015-04-13 17:39:12 -040064
Alex Gaynord3b5d9b2016-07-31 10:54:24 -040065from OpenSSL.SSL import (
66 OP_NO_QUERY_MTU, OP_COOKIE_EXCHANGE, OP_NO_TICKET, OP_NO_COMPRESSION,
67 MODE_RELEASE_BUFFERS)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040068
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040069from OpenSSL.SSL import (
Alex Gaynor5af32d02016-09-24 01:52:21 -040070 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040071 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
72 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
73 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
74 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040075
Alex Gaynor5af32d02016-09-24 01:52:21 -040076try:
77 from OpenSSL.SSL import (
78 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
79 )
80except ImportError:
81 SSL_ST_INIT = SSL_ST_BEFORE = SSL_ST_OK = SSL_ST_RENEGOTIATE = None
82
Alex Chanb7480992017-01-30 14:04:47 +000083from .util import WARNING_TYPE_EXPECTED, NON_ASCII, is_consistent_type
Hynek Schlawackf0e66852015-10-16 20:18:38 +020084from .test_crypto import (
85 cleartextCertificatePEM, cleartextPrivateKeyPEM,
86 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
87 root_cert_pem)
88
Hynek Schlawackde00dd52015-09-05 19:09:26 +020089
Alex Gaynord0bdd2d2016-09-10 14:23:46 -040090# openssl dhparam 1024 -out dh-1024.pem (note that 1024 is a small number of
91# bits to use)
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040092dhparam = """\
93-----BEGIN DH PARAMETERS-----
Alex Gaynord0bdd2d2016-09-10 14:23:46 -040094MIGHAoGBALdUMvn+C9MM+y5BWZs11mSeH6HHoEq0UVbzVq7UojC1hbsZUuGukQ3a
95Qh2/pwqb18BZFykrWB0zv/OkLa0kx4cuUgNrUVq1EFheBiX6YqryJ7t2sO09NQiO
96V7H54LmltOT/hEh6QWsJqb6BQgH65bswvV/XkYGja8/T0GzvbaVzAgEC
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040097-----END DH PARAMETERS-----
98"""
99
100
Hynek Schlawackb4f02402015-09-05 20:48:34 +0200101skip_if_py3 = pytest.mark.skipif(PY3, reason="Python 2 only")
Hynek Schlawackf8979a52015-09-05 21:25:25 +0200102skip_if_py26 = pytest.mark.skipif(
103 version_info[0:2] == (2, 6),
104 reason="Python 2.7 and later only"
105)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200106
107
Jean-Paul Calderone05826732015-04-12 11:38:49 -0400108def join_bytes_or_unicode(prefix, suffix):
109 """
110 Join two path components of either ``bytes`` or ``unicode``.
111
112 The return type is the same as the type of ``prefix``.
113 """
114 # If the types are the same, nothing special is necessary.
115 if type(prefix) == type(suffix):
116 return join(prefix, suffix)
117
118 # Otherwise, coerce suffix to the type of prefix.
119 if isinstance(prefix, text_type):
120 return join(prefix, suffix.decode(getfilesystemencoding()))
121 else:
122 return join(prefix, suffix.encode(getfilesystemencoding()))
123
124
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400125def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400126 return ok
127
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400128
Rick Deanb1ccd562009-07-09 23:52:39 -0500129def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400130 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400131 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400132 """
133 # Connect a pair of sockets
Rick Deanb1ccd562009-07-09 23:52:39 -0500134 port = socket()
135 port.bind(('', 0))
136 port.listen(1)
137 client = socket()
138 client.setblocking(False)
Jean-Paul Calderonef23c5d92009-07-23 17:58:15 -0400139 client.connect_ex(("127.0.0.1", port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400140 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500141 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500142
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400143 # Let's pass some unencrypted data to make sure our socket connection is
144 # fine. Just one byte, so we don't have to worry about buffers getting
145 # filled up or fragmentation.
Alex Gaynore7f51982016-09-11 11:48:14 -0400146 server.send(b"x")
147 assert client.recv(1024) == b"x"
148 client.send(b"y")
149 assert server.recv(1024) == b"y"
Rick Deanb1ccd562009-07-09 23:52:39 -0500150
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400151 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400152 server.setblocking(False)
153 client.setblocking(False)
Jim Shaver46f28912015-05-29 19:32:16 -0400154
Rick Deanb1ccd562009-07-09 23:52:39 -0500155 return (server, client)
156
157
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400158def handshake(client, server):
159 conns = [client, server]
160 while conns:
161 for conn in conns:
162 try:
163 conn.do_handshake()
164 except WantReadError:
165 pass
166 else:
167 conns.remove(conn)
168
169
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400170def _create_certificate_chain():
171 """
172 Construct and return a chain of certificates.
173
174 1. A new self-signed certificate authority certificate (cacert)
175 2. A new intermediate certificate signed by cacert (icert)
176 3. A new server certificate signed by icert (scert)
177 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400178 caext = X509Extension(b'basicConstraints', False, b'CA:true')
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400179
180 # Step 1
181 cakey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400182 cakey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400183 cacert = X509()
184 cacert.get_subject().commonName = "Authority Certificate"
185 cacert.set_issuer(cacert.get_subject())
186 cacert.set_pubkey(cakey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400187 cacert.set_notBefore(b"20000101000000Z")
188 cacert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400189 cacert.add_extensions([caext])
190 cacert.set_serial_number(0)
191 cacert.sign(cakey, "sha1")
192
193 # Step 2
194 ikey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400195 ikey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400196 icert = X509()
197 icert.get_subject().commonName = "Intermediate Certificate"
198 icert.set_issuer(cacert.get_subject())
199 icert.set_pubkey(ikey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400200 icert.set_notBefore(b"20000101000000Z")
201 icert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400202 icert.add_extensions([caext])
203 icert.set_serial_number(0)
204 icert.sign(cakey, "sha1")
205
206 # Step 3
207 skey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400208 skey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400209 scert = X509()
210 scert.get_subject().commonName = "Server Certificate"
211 scert.set_issuer(icert.get_subject())
212 scert.set_pubkey(skey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400213 scert.set_notBefore(b"20000101000000Z")
214 scert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400215 scert.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -0400216 X509Extension(b'basicConstraints', True, b'CA:false')])
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400217 scert.set_serial_number(0)
218 scert.sign(ikey, "sha1")
219
220 return [(cakey, cacert), (ikey, icert), (skey, scert)]
221
222
Alex Chan1c0cb662017-01-30 07:13:30 +0000223def loopback_client_factory(socket):
224 client = Connection(Context(TLSv1_METHOD), socket)
225 client.set_connect_state()
226 return client
227
228
229def loopback_server_factory(socket):
230 ctx = Context(TLSv1_METHOD)
231 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
232 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
233 server = Connection(ctx, socket)
234 server.set_accept_state()
235 return server
236
237
238def loopback(server_factory=None, client_factory=None):
239 """
240 Create a connected socket pair and force two connected SSL sockets
241 to talk to each other via memory BIOs.
242 """
243 if server_factory is None:
244 server_factory = loopback_server_factory
245 if client_factory is None:
246 client_factory = loopback_client_factory
247
248 (server, client) = socket_pair()
249 server = server_factory(server)
250 client = client_factory(client)
251
252 handshake(client, server)
253
254 server.setblocking(True)
255 client.setblocking(True)
256 return server, client
257
258
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000259def interact_in_memory(client_conn, server_conn):
260 """
261 Try to read application bytes from each of the two `Connection` objects.
262 Copy bytes back and forth between their send/receive buffers for as long
263 as there is anything to copy. When there is nothing more to copy,
264 return `None`. If one of them actually manages to deliver some application
265 bytes, return a two-tuple of the connection from which the bytes were read
266 and the bytes themselves.
267 """
268 wrote = True
269 while wrote:
270 # Loop until neither side has anything to say
271 wrote = False
272
273 # Copy stuff from each side's send buffer to the other side's
274 # receive buffer.
275 for (read, write) in [(client_conn, server_conn),
276 (server_conn, client_conn)]:
277
278 # Give the side a chance to generate some more bytes, or succeed.
279 try:
280 data = read.recv(2 ** 16)
281 except WantReadError:
282 # It didn't succeed, so we'll hope it generated some output.
283 pass
284 else:
285 # It did succeed, so we'll stop now and let the caller deal
286 # with it.
287 return (read, data)
288
289 while True:
290 # Keep copying as long as there's more stuff there.
291 try:
292 dirty = read.bio_read(4096)
293 except WantReadError:
294 # Okay, nothing more waiting to be sent. Stop
295 # processing this send buffer.
296 break
297 else:
298 # Keep track of the fact that someone generated some
299 # output.
300 wrote = True
301 write.bio_write(dirty)
302
303
Alex Chan532b79e2017-01-24 15:14:52 +0000304def handshake_in_memory(client_conn, server_conn):
305 """
306 Perform the TLS handshake between two `Connection` instances connected to
307 each other via memory BIOs.
308 """
309 client_conn.set_connect_state()
310 server_conn.set_accept_state()
311
312 for conn in [client_conn, server_conn]:
313 try:
314 conn.do_handshake()
315 except WantReadError:
316 pass
317
318 interact_in_memory(client_conn, server_conn)
319
320
Alex Chanb7480992017-01-30 14:04:47 +0000321class TestVersion(object):
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400322 """
Alex Chanb7480992017-01-30 14:04:47 +0000323 Tests for version information exposed by `OpenSSL.SSL.SSLeay_version` and
324 `OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400325 """
326 def test_OPENSSL_VERSION_NUMBER(self):
327 """
Alex Chanb7480992017-01-30 14:04:47 +0000328 `OPENSSL_VERSION_NUMBER` is an integer with status in the low byte and
329 the patch, fix, minor, and major versions in the nibbles above that.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400330 """
Alex Chanb7480992017-01-30 14:04:47 +0000331 assert isinstance(OPENSSL_VERSION_NUMBER, int)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400332
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400333 def test_SSLeay_version(self):
334 """
Alex Chanb7480992017-01-30 14:04:47 +0000335 `SSLeay_version` takes a version type indicator and returns one of a
336 number of version strings based on that indicator.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400337 """
338 versions = {}
339 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
340 SSLEAY_PLATFORM, SSLEAY_DIR]:
341 version = SSLeay_version(t)
342 versions[version] = t
Alex Chanb7480992017-01-30 14:04:47 +0000343 assert isinstance(version, bytes)
344 assert len(versions) == 5
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400345
346
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100347@pytest.fixture
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100348def ca_file(tmpdir):
349 """
350 Create a valid PEM file with CA certificates and return the path.
351 """
352 key = rsa.generate_private_key(
353 public_exponent=65537,
354 key_size=2048,
355 backend=default_backend()
356 )
357 public_key = key.public_key()
358
359 builder = x509.CertificateBuilder()
360 builder = builder.subject_name(x509.Name([
361 x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
362 ]))
363 builder = builder.issuer_name(x509.Name([
364 x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
365 ]))
366 one_day = datetime.timedelta(1, 0, 0)
367 builder = builder.not_valid_before(datetime.datetime.today() - one_day)
368 builder = builder.not_valid_after(datetime.datetime.today() + one_day)
369 builder = builder.serial_number(int(uuid.uuid4()))
370 builder = builder.public_key(public_key)
371 builder = builder.add_extension(
372 x509.BasicConstraints(ca=True, path_length=None), critical=True,
373 )
374
375 certificate = builder.sign(
376 private_key=key, algorithm=hashes.SHA256(),
377 backend=default_backend()
378 )
379
380 ca_file = tmpdir.join("test.pem")
381 ca_file.write_binary(
382 certificate.public_bytes(
383 encoding=serialization.Encoding.PEM,
384 )
385 )
386
387 return str(ca_file).encode("ascii")
388
389
390@pytest.fixture
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100391def context():
392 """
393 A simple TLS 1.0 context.
394 """
395 return Context(TLSv1_METHOD)
396
397
398class TestContext(object):
Hynek Schlawackaa861212016-03-13 13:53:48 +0100399 """
Alex Chan532b79e2017-01-24 15:14:52 +0000400 Unit tests for `OpenSSL.SSL.Context`.
Hynek Schlawackaa861212016-03-13 13:53:48 +0100401 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100402 @pytest.mark.parametrize("cipher_string", [
403 b"hello world:AES128-SHA",
404 u"hello world:AES128-SHA",
405 ])
406 def test_set_cipher_list(self, context, cipher_string):
407 """
Alex Chan532b79e2017-01-24 15:14:52 +0000408 `Context.set_cipher_list` accepts both byte and unicode strings
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100409 for naming the ciphers which connections created with the context
410 object will be able to choose from.
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100411 """
412 context.set_cipher_list(cipher_string)
413 conn = Connection(context, None)
414
415 assert "AES128-SHA" in conn.get_cipher_list()
416
417 @pytest.mark.parametrize("cipher_list,error", [
418 (object(), TypeError),
419 ("imaginary-cipher", Error),
420 ])
421 def test_set_cipher_list_wrong_args(self, context, cipher_list, error):
422 """
Alex Chan532b79e2017-01-24 15:14:52 +0000423 `Context.set_cipher_list` raises `TypeError` when passed a non-string
424 argument and raises `OpenSSL.SSL.Error` when passed an incorrect cipher
425 list string.
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100426 """
427 with pytest.raises(error):
428 context.set_cipher_list(cipher_list)
429
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100430 def test_load_client_ca(self, context, ca_file):
431 """
Alex Chan532b79e2017-01-24 15:14:52 +0000432 `Context.load_client_ca` works as far as we can tell.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100433 """
434 context.load_client_ca(ca_file)
435
436 def test_load_client_ca_invalid(self, context, tmpdir):
437 """
Alex Chan532b79e2017-01-24 15:14:52 +0000438 `Context.load_client_ca` raises an Error if the ca file is invalid.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100439 """
440 ca_file = tmpdir.join("test.pem")
441 ca_file.write("")
442
443 with pytest.raises(Error) as e:
444 context.load_client_ca(str(ca_file).encode("ascii"))
445
446 assert "PEM routines" == e.value.args[0][0][0]
447
448 def test_load_client_ca_unicode(self, context, ca_file):
449 """
450 Passing the path as unicode raises a warning but works.
451 """
452 pytest.deprecated_call(
453 context.load_client_ca, ca_file.decode("ascii")
454 )
455
456 def test_set_session_id(self, context):
457 """
Alex Chan532b79e2017-01-24 15:14:52 +0000458 `Context.set_session_id` works as far as we can tell.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100459 """
460 context.set_session_id(b"abc")
461
462 def test_set_session_id_fail(self, context):
463 """
Alex Chan532b79e2017-01-24 15:14:52 +0000464 `Context.set_session_id` errors are propagated.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100465 """
466 with pytest.raises(Error) as e:
467 context.set_session_id(b"abc" * 1000)
468
469 assert [
470 ("SSL routines",
471 "SSL_CTX_set_session_id_context",
472 "ssl session id context too long")
473 ] == e.value.args[0]
474
475 def test_set_session_id_unicode(self, context):
476 """
Alex Chan532b79e2017-01-24 15:14:52 +0000477 `Context.set_session_id` raises a warning if a unicode string is
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100478 passed.
479 """
480 pytest.deprecated_call(context.set_session_id, u"abc")
481
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400482 def test_method(self):
483 """
Alex Chan532b79e2017-01-24 15:14:52 +0000484 `Context` can be instantiated with one of `SSLv2_METHOD`,
485 `SSLv3_METHOD`, `SSLv23_METHOD`, `TLSv1_METHOD`, `TLSv1_1_METHOD`,
486 or `TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400487 """
Alex Gaynor5af32d02016-09-24 01:52:21 -0400488 methods = [SSLv23_METHOD, TLSv1_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400489 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400490 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400491
Alex Gaynor5af32d02016-09-24 01:52:21 -0400492 maybe = [SSLv2_METHOD, SSLv3_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400493 for meth in maybe:
494 try:
495 Context(meth)
496 except (Error, ValueError):
497 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
498 # don't. Difficult to say in advance.
499 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400500
Alex Chan532b79e2017-01-24 15:14:52 +0000501 with pytest.raises(TypeError):
502 Context("")
503 with pytest.raises(ValueError):
504 Context(10)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400505
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200506 @skip_if_py3
507 def test_method_long(self):
508 """
Alex Chan532b79e2017-01-24 15:14:52 +0000509 On Python 2 `Context` accepts values of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200510 """
511 Context(long(TLSv1_METHOD))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500512
Rick Deane15b1472009-07-09 15:53:42 -0500513 def test_type(self):
514 """
Alex Chan532b79e2017-01-24 15:14:52 +0000515 `Context` and `ContextType` refer to the same type object and can
516 be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500517 """
Alex Chan532b79e2017-01-24 15:14:52 +0000518 assert Context is ContextType
519 assert is_consistent_type(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500520
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400521 def test_use_privatekey(self):
522 """
Alex Chan532b79e2017-01-24 15:14:52 +0000523 `Context.use_privatekey` takes an `OpenSSL.crypto.PKey` instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400524 """
525 key = PKey()
526 key.generate_key(TYPE_RSA, 128)
527 ctx = Context(TLSv1_METHOD)
528 ctx.use_privatekey(key)
Alex Chan532b79e2017-01-24 15:14:52 +0000529 with pytest.raises(TypeError):
530 ctx.use_privatekey("")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400531
Alex Chan532b79e2017-01-24 15:14:52 +0000532 def test_use_privatekey_file_missing(self, tmpfile):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800533 """
Alex Chan532b79e2017-01-24 15:14:52 +0000534 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` when passed
535 the name of a file which does not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800536 """
537 ctx = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000538 with pytest.raises(Error):
539 ctx.use_privatekey_file(tmpfile)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800540
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400541 def _use_privatekey_file_test(self, pemfile, filetype):
542 """
543 Verify that calling ``Context.use_privatekey_file`` with the given
544 arguments does not raise an exception.
545 """
546 key = PKey()
547 key.generate_key(TYPE_RSA, 128)
548
549 with open(pemfile, "wt") as pem:
550 pem.write(
551 dump_privatekey(FILETYPE_PEM, key).decode("ascii")
552 )
553
554 ctx = Context(TLSv1_METHOD)
555 ctx.use_privatekey_file(pemfile, filetype)
556
Alex Chanfb078d82017-04-20 11:16:15 +0100557 @pytest.mark.parametrize('filetype', [object(), "", None, 1.0])
558 def test_wrong_privatekey_file_wrong_args(self, tmpfile, filetype):
559 """
560 `Context.use_privatekey_file` raises `TypeError` when called with
561 a `filetype` which is not a valid file encoding.
562 """
563 ctx = Context(TLSv1_METHOD)
564 with pytest.raises(TypeError):
565 ctx.use_privatekey_file(tmpfile, filetype)
566
Alex Chan532b79e2017-01-24 15:14:52 +0000567 def test_use_privatekey_file_bytes(self, tmpfile):
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400568 """
569 A private key can be specified from a file by passing a ``bytes``
570 instance giving the file name to ``Context.use_privatekey_file``.
571 """
572 self._use_privatekey_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +0000573 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400574 FILETYPE_PEM,
575 )
576
Alex Chan532b79e2017-01-24 15:14:52 +0000577 def test_use_privatekey_file_unicode(self, tmpfile):
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400578 """
579 A private key can be specified from a file by passing a ``unicode``
580 instance giving the file name to ``Context.use_privatekey_file``.
581 """
582 self._use_privatekey_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +0000583 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400584 FILETYPE_PEM,
585 )
586
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200587 @skip_if_py3
Alex Chan532b79e2017-01-24 15:14:52 +0000588 def test_use_privatekey_file_long(self, tmpfile):
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200589 """
Alex Chan532b79e2017-01-24 15:14:52 +0000590 On Python 2 `Context.use_privatekey_file` accepts a filetype of
591 type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200592 """
Alex Chan532b79e2017-01-24 15:14:52 +0000593 self._use_privatekey_file_test(tmpfile, long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500594
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800595 def test_use_certificate_wrong_args(self):
596 """
Alex Chan532b79e2017-01-24 15:14:52 +0000597 `Context.use_certificate_wrong_args` raises `TypeError` when not passed
598 exactly one `OpenSSL.crypto.X509` instance as an argument.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800599 """
600 ctx = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000601 with pytest.raises(TypeError):
602 ctx.use_certificate("hello, world")
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800603
604 def test_use_certificate_uninitialized(self):
605 """
Alex Chan532b79e2017-01-24 15:14:52 +0000606 `Context.use_certificate` raises `OpenSSL.SSL.Error` when passed a
607 `OpenSSL.crypto.X509` instance which has not been initialized
608 (ie, which does not actually have any certificate data).
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800609 """
610 ctx = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000611 with pytest.raises(Error):
612 ctx.use_certificate(X509())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800613
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800614 def test_use_certificate(self):
615 """
Alex Chan532b79e2017-01-24 15:14:52 +0000616 `Context.use_certificate` sets the certificate which will be
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800617 used to identify connections created using the context.
618 """
619 # TODO
620 # Hard to assert anything. But we could set a privatekey then ask
621 # OpenSSL if the cert and key agree using check_privatekey. Then as
622 # long as check_privatekey works right we're good...
623 ctx = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200624 ctx.use_certificate(
625 load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
626 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800627
628 def test_use_certificate_file_wrong_args(self):
629 """
Alex Chan532b79e2017-01-24 15:14:52 +0000630 `Context.use_certificate_file` raises `TypeError` if the first
631 argument is not a byte string or the second argument is not an integer.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800632 """
633 ctx = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000634 with pytest.raises(TypeError):
635 ctx.use_certificate_file(object(), FILETYPE_PEM)
636 with pytest.raises(TypeError):
637 ctx.use_certificate_file(b"somefile", object())
638 with pytest.raises(TypeError):
639 ctx.use_certificate_file(object(), FILETYPE_PEM)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800640
Alex Chan532b79e2017-01-24 15:14:52 +0000641 def test_use_certificate_file_missing(self, tmpfile):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800642 """
Alex Chan532b79e2017-01-24 15:14:52 +0000643 `Context.use_certificate_file` raises `OpenSSL.SSL.Error` if passed
644 the name of a file which does not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800645 """
646 ctx = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000647 with pytest.raises(Error):
648 ctx.use_certificate_file(tmpfile)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800649
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400650 def _use_certificate_file_test(self, certificate_file):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800651 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400652 Verify that calling ``Context.use_certificate_file`` with the given
653 filename doesn't raise an exception.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800654 """
655 # TODO
656 # Hard to assert anything. But we could set a privatekey then ask
657 # OpenSSL if the cert and key agree using check_privatekey. Then as
658 # long as check_privatekey works right we're good...
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400659 with open(certificate_file, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800660 pem_file.write(cleartextCertificatePEM)
661
662 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400663 ctx.use_certificate_file(certificate_file)
664
Alex Chan532b79e2017-01-24 15:14:52 +0000665 def test_use_certificate_file_bytes(self, tmpfile):
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400666 """
Alex Chan532b79e2017-01-24 15:14:52 +0000667 `Context.use_certificate_file` sets the certificate (given as a
668 `bytes` filename) which will be used to identify connections created
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400669 using the context.
670 """
Alex Chan532b79e2017-01-24 15:14:52 +0000671 filename = tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400672 self._use_certificate_file_test(filename)
673
Alex Chan532b79e2017-01-24 15:14:52 +0000674 def test_use_certificate_file_unicode(self, tmpfile):
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400675 """
Alex Chan532b79e2017-01-24 15:14:52 +0000676 `Context.use_certificate_file` sets the certificate (given as a
677 `bytes` filename) which will be used to identify connections created
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400678 using the context.
679 """
Alex Chan532b79e2017-01-24 15:14:52 +0000680 filename = tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400681 self._use_certificate_file_test(filename)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800682
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200683 @skip_if_py3
Alex Chan532b79e2017-01-24 15:14:52 +0000684 def test_use_certificate_file_long(self, tmpfile):
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200685 """
Alex Chan532b79e2017-01-24 15:14:52 +0000686 On Python 2 `Context.use_certificate_file` accepts a
687 filetype of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200688 """
Alex Chan532b79e2017-01-24 15:14:52 +0000689 pem_filename = tmpfile
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200690 with open(pem_filename, "wb") as pem_file:
691 pem_file.write(cleartextCertificatePEM)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500692
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200693 ctx = Context(TLSv1_METHOD)
694 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500695
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500696 def test_check_privatekey_valid(self):
697 """
Alex Chan532b79e2017-01-24 15:14:52 +0000698 `Context.check_privatekey` returns `None` if the `Context` instance
699 has been configured to use a matched key and certificate pair.
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500700 """
701 key = load_privatekey(FILETYPE_PEM, client_key_pem)
702 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
703 context = Context(TLSv1_METHOD)
704 context.use_privatekey(key)
705 context.use_certificate(cert)
Alex Chan532b79e2017-01-24 15:14:52 +0000706 assert None is context.check_privatekey()
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500707
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500708 def test_check_privatekey_invalid(self):
709 """
Alex Chan532b79e2017-01-24 15:14:52 +0000710 `Context.check_privatekey` raises `Error` if the `Context` instance
711 has been configured to use a key and certificate pair which don't
712 relate to each other.
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500713 """
714 key = load_privatekey(FILETYPE_PEM, client_key_pem)
715 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
716 context = Context(TLSv1_METHOD)
717 context.use_privatekey(key)
718 context.use_certificate(cert)
Alex Chan532b79e2017-01-24 15:14:52 +0000719 with pytest.raises(Error):
720 context.check_privatekey()
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400721
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400722 def test_app_data(self):
723 """
Alex Chan532b79e2017-01-24 15:14:52 +0000724 `Context.set_app_data` stores an object for later retrieval
725 using `Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400726 """
727 app_data = object()
728 context = Context(TLSv1_METHOD)
729 context.set_app_data(app_data)
Alex Chan532b79e2017-01-24 15:14:52 +0000730 assert context.get_app_data() is app_data
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400731
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400732 def test_set_options_wrong_args(self):
733 """
Alex Chan532b79e2017-01-24 15:14:52 +0000734 `Context.set_options` raises `TypeError` if called with
735 a non-`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400736 """
737 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000738 with pytest.raises(TypeError):
739 context.set_options(None)
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400740
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500741 def test_set_options(self):
742 """
Alex Chan532b79e2017-01-24 15:14:52 +0000743 `Context.set_options` returns the new options value.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500744 """
745 context = Context(TLSv1_METHOD)
746 options = context.set_options(OP_NO_SSLv2)
Alex Gaynor2310f8b2016-09-10 14:39:32 -0400747 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500748
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200749 @skip_if_py3
750 def test_set_options_long(self):
751 """
Alex Chan532b79e2017-01-24 15:14:52 +0000752 On Python 2 `Context.set_options` accepts values of type
753 `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200754 """
755 context = Context(TLSv1_METHOD)
756 options = context.set_options(long(OP_NO_SSLv2))
Alex Gaynor2310f8b2016-09-10 14:39:32 -0400757 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500758
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300759 def test_set_mode_wrong_args(self):
760 """
Alex Chan532b79e2017-01-24 15:14:52 +0000761 `Context.set_mode` raises `TypeError` if called with
762 a non-`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300763 """
764 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000765 with pytest.raises(TypeError):
766 context.set_mode(None)
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300767
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400768 def test_set_mode(self):
769 """
Alex Chan532b79e2017-01-24 15:14:52 +0000770 `Context.set_mode` accepts a mode bitvector and returns the
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400771 newly set mode.
772 """
773 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000774 assert MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500775
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400776 @skip_if_py3
777 def test_set_mode_long(self):
778 """
Alex Chan532b79e2017-01-24 15:14:52 +0000779 On Python 2 `Context.set_mode` accepts values of type `long` as well
780 as `int`.
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400781 """
782 context = Context(TLSv1_METHOD)
783 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
Alex Chan532b79e2017-01-24 15:14:52 +0000784 assert MODE_RELEASE_BUFFERS & mode
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400785
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400786 def test_set_timeout_wrong_args(self):
787 """
Alex Chan532b79e2017-01-24 15:14:52 +0000788 `Context.set_timeout` raises `TypeError` if called with
789 a non-`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400790 """
791 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000792 with pytest.raises(TypeError):
793 context.set_timeout(None)
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400794
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400795 def test_timeout(self):
796 """
Alex Chan532b79e2017-01-24 15:14:52 +0000797 `Context.set_timeout` sets the session timeout for all connections
798 created using the context object. `Context.get_timeout` retrieves
799 this value.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400800 """
801 context = Context(TLSv1_METHOD)
802 context.set_timeout(1234)
Alex Chan532b79e2017-01-24 15:14:52 +0000803 assert context.get_timeout() == 1234
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400804
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200805 @skip_if_py3
806 def test_timeout_long(self):
807 """
Alex Chan532b79e2017-01-24 15:14:52 +0000808 On Python 2 `Context.set_timeout` accepts values of type `long` as
809 well as int.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200810 """
811 context = Context(TLSv1_METHOD)
812 context.set_timeout(long(1234))
Alex Chan532b79e2017-01-24 15:14:52 +0000813 assert context.get_timeout() == 1234
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500814
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400815 def test_set_verify_depth_wrong_args(self):
816 """
Alex Chan532b79e2017-01-24 15:14:52 +0000817 `Context.set_verify_depth` raises `TypeError` if called with a
818 non-`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400819 """
820 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000821 with pytest.raises(TypeError):
822 context.set_verify_depth(None)
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400823
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400824 def test_verify_depth(self):
825 """
Alex Chan532b79e2017-01-24 15:14:52 +0000826 `Context.set_verify_depth` sets the number of certificates in
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200827 a chain to follow before giving up. The value can be retrieved with
Alex Chan532b79e2017-01-24 15:14:52 +0000828 `Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400829 """
830 context = Context(TLSv1_METHOD)
831 context.set_verify_depth(11)
Alex Chan532b79e2017-01-24 15:14:52 +0000832 assert context.get_verify_depth() == 11
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400833
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200834 @skip_if_py3
835 def test_verify_depth_long(self):
836 """
Alex Chan532b79e2017-01-24 15:14:52 +0000837 On Python 2 `Context.set_verify_depth` accepts values of type `long`
838 as well as int.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200839 """
840 context = Context(TLSv1_METHOD)
841 context.set_verify_depth(long(11))
Alex Chan532b79e2017-01-24 15:14:52 +0000842 assert context.get_verify_depth() == 11
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500843
Alex Chan532b79e2017-01-24 15:14:52 +0000844 def _write_encrypted_pem(self, passphrase, tmpfile):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400845 """
846 Write a new private key out to a new file, encrypted using the given
847 passphrase. Return the path to the new file.
848 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400849 key = PKey()
850 key.generate_key(TYPE_RSA, 128)
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400851 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
Alex Chan532b79e2017-01-24 15:14:52 +0000852 with open(tmpfile, 'w') as fObj:
853 fObj.write(pem.decode('ascii'))
854 return tmpfile
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400855
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400856 def test_set_passwd_cb_wrong_args(self):
857 """
Alex Chan532b79e2017-01-24 15:14:52 +0000858 `Context.set_passwd_cb` raises `TypeError` if called with a
859 non-callable first argument.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400860 """
861 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +0000862 with pytest.raises(TypeError):
863 context.set_passwd_cb(None)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400864
Alex Chan532b79e2017-01-24 15:14:52 +0000865 def test_set_passwd_cb(self, tmpfile):
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400866 """
Alex Chan532b79e2017-01-24 15:14:52 +0000867 `Context.set_passwd_cb` accepts a callable which will be invoked when
868 a private key is loaded from an encrypted PEM.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400869 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400870 passphrase = b"foobar"
Alex Chan532b79e2017-01-24 15:14:52 +0000871 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400872 calledWith = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200873
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400874 def passphraseCallback(maxlen, verify, extra):
875 calledWith.append((maxlen, verify, extra))
876 return passphrase
877 context = Context(TLSv1_METHOD)
878 context.set_passwd_cb(passphraseCallback)
879 context.use_privatekey_file(pemFile)
Alex Chan532b79e2017-01-24 15:14:52 +0000880 assert len(calledWith) == 1
881 assert isinstance(calledWith[0][0], int)
882 assert isinstance(calledWith[0][1], int)
883 assert calledWith[0][2] is None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400884
Alex Chan532b79e2017-01-24 15:14:52 +0000885 def test_passwd_callback_exception(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400886 """
Alex Chan532b79e2017-01-24 15:14:52 +0000887 `Context.use_privatekey_file` propagates any exception raised
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200888 by the passphrase callback.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400889 """
Alex Chan532b79e2017-01-24 15:14:52 +0000890 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200891
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400892 def passphraseCallback(maxlen, verify, extra):
893 raise RuntimeError("Sorry, I am a fail.")
894
895 context = Context(TLSv1_METHOD)
896 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000897 with pytest.raises(RuntimeError):
898 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400899
Alex Chan532b79e2017-01-24 15:14:52 +0000900 def test_passwd_callback_false(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400901 """
Alex Chan532b79e2017-01-24 15:14:52 +0000902 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
903 passphrase callback returns a false value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400904 """
Alex Chan532b79e2017-01-24 15:14:52 +0000905 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200906
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400907 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500908 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400909
910 context = Context(TLSv1_METHOD)
911 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000912 with pytest.raises(Error):
913 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400914
Alex Chan532b79e2017-01-24 15:14:52 +0000915 def test_passwd_callback_non_string(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400916 """
Alex Chan532b79e2017-01-24 15:14:52 +0000917 `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
918 passphrase callback returns a true non-string value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400919 """
Alex Chan532b79e2017-01-24 15:14:52 +0000920 pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200921
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400922 def passphraseCallback(maxlen, verify, extra):
923 return 10
924
925 context = Context(TLSv1_METHOD)
926 context.set_passwd_cb(passphraseCallback)
Alex Chan532b79e2017-01-24 15:14:52 +0000927 # TODO: Surely this is the wrong error?
928 with pytest.raises(ValueError):
929 context.use_privatekey_file(pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400930
Alex Chan532b79e2017-01-24 15:14:52 +0000931 def test_passwd_callback_too_long(self, tmpfile):
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400932 """
933 If the passphrase returned by the passphrase callback returns a string
934 longer than the indicated maximum length, it is truncated.
935 """
936 # A priori knowledge!
Alex Gaynore7f51982016-09-11 11:48:14 -0400937 passphrase = b"x" * 1024
Alex Chan532b79e2017-01-24 15:14:52 +0000938 pemFile = self._write_encrypted_pem(passphrase, tmpfile)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200939
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400940 def passphraseCallback(maxlen, verify, extra):
941 assert maxlen == 1024
Alex Gaynore7f51982016-09-11 11:48:14 -0400942 return passphrase + b"y"
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400943
944 context = Context(TLSv1_METHOD)
945 context.set_passwd_cb(passphraseCallback)
946 # This shall succeed because the truncated result is the correct
947 # passphrase.
948 context.use_privatekey_file(pemFile)
949
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400950 def test_set_info_callback(self):
951 """
Alex Chan532b79e2017-01-24 15:14:52 +0000952 `Context.set_info_callback` accepts a callable which will be
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200953 invoked when certain information about an SSL connection is available.
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400954 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500955 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400956
957 clientSSL = Connection(Context(TLSv1_METHOD), client)
958 clientSSL.set_connect_state()
959
960 called = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200961
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400962 def info(conn, where, ret):
963 called.append((conn, where, ret))
964 context = Context(TLSv1_METHOD)
965 context.set_info_callback(info)
966 context.use_certificate(
967 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
968 context.use_privatekey(
969 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
970
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400971 serverSSL = Connection(context, server)
972 serverSSL.set_accept_state()
973
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500974 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400975
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500976 # The callback must always be called with a Connection instance as the
977 # first argument. It would probably be better to split this into
978 # separate tests for client and server side info callbacks so we could
979 # assert it is called with the right Connection instance. It would
980 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500981 notConnections = [
982 conn for (conn, where, ret) in called
983 if not isinstance(conn, Connection)]
Alex Chan532b79e2017-01-24 15:14:52 +0000984 assert [] == notConnections, (
985 "Some info callback arguments were not Connection instances.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400986
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400987 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400988 """
989 Create a client context which will verify the peer certificate and call
Alex Chan532b79e2017-01-24 15:14:52 +0000990 its `load_verify_locations` method with the given arguments.
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400991 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400992 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500993 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400994
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400995 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400996 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400997 # Require that the server certificate verify properly or the
998 # connection will fail.
999 clientContext.set_verify(
1000 VERIFY_PEER,
1001 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
1002
1003 clientSSL = Connection(clientContext, client)
1004 clientSSL.set_connect_state()
1005
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001006 serverContext = Context(TLSv1_METHOD)
1007 serverContext.use_certificate(
1008 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1009 serverContext.use_privatekey(
1010 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1011
1012 serverSSL = Connection(serverContext, server)
1013 serverSSL.set_accept_state()
1014
Jean-Paul Calderonef8742032010-09-25 00:00:32 -04001015 # Without load_verify_locations above, the handshake
1016 # will fail:
1017 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
1018 # 'certificate verify failed')]
1019 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001020
1021 cert = clientSSL.get_peer_certificate()
Alex Chan532b79e2017-01-24 15:14:52 +00001022 assert cert.get_subject().CN == 'Testing Root CA'
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001023
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001024 def _load_verify_cafile(self, cafile):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001025 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001026 Verify that if path to a file containing a certificate is passed to
Alex Chan532b79e2017-01-24 15:14:52 +00001027 `Context.load_verify_locations` for the ``cafile`` parameter, that
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001028 certificate is used as a trust root for the purposes of verifying
Alex Chan532b79e2017-01-24 15:14:52 +00001029 connections created using that `Context`.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001030 """
Alex Chan532b79e2017-01-24 15:14:52 +00001031 with open(cafile, 'w') as fObj:
1032 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001033
1034 self._load_verify_locations_test(cafile)
1035
Alex Chan532b79e2017-01-24 15:14:52 +00001036 def test_load_verify_bytes_cafile(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001037 """
Alex Chan532b79e2017-01-24 15:14:52 +00001038 `Context.load_verify_locations` accepts a file name as a `bytes`
1039 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001040 """
Alex Chan532b79e2017-01-24 15:14:52 +00001041 cafile = tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001042 self._load_verify_cafile(cafile)
1043
Alex Chan532b79e2017-01-24 15:14:52 +00001044 def test_load_verify_unicode_cafile(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001045 """
Alex Chan532b79e2017-01-24 15:14:52 +00001046 `Context.load_verify_locations` accepts a file name as a `unicode`
1047 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001048 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001049 self._load_verify_cafile(
Alex Chan532b79e2017-01-24 15:14:52 +00001050 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001051 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001052
Alex Chan532b79e2017-01-24 15:14:52 +00001053 def test_load_verify_invalid_file(self, tmpfile):
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001054 """
Alex Chan532b79e2017-01-24 15:14:52 +00001055 `Context.load_verify_locations` raises `Error` when passed a
1056 non-existent cafile.
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001057 """
1058 clientContext = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001059 with pytest.raises(Error):
1060 clientContext.load_verify_locations(tmpfile)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001061
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001062 def _load_verify_directory_locations_capath(self, capath):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001063 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001064 Verify that if path to a directory containing certificate files is
1065 passed to ``Context.load_verify_locations`` for the ``capath``
1066 parameter, those certificates are used as trust roots for the purposes
1067 of verifying connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001068 """
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001069 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -04001070 # Hash values computed manually with c_rehash to avoid depending on
1071 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
1072 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001073 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001074 cafile = join_bytes_or_unicode(capath, name)
1075 with open(cafile, 'w') as fObj:
1076 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001077
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001078 self._load_verify_locations_test(None, capath)
1079
Alex Chan532b79e2017-01-24 15:14:52 +00001080 def test_load_verify_directory_bytes_capath(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001081 """
Alex Chan532b79e2017-01-24 15:14:52 +00001082 `Context.load_verify_locations` accepts a directory name as a `bytes`
1083 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001084 """
1085 self._load_verify_directory_locations_capath(
Alex Chan532b79e2017-01-24 15:14:52 +00001086 tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001087 )
1088
Alex Chan532b79e2017-01-24 15:14:52 +00001089 def test_load_verify_directory_unicode_capath(self, tmpfile):
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001090 """
Alex Chan532b79e2017-01-24 15:14:52 +00001091 `Context.load_verify_locations` accepts a directory name as a `unicode`
1092 instance and uses the certificates within for verification purposes.
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001093 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001094 self._load_verify_directory_locations_capath(
Alex Chan532b79e2017-01-24 15:14:52 +00001095 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001096 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001097
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001098 def test_load_verify_locations_wrong_args(self):
1099 """
Alex Chan532b79e2017-01-24 15:14:52 +00001100 `Context.load_verify_locations` raises `TypeError` if with non-`str`
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001101 arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001102 """
1103 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001104 with pytest.raises(TypeError):
1105 context.load_verify_locations(object())
1106 with pytest.raises(TypeError):
1107 context.load_verify_locations(object(), object())
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001108
Hynek Schlawack734d3022015-09-05 19:19:32 +02001109 @pytest.mark.skipif(
Paul Kehrer55fb3412017-06-29 18:44:08 -05001110 not platform.startswith("linux"),
1111 reason="Loading fallback paths is a linux-specific behavior to "
1112 "accommodate pyca/cryptography manylinux1 wheels"
1113 )
1114 def test_fallback_default_verify_paths(self, monkeypatch):
1115 """
1116 Test that we load certificates successfully on linux from the fallback
1117 path. To do this we set the _CRYPTOGRAPHY_MANYLINUX1_CA_FILE and
1118 _CRYPTOGRAPHY_MANYLINUX1_CA_DIR vars to be equal to whatever the
1119 current OpenSSL default is and we disable
1120 SSL_CTX_SET_default_verify_paths so that it can't find certs unless
1121 it loads via fallback.
1122 """
1123 context = Context(TLSv1_METHOD)
1124 monkeypatch.setattr(
1125 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1126 )
1127 monkeypatch.setattr(
1128 SSL,
1129 "_CRYPTOGRAPHY_MANYLINUX1_CA_FILE",
1130 _ffi.string(_lib.X509_get_default_cert_file())
1131 )
1132 monkeypatch.setattr(
1133 SSL,
1134 "_CRYPTOGRAPHY_MANYLINUX1_CA_DIR",
1135 _ffi.string(_lib.X509_get_default_cert_dir())
1136 )
1137 context.set_default_verify_paths()
1138 store = context.get_cert_store()
1139 sk_obj = _lib.X509_STORE_get0_objects(store._store)
1140 assert sk_obj != _ffi.NULL
1141 num = _lib.sk_X509_OBJECT_num(sk_obj)
1142 assert num != 0
1143
1144 def test_check_env_vars(self, monkeypatch):
1145 """
1146 Test that we return True/False appropriately if the env vars are set.
1147 """
1148 context = Context(TLSv1_METHOD)
1149 dir_var = "CUSTOM_DIR_VAR"
1150 file_var = "CUSTOM_FILE_VAR"
1151 assert context._check_env_vars_set(dir_var, file_var) is False
1152 monkeypatch.setenv(dir_var, "value")
1153 monkeypatch.setenv(file_var, "value")
1154 assert context._check_env_vars_set(dir_var, file_var) is True
1155 assert context._check_env_vars_set(dir_var, file_var) is True
1156
1157 def test_verify_no_fallback_if_env_vars_set(self, monkeypatch):
1158 """
1159 Test that we don't use the fallback path if env vars are set.
1160 """
1161 context = Context(TLSv1_METHOD)
1162 monkeypatch.setattr(
1163 _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
1164 )
1165 dir_env_var = _ffi.string(
1166 _lib.X509_get_default_cert_dir_env()
1167 ).decode("ascii")
1168 file_env_var = _ffi.string(
1169 _lib.X509_get_default_cert_file_env()
1170 ).decode("ascii")
1171 monkeypatch.setenv(dir_env_var, "value")
1172 monkeypatch.setenv(file_env_var, "value")
1173 context.set_default_verify_paths()
1174
1175 monkeypatch.setattr(
1176 context,
1177 "_fallback_default_verify_paths",
1178 raiser(SystemError)
1179 )
1180 context.set_default_verify_paths()
1181
1182 @pytest.mark.skipif(
Hynek Schlawack734d3022015-09-05 19:19:32 +02001183 platform == "win32",
1184 reason="set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001185 "See LP#404343 and LP#404344."
Hynek Schlawack734d3022015-09-05 19:19:32 +02001186 )
1187 def test_set_default_verify_paths(self):
1188 """
Alex Chan532b79e2017-01-24 15:14:52 +00001189 `Context.set_default_verify_paths` causes the platform-specific CA
1190 certificate locations to be used for verification purposes.
Hynek Schlawack734d3022015-09-05 19:19:32 +02001191 """
1192 # Testing this requires a server with a certificate signed by one
1193 # of the CAs in the platform CA location. Getting one of those
1194 # costs money. Fortunately (or unfortunately, depending on your
1195 # perspective), it's easy to think of a public server on the
1196 # internet which has such a certificate. Connecting to the network
1197 # in a unit test is bad, but it's the only way I can think of to
1198 # really test this. -exarkun
Hynek Schlawackbf887932015-10-21 17:13:47 +02001199 context = Context(SSLv23_METHOD)
Hynek Schlawack734d3022015-09-05 19:19:32 +02001200 context.set_default_verify_paths()
1201 context.set_verify(
1202 VERIFY_PEER,
1203 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001204
Hynek Schlawack734d3022015-09-05 19:19:32 +02001205 client = socket()
Hynek Schlawackbf887932015-10-21 17:13:47 +02001206 client.connect(("encrypted.google.com", 443))
Hynek Schlawack734d3022015-09-05 19:19:32 +02001207 clientSSL = Connection(context, client)
1208 clientSSL.set_connect_state()
1209 clientSSL.do_handshake()
1210 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Alex Chan532b79e2017-01-24 15:14:52 +00001211 assert clientSSL.recv(1024)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001212
Paul Kehrer55fb3412017-06-29 18:44:08 -05001213 def test_fallback_path_is_not_file_or_dir(self):
1214 """
1215 Test that when passed empty arrays or paths that do not exist no
1216 errors are raised.
1217 """
1218 context = Context(TLSv1_METHOD)
1219 context._fallback_default_verify_paths([], [])
1220 context._fallback_default_verify_paths(
1221 ["/not/a/file"], ["/not/a/dir"]
1222 )
1223
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001224 def test_add_extra_chain_cert_invalid_cert(self):
1225 """
Alex Chan532b79e2017-01-24 15:14:52 +00001226 `Context.add_extra_chain_cert` raises `TypeError` if called with an
1227 object which is not an instance of `X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001228 """
1229 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001230 with pytest.raises(TypeError):
1231 context.add_extra_chain_cert(object())
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001232
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001233 def _handshake_test(self, serverContext, clientContext):
1234 """
1235 Verify that a client and server created with the given contexts can
1236 successfully handshake and communicate.
1237 """
1238 serverSocket, clientSocket = socket_pair()
1239
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001240 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001241 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001242
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001243 client = Connection(clientContext, clientSocket)
1244 client.set_connect_state()
1245
1246 # Make them talk to each other.
Alex Chan532b79e2017-01-24 15:14:52 +00001247 # interact_in_memory(client, server)
1248 for _ in range(3):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001249 for s in [client, server]:
1250 try:
1251 s.do_handshake()
1252 except WantReadError:
1253 pass
1254
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001255 def test_set_verify_callback_connection_argument(self):
1256 """
1257 The first argument passed to the verify callback is the
Alex Chan532b79e2017-01-24 15:14:52 +00001258 `Connection` instance for which verification is taking place.
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001259 """
1260 serverContext = Context(TLSv1_METHOD)
1261 serverContext.use_privatekey(
1262 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1263 serverContext.use_certificate(
1264 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1265 serverConnection = Connection(serverContext, None)
1266
1267 class VerifyCallback(object):
1268 def callback(self, connection, *args):
1269 self.connection = connection
1270 return 1
1271
1272 verify = VerifyCallback()
1273 clientContext = Context(TLSv1_METHOD)
1274 clientContext.set_verify(VERIFY_PEER, verify.callback)
1275 clientConnection = Connection(clientContext, None)
1276 clientConnection.set_connect_state()
1277
Alex Chan532b79e2017-01-24 15:14:52 +00001278 handshake_in_memory(clientConnection, serverConnection)
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001279
Alex Chan532b79e2017-01-24 15:14:52 +00001280 assert verify.connection is clientConnection
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001281
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001282 def test_set_verify_callback_exception(self):
1283 """
Alex Chan532b79e2017-01-24 15:14:52 +00001284 If the verify callback passed to `Context.set_verify` raises an
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001285 exception, verification fails and the exception is propagated to the
Alex Chan532b79e2017-01-24 15:14:52 +00001286 caller of `Connection.do_handshake`.
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001287 """
1288 serverContext = Context(TLSv1_METHOD)
1289 serverContext.use_privatekey(
1290 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1291 serverContext.use_certificate(
1292 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1293
1294 clientContext = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001295
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001296 def verify_callback(*args):
1297 raise Exception("silly verify failure")
1298 clientContext.set_verify(VERIFY_PEER, verify_callback)
1299
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001300 with pytest.raises(Exception) as exc:
1301 self._handshake_test(serverContext, clientContext)
1302
Alex Chan532b79e2017-01-24 15:14:52 +00001303 assert "silly verify failure" == str(exc.value)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001304
Alex Chan532b79e2017-01-24 15:14:52 +00001305 def test_add_extra_chain_cert(self, tmpdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001306 """
Alex Chan532b79e2017-01-24 15:14:52 +00001307 `Context.add_extra_chain_cert` accepts an `X509`
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001308 instance to add to the certificate chain.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001309
Alex Chan532b79e2017-01-24 15:14:52 +00001310 See `_create_certificate_chain` for the details of the
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001311 certificate chain tested.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001312
1313 The chain is tested by starting a server with scert and connecting
1314 to it with a client which trusts cacert and requires verification to
1315 succeed.
1316 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001317 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001318 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1319
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001320 # Dump the CA certificate to a file because that's the only way to load
1321 # it as a trusted CA in the client context.
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001322 for cert, name in [(cacert, 'ca.pem'),
1323 (icert, 'i.pem'),
1324 (scert, 's.pem')]:
Alex Chan532b79e2017-01-24 15:14:52 +00001325 with tmpdir.join(name).open('w') as f:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001326 f.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001327
Hynek Schlawack1902c012015-04-16 15:06:41 -04001328 for key, name in [(cakey, 'ca.key'),
1329 (ikey, 'i.key'),
1330 (skey, 's.key')]:
Alex Chan532b79e2017-01-24 15:14:52 +00001331 with tmpdir.join(name).open('w') as f:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001332 f.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001333
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001334 # Create the server context
1335 serverContext = Context(TLSv1_METHOD)
1336 serverContext.use_privatekey(skey)
1337 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001338 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001339 serverContext.add_extra_chain_cert(icert)
1340
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001341 # Create the client
1342 clientContext = Context(TLSv1_METHOD)
1343 clientContext.set_verify(
1344 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Alex Chan532b79e2017-01-24 15:14:52 +00001345 clientContext.load_verify_locations(str(tmpdir.join("ca.pem")))
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001346
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001347 # Try it out.
1348 self._handshake_test(serverContext, clientContext)
1349
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001350 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001351 """
Alex Chan532b79e2017-01-24 15:14:52 +00001352 Verify that `Context.use_certificate_chain_file` reads a
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001353 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001354
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001355 The chain is tested by starting a server with scert and connecting to
1356 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001357 succeed.
1358 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001359 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001360 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1361
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001362 makedirs(certdir)
1363
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001364 chainFile = join_bytes_or_unicode(certdir, "chain.pem")
1365 caFile = join_bytes_or_unicode(certdir, "ca.pem")
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001366
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001367 # Write out the chain file.
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001368 with open(chainFile, 'wb') as fObj:
1369 # Most specific to least general.
1370 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1371 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1372 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1373
1374 with open(caFile, 'w') as fObj:
1375 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001376
1377 serverContext = Context(TLSv1_METHOD)
1378 serverContext.use_certificate_chain_file(chainFile)
1379 serverContext.use_privatekey(skey)
1380
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001381 clientContext = Context(TLSv1_METHOD)
1382 clientContext.set_verify(
1383 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001384 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001385
1386 self._handshake_test(serverContext, clientContext)
1387
Alex Chan532b79e2017-01-24 15:14:52 +00001388 def test_use_certificate_chain_file_bytes(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001389 """
1390 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1391 an instance of ``bytes``) to specify additional certificates to use to
1392 construct and verify a trust chain.
1393 """
1394 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001395 tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001396 )
1397
Alex Chan532b79e2017-01-24 15:14:52 +00001398 def test_use_certificate_chain_file_unicode(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001399 """
1400 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1401 an instance of ``unicode``) to specify additional certificates to use
1402 to construct and verify a trust chain.
1403 """
1404 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001405 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001406 )
1407
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001408 def test_use_certificate_chain_file_wrong_args(self):
1409 """
Alex Chan532b79e2017-01-24 15:14:52 +00001410 `Context.use_certificate_chain_file` raises `TypeError` if passed a
1411 non-byte string single argument.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001412 """
1413 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001414 with pytest.raises(TypeError):
1415 context.use_certificate_chain_file(object())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001416
Alex Chan532b79e2017-01-24 15:14:52 +00001417 def test_use_certificate_chain_file_missing_file(self, tmpfile):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001418 """
Alex Chan532b79e2017-01-24 15:14:52 +00001419 `Context.use_certificate_chain_file` raises `OpenSSL.SSL.Error` when
1420 passed a bad chain file name (for example, the name of a file which
1421 does not exist).
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001422 """
1423 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001424 with pytest.raises(Error):
1425 context.use_certificate_chain_file(tmpfile)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001426
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001427 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001428 """
Alex Chan532b79e2017-01-24 15:14:52 +00001429 `Context.get_verify_mode` returns the verify mode flags previously
1430 passed to `Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001431 """
1432 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001433 assert context.get_verify_mode() == 0
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001434 context.set_verify(
1435 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
Alex Chan532b79e2017-01-24 15:14:52 +00001436 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001437
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001438 @skip_if_py3
1439 def test_set_verify_mode_long(self):
1440 """
Alex Chan532b79e2017-01-24 15:14:52 +00001441 On Python 2 `Context.set_verify_mode` accepts values of type `long`
1442 as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001443 """
1444 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001445 assert context.get_verify_mode() == 0
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001446 context.set_verify(
Hynek Schlawackb4ceed32015-09-05 20:55:19 +02001447 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None
1448 ) # pragma: nocover
Alex Chan532b79e2017-01-24 15:14:52 +00001449 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001450
Alex Chanfb078d82017-04-20 11:16:15 +01001451 @pytest.mark.parametrize('mode', [None, 1.0, object(), 'mode'])
1452 def test_set_verify_wrong_mode_arg(self, mode):
1453 """
1454 `Context.set_verify` raises `TypeError` if the first argument is
1455 not an integer.
1456 """
1457 context = Context(TLSv1_METHOD)
1458 with pytest.raises(TypeError):
1459 context.set_verify(mode=mode, callback=lambda *args: None)
1460
1461 @pytest.mark.parametrize('callback', [None, 1.0, 'mode', ('foo', 'bar')])
1462 def test_set_verify_wrong_callable_arg(self, callback):
1463 """
1464 `Context.set_verify` raises `TypeError` if the the second argument
1465 is not callable.
1466 """
1467 context = Context(TLSv1_METHOD)
1468 with pytest.raises(TypeError):
1469 context.set_verify(mode=VERIFY_PEER, callback=callback)
1470
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001471 def test_load_tmp_dh_wrong_args(self):
1472 """
Alex Chan532b79e2017-01-24 15:14:52 +00001473 `Context.load_tmp_dh` raises `TypeError` if called with a
1474 non-`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001475 """
1476 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001477 with pytest.raises(TypeError):
1478 context.load_tmp_dh(object())
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001479
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001480 def test_load_tmp_dh_missing_file(self):
1481 """
Alex Chan532b79e2017-01-24 15:14:52 +00001482 `Context.load_tmp_dh` raises `OpenSSL.SSL.Error` if the
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001483 specified file does not exist.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001484 """
1485 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001486 with pytest.raises(Error):
1487 context.load_tmp_dh(b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001488
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001489 def _load_tmp_dh_test(self, dhfilename):
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001490 """
1491 Verify that calling ``Context.load_tmp_dh`` with the given filename
1492 does not raise an exception.
1493 """
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001494 context = Context(TLSv1_METHOD)
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001495 with open(dhfilename, "w") as dhfile:
1496 dhfile.write(dhparam)
1497
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001498 context.load_tmp_dh(dhfilename)
1499 # XXX What should I assert here? -exarkun
1500
Alex Chan532b79e2017-01-24 15:14:52 +00001501 def test_load_tmp_dh_bytes(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001502 """
Alex Chan532b79e2017-01-24 15:14:52 +00001503 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001504 specified file (given as ``bytes``).
1505 """
1506 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001507 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001508 )
1509
Alex Chan532b79e2017-01-24 15:14:52 +00001510 def test_load_tmp_dh_unicode(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001511 """
Alex Chan532b79e2017-01-24 15:14:52 +00001512 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001513 specified file (given as ``unicode``).
1514 """
1515 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001516 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001517 )
1518
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001519 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001520 """
Alex Chan532b79e2017-01-24 15:14:52 +00001521 `Context.set_tmp_ecdh` sets the elliptic curve for Diffie-Hellman to
1522 the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001523 """
1524 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001525 for curve in get_elliptic_curves():
Hynek Schlawacka07fa8c2015-10-17 10:15:28 +02001526 if curve.name.startswith(u"Oakley-"):
Hynek Schlawack7408aff2015-10-17 09:51:16 +02001527 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1528 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1529 # error queue on OpenSSL 1.0.2.
1530 continue
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001531 # The only easily "assertable" thing is that it does not raise an
1532 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001533 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001534
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001535 def test_set_session_cache_mode_wrong_args(self):
1536 """
Alex Chan532b79e2017-01-24 15:14:52 +00001537 `Context.set_session_cache_mode` raises `TypeError` if called with
1538 a non-integer argument.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001539 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001540 """
1541 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001542 with pytest.raises(TypeError):
1543 context.set_session_cache_mode(object())
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001544
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001545 def test_session_cache_mode(self):
1546 """
Alex Chan532b79e2017-01-24 15:14:52 +00001547 `Context.set_session_cache_mode` specifies how sessions are cached.
1548 The setting can be retrieved via `Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001549 """
1550 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001551 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001552 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
Alex Chan532b79e2017-01-24 15:14:52 +00001553 assert SESS_CACHE_OFF == off
1554 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001555
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001556 @skip_if_py3
1557 def test_session_cache_mode_long(self):
1558 """
Alex Chan532b79e2017-01-24 15:14:52 +00001559 On Python 2 `Context.set_session_cache_mode` accepts values
1560 of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001561 """
1562 context = Context(TLSv1_METHOD)
1563 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
Alex Chan532b79e2017-01-24 15:14:52 +00001564 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001565
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 def test_get_cert_store(self):
1567 """
Alex Chan532b79e2017-01-24 15:14:52 +00001568 `Context.get_cert_store` returns a `X509Store` instance.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001569 """
1570 context = Context(TLSv1_METHOD)
1571 store = context.get_cert_store()
Alex Chan532b79e2017-01-24 15:14:52 +00001572 assert isinstance(store, X509Store)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573
1574
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001575class TestServerNameCallback(object):
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001576 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001577 Tests for `Context.set_tlsext_servername_callback` and its
1578 interaction with `Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001579 """
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001580 def test_old_callback_forgotten(self):
1581 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001582 If `Context.set_tlsext_servername_callback` is used to specify
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001583 a new callback, the one it replaces is dereferenced.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001584 """
Alex Chanfb078d82017-04-20 11:16:15 +01001585 def callback(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001586 pass
1587
Alex Chanfb078d82017-04-20 11:16:15 +01001588 def replacement(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001589 pass
1590
1591 context = Context(TLSv1_METHOD)
1592 context.set_tlsext_servername_callback(callback)
1593
1594 tracker = ref(callback)
1595 del callback
1596
1597 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001598
1599 # One run of the garbage collector happens to work on CPython. PyPy
1600 # doesn't collect the underlying object until a second run for whatever
1601 # reason. That's fine, it still demonstrates our code has properly
1602 # dropped the reference.
1603 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001604 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001605
1606 callback = tracker()
1607 if callback is not None:
1608 referrers = get_referrers(callback)
Alex Chanfb078d82017-04-20 11:16:15 +01001609 if len(referrers) > 1: # pragma: nocover
1610 pytest.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001611
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001612 def test_no_servername(self):
1613 """
1614 When a client specifies no server name, the callback passed to
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001615 `Context.set_tlsext_servername_callback` is invoked and the
1616 result of `Connection.get_servername` is `None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001617 """
1618 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001619
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001620 def servername(conn):
1621 args.append((conn, conn.get_servername()))
1622 context = Context(TLSv1_METHOD)
1623 context.set_tlsext_servername_callback(servername)
1624
1625 # Lose our reference to it. The Context is responsible for keeping it
1626 # alive now.
1627 del servername
1628 collect()
1629
1630 # Necessary to actually accept the connection
1631 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001632 context.use_certificate(
1633 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001634
1635 # Do a little connection to trigger the logic
1636 server = Connection(context, None)
1637 server.set_accept_state()
1638
1639 client = Connection(Context(TLSv1_METHOD), None)
1640 client.set_connect_state()
1641
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001642 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001643
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001644 assert args == [(server, None)]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001645
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001646 def test_servername(self):
1647 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001648 When a client specifies a server name in its hello message, the
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001649 callback passed to `Contexts.set_tlsext_servername_callback` is
1650 invoked and the result of `Connection.get_servername` is that
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001651 server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001652 """
1653 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001654
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001655 def servername(conn):
1656 args.append((conn, conn.get_servername()))
1657 context = Context(TLSv1_METHOD)
1658 context.set_tlsext_servername_callback(servername)
1659
1660 # Necessary to actually accept the connection
1661 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001662 context.use_certificate(
1663 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001664
1665 # Do a little connection to trigger the logic
1666 server = Connection(context, None)
1667 server.set_accept_state()
1668
1669 client = Connection(Context(TLSv1_METHOD), None)
1670 client.set_connect_state()
Alex Gaynore7f51982016-09-11 11:48:14 -04001671 client.set_tlsext_host_name(b"foo1.example.com")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001672
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001673 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001674
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001675 assert args == [(server, b"foo1.example.com")]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001676
1677
Alex Chan9e08b3e2016-11-10 12:18:54 +00001678class TestNextProtoNegotiation(object):
Cory Benfield84a121e2014-03-31 20:30:25 +01001679 """
1680 Test for Next Protocol Negotiation in PyOpenSSL.
1681 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001682 def test_npn_success(self):
1683 """
1684 Tests that clients and servers that agree on the negotiated next
1685 protocol can correct establish a connection, and that the agreed
1686 protocol is reported by the connections.
1687 """
1688 advertise_args = []
1689 select_args = []
1690
1691 def advertise(conn):
1692 advertise_args.append((conn,))
1693 return [b'http/1.1', b'spdy/2']
1694
1695 def select(conn, options):
1696 select_args.append((conn, options))
1697 return b'spdy/2'
1698
1699 server_context = Context(TLSv1_METHOD)
1700 server_context.set_npn_advertise_callback(advertise)
1701
1702 client_context = Context(TLSv1_METHOD)
1703 client_context.set_npn_select_callback(select)
1704
1705 # Necessary to actually accept the connection
1706 server_context.use_privatekey(
1707 load_privatekey(FILETYPE_PEM, server_key_pem))
1708 server_context.use_certificate(
1709 load_certificate(FILETYPE_PEM, server_cert_pem))
1710
1711 # Do a little connection to trigger the logic
1712 server = Connection(server_context, None)
1713 server.set_accept_state()
1714
1715 client = Connection(client_context, None)
1716 client.set_connect_state()
1717
1718 interact_in_memory(server, client)
1719
1720 assert advertise_args == [(server,)]
1721 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1722
1723 assert server.get_next_proto_negotiated() == b'spdy/2'
1724 assert client.get_next_proto_negotiated() == b'spdy/2'
1725
1726 def test_npn_client_fail(self):
1727 """
1728 Tests that when clients and servers cannot agree on what protocol
1729 to use next that the TLS connection does not get established.
1730 """
1731 advertise_args = []
1732 select_args = []
1733
1734 def advertise(conn):
1735 advertise_args.append((conn,))
1736 return [b'http/1.1', b'spdy/2']
1737
1738 def select(conn, options):
1739 select_args.append((conn, options))
1740 return b''
1741
1742 server_context = Context(TLSv1_METHOD)
1743 server_context.set_npn_advertise_callback(advertise)
1744
1745 client_context = Context(TLSv1_METHOD)
1746 client_context.set_npn_select_callback(select)
1747
1748 # Necessary to actually accept the connection
1749 server_context.use_privatekey(
1750 load_privatekey(FILETYPE_PEM, server_key_pem))
1751 server_context.use_certificate(
1752 load_certificate(FILETYPE_PEM, server_cert_pem))
1753
1754 # Do a little connection to trigger the logic
1755 server = Connection(server_context, None)
1756 server.set_accept_state()
1757
1758 client = Connection(client_context, None)
1759 client.set_connect_state()
1760
1761 # If the client doesn't return anything, the connection will fail.
1762 with pytest.raises(Error):
1763 interact_in_memory(server, client)
1764
1765 assert advertise_args == [(server,)]
1766 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1767
1768 def test_npn_select_error(self):
1769 """
1770 Test that we can handle exceptions in the select callback. If
1771 select fails it should be fatal to the connection.
1772 """
1773 advertise_args = []
1774
1775 def advertise(conn):
1776 advertise_args.append((conn,))
1777 return [b'http/1.1', b'spdy/2']
1778
1779 def select(conn, options):
1780 raise TypeError
1781
1782 server_context = Context(TLSv1_METHOD)
1783 server_context.set_npn_advertise_callback(advertise)
1784
1785 client_context = Context(TLSv1_METHOD)
1786 client_context.set_npn_select_callback(select)
1787
1788 # Necessary to actually accept the connection
1789 server_context.use_privatekey(
1790 load_privatekey(FILETYPE_PEM, server_key_pem))
1791 server_context.use_certificate(
1792 load_certificate(FILETYPE_PEM, server_cert_pem))
1793
1794 # Do a little connection to trigger the logic
1795 server = Connection(server_context, None)
1796 server.set_accept_state()
1797
1798 client = Connection(client_context, None)
1799 client.set_connect_state()
1800
1801 # If the callback throws an exception it should be raised here.
1802 with pytest.raises(TypeError):
1803 interact_in_memory(server, client)
1804 assert advertise_args == [(server,), ]
1805
1806 def test_npn_advertise_error(self):
1807 """
1808 Test that we can handle exceptions in the advertise callback. If
1809 advertise fails no NPN is advertised to the client.
1810 """
1811 select_args = []
1812
1813 def advertise(conn):
1814 raise TypeError
1815
1816 def select(conn, options): # pragma: nocover
Cory Benfieldba1820d2015-04-13 17:39:12 -04001817 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001818 Assert later that no args are actually appended.
Cory Benfieldba1820d2015-04-13 17:39:12 -04001819 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001820 select_args.append((conn, options))
1821 return b''
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001822
Alex Chan9e08b3e2016-11-10 12:18:54 +00001823 server_context = Context(TLSv1_METHOD)
1824 server_context.set_npn_advertise_callback(advertise)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001825
Alex Chan9e08b3e2016-11-10 12:18:54 +00001826 client_context = Context(TLSv1_METHOD)
1827 client_context.set_npn_select_callback(select)
Cory Benfield84a121e2014-03-31 20:30:25 +01001828
Alex Chan9e08b3e2016-11-10 12:18:54 +00001829 # Necessary to actually accept the connection
1830 server_context.use_privatekey(
1831 load_privatekey(FILETYPE_PEM, server_key_pem))
1832 server_context.use_certificate(
1833 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield84a121e2014-03-31 20:30:25 +01001834
Alex Chan9e08b3e2016-11-10 12:18:54 +00001835 # Do a little connection to trigger the logic
1836 server = Connection(server_context, None)
1837 server.set_accept_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001838
Alex Chan9e08b3e2016-11-10 12:18:54 +00001839 client = Connection(client_context, None)
1840 client.set_connect_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001841
Alex Chan9e08b3e2016-11-10 12:18:54 +00001842 # If the client doesn't return anything, the connection will fail.
1843 with pytest.raises(TypeError):
1844 interact_in_memory(server, client)
1845 assert select_args == []
Cory Benfield0ea76e72015-03-22 09:05:28 +00001846
1847
Alex Chanec1e32d2016-11-10 14:11:45 +00001848class TestApplicationLayerProtoNegotiation(object):
Cory Benfield12eae892014-06-07 15:42:56 +01001849 """
1850 Tests for ALPN in PyOpenSSL.
1851 """
Cory Benfielde46fa842015-04-13 16:50:49 -04001852 # Skip tests on versions that don't support ALPN.
1853 if _lib.Cryptography_HAS_ALPN:
Cory Benfield12eae892014-06-07 15:42:56 +01001854
Cory Benfielde46fa842015-04-13 16:50:49 -04001855 def test_alpn_success(self):
1856 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001857 Clients and servers that agree on the negotiated ALPN protocol can
1858 correct establish a connection, and the agreed protocol is reported
1859 by the connections.
Cory Benfielde46fa842015-04-13 16:50:49 -04001860 """
1861 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001862
Cory Benfielde46fa842015-04-13 16:50:49 -04001863 def select(conn, options):
1864 select_args.append((conn, options))
1865 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001866
Cory Benfielde46fa842015-04-13 16:50:49 -04001867 client_context = Context(TLSv1_METHOD)
1868 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001869
Cory Benfielde46fa842015-04-13 16:50:49 -04001870 server_context = Context(TLSv1_METHOD)
1871 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001872
Cory Benfielde46fa842015-04-13 16:50:49 -04001873 # Necessary to actually accept the connection
1874 server_context.use_privatekey(
1875 load_privatekey(FILETYPE_PEM, server_key_pem))
1876 server_context.use_certificate(
1877 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001878
Cory Benfielde46fa842015-04-13 16:50:49 -04001879 # Do a little connection to trigger the logic
1880 server = Connection(server_context, None)
1881 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001882
Cory Benfielde46fa842015-04-13 16:50:49 -04001883 client = Connection(client_context, None)
1884 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001885
Alex Chanec1e32d2016-11-10 14:11:45 +00001886 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001887
Alex Chanec1e32d2016-11-10 14:11:45 +00001888 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfielde46fa842015-04-13 16:50:49 -04001889
Alex Chanec1e32d2016-11-10 14:11:45 +00001890 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1891 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001892
Cory Benfielde46fa842015-04-13 16:50:49 -04001893 def test_alpn_set_on_connection(self):
1894 """
1895 The same as test_alpn_success, but setting the ALPN protocols on
1896 the connection rather than the context.
1897 """
1898 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001899
Cory Benfielde46fa842015-04-13 16:50:49 -04001900 def select(conn, options):
1901 select_args.append((conn, options))
1902 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001903
Cory Benfielde46fa842015-04-13 16:50:49 -04001904 # Setup the client context but don't set any ALPN protocols.
1905 client_context = Context(TLSv1_METHOD)
Cory Benfield12eae892014-06-07 15:42:56 +01001906
Cory Benfielde46fa842015-04-13 16:50:49 -04001907 server_context = Context(TLSv1_METHOD)
1908 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001909
Cory Benfielde46fa842015-04-13 16:50:49 -04001910 # Necessary to actually accept the connection
1911 server_context.use_privatekey(
1912 load_privatekey(FILETYPE_PEM, server_key_pem))
1913 server_context.use_certificate(
1914 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001915
Cory Benfielde46fa842015-04-13 16:50:49 -04001916 # Do a little connection to trigger the logic
1917 server = Connection(server_context, None)
1918 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001919
Cory Benfielde46fa842015-04-13 16:50:49 -04001920 # Set the ALPN protocols on the client connection.
1921 client = Connection(client_context, None)
1922 client.set_alpn_protos([b'http/1.1', b'spdy/2'])
1923 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001924
Alex Chanec1e32d2016-11-10 14:11:45 +00001925 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001926
Alex Chanec1e32d2016-11-10 14:11:45 +00001927 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001928
Alex Chanec1e32d2016-11-10 14:11:45 +00001929 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1930 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001931
Cory Benfielde46fa842015-04-13 16:50:49 -04001932 def test_alpn_server_fail(self):
1933 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001934 When clients and servers cannot agree on what protocol to use next
1935 the TLS connection does not get established.
Cory Benfielde46fa842015-04-13 16:50:49 -04001936 """
1937 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001938
Cory Benfielde46fa842015-04-13 16:50:49 -04001939 def select(conn, options):
1940 select_args.append((conn, options))
1941 return b''
Cory Benfield12eae892014-06-07 15:42:56 +01001942
Cory Benfielde46fa842015-04-13 16:50:49 -04001943 client_context = Context(TLSv1_METHOD)
1944 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001945
Cory Benfielde46fa842015-04-13 16:50:49 -04001946 server_context = Context(TLSv1_METHOD)
1947 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001948
Cory Benfielde46fa842015-04-13 16:50:49 -04001949 # Necessary to actually accept the connection
1950 server_context.use_privatekey(
1951 load_privatekey(FILETYPE_PEM, server_key_pem))
1952 server_context.use_certificate(
1953 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001954
Cory Benfielde46fa842015-04-13 16:50:49 -04001955 # Do a little connection to trigger the logic
1956 server = Connection(server_context, None)
1957 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001958
Cory Benfielde46fa842015-04-13 16:50:49 -04001959 client = Connection(client_context, None)
1960 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001961
Cory Benfielde46fa842015-04-13 16:50:49 -04001962 # If the client doesn't return anything, the connection will fail.
Alex Chanec1e32d2016-11-10 14:11:45 +00001963 with pytest.raises(Error):
1964 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001965
Alex Chanec1e32d2016-11-10 14:11:45 +00001966 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001967
Cory Benfielde46fa842015-04-13 16:50:49 -04001968 def test_alpn_no_server(self):
1969 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001970 When clients and servers cannot agree on what protocol to use next
1971 because the server doesn't offer ALPN, no protocol is negotiated.
Cory Benfielde46fa842015-04-13 16:50:49 -04001972 """
1973 client_context = Context(TLSv1_METHOD)
1974 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfielde3d57152015-04-11 17:57:35 -04001975
Cory Benfielde46fa842015-04-13 16:50:49 -04001976 server_context = Context(TLSv1_METHOD)
Cory Benfielde3d57152015-04-11 17:57:35 -04001977
Cory Benfielde46fa842015-04-13 16:50:49 -04001978 # Necessary to actually accept the connection
1979 server_context.use_privatekey(
1980 load_privatekey(FILETYPE_PEM, server_key_pem))
1981 server_context.use_certificate(
1982 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfielde3d57152015-04-11 17:57:35 -04001983
Cory Benfielde46fa842015-04-13 16:50:49 -04001984 # Do a little connection to trigger the logic
1985 server = Connection(server_context, None)
1986 server.set_accept_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001987
Cory Benfielde46fa842015-04-13 16:50:49 -04001988 client = Connection(client_context, None)
1989 client.set_connect_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001990
Cory Benfielde46fa842015-04-13 16:50:49 -04001991 # Do the dance.
Alex Chanec1e32d2016-11-10 14:11:45 +00001992 interact_in_memory(server, client)
Cory Benfielde3d57152015-04-11 17:57:35 -04001993
Alex Chanec1e32d2016-11-10 14:11:45 +00001994 assert client.get_alpn_proto_negotiated() == b''
Cory Benfielde3d57152015-04-11 17:57:35 -04001995
Cory Benfielde46fa842015-04-13 16:50:49 -04001996 def test_alpn_callback_exception(self):
1997 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001998 We can handle exceptions in the ALPN select callback.
Cory Benfielde46fa842015-04-13 16:50:49 -04001999 """
2000 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002001
Cory Benfielde46fa842015-04-13 16:50:49 -04002002 def select(conn, options):
2003 select_args.append((conn, options))
Cory Benfieldef401452015-04-13 18:17:36 -04002004 raise TypeError()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002005
Cory Benfielde46fa842015-04-13 16:50:49 -04002006 client_context = Context(TLSv1_METHOD)
2007 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfieldf1177e72015-04-12 09:11:49 -04002008
Cory Benfielde46fa842015-04-13 16:50:49 -04002009 server_context = Context(TLSv1_METHOD)
2010 server_context.set_alpn_select_callback(select)
Cory Benfieldf1177e72015-04-12 09:11:49 -04002011
Cory Benfielde46fa842015-04-13 16:50:49 -04002012 # Necessary to actually accept the connection
2013 server_context.use_privatekey(
2014 load_privatekey(FILETYPE_PEM, server_key_pem))
2015 server_context.use_certificate(
2016 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfieldf1177e72015-04-12 09:11:49 -04002017
Cory Benfielde46fa842015-04-13 16:50:49 -04002018 # Do a little connection to trigger the logic
2019 server = Connection(server_context, None)
2020 server.set_accept_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002021
Cory Benfielde46fa842015-04-13 16:50:49 -04002022 client = Connection(client_context, None)
2023 client.set_connect_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002024
Alex Chanec1e32d2016-11-10 14:11:45 +00002025 with pytest.raises(TypeError):
2026 interact_in_memory(server, client)
2027 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfieldf1177e72015-04-12 09:11:49 -04002028
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002029 else:
2030 # No ALPN.
2031 def test_alpn_not_implemented(self):
Cory Benfieldef401452015-04-13 18:17:36 -04002032 """
2033 If ALPN is not in OpenSSL, we should raise NotImplementedError.
2034 """
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002035 # Test the context methods first.
2036 context = Context(TLSv1_METHOD)
Alex Chanec1e32d2016-11-10 14:11:45 +00002037 with pytest.raises(NotImplementedError):
2038 context.set_alpn_protos(None)
2039 with pytest.raises(NotImplementedError):
2040 context.set_alpn_select_callback(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002041
2042 # Now test a connection.
2043 conn = Connection(context)
Alex Chanec1e32d2016-11-10 14:11:45 +00002044 with pytest.raises(NotImplementedError):
2045 conn.set_alpn_protos(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002046
Cory Benfieldf1177e72015-04-12 09:11:49 -04002047
Alex Chanec1e32d2016-11-10 14:11:45 +00002048class TestSession(object):
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002049 """
2050 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2051 """
2052 def test_construction(self):
2053 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002054 :py:class:`Session` can be constructed with no arguments, creating
2055 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002056 """
2057 new_session = Session()
Alex Chanec1e32d2016-11-10 14:11:45 +00002058 assert isinstance(new_session, Session)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002059
2060
Alex Chan1c0cb662017-01-30 07:13:30 +00002061class TestConnection(object):
Rick Deane15b1472009-07-09 15:53:42 -05002062 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002063 Unit tests for `OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002064 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002065 # XXX get_peer_certificate -> None
2066 # XXX sock_shutdown
2067 # XXX master_key -> TypeError
2068 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002069 # XXX connect -> TypeError
2070 # XXX connect_ex -> TypeError
2071 # XXX set_connect_state -> TypeError
2072 # XXX set_accept_state -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002073 # XXX do_handshake -> TypeError
2074 # XXX bio_read -> TypeError
2075 # XXX recv -> TypeError
2076 # XXX send -> TypeError
2077 # XXX bio_write -> TypeError
2078
Rick Deane15b1472009-07-09 15:53:42 -05002079 def test_type(self):
2080 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002081 `Connection` and `ConnectionType` refer to the same type object and
2082 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002083 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002084 assert Connection is ConnectionType
Rick Deane15b1472009-07-09 15:53:42 -05002085 ctx = Context(TLSv1_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002086 assert is_consistent_type(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002087
Alex Chanfb078d82017-04-20 11:16:15 +01002088 @pytest.mark.parametrize('bad_context', [object(), 'context', None, 1])
2089 def test_wrong_args(self, bad_context):
2090 """
2091 `Connection.__init__` raises `TypeError` if called with a non-`Context`
2092 instance argument.
2093 """
2094 with pytest.raises(TypeError):
2095 Connection(bad_context)
2096
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002097 def test_get_context(self):
2098 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002099 `Connection.get_context` returns the `Context` instance used to
2100 construct the `Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002101 """
2102 context = Context(TLSv1_METHOD)
2103 connection = Connection(context, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002104 assert connection.get_context() is context
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002105
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002106 def test_set_context_wrong_args(self):
2107 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002108 `Connection.set_context` raises `TypeError` if called with a
Alex Chanfb078d82017-04-20 11:16:15 +01002109 non-`Context` instance argument.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002110 """
2111 ctx = Context(TLSv1_METHOD)
2112 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002113 with pytest.raises(TypeError):
2114 connection.set_context(object())
2115 with pytest.raises(TypeError):
2116 connection.set_context("hello")
2117 with pytest.raises(TypeError):
2118 connection.set_context(1)
2119 assert ctx is connection.get_context()
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002120
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002121 def test_set_context(self):
2122 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002123 `Connection.set_context` specifies a new `Context` instance to be
2124 used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002125 """
2126 original = Context(SSLv23_METHOD)
2127 replacement = Context(TLSv1_METHOD)
2128 connection = Connection(original, None)
2129 connection.set_context(replacement)
Alex Chan1c0cb662017-01-30 07:13:30 +00002130 assert replacement is connection.get_context()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002131 # Lose our references to the contexts, just in case the Connection
2132 # isn't properly managing its own contributions to their reference
2133 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002134 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002135 collect()
2136
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002137 def test_set_tlsext_host_name_wrong_args(self):
2138 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002139 If `Connection.set_tlsext_host_name` is called with a non-byte string
2140 argument or a byte string with an embedded NUL, `TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002141 """
2142 conn = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002143 with pytest.raises(TypeError):
2144 conn.set_tlsext_host_name(object())
2145 with pytest.raises(TypeError):
2146 conn.set_tlsext_host_name(b"with\0null")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002147
Abraham Martinc5484ba2015-03-25 15:33:05 +00002148 if PY3:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002149 # On Python 3.x, don't accidentally implicitly convert from text.
Alex Chan1c0cb662017-01-30 07:13:30 +00002150 with pytest.raises(TypeError):
2151 conn.set_tlsext_host_name(b"example.com".decode("ascii"))
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002152
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002153 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002154 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002155 `Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002156 immediate read.
2157 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002158 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002159 assert connection.pending() == 0
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002160
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002161 def test_peek(self):
2162 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002163 `Connection.recv` peeks into the connection if `socket.MSG_PEEK` is
2164 passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002165 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002166 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002167 server.send(b'xy')
Alex Chan1c0cb662017-01-30 07:13:30 +00002168 assert client.recv(2, MSG_PEEK) == b'xy'
2169 assert client.recv(2, MSG_PEEK) == b'xy'
2170 assert client.recv(2) == b'xy'
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002171
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002172 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002173 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002174 `Connection.connect` raises `TypeError` if called with a non-address
2175 argument.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002176 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002177 connection = Connection(Context(TLSv1_METHOD), socket())
Alex Chan1c0cb662017-01-30 07:13:30 +00002178 with pytest.raises(TypeError):
2179 connection.connect(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002180
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002181 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002182 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002183 `Connection.connect` raises `socket.error` if the underlying socket
2184 connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002185 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002186 client = socket()
2187 context = Context(TLSv1_METHOD)
2188 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002189 # pytest.raises here doesn't work because of a bug in py.test on Python
2190 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002191 try:
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002192 clientSSL.connect(("127.0.0.1", 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002193 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002194 exc = e
2195 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002196
2197 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002198 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002199 `Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002200 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002201 port = socket()
2202 port.bind(('', 0))
2203 port.listen(3)
2204
2205 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002206 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
2207 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002208
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002209 @pytest.mark.skipif(
2210 platform == "darwin",
2211 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
2212 )
2213 def test_connect_ex(self):
2214 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002215 If there is a connection error, `Connection.connect_ex` returns the
2216 errno instead of raising an exception.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002217 """
2218 port = socket()
2219 port.bind(('', 0))
2220 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002221
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002222 clientSSL = Connection(Context(TLSv1_METHOD), socket())
2223 clientSSL.setblocking(False)
2224 result = clientSSL.connect_ex(port.getsockname())
2225 expected = (EINPROGRESS, EWOULDBLOCK)
Alex Chan1c0cb662017-01-30 07:13:30 +00002226 assert result in expected
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002227
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002228 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002229 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002230 `Connection.accept` accepts a pending connection attempt and returns a
2231 tuple of a new `Connection` (the accepted client) and the address the
2232 connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002233 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002234 ctx = Context(TLSv1_METHOD)
2235 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2236 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002237 port = socket()
2238 portSSL = Connection(ctx, port)
2239 portSSL.bind(('', 0))
2240 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002241
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002242 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002243
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002244 # Calling portSSL.getsockname() here to get the server IP address
2245 # sounds great, but frequently fails on Windows.
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002246 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002247
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002248 serverSSL, address = portSSL.accept()
2249
Alex Chan1c0cb662017-01-30 07:13:30 +00002250 assert isinstance(serverSSL, Connection)
2251 assert serverSSL.get_context() is ctx
2252 assert address == clientSSL.getsockname()
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002253
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002254 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002255 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002256 `Connection.set_shutdown` raises `TypeError` if called with arguments
2257 other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002258 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002259 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002260 with pytest.raises(TypeError):
2261 connection.set_shutdown(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002262
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002263 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002264 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002265 `Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002266 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002267 server, client = loopback()
2268 assert not server.shutdown()
2269 assert server.get_shutdown() == SENT_SHUTDOWN
2270 with pytest.raises(ZeroReturnError):
2271 client.recv(1024)
2272 assert client.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002273 client.shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002274 assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
2275 with pytest.raises(ZeroReturnError):
2276 server.recv(1024)
2277 assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002278
Paul Aurichc85e0862015-01-08 08:34:33 -08002279 def test_shutdown_closed(self):
2280 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002281 If the underlying socket is closed, `Connection.shutdown` propagates
2282 the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002283 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002284 server, client = loopback()
Paul Aurichc85e0862015-01-08 08:34:33 -08002285 server.sock_shutdown(2)
Alex Chan1c0cb662017-01-30 07:13:30 +00002286 with pytest.raises(SysCallError) as exc:
2287 server.shutdown()
Alex Chanfb078d82017-04-20 11:16:15 +01002288 if platform == "win32":
2289 assert exc.value.args[0] == ESHUTDOWN
2290 else:
2291 assert exc.value.args[0] == EPIPE
Paul Aurichc85e0862015-01-08 08:34:33 -08002292
Glyph89389472015-04-14 17:29:26 -04002293 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002294 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002295 If the underlying connection is truncated, `Connection.shutdown`
2296 raises an `Error`.
Glyph6064ec32015-04-14 16:38:22 -04002297 """
Glyph89389472015-04-14 17:29:26 -04002298 server_ctx = Context(TLSv1_METHOD)
2299 client_ctx = Context(TLSv1_METHOD)
2300 server_ctx.use_privatekey(
2301 load_privatekey(FILETYPE_PEM, server_key_pem))
2302 server_ctx.use_certificate(
2303 load_certificate(FILETYPE_PEM, server_cert_pem))
2304 server = Connection(server_ctx, None)
2305 client = Connection(client_ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002306 handshake_in_memory(client, server)
2307 assert not server.shutdown()
2308 with pytest.raises(WantReadError):
2309 server.shutdown()
Glyph89389472015-04-14 17:29:26 -04002310 server.bio_shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002311 with pytest.raises(Error):
2312 server.shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002313
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002314 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002315 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002316 `Connection.set_shutdown` sets the state of the SSL connection
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002317 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002318 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002319 connection = Connection(Context(TLSv1_METHOD), socket())
2320 connection.set_shutdown(RECEIVED_SHUTDOWN)
Alex Chan1c0cb662017-01-30 07:13:30 +00002321 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002322
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002323 @skip_if_py3
2324 def test_set_shutdown_long(self):
2325 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002326 On Python 2 `Connection.set_shutdown` accepts an argument
2327 of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002328 """
2329 connection = Connection(Context(TLSv1_METHOD), socket())
2330 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
Alex Chan1c0cb662017-01-30 07:13:30 +00002331 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002332
kjavaf248592015-09-07 12:14:01 +01002333 def test_state_string(self):
2334 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002335 `Connection.state_string` verbosely describes the current state of
2336 the `Connection`.
kjavaf248592015-09-07 12:14:01 +01002337 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002338 server, client = socket_pair()
Alex Chan1c0cb662017-01-30 07:13:30 +00002339 server = loopback_server_factory(server)
2340 client = loopback_client_factory(client)
kjavaf248592015-09-07 12:14:01 +01002341
Alex Gaynor5af32d02016-09-24 01:52:21 -04002342 assert server.get_state_string() in [
2343 b"before/accept initialization", b"before SSL initialization"
2344 ]
2345 assert client.get_state_string() in [
2346 b"before/connect initialization", b"before SSL initialization"
2347 ]
kjavaf248592015-09-07 12:14:01 +01002348
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002349 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002350 """
2351 Any object can be set as app data by passing it to
Alex Chan1c0cb662017-01-30 07:13:30 +00002352 `Connection.set_app_data` and later retrieved with
2353 `Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002354 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002355 conn = Connection(Context(TLSv1_METHOD), None)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002356 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002357 app_data = object()
2358 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002359 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002360
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002361 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002362 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002363 `Connection.makefile` is not implemented and calling that
2364 method raises `NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002365 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002366 conn = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002367 with pytest.raises(NotImplementedError):
2368 conn.makefile()
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002369
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002370 def test_get_peer_cert_chain(self):
2371 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002372 `Connection.get_peer_cert_chain` returns a list of certificates
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002373 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002374 """
2375 chain = _create_certificate_chain()
2376 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2377
2378 serverContext = Context(TLSv1_METHOD)
2379 serverContext.use_privatekey(skey)
2380 serverContext.use_certificate(scert)
2381 serverContext.add_extra_chain_cert(icert)
2382 serverContext.add_extra_chain_cert(cacert)
2383 server = Connection(serverContext, None)
2384 server.set_accept_state()
2385
2386 # Create the client
2387 clientContext = Context(TLSv1_METHOD)
2388 clientContext.set_verify(VERIFY_NONE, verify_cb)
2389 client = Connection(clientContext, None)
2390 client.set_connect_state()
2391
Alex Chan1c0cb662017-01-30 07:13:30 +00002392 interact_in_memory(client, server)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002393
2394 chain = client.get_peer_cert_chain()
Alex Chan1c0cb662017-01-30 07:13:30 +00002395 assert len(chain) == 3
2396 assert "Server Certificate" == chain[0].get_subject().CN
2397 assert "Intermediate Certificate" == chain[1].get_subject().CN
2398 assert "Authority Certificate" == chain[2].get_subject().CN
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002399
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002400 def test_get_peer_cert_chain_none(self):
2401 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002402 `Connection.get_peer_cert_chain` returns `None` if the peer sends
2403 no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002404 """
2405 ctx = Context(TLSv1_METHOD)
2406 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2407 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2408 server = Connection(ctx, None)
2409 server.set_accept_state()
2410 client = Connection(Context(TLSv1_METHOD), None)
2411 client.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002412 interact_in_memory(client, server)
2413 assert None is server.get_peer_cert_chain()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002414
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002415 def test_get_session_unconnected(self):
2416 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002417 `Connection.get_session` returns `None` when used with an object
2418 which has not been connected.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002419 """
2420 ctx = Context(TLSv1_METHOD)
2421 server = Connection(ctx, None)
2422 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002423 assert None is session
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002424
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002425 def test_server_get_session(self):
2426 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002427 On the server side of a connection, `Connection.get_session` returns a
2428 `Session` instance representing the SSL session for that connection.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002429 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002430 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002431 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002432 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002433
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002434 def test_client_get_session(self):
2435 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002436 On the client side of a connection, `Connection.get_session`
2437 returns a `Session` instance representing the SSL session for
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002438 that connection.
2439 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002440 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002441 session = client.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002442 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002443
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002444 def test_set_session_wrong_args(self):
2445 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002446 `Connection.set_session` raises `TypeError` if called with an object
2447 that is not an instance of `Session`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002448 """
2449 ctx = Context(TLSv1_METHOD)
2450 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002451 with pytest.raises(TypeError):
2452 connection.set_session(123)
2453 with pytest.raises(TypeError):
2454 connection.set_session("hello")
2455 with pytest.raises(TypeError):
2456 connection.set_session(object())
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002457
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002458 def test_client_set_session(self):
2459 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002460 `Connection.set_session`, when used prior to a connection being
2461 established, accepts a `Session` instance and causes an attempt to
2462 re-use the session it represents when the SSL handshake is performed.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002463 """
2464 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2465 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2466 ctx = Context(TLSv1_METHOD)
2467 ctx.use_privatekey(key)
2468 ctx.use_certificate(cert)
2469 ctx.set_session_id("unity-test")
2470
2471 def makeServer(socket):
2472 server = Connection(ctx, socket)
2473 server.set_accept_state()
2474 return server
2475
Alex Chan1c0cb662017-01-30 07:13:30 +00002476 originalServer, originalClient = loopback(
2477 server_factory=makeServer)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002478 originalSession = originalClient.get_session()
2479
2480 def makeClient(socket):
Alex Chan1c0cb662017-01-30 07:13:30 +00002481 client = loopback_client_factory(socket)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002482 client.set_session(originalSession)
2483 return client
Alex Chan1c0cb662017-01-30 07:13:30 +00002484 resumedServer, resumedClient = loopback(
2485 server_factory=makeServer,
2486 client_factory=makeClient)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002487
2488 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002489 # identifier for the session (new enough versions of OpenSSL expose
2490 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002491 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002492 # session is re-used. As long as the master key for the two
2493 # connections is the same, the session was re-used!
Alex Chan1c0cb662017-01-30 07:13:30 +00002494 assert originalServer.master_key() == resumedServer.master_key()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002495
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002496 def test_set_session_wrong_method(self):
2497 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002498 If `Connection.set_session` is passed a `Session` instance associated
2499 with a context using a different SSL method than the `Connection`
2500 is using, a `OpenSSL.SSL.Error` is raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002501 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002502 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2503 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2504 # is a way to check for 1.1.0)
Alex Gaynoraa32e712017-06-29 20:56:12 -07002505 if SSL_ST_INIT is None:
2506 v1 = TLSv1_2_METHOD
2507 v2 = TLSv1_METHOD
2508 elif hasattr(_lib, "SSLv3_method"):
Alex Gaynor5af32d02016-09-24 01:52:21 -04002509 v1 = TLSv1_METHOD
2510 v2 = SSLv3_METHOD
2511 else:
Alex Gaynoraa32e712017-06-29 20:56:12 -07002512 pytest.skip("Test requires either OpenSSL 1.1.0 or SSLv3")
Alex Gaynor5af32d02016-09-24 01:52:21 -04002513
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002514 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2515 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002516 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002517 ctx.use_privatekey(key)
2518 ctx.use_certificate(cert)
2519 ctx.set_session_id("unity-test")
2520
2521 def makeServer(socket):
2522 server = Connection(ctx, socket)
2523 server.set_accept_state()
2524 return server
2525
Alex Gaynor5af32d02016-09-24 01:52:21 -04002526 def makeOriginalClient(socket):
2527 client = Connection(Context(v1), socket)
2528 client.set_connect_state()
2529 return client
2530
Alex Chan1c0cb662017-01-30 07:13:30 +00002531 originalServer, originalClient = loopback(
2532 server_factory=makeServer, client_factory=makeOriginalClient)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002533 originalSession = originalClient.get_session()
2534
2535 def makeClient(socket):
2536 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002537 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002538 client.set_connect_state()
2539 client.set_session(originalSession)
2540 return client
2541
Alex Chan1c0cb662017-01-30 07:13:30 +00002542 with pytest.raises(Error):
2543 loopback(client_factory=makeClient, server_factory=makeServer)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002544
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002545 def test_wantWriteError(self):
2546 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002547 `Connection` methods which generate output raise
2548 `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002549 fail indicating a should-write state.
2550 """
2551 client_socket, server_socket = socket_pair()
2552 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002553 # anything. Only write a single byte at a time so we can be sure we
2554 # completely fill the buffer. Even though the socket API is allowed to
2555 # signal a short write via its return value it seems this doesn't
2556 # always happen on all platforms (FreeBSD and OS X particular) for the
2557 # very last bit of available buffer space.
2558 msg = b"x"
2559 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002560 try:
2561 client_socket.send(msg)
2562 except error as e:
2563 if e.errno == EWOULDBLOCK:
2564 break
2565 raise
2566 else:
Alex Chan1c0cb662017-01-30 07:13:30 +00002567 pytest.fail(
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002568 "Failed to fill socket buffer, cannot test BIO want write")
2569
2570 ctx = Context(TLSv1_METHOD)
2571 conn = Connection(ctx, client_socket)
2572 # Client's speak first, so make it an SSL client
2573 conn.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002574 with pytest.raises(WantWriteError):
2575 conn.do_handshake()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002576
2577 # XXX want_read
2578
Fedor Brunner416f4a12014-03-28 13:18:38 +01002579 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002580 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002581 `Connection.get_finished` returns `None` before TLS handshake
2582 is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002583 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002584 ctx = Context(TLSv1_METHOD)
2585 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002586 assert connection.get_finished() is None
Fedor Brunner416f4a12014-03-28 13:18:38 +01002587
2588 def test_get_peer_finished_before_connect(self):
2589 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002590 `Connection.get_peer_finished` returns `None` before TLS handshake
2591 is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002592 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002593 ctx = Context(TLSv1_METHOD)
2594 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002595 assert connection.get_peer_finished() is None
Fedor Brunner5747b932014-03-05 14:22:34 +01002596
Fedor Brunner416f4a12014-03-28 13:18:38 +01002597 def test_get_finished(self):
2598 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002599 `Connection.get_finished` method returns the TLS Finished message send
2600 from client, or server. Finished messages are send during
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002601 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002602 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002603 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002604
Alex Chan1c0cb662017-01-30 07:13:30 +00002605 assert server.get_finished() is not None
2606 assert len(server.get_finished()) > 0
Fedor Brunner416f4a12014-03-28 13:18:38 +01002607
2608 def test_get_peer_finished(self):
2609 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002610 `Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002611 message received from client, or server. Finished messages are send
2612 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002613 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002614 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002615
Alex Chan1c0cb662017-01-30 07:13:30 +00002616 assert server.get_peer_finished() is not None
2617 assert len(server.get_peer_finished()) > 0
Fedor Brunner5747b932014-03-05 14:22:34 +01002618
Fedor Brunner416f4a12014-03-28 13:18:38 +01002619 def test_tls_finished_message_symmetry(self):
2620 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002621 The TLS Finished message send by server must be the TLS Finished
2622 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002623
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002624 The TLS Finished message send by client must be the TLS Finished
2625 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002626 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002627 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002628
Alex Chan1c0cb662017-01-30 07:13:30 +00002629 assert server.get_finished() == client.get_peer_finished()
2630 assert client.get_finished() == server.get_peer_finished()
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002631
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002632 def test_get_cipher_name_before_connect(self):
2633 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002634 `Connection.get_cipher_name` returns `None` if no connection
2635 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002636 """
2637 ctx = Context(TLSv1_METHOD)
2638 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002639 assert conn.get_cipher_name() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002640
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002641 def test_get_cipher_name(self):
2642 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002643 `Connection.get_cipher_name` returns a `unicode` string giving the
2644 name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002645 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002646 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002647 server_cipher_name, client_cipher_name = \
2648 server.get_cipher_name(), client.get_cipher_name()
2649
Alex Chan1c0cb662017-01-30 07:13:30 +00002650 assert isinstance(server_cipher_name, text_type)
2651 assert isinstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002652
Alex Chan1c0cb662017-01-30 07:13:30 +00002653 assert server_cipher_name == client_cipher_name
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002654
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002655 def test_get_cipher_version_before_connect(self):
2656 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002657 `Connection.get_cipher_version` returns `None` if no connection
2658 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002659 """
2660 ctx = Context(TLSv1_METHOD)
2661 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002662 assert conn.get_cipher_version() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002663
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002664 def test_get_cipher_version(self):
2665 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002666 `Connection.get_cipher_version` returns a `unicode` string giving
2667 the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002668 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002669 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002670 server_cipher_version, client_cipher_version = \
2671 server.get_cipher_version(), client.get_cipher_version()
2672
Alex Chan1c0cb662017-01-30 07:13:30 +00002673 assert isinstance(server_cipher_version, text_type)
2674 assert isinstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002675
Alex Chan1c0cb662017-01-30 07:13:30 +00002676 assert server_cipher_version == client_cipher_version
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002677
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002678 def test_get_cipher_bits_before_connect(self):
2679 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002680 `Connection.get_cipher_bits` returns `None` if no connection has
2681 been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002682 """
2683 ctx = Context(TLSv1_METHOD)
2684 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002685 assert conn.get_cipher_bits() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002686
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002687 def test_get_cipher_bits(self):
2688 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002689 `Connection.get_cipher_bits` returns the number of secret bits
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002690 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002691 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002692 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002693 server_cipher_bits, client_cipher_bits = \
2694 server.get_cipher_bits(), client.get_cipher_bits()
2695
Alex Chan1c0cb662017-01-30 07:13:30 +00002696 assert isinstance(server_cipher_bits, int)
2697 assert isinstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002698
Alex Chan1c0cb662017-01-30 07:13:30 +00002699 assert server_cipher_bits == client_cipher_bits
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002700
Jim Shaverabff1882015-05-27 09:15:55 -04002701 def test_get_protocol_version_name(self):
2702 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002703 `Connection.get_protocol_version_name()` returns a string giving the
2704 protocol version of the current connection.
Jim Shaverabff1882015-05-27 09:15:55 -04002705 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002706 server, client = loopback()
Jim Shaverabff1882015-05-27 09:15:55 -04002707 client_protocol_version_name = client.get_protocol_version_name()
2708 server_protocol_version_name = server.get_protocol_version_name()
2709
Alex Chan1c0cb662017-01-30 07:13:30 +00002710 assert isinstance(server_protocol_version_name, text_type)
2711 assert isinstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002712
Alex Chan1c0cb662017-01-30 07:13:30 +00002713 assert server_protocol_version_name == client_protocol_version_name
Jim Shaverabff1882015-05-27 09:15:55 -04002714
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002715 def test_get_protocol_version(self):
2716 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002717 `Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002718 giving the protocol version of the current connection.
2719 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002720 server, client = loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002721 client_protocol_version = client.get_protocol_version()
2722 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002723
Alex Chan1c0cb662017-01-30 07:13:30 +00002724 assert isinstance(server_protocol_version, int)
2725 assert isinstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002726
Alex Chan1c0cb662017-01-30 07:13:30 +00002727 assert server_protocol_version == client_protocol_version
2728
2729 def test_wantReadError(self):
2730 """
2731 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
2732 no bytes available to be read from the BIO.
2733 """
2734 ctx = Context(TLSv1_METHOD)
2735 conn = Connection(ctx, None)
2736 with pytest.raises(WantReadError):
2737 conn.bio_read(1024)
2738
Alex Chanfb078d82017-04-20 11:16:15 +01002739 @pytest.mark.parametrize('bufsize', [1.0, None, object(), 'bufsize'])
2740 def test_bio_read_wrong_args(self, bufsize):
2741 """
2742 `Connection.bio_read` raises `TypeError` if passed a non-integer
2743 argument.
2744 """
2745 ctx = Context(TLSv1_METHOD)
2746 conn = Connection(ctx, None)
2747 with pytest.raises(TypeError):
2748 conn.bio_read(bufsize)
2749
Alex Chan1c0cb662017-01-30 07:13:30 +00002750 def test_buffer_size(self):
2751 """
2752 `Connection.bio_read` accepts an integer giving the maximum number
2753 of bytes to read and return.
2754 """
2755 ctx = Context(TLSv1_METHOD)
2756 conn = Connection(ctx, None)
2757 conn.set_connect_state()
2758 try:
2759 conn.do_handshake()
2760 except WantReadError:
2761 pass
2762 data = conn.bio_read(2)
2763 assert 2 == len(data)
2764
2765 @skip_if_py3
2766 def test_buffer_size_long(self):
2767 """
2768 On Python 2 `Connection.bio_read` accepts values of type `long` as
2769 well as `int`.
2770 """
2771 ctx = Context(TLSv1_METHOD)
2772 conn = Connection(ctx, None)
2773 conn.set_connect_state()
2774 try:
2775 conn.do_handshake()
2776 except WantReadError:
2777 pass
2778 data = conn.bio_read(long(2))
2779 assert 2 == len(data)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002780
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002781
Alex Chanb7480992017-01-30 14:04:47 +00002782class TestConnectionGetCipherList(object):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002783 """
Alex Chanb7480992017-01-30 14:04:47 +00002784 Tests for `Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002785 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002786 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002787 """
Alex Chanb7480992017-01-30 14:04:47 +00002788 `Connection.get_cipher_list` returns a list of `bytes` giving the
2789 names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002790 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002791 connection = Connection(Context(TLSv1_METHOD), None)
2792 ciphers = connection.get_cipher_list()
Alex Chanb7480992017-01-30 14:04:47 +00002793 assert isinstance(ciphers, list)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002794 for cipher in ciphers:
Alex Chanb7480992017-01-30 14:04:47 +00002795 assert isinstance(cipher, str)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002796
2797
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002798class VeryLarge(bytes):
2799 """
2800 Mock object so that we don't have to allocate 2**31 bytes
2801 """
2802 def __len__(self):
2803 return 2**31
2804
2805
Alex Chanb7480992017-01-30 14:04:47 +00002806class TestConnectionSend(object):
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002807 """
Alex Chanb7480992017-01-30 14:04:47 +00002808 Tests for `Connection.send`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002809 """
2810 def test_wrong_args(self):
2811 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002812 When called with arguments other than string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00002813 parameter, `Connection.send` raises `TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002814 """
2815 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00002816 with pytest.raises(TypeError):
2817 connection.send(object())
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002818
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002819 def test_short_bytes(self):
2820 """
Alex Chanb7480992017-01-30 14:04:47 +00002821 When passed a short byte string, `Connection.send` transmits all of it
2822 and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002823 """
Alex Chanb7480992017-01-30 14:04:47 +00002824 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002825 count = server.send(b'xy')
Alex Chanb7480992017-01-30 14:04:47 +00002826 assert count == 2
2827 assert client.recv(2) == b'xy'
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002828
Abraham Martinef063482015-03-25 14:06:24 +00002829 def test_text(self):
2830 """
Alex Chanb7480992017-01-30 14:04:47 +00002831 When passed a text, `Connection.send` transmits all of it and
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002832 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002833 """
Alex Chanb7480992017-01-30 14:04:47 +00002834 server, client = loopback()
2835 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00002836 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002837 count = server.send(b"xy".decode("ascii"))
Alex Chanb7480992017-01-30 14:04:47 +00002838 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002839 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002840 WARNING_TYPE_EXPECTED
Alex Chanb7480992017-01-30 14:04:47 +00002841 ) == str(w[-1].message))
2842 assert count == 2
2843 assert client.recv(2) == b'xy'
Abraham Martinef063482015-03-25 14:06:24 +00002844
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002845 @skip_if_py26
2846 def test_short_memoryview(self):
2847 """
2848 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002849 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002850 of bytes sent.
2851 """
Alex Chanb7480992017-01-30 14:04:47 +00002852 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002853 count = server.send(memoryview(b'xy'))
Alex Chanb7480992017-01-30 14:04:47 +00002854 assert count == 2
2855 assert client.recv(2) == b'xy'
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002856
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002857 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002858 def test_short_buffer(self):
2859 """
2860 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002861 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002862 of bytes sent.
2863 """
Alex Chanb7480992017-01-30 14:04:47 +00002864 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002865 count = server.send(buffer(b'xy'))
Alex Chanb7480992017-01-30 14:04:47 +00002866 assert count == 2
2867 assert client.recv(2) == b'xy'
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002868
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002869 @pytest.mark.skipif(
2870 sys.maxsize < 2**31,
2871 reason="sys.maxsize < 2**31 - test requires 64 bit"
2872 )
2873 def test_buf_too_large(self):
2874 """
2875 When passed a buffer containing >= 2**31 bytes,
2876 `Connection.send` bails out as SSL_write only
2877 accepts an int for the buffer length.
2878 """
2879 connection = Connection(Context(TLSv1_METHOD), None)
2880 with pytest.raises(ValueError) as exc_info:
2881 connection.send(VeryLarge())
2882 exc_info.match(r"Cannot send more than .+ bytes at once")
2883
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002884
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002885def _make_memoryview(size):
2886 """
2887 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2888 size.
2889 """
2890 return memoryview(bytearray(size))
2891
2892
Alex Chanb7480992017-01-30 14:04:47 +00002893class TestConnectionRecvInto(object):
Cory Benfield62d10332014-06-15 10:03:41 +01002894 """
Alex Chanb7480992017-01-30 14:04:47 +00002895 Tests for `Connection.recv_into`.
Cory Benfield62d10332014-06-15 10:03:41 +01002896 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002897 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002898 """
Alex Chanb7480992017-01-30 14:04:47 +00002899 Assert that when the given buffer is passed to `Connection.recv_into`,
2900 whatever bytes are available to be received that fit into that buffer
2901 are written into that buffer.
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002902 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002903 output_buffer = factory(5)
2904
Alex Chanb7480992017-01-30 14:04:47 +00002905 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002906 server.send(b'xy')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002907
Alex Chanb7480992017-01-30 14:04:47 +00002908 assert client.recv_into(output_buffer) == 2
2909 assert output_buffer == bytearray(b'xy\x00\x00\x00')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002910
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002911 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002912 """
Alex Chanb7480992017-01-30 14:04:47 +00002913 `Connection.recv_into` can be passed a `bytearray` instance and data
2914 in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002915 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002916 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002917
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002918 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002919 """
Alex Chanb7480992017-01-30 14:04:47 +00002920 Assert that when the given buffer is passed to `Connection.recv_into`
2921 along with a value for `nbytes` that is less than the size of that
2922 buffer, only `nbytes` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002923 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002924 output_buffer = factory(10)
2925
Alex Chanb7480992017-01-30 14:04:47 +00002926 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002927 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002928
Alex Chanb7480992017-01-30 14:04:47 +00002929 assert client.recv_into(output_buffer, 5) == 5
2930 assert output_buffer == bytearray(b'abcde\x00\x00\x00\x00\x00')
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002931
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002932 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002933 """
Alex Chanb7480992017-01-30 14:04:47 +00002934 When called with a `bytearray` instance, `Connection.recv_into`
2935 respects the `nbytes` parameter and doesn't copy in more than that
2936 number of bytes.
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002937 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002938 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002939
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002940 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002941 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002942 Assert that if there are more bytes available to be read from the
2943 receive buffer than would fit into the buffer passed to
Alex Chanb7480992017-01-30 14:04:47 +00002944 `Connection.recv_into`, only as many as fit are written into it.
Cory Benfield62d10332014-06-15 10:03:41 +01002945 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002946 output_buffer = factory(5)
2947
Alex Chanb7480992017-01-30 14:04:47 +00002948 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002949 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002950
Alex Chanb7480992017-01-30 14:04:47 +00002951 assert client.recv_into(output_buffer) == 5
2952 assert output_buffer == bytearray(b'abcde')
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002953 rest = client.recv(5)
Alex Chanb7480992017-01-30 14:04:47 +00002954 assert b'fghij' == rest
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002955
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002956 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002957 """
Alex Chanb7480992017-01-30 14:04:47 +00002958 When called with a `bytearray` instance, `Connection.recv_into`
2959 respects the size of the array and doesn't write more bytes into it
2960 than will fit.
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002961 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002962 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002963
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002964 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002965 """
Alex Chanb7480992017-01-30 14:04:47 +00002966 When called with a `bytearray` instance and an `nbytes` value that is
2967 too large, `Connection.recv_into` respects the size of the array and
2968 not the `nbytes` value and doesn't write more bytes into the buffer
2969 than will fit.
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002970 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002971 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002972
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002973 def test_peek(self):
Alex Chanb7480992017-01-30 14:04:47 +00002974 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002975 server.send(b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002976
2977 for _ in range(2):
2978 output_buffer = bytearray(5)
Alex Chanb7480992017-01-30 14:04:47 +00002979 assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
2980 assert output_buffer == bytearray(b'xy\x00\x00\x00')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002981
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002982 @skip_if_py26
2983 def test_memoryview_no_length(self):
2984 """
Alex Chanb7480992017-01-30 14:04:47 +00002985 `Connection.recv_into` can be passed a `memoryview` instance and data
2986 in the receive buffer is written to it.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002987 """
2988 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002989
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002990 @skip_if_py26
2991 def test_memoryview_respects_length(self):
2992 """
Alex Chanb7480992017-01-30 14:04:47 +00002993 When called with a `memoryview` instance, `Connection.recv_into`
2994 respects the ``nbytes`` parameter and doesn't copy more than that
2995 number of bytes in.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002996 """
2997 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01002998
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002999 @skip_if_py26
3000 def test_memoryview_doesnt_overfill(self):
3001 """
Alex Chanb7480992017-01-30 14:04:47 +00003002 When called with a `memoryview` instance, `Connection.recv_into`
3003 respects the size of the array and doesn't write more bytes into it
3004 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003005 """
3006 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003007
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003008 @skip_if_py26
3009 def test_memoryview_really_doesnt_overfill(self):
3010 """
Alex Chanb7480992017-01-30 14:04:47 +00003011 When called with a `memoryview` instance and an `nbytes` value that is
3012 too large, `Connection.recv_into` respects the size of the array and
3013 not the `nbytes` value and doesn't write more bytes into the buffer
3014 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003015 """
3016 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003017
Cory Benfield62d10332014-06-15 10:03:41 +01003018
Alex Chanb7480992017-01-30 14:04:47 +00003019class TestConnectionSendall(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003020 """
Alex Chanb7480992017-01-30 14:04:47 +00003021 Tests for `Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003022 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003023 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003024 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003025 When called with arguments other than a string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00003026 parameter, `Connection.sendall` raises `TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003027 """
3028 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003029 with pytest.raises(TypeError):
3030 connection.sendall(object())
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003031
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003032 def test_short(self):
3033 """
Alex Chanb7480992017-01-30 14:04:47 +00003034 `Connection.sendall` transmits all of the bytes in the string
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003035 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003036 """
Alex Chanb7480992017-01-30 14:04:47 +00003037 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003038 server.sendall(b'x')
Alex Chanb7480992017-01-30 14:04:47 +00003039 assert client.recv(1) == b'x'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003040
Abraham Martinef063482015-03-25 14:06:24 +00003041 def test_text(self):
3042 """
Alex Chanb7480992017-01-30 14:04:47 +00003043 `Connection.sendall` transmits all the content in the string passed
3044 to it, raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003045 """
Alex Chanb7480992017-01-30 14:04:47 +00003046 server, client = loopback()
3047 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00003048 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003049 server.sendall(b"x".decode("ascii"))
Alex Chanb7480992017-01-30 14:04:47 +00003050 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003051 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003052 WARNING_TYPE_EXPECTED
Alex Chanb7480992017-01-30 14:04:47 +00003053 ) == str(w[-1].message))
3054 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003055
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003056 @skip_if_py26
3057 def test_short_memoryview(self):
3058 """
3059 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003060 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003061 """
Alex Chanb7480992017-01-30 14:04:47 +00003062 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003063 server.sendall(memoryview(b'x'))
Alex Chanb7480992017-01-30 14:04:47 +00003064 assert client.recv(1) == b'x'
Abraham Martinef063482015-03-25 14:06:24 +00003065
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003066 @skip_if_py3
3067 def test_short_buffers(self):
3068 """
3069 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003070 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003071 """
Alex Chanb7480992017-01-30 14:04:47 +00003072 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003073 server.sendall(buffer(b'x'))
Alex Chanb7480992017-01-30 14:04:47 +00003074 assert client.recv(1) == b'x'
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003075
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003076 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003077 """
Alex Chanb7480992017-01-30 14:04:47 +00003078 `Connection.sendall` transmits all the bytes in the string passed to it
3079 even if this requires multiple calls of an underlying write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003080 """
Alex Chanb7480992017-01-30 14:04:47 +00003081 server, client = loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003082 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003083 # On Windows, after 32k of bytes the write will block (forever
3084 # - because no one is yet reading).
Alex Gaynore7f51982016-09-11 11:48:14 -04003085 message = b'x' * (1024 * 32 - 1) + b'y'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003086 server.sendall(message)
3087 accum = []
3088 received = 0
3089 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003090 data = client.recv(1024)
3091 accum.append(data)
3092 received += len(data)
Alex Chanb7480992017-01-30 14:04:47 +00003093 assert message == b''.join(accum)
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003094
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003095 def test_closed(self):
3096 """
Alex Chanb7480992017-01-30 14:04:47 +00003097 If the underlying socket is closed, `Connection.sendall` propagates the
3098 write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003099 """
Alex Chanb7480992017-01-30 14:04:47 +00003100 server, client = loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003101 server.sock_shutdown(2)
Alex Chanb7480992017-01-30 14:04:47 +00003102 with pytest.raises(SysCallError) as err:
3103 server.sendall(b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003104 if platform == "win32":
Alex Chanb7480992017-01-30 14:04:47 +00003105 assert err.value.args[0] == ESHUTDOWN
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003106 else:
Alex Chanb7480992017-01-30 14:04:47 +00003107 assert err.value.args[0] == EPIPE
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003108
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003109
Alex Chanb7480992017-01-30 14:04:47 +00003110class TestConnectionRenegotiate(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003111 """
3112 Tests for SSL renegotiation APIs.
3113 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003114 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003115 """
Alex Chanb7480992017-01-30 14:04:47 +00003116 `Connection.total_renegotiations` returns `0` before any renegotiations
3117 have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003118 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003119 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003120 assert connection.total_renegotiations() == 0
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003121
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003122 def test_renegotiate(self):
3123 """
3124 Go through a complete renegotiation cycle.
3125 """
Alex Chanb7480992017-01-30 14:04:47 +00003126 server, client = loopback()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003127
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003128 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003129
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003130 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003131
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003132 assert 0 == server.total_renegotiations()
3133 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003134
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003135 assert True is server.renegotiate()
3136
3137 assert True is server.renegotiate_pending()
3138
3139 server.setblocking(False)
3140 client.setblocking(False)
3141
3142 client.do_handshake()
3143 server.do_handshake()
3144
3145 assert 1 == server.total_renegotiations()
3146 while False is server.renegotiate_pending():
3147 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003148
3149
Alex Chanb7480992017-01-30 14:04:47 +00003150class TestError(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003151 """
Alex Chanb7480992017-01-30 14:04:47 +00003152 Unit tests for `OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003153 """
3154 def test_type(self):
3155 """
Alex Chanb7480992017-01-30 14:04:47 +00003156 `Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003157 """
Alex Chanb7480992017-01-30 14:04:47 +00003158 assert issubclass(Error, Exception)
3159 assert Error.__name__ == 'Error'
Rick Deane15b1472009-07-09 15:53:42 -05003160
3161
Alex Chanb7480992017-01-30 14:04:47 +00003162class TestConstants(object):
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003163 """
Alex Chanb7480992017-01-30 14:04:47 +00003164 Tests for the values of constants exposed in `OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003165
3166 These are values defined by OpenSSL intended only to be used as flags to
3167 OpenSSL APIs. The only assertions it seems can be made about them is
3168 their values.
3169 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003170 @pytest.mark.skipif(
3171 OP_NO_QUERY_MTU is None,
3172 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3173 )
3174 def test_op_no_query_mtu(self):
3175 """
Alex Chanb7480992017-01-30 14:04:47 +00003176 The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3177 of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003178 """
Alex Chanb7480992017-01-30 14:04:47 +00003179 assert OP_NO_QUERY_MTU == 0x1000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003180
Hynek Schlawack35618382015-09-05 21:54:25 +02003181 @pytest.mark.skipif(
3182 OP_COOKIE_EXCHANGE is None,
3183 reason="OP_COOKIE_EXCHANGE unavailable - "
3184 "OpenSSL version may be too old"
3185 )
3186 def test_op_cookie_exchange(self):
3187 """
Alex Chanb7480992017-01-30 14:04:47 +00003188 The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3189 value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003190 """
Alex Chanb7480992017-01-30 14:04:47 +00003191 assert OP_COOKIE_EXCHANGE == 0x2000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003192
Hynek Schlawack35618382015-09-05 21:54:25 +02003193 @pytest.mark.skipif(
3194 OP_NO_TICKET is None,
3195 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3196 )
3197 def test_op_no_ticket(self):
3198 """
Alex Chanb7480992017-01-30 14:04:47 +00003199 The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3200 `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003201 """
Alex Chanb7480992017-01-30 14:04:47 +00003202 assert OP_NO_TICKET == 0x4000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003203
Hynek Schlawack35618382015-09-05 21:54:25 +02003204 @pytest.mark.skipif(
3205 OP_NO_COMPRESSION is None,
3206 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3207 )
3208 def test_op_no_compression(self):
3209 """
Alex Chanb7480992017-01-30 14:04:47 +00003210 The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3211 value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003212 """
Alex Chanb7480992017-01-30 14:04:47 +00003213 assert OP_NO_COMPRESSION == 0x20000
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003214
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003215 def test_sess_cache_off(self):
3216 """
Alex Chanb7480992017-01-30 14:04:47 +00003217 The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3218 `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003219 """
Alex Chanb7480992017-01-30 14:04:47 +00003220 assert 0x0 == SESS_CACHE_OFF
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003221
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003222 def test_sess_cache_client(self):
3223 """
Alex Chanb7480992017-01-30 14:04:47 +00003224 The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3225 `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003226 """
Alex Chanb7480992017-01-30 14:04:47 +00003227 assert 0x1 == SESS_CACHE_CLIENT
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003228
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003229 def test_sess_cache_server(self):
3230 """
Alex Chanb7480992017-01-30 14:04:47 +00003231 The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3232 `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003233 """
Alex Chanb7480992017-01-30 14:04:47 +00003234 assert 0x2 == SESS_CACHE_SERVER
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003235
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003236 def test_sess_cache_both(self):
3237 """
Alex Chanb7480992017-01-30 14:04:47 +00003238 The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3239 `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003240 """
Alex Chanb7480992017-01-30 14:04:47 +00003241 assert 0x3 == SESS_CACHE_BOTH
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003242
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003243 def test_sess_cache_no_auto_clear(self):
3244 """
Alex Chanb7480992017-01-30 14:04:47 +00003245 The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3246 value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3247 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003248 """
Alex Chanb7480992017-01-30 14:04:47 +00003249 assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003250
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003251 def test_sess_cache_no_internal_lookup(self):
3252 """
Alex Chanb7480992017-01-30 14:04:47 +00003253 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3254 the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3255 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003256 """
Alex Chanb7480992017-01-30 14:04:47 +00003257 assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003258
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003259 def test_sess_cache_no_internal_store(self):
3260 """
Alex Chanb7480992017-01-30 14:04:47 +00003261 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3262 the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3263 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003264 """
Alex Chanb7480992017-01-30 14:04:47 +00003265 assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003266
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003267 def test_sess_cache_no_internal(self):
3268 """
Alex Chanb7480992017-01-30 14:04:47 +00003269 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3270 value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
3271 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003272 """
Alex Chanb7480992017-01-30 14:04:47 +00003273 assert 0x300 == SESS_CACHE_NO_INTERNAL
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003274
3275
Alex Chanb7480992017-01-30 14:04:47 +00003276class TestMemoryBIO(object):
Rick Deanb71c0d22009-04-01 14:09:23 -05003277 """
Alex Chanb7480992017-01-30 14:04:47 +00003278 Tests for `OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003279 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003280 def _server(self, sock):
3281 """
Alex Chanb7480992017-01-30 14:04:47 +00003282 Create a new server-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003283 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003284 # Create the server side Connection. This is mostly setup boilerplate
3285 # - use TLSv1, use a particular certificate, etc.
3286 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003287 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003288 server_ctx.set_verify(
3289 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3290 verify_cb
3291 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003292 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003293 server_ctx.use_privatekey(
3294 load_privatekey(FILETYPE_PEM, server_key_pem))
3295 server_ctx.use_certificate(
3296 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003297 server_ctx.check_privatekey()
3298 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003299 # Here the Connection is actually created. If None is passed as the
3300 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003301 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003302 server_conn.set_accept_state()
3303 return server_conn
3304
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003305 def _client(self, sock):
3306 """
Alex Chanb7480992017-01-30 14:04:47 +00003307 Create a new client-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003308 """
3309 # Now create the client side Connection. Similar boilerplate to the
3310 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003311 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003312 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003313 client_ctx.set_verify(
3314 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3315 verify_cb
3316 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003317 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003318 client_ctx.use_privatekey(
3319 load_privatekey(FILETYPE_PEM, client_key_pem))
3320 client_ctx.use_certificate(
3321 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003322 client_ctx.check_privatekey()
3323 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003324 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003325 client_conn.set_connect_state()
3326 return client_conn
3327
Alex Chanb7480992017-01-30 14:04:47 +00003328 def test_memory_connect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003329 """
Alex Chanb7480992017-01-30 14:04:47 +00003330 Two `Connection`s which use memory BIOs can be manually connected by
3331 reading from the output of each and writing those bytes to the input of
3332 the other and in this way establish a connection and exchange
3333 application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003334 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003335 server_conn = self._server(None)
3336 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003337
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003338 # There should be no key or nonces yet.
Alex Chanb7480992017-01-30 14:04:47 +00003339 assert server_conn.master_key() is None
3340 assert server_conn.client_random() is None
3341 assert server_conn.server_random() is None
Rick Deanb71c0d22009-04-01 14:09:23 -05003342
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003343 # First, the handshake needs to happen. We'll deliver bytes back and
3344 # forth between the client and server until neither of them feels like
3345 # speaking any more.
Alex Chanb7480992017-01-30 14:04:47 +00003346 assert interact_in_memory(client_conn, server_conn) is None
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003347
3348 # Now that the handshake is done, there should be a key and nonces.
Alex Chanb7480992017-01-30 14:04:47 +00003349 assert server_conn.master_key() is not None
3350 assert server_conn.client_random() is not None
3351 assert server_conn.server_random() is not None
3352 assert server_conn.client_random() == client_conn.client_random()
3353 assert server_conn.server_random() == client_conn.server_random()
3354 assert server_conn.client_random() != server_conn.server_random()
3355 assert client_conn.client_random() != client_conn.server_random()
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003356
3357 # Here are the bytes we'll try to send.
Alex Gaynore7f51982016-09-11 11:48:14 -04003358 important_message = b'One if by land, two if by sea.'
Rick Deanb71c0d22009-04-01 14:09:23 -05003359
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003360 server_conn.write(important_message)
Alex Chanb7480992017-01-30 14:04:47 +00003361 assert (
3362 interact_in_memory(client_conn, server_conn) ==
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003363 (client_conn, important_message))
3364
3365 client_conn.write(important_message[::-1])
Alex Chanb7480992017-01-30 14:04:47 +00003366 assert (
3367 interact_in_memory(client_conn, server_conn) ==
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003368 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003369
Alex Chanb7480992017-01-30 14:04:47 +00003370 def test_socket_connect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003371 """
Alex Chanb7480992017-01-30 14:04:47 +00003372 Just like `test_memory_connect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003373
Hynek Schlawack35618382015-09-05 21:54:25 +02003374 This is primarily to rule out the memory BIO code as the source of any
Alex Chanb7480992017-01-30 14:04:47 +00003375 problems encountered while passing data over a `Connection` (if
Hynek Schlawack35618382015-09-05 21:54:25 +02003376 this test fails, there must be a problem outside the memory BIO code,
3377 as no memory BIO is involved here). Even though this isn't a memory
3378 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003379 """
Alex Chanb7480992017-01-30 14:04:47 +00003380 server_conn, client_conn = loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003381
Alex Gaynore7f51982016-09-11 11:48:14 -04003382 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003383 client_conn.send(important_message)
3384 msg = server_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003385 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003386
3387 # Again in the other direction, just for fun.
3388 important_message = important_message[::-1]
3389 server_conn.send(important_message)
3390 msg = client_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003391 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003392
Alex Chanb7480992017-01-30 14:04:47 +00003393 def test_socket_overrides_memory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003394 """
Alex Chanb7480992017-01-30 14:04:47 +00003395 Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
3396 work on `OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003397 """
Alex Gaynor51d424c2016-09-10 14:50:11 -04003398 context = Context(TLSv1_METHOD)
Rick Deanb71c0d22009-04-01 14:09:23 -05003399 client = socket()
3400 clientSSL = Connection(context, client)
Alex Chanb7480992017-01-30 14:04:47 +00003401 with pytest.raises(TypeError):
3402 clientSSL.bio_read(100)
3403 with pytest.raises(TypeError):
3404 clientSSL.bio_write("foo")
3405 with pytest.raises(TypeError):
3406 clientSSL.bio_shutdown()
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003407
Alex Chanb7480992017-01-30 14:04:47 +00003408 def test_outgoing_overflow(self):
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003409 """
3410 If more bytes than can be written to the memory BIO are passed to
Alex Chanb7480992017-01-30 14:04:47 +00003411 `Connection.send` at once, the number of bytes which were written is
3412 returned and that many bytes from the beginning of the input can be
3413 read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003414 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003415 server = self._server(None)
3416 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003417
Alex Chanb7480992017-01-30 14:04:47 +00003418 interact_in_memory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003419
3420 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003421 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003422 # Sanity check. We're trying to test what happens when the entire
3423 # input can't be sent. If the entire input was sent, this test is
3424 # meaningless.
Alex Chanb7480992017-01-30 14:04:47 +00003425 assert sent < size
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003426
Alex Chanb7480992017-01-30 14:04:47 +00003427 receiver, received = interact_in_memory(client, server)
3428 assert receiver is server
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003429
3430 # We can rely on all of these bytes being received at once because
Alex Chanb7480992017-01-30 14:04:47 +00003431 # loopback passes 2 ** 16 to recv - more than 2 ** 15.
3432 assert len(received) == sent
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003433
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003434 def test_shutdown(self):
3435 """
Alex Chanb7480992017-01-30 14:04:47 +00003436 `Connection.bio_shutdown` signals the end of the data stream
3437 from which the `Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003438 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003439 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003440 server.bio_shutdown()
Alex Chanb7480992017-01-30 14:04:47 +00003441 with pytest.raises(Error) as err:
3442 server.recv(1024)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003443 # We don't want WantReadError or ZeroReturnError or anything - it's a
3444 # handshake failure.
Alex Chanb7480992017-01-30 14:04:47 +00003445 assert type(err.value) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003446
Alex Chanb7480992017-01-30 14:04:47 +00003447 def test_unexpected_EOF(self):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003448 """
3449 If the connection is lost before an orderly SSL shutdown occurs,
Alex Chanb7480992017-01-30 14:04:47 +00003450 `OpenSSL.SSL.SysCallError` is raised with a message of
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003451 "Unexpected EOF".
3452 """
Alex Chanb7480992017-01-30 14:04:47 +00003453 server_conn, client_conn = loopback()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003454 client_conn.sock_shutdown(SHUT_RDWR)
Alex Chanb7480992017-01-30 14:04:47 +00003455 with pytest.raises(SysCallError) as err:
3456 server_conn.recv(1024)
3457 assert err.value.args == (-1, "Unexpected EOF")
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003458
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003459 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003460 """
Alex Chanb7480992017-01-30 14:04:47 +00003461 Verify the return value of the `get_client_ca_list` method for
Hynek Schlawack35618382015-09-05 21:54:25 +02003462 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003463
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003464 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003465 before the client and server are connected to each other. This
3466 function should specify a list of CAs for the server to send to the
3467 client and return that same list. The list will be used to verify
Alex Chanb7480992017-01-30 14:04:47 +00003468 that `get_client_ca_list` returns the proper value at
Hynek Schlawack35618382015-09-05 21:54:25 +02003469 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003470 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003471 server = self._server(None)
3472 client = self._client(None)
Alex Chanb7480992017-01-30 14:04:47 +00003473 assert client.get_client_ca_list() == []
3474 assert server.get_client_ca_list() == []
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003475 ctx = server.get_context()
3476 expected = func(ctx)
Alex Chanb7480992017-01-30 14:04:47 +00003477 assert client.get_client_ca_list() == []
3478 assert server.get_client_ca_list() == expected
3479 interact_in_memory(client, server)
3480 assert client.get_client_ca_list() == expected
3481 assert server.get_client_ca_list() == expected
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003482
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003483 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003484 """
Alex Chanb7480992017-01-30 14:04:47 +00003485 `Context.set_client_ca_list` raises a `TypeError` if called with a
3486 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003487 """
3488 ctx = Context(TLSv1_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003489 with pytest.raises(TypeError):
3490 ctx.set_client_ca_list("spam")
3491 with pytest.raises(TypeError):
3492 ctx.set_client_ca_list(["spam"])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003493
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003494 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003495 """
Alex Chanb7480992017-01-30 14:04:47 +00003496 If passed an empty list, `Context.set_client_ca_list` configures the
3497 context to send no CA names to the client and, on both the server and
3498 client sides, `Connection.get_client_ca_list` returns an empty list
3499 after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003500 """
3501 def no_ca(ctx):
3502 ctx.set_client_ca_list([])
3503 return []
3504 self._check_client_ca_list(no_ca)
3505
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003506 def test_set_one_ca_list(self):
3507 """
3508 If passed a list containing a single X509Name,
Alex Chanb7480992017-01-30 14:04:47 +00003509 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003510 that CA name to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003511 `Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003512 X509Name after the connection is set up.
3513 """
3514 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3515 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003516
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003517 def single_ca(ctx):
3518 ctx.set_client_ca_list([cadesc])
3519 return [cadesc]
3520 self._check_client_ca_list(single_ca)
3521
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003522 def test_set_multiple_ca_list(self):
3523 """
3524 If passed a list containing multiple X509Name objects,
Alex Chanb7480992017-01-30 14:04:47 +00003525 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003526 those CA names to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003527 `Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003528 X509Names after the connection is set up.
3529 """
3530 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3531 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3532
3533 sedesc = secert.get_subject()
3534 cldesc = clcert.get_subject()
3535
3536 def multiple_ca(ctx):
3537 L = [sedesc, cldesc]
3538 ctx.set_client_ca_list(L)
3539 return L
3540 self._check_client_ca_list(multiple_ca)
3541
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003542 def test_reset_ca_list(self):
3543 """
3544 If called multiple times, only the X509Names passed to the final call
Alex Chanb7480992017-01-30 14:04:47 +00003545 of `Context.set_client_ca_list` are used to configure the CA
Hynek Schlawack35618382015-09-05 21:54:25 +02003546 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003547 """
3548 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3549 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3550 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3551
3552 cadesc = cacert.get_subject()
3553 sedesc = secert.get_subject()
3554 cldesc = clcert.get_subject()
3555
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003556 def changed_ca(ctx):
3557 ctx.set_client_ca_list([sedesc, cldesc])
3558 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003559 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003560 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003561
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003562 def test_mutated_ca_list(self):
3563 """
Alex Chanb7480992017-01-30 14:04:47 +00003564 If the list passed to `Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003565 afterwards, this does not affect the list of CA names sent to the
3566 client.
3567 """
3568 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3569 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3570
3571 cadesc = cacert.get_subject()
3572 sedesc = secert.get_subject()
3573
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003574 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003575 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003576 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003577 L.append(sedesc)
3578 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003579 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003580
Alex Chanb7480992017-01-30 14:04:47 +00003581 def test_add_client_ca_wrong_args(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003582 """
Alex Chanb7480992017-01-30 14:04:47 +00003583 `Context.add_client_ca` raises `TypeError` if called with
3584 a non-X509 object.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003585 """
3586 ctx = Context(TLSv1_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003587 with pytest.raises(TypeError):
3588 ctx.add_client_ca("spam")
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003589
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003590 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003591 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003592 A certificate's subject can be added as a CA to be sent to the client
Alex Chanb7480992017-01-30 14:04:47 +00003593 with `Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003594 """
3595 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3596 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003597
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003598 def single_ca(ctx):
3599 ctx.add_client_ca(cacert)
3600 return [cadesc]
3601 self._check_client_ca_list(single_ca)
3602
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003603 def test_multiple_add_client_ca(self):
3604 """
3605 Multiple CA names can be sent to the client by calling
Alex Chanb7480992017-01-30 14:04:47 +00003606 `Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003607 """
3608 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3609 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3610
3611 cadesc = cacert.get_subject()
3612 sedesc = secert.get_subject()
3613
3614 def multiple_ca(ctx):
3615 ctx.add_client_ca(cacert)
3616 ctx.add_client_ca(secert)
3617 return [cadesc, sedesc]
3618 self._check_client_ca_list(multiple_ca)
3619
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003620 def test_set_and_add_client_ca(self):
3621 """
Alex Chanb7480992017-01-30 14:04:47 +00003622 A call to `Context.set_client_ca_list` followed by a call to
3623 `Context.add_client_ca` results in using the CA names from the
Hynek Schlawack35618382015-09-05 21:54:25 +02003624 first call and the CA name from the second call.
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 mixed_set_add_ca(ctx):
3635 ctx.set_client_ca_list([cadesc, sedesc])
3636 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003637 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003638 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003639
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003640 def test_set_after_add_client_ca(self):
3641 """
Alex Chanb7480992017-01-30 14:04:47 +00003642 A call to `Context.set_client_ca_list` after a call to
3643 `Context.add_client_ca` replaces the CA name specified by the
Hynek Schlawack35618382015-09-05 21:54:25 +02003644 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003645 """
3646 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3647 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3648 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3649
3650 cadesc = cacert.get_subject()
3651 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003652
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003653 def set_replaces_add_ca(ctx):
3654 ctx.add_client_ca(clcert)
3655 ctx.set_client_ca_list([cadesc])
3656 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003657 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003658 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003659
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003660
Alex Chanb7480992017-01-30 14:04:47 +00003661class TestInfoConstants(object):
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003662 """
3663 Tests for assorted constants exposed for use in info callbacks.
3664 """
3665 def test_integers(self):
3666 """
3667 All of the info constants are integers.
3668
3669 This is a very weak test. It would be nice to have one that actually
3670 verifies that as certain info events happen, the value passed to the
3671 info callback matches up with the constant exposed by OpenSSL.SSL.
3672 """
3673 for const in [
Alex Gaynor5af32d02016-09-24 01:52:21 -04003674 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003675 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3676 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3677 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003678 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3679 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003680 assert isinstance(const, int)
3681
3682 # These constants don't exist on OpenSSL 1.1.0
3683 for const in [
3684 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
3685 ]:
3686 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003687
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003688
Cory Benfield1d142142016-03-30 11:51:45 +01003689class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003690 """
3691 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003692 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003693 """
3694 def test_available(self):
3695 """
3696 When the OpenSSL functionality is available the decorated functions
3697 work appropriately.
3698 """
3699 feature_guard = _make_requires(True, "Error text")
3700 results = []
3701
3702 @feature_guard
3703 def inner():
3704 results.append(True)
3705 return True
3706
Cory Benfield2333e5e2016-03-30 14:24:16 +01003707 assert inner() is True
3708 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003709
3710 def test_unavailable(self):
3711 """
3712 When the OpenSSL functionality is not available the decorated function
3713 does not execute and NotImplementedError is raised.
3714 """
3715 feature_guard = _make_requires(False, "Error text")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003716
3717 @feature_guard
Alex Chanfb078d82017-04-20 11:16:15 +01003718 def inner(): # pragma: nocover
3719 pytest.fail("Should not be called")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003720
Cory Benfield1d142142016-03-30 11:51:45 +01003721 with pytest.raises(NotImplementedError) as e:
3722 inner()
3723
3724 assert "Error text" in str(e.value)
Cory Benfield496652a2017-01-24 11:42:56 +00003725
3726
Alex Chanb7480992017-01-30 14:04:47 +00003727class TestOCSP(object):
Cory Benfield496652a2017-01-24 11:42:56 +00003728 """
3729 Tests for PyOpenSSL's OCSP stapling support.
3730 """
3731 sample_ocsp_data = b"this is totally ocsp data"
3732
3733 def _client_connection(self, callback, data, request_ocsp=True):
3734 """
3735 Builds a client connection suitable for using OCSP.
3736
3737 :param callback: The callback to register for OCSP.
3738 :param data: The opaque data object that will be handed to the
3739 OCSP callback.
3740 :param request_ocsp: Whether the client will actually ask for OCSP
3741 stapling. Useful for testing only.
3742 """
3743 ctx = Context(SSLv23_METHOD)
3744 ctx.set_ocsp_client_callback(callback, data)
3745 client = Connection(ctx)
3746
3747 if request_ocsp:
3748 client.request_ocsp()
3749
3750 client.set_connect_state()
3751 return client
3752
3753 def _server_connection(self, callback, data):
3754 """
3755 Builds a server connection suitable for using OCSP.
3756
3757 :param callback: The callback to register for OCSP.
3758 :param data: The opaque data object that will be handed to the
3759 OCSP callback.
3760 """
3761 ctx = Context(SSLv23_METHOD)
3762 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
3763 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
3764 ctx.set_ocsp_server_callback(callback, data)
3765 server = Connection(ctx)
3766 server.set_accept_state()
3767 return server
3768
3769 def test_callbacks_arent_called_by_default(self):
3770 """
3771 If both the client and the server have registered OCSP callbacks, but
3772 the client does not send the OCSP request, neither callback gets
3773 called.
3774 """
Alex Chanfb078d82017-04-20 11:16:15 +01003775 def ocsp_callback(*args, **kwargs): # pragma: nocover
3776 pytest.fail("Should not be called")
Cory Benfield496652a2017-01-24 11:42:56 +00003777
3778 client = self._client_connection(
3779 callback=ocsp_callback, data=None, request_ocsp=False
3780 )
3781 server = self._server_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003782 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003783
Cory Benfield496652a2017-01-24 11:42:56 +00003784 def test_client_negotiates_without_server(self):
3785 """
3786 If the client wants to do OCSP but the server does not, the handshake
3787 succeeds, and the client callback fires with an empty byte string.
3788 """
3789 called = []
3790
3791 def ocsp_callback(conn, ocsp_data, ignored):
3792 called.append(ocsp_data)
3793 return True
3794
3795 client = self._client_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003796 server = loopback_server_factory(socket=None)
3797 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003798
3799 assert len(called) == 1
3800 assert called[0] == b''
3801
3802 def test_client_receives_servers_data(self):
3803 """
3804 The data the server sends in its callback is received by the client.
3805 """
3806 calls = []
3807
3808 def server_callback(*args, **kwargs):
3809 return self.sample_ocsp_data
3810
3811 def client_callback(conn, ocsp_data, ignored):
3812 calls.append(ocsp_data)
3813 return True
3814
3815 client = self._client_connection(callback=client_callback, data=None)
3816 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003817 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003818
3819 assert len(calls) == 1
3820 assert calls[0] == self.sample_ocsp_data
3821
3822 def test_callbacks_are_invoked_with_connections(self):
3823 """
3824 The first arguments to both callbacks are their respective connections.
3825 """
3826 client_calls = []
3827 server_calls = []
3828
3829 def client_callback(conn, *args, **kwargs):
3830 client_calls.append(conn)
3831 return True
3832
3833 def server_callback(conn, *args, **kwargs):
3834 server_calls.append(conn)
3835 return self.sample_ocsp_data
3836
3837 client = self._client_connection(callback=client_callback, data=None)
3838 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003839 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003840
3841 assert len(client_calls) == 1
3842 assert len(server_calls) == 1
3843 assert client_calls[0] is client
3844 assert server_calls[0] is server
3845
3846 def test_opaque_data_is_passed_through(self):
3847 """
3848 Both callbacks receive an opaque, user-provided piece of data in their
3849 callbacks as the final argument.
3850 """
3851 calls = []
3852
3853 def server_callback(*args):
3854 calls.append(args)
3855 return self.sample_ocsp_data
3856
3857 def client_callback(*args):
3858 calls.append(args)
3859 return True
3860
3861 sentinel = object()
3862
3863 client = self._client_connection(
3864 callback=client_callback, data=sentinel
3865 )
3866 server = self._server_connection(
3867 callback=server_callback, data=sentinel
3868 )
Alex Chanb7480992017-01-30 14:04:47 +00003869 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003870
3871 assert len(calls) == 2
3872 assert calls[0][-1] is sentinel
3873 assert calls[1][-1] is sentinel
3874
3875 def test_server_returns_empty_string(self):
3876 """
3877 If the server returns an empty bytestring from its callback, the
3878 client callback is called with the empty bytestring.
3879 """
3880 client_calls = []
3881
3882 def server_callback(*args):
3883 return b''
3884
3885 def client_callback(conn, ocsp_data, ignored):
3886 client_calls.append(ocsp_data)
3887 return True
3888
3889 client = self._client_connection(callback=client_callback, data=None)
3890 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003891 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003892
3893 assert len(client_calls) == 1
3894 assert client_calls[0] == b''
3895
3896 def test_client_returns_false_terminates_handshake(self):
3897 """
3898 If the client returns False from its callback, the handshake fails.
3899 """
3900 def server_callback(*args):
3901 return self.sample_ocsp_data
3902
3903 def client_callback(*args):
3904 return False
3905
3906 client = self._client_connection(callback=client_callback, data=None)
3907 server = self._server_connection(callback=server_callback, data=None)
3908
3909 with pytest.raises(Error):
Alex Chanb7480992017-01-30 14:04:47 +00003910 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003911
3912 def test_exceptions_in_client_bubble_up(self):
3913 """
3914 The callbacks thrown in the client callback bubble up to the caller.
3915 """
3916 class SentinelException(Exception):
3917 pass
3918
3919 def server_callback(*args):
3920 return self.sample_ocsp_data
3921
3922 def client_callback(*args):
3923 raise SentinelException()
3924
3925 client = self._client_connection(callback=client_callback, data=None)
3926 server = self._server_connection(callback=server_callback, data=None)
3927
3928 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00003929 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003930
3931 def test_exceptions_in_server_bubble_up(self):
3932 """
3933 The callbacks thrown in the server callback bubble up to the caller.
3934 """
3935 class SentinelException(Exception):
3936 pass
3937
3938 def server_callback(*args):
3939 raise SentinelException()
3940
Alex Chanfb078d82017-04-20 11:16:15 +01003941 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00003942 pytest.fail("Should not be called")
3943
3944 client = self._client_connection(callback=client_callback, data=None)
3945 server = self._server_connection(callback=server_callback, data=None)
3946
3947 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00003948 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003949
3950 def test_server_must_return_bytes(self):
3951 """
3952 The server callback must return a bytestring, or a TypeError is thrown.
3953 """
3954 def server_callback(*args):
3955 return self.sample_ocsp_data.decode('ascii')
3956
Alex Chanfb078d82017-04-20 11:16:15 +01003957 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00003958 pytest.fail("Should not be called")
3959
3960 client = self._client_connection(callback=client_callback, data=None)
3961 server = self._server_connection(callback=server_callback, data=None)
3962
3963 with pytest.raises(TypeError):
Alex Chanb7480992017-01-30 14:04:47 +00003964 handshake_in_memory(client, server)