blob: 5bb4451463775647cc9de5cb4f96b9ccb5b0ef4c [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
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001199
Hynek Schlawack734d3022015-09-05 19:19:32 +02001200 # Arg, verisign.com doesn't speak anything newer than TLS 1.0
Hynek Schlawackbf887932015-10-21 17:13:47 +02001201 context = Context(SSLv23_METHOD)
Hynek Schlawack734d3022015-09-05 19:19:32 +02001202 context.set_default_verify_paths()
1203 context.set_verify(
1204 VERIFY_PEER,
1205 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001206
Hynek Schlawack734d3022015-09-05 19:19:32 +02001207 client = socket()
Hynek Schlawackbf887932015-10-21 17:13:47 +02001208 client.connect(("encrypted.google.com", 443))
Hynek Schlawack734d3022015-09-05 19:19:32 +02001209 clientSSL = Connection(context, client)
1210 clientSSL.set_connect_state()
1211 clientSSL.do_handshake()
1212 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Alex Chan532b79e2017-01-24 15:14:52 +00001213 assert clientSSL.recv(1024)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001214
Paul Kehrer55fb3412017-06-29 18:44:08 -05001215 def test_fallback_path_is_not_file_or_dir(self):
1216 """
1217 Test that when passed empty arrays or paths that do not exist no
1218 errors are raised.
1219 """
1220 context = Context(TLSv1_METHOD)
1221 context._fallback_default_verify_paths([], [])
1222 context._fallback_default_verify_paths(
1223 ["/not/a/file"], ["/not/a/dir"]
1224 )
1225
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001226 def test_add_extra_chain_cert_invalid_cert(self):
1227 """
Alex Chan532b79e2017-01-24 15:14:52 +00001228 `Context.add_extra_chain_cert` raises `TypeError` if called with an
1229 object which is not an instance of `X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001230 """
1231 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001232 with pytest.raises(TypeError):
1233 context.add_extra_chain_cert(object())
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001234
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001235 def _handshake_test(self, serverContext, clientContext):
1236 """
1237 Verify that a client and server created with the given contexts can
1238 successfully handshake and communicate.
1239 """
1240 serverSocket, clientSocket = socket_pair()
1241
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001242 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001243 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001244
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001245 client = Connection(clientContext, clientSocket)
1246 client.set_connect_state()
1247
1248 # Make them talk to each other.
Alex Chan532b79e2017-01-24 15:14:52 +00001249 # interact_in_memory(client, server)
1250 for _ in range(3):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001251 for s in [client, server]:
1252 try:
1253 s.do_handshake()
1254 except WantReadError:
1255 pass
1256
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001257 def test_set_verify_callback_connection_argument(self):
1258 """
1259 The first argument passed to the verify callback is the
Alex Chan532b79e2017-01-24 15:14:52 +00001260 `Connection` instance for which verification is taking place.
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001261 """
1262 serverContext = Context(TLSv1_METHOD)
1263 serverContext.use_privatekey(
1264 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1265 serverContext.use_certificate(
1266 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1267 serverConnection = Connection(serverContext, None)
1268
1269 class VerifyCallback(object):
1270 def callback(self, connection, *args):
1271 self.connection = connection
1272 return 1
1273
1274 verify = VerifyCallback()
1275 clientContext = Context(TLSv1_METHOD)
1276 clientContext.set_verify(VERIFY_PEER, verify.callback)
1277 clientConnection = Connection(clientContext, None)
1278 clientConnection.set_connect_state()
1279
Alex Chan532b79e2017-01-24 15:14:52 +00001280 handshake_in_memory(clientConnection, serverConnection)
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001281
Alex Chan532b79e2017-01-24 15:14:52 +00001282 assert verify.connection is clientConnection
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001283
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001284 def test_set_verify_callback_exception(self):
1285 """
Alex Chan532b79e2017-01-24 15:14:52 +00001286 If the verify callback passed to `Context.set_verify` raises an
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001287 exception, verification fails and the exception is propagated to the
Alex Chan532b79e2017-01-24 15:14:52 +00001288 caller of `Connection.do_handshake`.
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001289 """
1290 serverContext = Context(TLSv1_METHOD)
1291 serverContext.use_privatekey(
1292 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1293 serverContext.use_certificate(
1294 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1295
1296 clientContext = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001297
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001298 def verify_callback(*args):
1299 raise Exception("silly verify failure")
1300 clientContext.set_verify(VERIFY_PEER, verify_callback)
1301
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001302 with pytest.raises(Exception) as exc:
1303 self._handshake_test(serverContext, clientContext)
1304
Alex Chan532b79e2017-01-24 15:14:52 +00001305 assert "silly verify failure" == str(exc.value)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001306
Alex Chan532b79e2017-01-24 15:14:52 +00001307 def test_add_extra_chain_cert(self, tmpdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001308 """
Alex Chan532b79e2017-01-24 15:14:52 +00001309 `Context.add_extra_chain_cert` accepts an `X509`
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001310 instance to add to the certificate chain.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001311
Alex Chan532b79e2017-01-24 15:14:52 +00001312 See `_create_certificate_chain` for the details of the
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001313 certificate chain tested.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001314
1315 The chain is tested by starting a server with scert and connecting
1316 to it with a client which trusts cacert and requires verification to
1317 succeed.
1318 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001319 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001320 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1321
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001322 # Dump the CA certificate to a file because that's the only way to load
1323 # it as a trusted CA in the client context.
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001324 for cert, name in [(cacert, 'ca.pem'),
1325 (icert, 'i.pem'),
1326 (scert, 's.pem')]:
Alex Chan532b79e2017-01-24 15:14:52 +00001327 with tmpdir.join(name).open('w') as f:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001328 f.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001329
Hynek Schlawack1902c012015-04-16 15:06:41 -04001330 for key, name in [(cakey, 'ca.key'),
1331 (ikey, 'i.key'),
1332 (skey, 's.key')]:
Alex Chan532b79e2017-01-24 15:14:52 +00001333 with tmpdir.join(name).open('w') as f:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001334 f.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001335
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001336 # Create the server context
1337 serverContext = Context(TLSv1_METHOD)
1338 serverContext.use_privatekey(skey)
1339 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001340 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001341 serverContext.add_extra_chain_cert(icert)
1342
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001343 # Create the client
1344 clientContext = Context(TLSv1_METHOD)
1345 clientContext.set_verify(
1346 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Alex Chan532b79e2017-01-24 15:14:52 +00001347 clientContext.load_verify_locations(str(tmpdir.join("ca.pem")))
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001348
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001349 # Try it out.
1350 self._handshake_test(serverContext, clientContext)
1351
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001352 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001353 """
Alex Chan532b79e2017-01-24 15:14:52 +00001354 Verify that `Context.use_certificate_chain_file` reads a
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001355 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001356
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001357 The chain is tested by starting a server with scert and connecting to
1358 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001359 succeed.
1360 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001361 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001362 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1363
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001364 makedirs(certdir)
1365
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001366 chainFile = join_bytes_or_unicode(certdir, "chain.pem")
1367 caFile = join_bytes_or_unicode(certdir, "ca.pem")
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001368
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001369 # Write out the chain file.
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001370 with open(chainFile, 'wb') as fObj:
1371 # Most specific to least general.
1372 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1373 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1374 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1375
1376 with open(caFile, 'w') as fObj:
1377 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001378
1379 serverContext = Context(TLSv1_METHOD)
1380 serverContext.use_certificate_chain_file(chainFile)
1381 serverContext.use_privatekey(skey)
1382
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001383 clientContext = Context(TLSv1_METHOD)
1384 clientContext.set_verify(
1385 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001386 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001387
1388 self._handshake_test(serverContext, clientContext)
1389
Alex Chan532b79e2017-01-24 15:14:52 +00001390 def test_use_certificate_chain_file_bytes(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001391 """
1392 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1393 an instance of ``bytes``) to specify additional certificates to use to
1394 construct and verify a trust chain.
1395 """
1396 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001397 tmpfile + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001398 )
1399
Alex Chan532b79e2017-01-24 15:14:52 +00001400 def test_use_certificate_chain_file_unicode(self, tmpfile):
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001401 """
1402 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1403 an instance of ``unicode``) to specify additional certificates to use
1404 to construct and verify a trust chain.
1405 """
1406 self._use_certificate_chain_file_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001407 tmpfile.decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001408 )
1409
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001410 def test_use_certificate_chain_file_wrong_args(self):
1411 """
Alex Chan532b79e2017-01-24 15:14:52 +00001412 `Context.use_certificate_chain_file` raises `TypeError` if passed a
1413 non-byte string single argument.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001414 """
1415 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001416 with pytest.raises(TypeError):
1417 context.use_certificate_chain_file(object())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001418
Alex Chan532b79e2017-01-24 15:14:52 +00001419 def test_use_certificate_chain_file_missing_file(self, tmpfile):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001420 """
Alex Chan532b79e2017-01-24 15:14:52 +00001421 `Context.use_certificate_chain_file` raises `OpenSSL.SSL.Error` when
1422 passed a bad chain file name (for example, the name of a file which
1423 does not exist).
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001424 """
1425 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001426 with pytest.raises(Error):
1427 context.use_certificate_chain_file(tmpfile)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001428
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001429 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001430 """
Alex Chan532b79e2017-01-24 15:14:52 +00001431 `Context.get_verify_mode` returns the verify mode flags previously
1432 passed to `Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001433 """
1434 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001435 assert context.get_verify_mode() == 0
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001436 context.set_verify(
1437 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
Alex Chan532b79e2017-01-24 15:14:52 +00001438 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001439
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001440 @skip_if_py3
1441 def test_set_verify_mode_long(self):
1442 """
Alex Chan532b79e2017-01-24 15:14:52 +00001443 On Python 2 `Context.set_verify_mode` accepts values of type `long`
1444 as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001445 """
1446 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001447 assert context.get_verify_mode() == 0
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001448 context.set_verify(
Hynek Schlawackb4ceed32015-09-05 20:55:19 +02001449 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None
1450 ) # pragma: nocover
Alex Chan532b79e2017-01-24 15:14:52 +00001451 assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001452
Alex Chanfb078d82017-04-20 11:16:15 +01001453 @pytest.mark.parametrize('mode', [None, 1.0, object(), 'mode'])
1454 def test_set_verify_wrong_mode_arg(self, mode):
1455 """
1456 `Context.set_verify` raises `TypeError` if the first argument is
1457 not an integer.
1458 """
1459 context = Context(TLSv1_METHOD)
1460 with pytest.raises(TypeError):
1461 context.set_verify(mode=mode, callback=lambda *args: None)
1462
1463 @pytest.mark.parametrize('callback', [None, 1.0, 'mode', ('foo', 'bar')])
1464 def test_set_verify_wrong_callable_arg(self, callback):
1465 """
1466 `Context.set_verify` raises `TypeError` if the the second argument
1467 is not callable.
1468 """
1469 context = Context(TLSv1_METHOD)
1470 with pytest.raises(TypeError):
1471 context.set_verify(mode=VERIFY_PEER, callback=callback)
1472
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001473 def test_load_tmp_dh_wrong_args(self):
1474 """
Alex Chan532b79e2017-01-24 15:14:52 +00001475 `Context.load_tmp_dh` raises `TypeError` if called with a
1476 non-`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001477 """
1478 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001479 with pytest.raises(TypeError):
1480 context.load_tmp_dh(object())
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001481
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001482 def test_load_tmp_dh_missing_file(self):
1483 """
Alex Chan532b79e2017-01-24 15:14:52 +00001484 `Context.load_tmp_dh` raises `OpenSSL.SSL.Error` if the
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001485 specified file does not exist.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001486 """
1487 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001488 with pytest.raises(Error):
1489 context.load_tmp_dh(b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001490
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001491 def _load_tmp_dh_test(self, dhfilename):
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001492 """
1493 Verify that calling ``Context.load_tmp_dh`` with the given filename
1494 does not raise an exception.
1495 """
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001496 context = Context(TLSv1_METHOD)
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001497 with open(dhfilename, "w") as dhfile:
1498 dhfile.write(dhparam)
1499
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001500 context.load_tmp_dh(dhfilename)
1501 # XXX What should I assert here? -exarkun
1502
Alex Chan532b79e2017-01-24 15:14:52 +00001503 def test_load_tmp_dh_bytes(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001504 """
Alex Chan532b79e2017-01-24 15:14:52 +00001505 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001506 specified file (given as ``bytes``).
1507 """
1508 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001509 tmpfile + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001510 )
1511
Alex Chan532b79e2017-01-24 15:14:52 +00001512 def test_load_tmp_dh_unicode(self, tmpfile):
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001513 """
Alex Chan532b79e2017-01-24 15:14:52 +00001514 `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001515 specified file (given as ``unicode``).
1516 """
1517 self._load_tmp_dh_test(
Alex Chan532b79e2017-01-24 15:14:52 +00001518 tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001519 )
1520
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001521 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001522 """
Alex Chan532b79e2017-01-24 15:14:52 +00001523 `Context.set_tmp_ecdh` sets the elliptic curve for Diffie-Hellman to
1524 the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001525 """
1526 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001527 for curve in get_elliptic_curves():
Hynek Schlawacka07fa8c2015-10-17 10:15:28 +02001528 if curve.name.startswith(u"Oakley-"):
Hynek Schlawack7408aff2015-10-17 09:51:16 +02001529 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1530 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1531 # error queue on OpenSSL 1.0.2.
1532 continue
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001533 # The only easily "assertable" thing is that it does not raise an
1534 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001535 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001536
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001537 def test_set_session_cache_mode_wrong_args(self):
1538 """
Alex Chan532b79e2017-01-24 15:14:52 +00001539 `Context.set_session_cache_mode` raises `TypeError` if called with
1540 a non-integer argument.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001541 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001542 """
1543 context = Context(TLSv1_METHOD)
Alex Chan532b79e2017-01-24 15:14:52 +00001544 with pytest.raises(TypeError):
1545 context.set_session_cache_mode(object())
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001546
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001547 def test_session_cache_mode(self):
1548 """
Alex Chan532b79e2017-01-24 15:14:52 +00001549 `Context.set_session_cache_mode` specifies how sessions are cached.
1550 The setting can be retrieved via `Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001551 """
1552 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001553 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001554 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
Alex Chan532b79e2017-01-24 15:14:52 +00001555 assert SESS_CACHE_OFF == off
1556 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001557
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001558 @skip_if_py3
1559 def test_session_cache_mode_long(self):
1560 """
Alex Chan532b79e2017-01-24 15:14:52 +00001561 On Python 2 `Context.set_session_cache_mode` accepts values
1562 of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001563 """
1564 context = Context(TLSv1_METHOD)
1565 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
Alex Chan532b79e2017-01-24 15:14:52 +00001566 assert SESS_CACHE_BOTH == context.get_session_cache_mode()
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001567
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001568 def test_get_cert_store(self):
1569 """
Alex Chan532b79e2017-01-24 15:14:52 +00001570 `Context.get_cert_store` returns a `X509Store` instance.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571 """
1572 context = Context(TLSv1_METHOD)
1573 store = context.get_cert_store()
Alex Chan532b79e2017-01-24 15:14:52 +00001574 assert isinstance(store, X509Store)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001575
1576
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001577class TestServerNameCallback(object):
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001578 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001579 Tests for `Context.set_tlsext_servername_callback` and its
1580 interaction with `Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001581 """
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001582 def test_old_callback_forgotten(self):
1583 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001584 If `Context.set_tlsext_servername_callback` is used to specify
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001585 a new callback, the one it replaces is dereferenced.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001586 """
Alex Chanfb078d82017-04-20 11:16:15 +01001587 def callback(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001588 pass
1589
Alex Chanfb078d82017-04-20 11:16:15 +01001590 def replacement(connection): # pragma: no cover
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001591 pass
1592
1593 context = Context(TLSv1_METHOD)
1594 context.set_tlsext_servername_callback(callback)
1595
1596 tracker = ref(callback)
1597 del callback
1598
1599 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001600
1601 # One run of the garbage collector happens to work on CPython. PyPy
1602 # doesn't collect the underlying object until a second run for whatever
1603 # reason. That's fine, it still demonstrates our code has properly
1604 # dropped the reference.
1605 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001606 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001607
1608 callback = tracker()
1609 if callback is not None:
1610 referrers = get_referrers(callback)
Alex Chanfb078d82017-04-20 11:16:15 +01001611 if len(referrers) > 1: # pragma: nocover
1612 pytest.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001613
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001614 def test_no_servername(self):
1615 """
1616 When a client specifies no server name, the callback passed to
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001617 `Context.set_tlsext_servername_callback` is invoked and the
1618 result of `Connection.get_servername` is `None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001619 """
1620 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001621
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001622 def servername(conn):
1623 args.append((conn, conn.get_servername()))
1624 context = Context(TLSv1_METHOD)
1625 context.set_tlsext_servername_callback(servername)
1626
1627 # Lose our reference to it. The Context is responsible for keeping it
1628 # alive now.
1629 del servername
1630 collect()
1631
1632 # Necessary to actually accept the connection
1633 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001634 context.use_certificate(
1635 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001636
1637 # Do a little connection to trigger the logic
1638 server = Connection(context, None)
1639 server.set_accept_state()
1640
1641 client = Connection(Context(TLSv1_METHOD), None)
1642 client.set_connect_state()
1643
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001644 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001645
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001646 assert args == [(server, None)]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001647
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001648 def test_servername(self):
1649 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001650 When a client specifies a server name in its hello message, the
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001651 callback passed to `Contexts.set_tlsext_servername_callback` is
1652 invoked and the result of `Connection.get_servername` is that
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001653 server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001654 """
1655 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001656
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001657 def servername(conn):
1658 args.append((conn, conn.get_servername()))
1659 context = Context(TLSv1_METHOD)
1660 context.set_tlsext_servername_callback(servername)
1661
1662 # Necessary to actually accept the connection
1663 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001664 context.use_certificate(
1665 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001666
1667 # Do a little connection to trigger the logic
1668 server = Connection(context, None)
1669 server.set_accept_state()
1670
1671 client = Connection(Context(TLSv1_METHOD), None)
1672 client.set_connect_state()
Alex Gaynore7f51982016-09-11 11:48:14 -04001673 client.set_tlsext_host_name(b"foo1.example.com")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001674
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001675 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001676
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001677 assert args == [(server, b"foo1.example.com")]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001678
1679
Alex Chan9e08b3e2016-11-10 12:18:54 +00001680class TestNextProtoNegotiation(object):
Cory Benfield84a121e2014-03-31 20:30:25 +01001681 """
1682 Test for Next Protocol Negotiation in PyOpenSSL.
1683 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001684 def test_npn_success(self):
1685 """
1686 Tests that clients and servers that agree on the negotiated next
1687 protocol can correct establish a connection, and that the agreed
1688 protocol is reported by the connections.
1689 """
1690 advertise_args = []
1691 select_args = []
1692
1693 def advertise(conn):
1694 advertise_args.append((conn,))
1695 return [b'http/1.1', b'spdy/2']
1696
1697 def select(conn, options):
1698 select_args.append((conn, options))
1699 return b'spdy/2'
1700
1701 server_context = Context(TLSv1_METHOD)
1702 server_context.set_npn_advertise_callback(advertise)
1703
1704 client_context = Context(TLSv1_METHOD)
1705 client_context.set_npn_select_callback(select)
1706
1707 # Necessary to actually accept the connection
1708 server_context.use_privatekey(
1709 load_privatekey(FILETYPE_PEM, server_key_pem))
1710 server_context.use_certificate(
1711 load_certificate(FILETYPE_PEM, server_cert_pem))
1712
1713 # Do a little connection to trigger the logic
1714 server = Connection(server_context, None)
1715 server.set_accept_state()
1716
1717 client = Connection(client_context, None)
1718 client.set_connect_state()
1719
1720 interact_in_memory(server, client)
1721
1722 assert advertise_args == [(server,)]
1723 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1724
1725 assert server.get_next_proto_negotiated() == b'spdy/2'
1726 assert client.get_next_proto_negotiated() == b'spdy/2'
1727
1728 def test_npn_client_fail(self):
1729 """
1730 Tests that when clients and servers cannot agree on what protocol
1731 to use next that the TLS connection does not get established.
1732 """
1733 advertise_args = []
1734 select_args = []
1735
1736 def advertise(conn):
1737 advertise_args.append((conn,))
1738 return [b'http/1.1', b'spdy/2']
1739
1740 def select(conn, options):
1741 select_args.append((conn, options))
1742 return b''
1743
1744 server_context = Context(TLSv1_METHOD)
1745 server_context.set_npn_advertise_callback(advertise)
1746
1747 client_context = Context(TLSv1_METHOD)
1748 client_context.set_npn_select_callback(select)
1749
1750 # Necessary to actually accept the connection
1751 server_context.use_privatekey(
1752 load_privatekey(FILETYPE_PEM, server_key_pem))
1753 server_context.use_certificate(
1754 load_certificate(FILETYPE_PEM, server_cert_pem))
1755
1756 # Do a little connection to trigger the logic
1757 server = Connection(server_context, None)
1758 server.set_accept_state()
1759
1760 client = Connection(client_context, None)
1761 client.set_connect_state()
1762
1763 # If the client doesn't return anything, the connection will fail.
1764 with pytest.raises(Error):
1765 interact_in_memory(server, client)
1766
1767 assert advertise_args == [(server,)]
1768 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1769
1770 def test_npn_select_error(self):
1771 """
1772 Test that we can handle exceptions in the select callback. If
1773 select fails it should be fatal to the connection.
1774 """
1775 advertise_args = []
1776
1777 def advertise(conn):
1778 advertise_args.append((conn,))
1779 return [b'http/1.1', b'spdy/2']
1780
1781 def select(conn, options):
1782 raise TypeError
1783
1784 server_context = Context(TLSv1_METHOD)
1785 server_context.set_npn_advertise_callback(advertise)
1786
1787 client_context = Context(TLSv1_METHOD)
1788 client_context.set_npn_select_callback(select)
1789
1790 # Necessary to actually accept the connection
1791 server_context.use_privatekey(
1792 load_privatekey(FILETYPE_PEM, server_key_pem))
1793 server_context.use_certificate(
1794 load_certificate(FILETYPE_PEM, server_cert_pem))
1795
1796 # Do a little connection to trigger the logic
1797 server = Connection(server_context, None)
1798 server.set_accept_state()
1799
1800 client = Connection(client_context, None)
1801 client.set_connect_state()
1802
1803 # If the callback throws an exception it should be raised here.
1804 with pytest.raises(TypeError):
1805 interact_in_memory(server, client)
1806 assert advertise_args == [(server,), ]
1807
1808 def test_npn_advertise_error(self):
1809 """
1810 Test that we can handle exceptions in the advertise callback. If
1811 advertise fails no NPN is advertised to the client.
1812 """
1813 select_args = []
1814
1815 def advertise(conn):
1816 raise TypeError
1817
1818 def select(conn, options): # pragma: nocover
Cory Benfieldba1820d2015-04-13 17:39:12 -04001819 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001820 Assert later that no args are actually appended.
Cory Benfieldba1820d2015-04-13 17:39:12 -04001821 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001822 select_args.append((conn, options))
1823 return b''
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001824
Alex Chan9e08b3e2016-11-10 12:18:54 +00001825 server_context = Context(TLSv1_METHOD)
1826 server_context.set_npn_advertise_callback(advertise)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001827
Alex Chan9e08b3e2016-11-10 12:18:54 +00001828 client_context = Context(TLSv1_METHOD)
1829 client_context.set_npn_select_callback(select)
Cory Benfield84a121e2014-03-31 20:30:25 +01001830
Alex Chan9e08b3e2016-11-10 12:18:54 +00001831 # Necessary to actually accept the connection
1832 server_context.use_privatekey(
1833 load_privatekey(FILETYPE_PEM, server_key_pem))
1834 server_context.use_certificate(
1835 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield84a121e2014-03-31 20:30:25 +01001836
Alex Chan9e08b3e2016-11-10 12:18:54 +00001837 # Do a little connection to trigger the logic
1838 server = Connection(server_context, None)
1839 server.set_accept_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001840
Alex Chan9e08b3e2016-11-10 12:18:54 +00001841 client = Connection(client_context, None)
1842 client.set_connect_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001843
Alex Chan9e08b3e2016-11-10 12:18:54 +00001844 # If the client doesn't return anything, the connection will fail.
1845 with pytest.raises(TypeError):
1846 interact_in_memory(server, client)
1847 assert select_args == []
Cory Benfield0ea76e72015-03-22 09:05:28 +00001848
1849
Alex Chanec1e32d2016-11-10 14:11:45 +00001850class TestApplicationLayerProtoNegotiation(object):
Cory Benfield12eae892014-06-07 15:42:56 +01001851 """
1852 Tests for ALPN in PyOpenSSL.
1853 """
Cory Benfielde46fa842015-04-13 16:50:49 -04001854 # Skip tests on versions that don't support ALPN.
1855 if _lib.Cryptography_HAS_ALPN:
Cory Benfield12eae892014-06-07 15:42:56 +01001856
Cory Benfielde46fa842015-04-13 16:50:49 -04001857 def test_alpn_success(self):
1858 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001859 Clients and servers that agree on the negotiated ALPN protocol can
1860 correct establish a connection, and the agreed protocol is reported
1861 by the connections.
Cory Benfielde46fa842015-04-13 16:50:49 -04001862 """
1863 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001864
Cory Benfielde46fa842015-04-13 16:50:49 -04001865 def select(conn, options):
1866 select_args.append((conn, options))
1867 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001868
Cory Benfielde46fa842015-04-13 16:50:49 -04001869 client_context = Context(TLSv1_METHOD)
1870 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001871
Cory Benfielde46fa842015-04-13 16:50:49 -04001872 server_context = Context(TLSv1_METHOD)
1873 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001874
Cory Benfielde46fa842015-04-13 16:50:49 -04001875 # Necessary to actually accept the connection
1876 server_context.use_privatekey(
1877 load_privatekey(FILETYPE_PEM, server_key_pem))
1878 server_context.use_certificate(
1879 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001880
Cory Benfielde46fa842015-04-13 16:50:49 -04001881 # Do a little connection to trigger the logic
1882 server = Connection(server_context, None)
1883 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001884
Cory Benfielde46fa842015-04-13 16:50:49 -04001885 client = Connection(client_context, None)
1886 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001887
Alex Chanec1e32d2016-11-10 14:11:45 +00001888 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001889
Alex Chanec1e32d2016-11-10 14:11:45 +00001890 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfielde46fa842015-04-13 16:50:49 -04001891
Alex Chanec1e32d2016-11-10 14:11:45 +00001892 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1893 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001894
Cory Benfielde46fa842015-04-13 16:50:49 -04001895 def test_alpn_set_on_connection(self):
1896 """
1897 The same as test_alpn_success, but setting the ALPN protocols on
1898 the connection rather than the context.
1899 """
1900 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001901
Cory Benfielde46fa842015-04-13 16:50:49 -04001902 def select(conn, options):
1903 select_args.append((conn, options))
1904 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001905
Cory Benfielde46fa842015-04-13 16:50:49 -04001906 # Setup the client context but don't set any ALPN protocols.
1907 client_context = Context(TLSv1_METHOD)
Cory Benfield12eae892014-06-07 15:42:56 +01001908
Cory Benfielde46fa842015-04-13 16:50:49 -04001909 server_context = Context(TLSv1_METHOD)
1910 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001911
Cory Benfielde46fa842015-04-13 16:50:49 -04001912 # Necessary to actually accept the connection
1913 server_context.use_privatekey(
1914 load_privatekey(FILETYPE_PEM, server_key_pem))
1915 server_context.use_certificate(
1916 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001917
Cory Benfielde46fa842015-04-13 16:50:49 -04001918 # Do a little connection to trigger the logic
1919 server = Connection(server_context, None)
1920 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001921
Cory Benfielde46fa842015-04-13 16:50:49 -04001922 # Set the ALPN protocols on the client connection.
1923 client = Connection(client_context, None)
1924 client.set_alpn_protos([b'http/1.1', b'spdy/2'])
1925 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001926
Alex Chanec1e32d2016-11-10 14:11:45 +00001927 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001928
Alex Chanec1e32d2016-11-10 14:11:45 +00001929 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001930
Alex Chanec1e32d2016-11-10 14:11:45 +00001931 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1932 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001933
Cory Benfielde46fa842015-04-13 16:50:49 -04001934 def test_alpn_server_fail(self):
1935 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001936 When clients and servers cannot agree on what protocol to use next
1937 the TLS connection does not get established.
Cory Benfielde46fa842015-04-13 16:50:49 -04001938 """
1939 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001940
Cory Benfielde46fa842015-04-13 16:50:49 -04001941 def select(conn, options):
1942 select_args.append((conn, options))
1943 return b''
Cory Benfield12eae892014-06-07 15:42:56 +01001944
Cory Benfielde46fa842015-04-13 16:50:49 -04001945 client_context = Context(TLSv1_METHOD)
1946 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001947
Cory Benfielde46fa842015-04-13 16:50:49 -04001948 server_context = Context(TLSv1_METHOD)
1949 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001950
Cory Benfielde46fa842015-04-13 16:50:49 -04001951 # Necessary to actually accept the connection
1952 server_context.use_privatekey(
1953 load_privatekey(FILETYPE_PEM, server_key_pem))
1954 server_context.use_certificate(
1955 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001956
Cory Benfielde46fa842015-04-13 16:50:49 -04001957 # Do a little connection to trigger the logic
1958 server = Connection(server_context, None)
1959 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001960
Cory Benfielde46fa842015-04-13 16:50:49 -04001961 client = Connection(client_context, None)
1962 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001963
Cory Benfielde46fa842015-04-13 16:50:49 -04001964 # If the client doesn't return anything, the connection will fail.
Alex Chanec1e32d2016-11-10 14:11:45 +00001965 with pytest.raises(Error):
1966 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001967
Alex Chanec1e32d2016-11-10 14:11:45 +00001968 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001969
Cory Benfielde46fa842015-04-13 16:50:49 -04001970 def test_alpn_no_server(self):
1971 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001972 When clients and servers cannot agree on what protocol to use next
1973 because the server doesn't offer ALPN, no protocol is negotiated.
Cory Benfielde46fa842015-04-13 16:50:49 -04001974 """
1975 client_context = Context(TLSv1_METHOD)
1976 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfielde3d57152015-04-11 17:57:35 -04001977
Cory Benfielde46fa842015-04-13 16:50:49 -04001978 server_context = Context(TLSv1_METHOD)
Cory Benfielde3d57152015-04-11 17:57:35 -04001979
Cory Benfielde46fa842015-04-13 16:50:49 -04001980 # Necessary to actually accept the connection
1981 server_context.use_privatekey(
1982 load_privatekey(FILETYPE_PEM, server_key_pem))
1983 server_context.use_certificate(
1984 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfielde3d57152015-04-11 17:57:35 -04001985
Cory Benfielde46fa842015-04-13 16:50:49 -04001986 # Do a little connection to trigger the logic
1987 server = Connection(server_context, None)
1988 server.set_accept_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001989
Cory Benfielde46fa842015-04-13 16:50:49 -04001990 client = Connection(client_context, None)
1991 client.set_connect_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001992
Cory Benfielde46fa842015-04-13 16:50:49 -04001993 # Do the dance.
Alex Chanec1e32d2016-11-10 14:11:45 +00001994 interact_in_memory(server, client)
Cory Benfielde3d57152015-04-11 17:57:35 -04001995
Alex Chanec1e32d2016-11-10 14:11:45 +00001996 assert client.get_alpn_proto_negotiated() == b''
Cory Benfielde3d57152015-04-11 17:57:35 -04001997
Cory Benfielde46fa842015-04-13 16:50:49 -04001998 def test_alpn_callback_exception(self):
1999 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04002000 We can handle exceptions in the ALPN select callback.
Cory Benfielde46fa842015-04-13 16:50:49 -04002001 """
2002 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002003
Cory Benfielde46fa842015-04-13 16:50:49 -04002004 def select(conn, options):
2005 select_args.append((conn, options))
Cory Benfieldef401452015-04-13 18:17:36 -04002006 raise TypeError()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002007
Cory Benfielde46fa842015-04-13 16:50:49 -04002008 client_context = Context(TLSv1_METHOD)
2009 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfieldf1177e72015-04-12 09:11:49 -04002010
Cory Benfielde46fa842015-04-13 16:50:49 -04002011 server_context = Context(TLSv1_METHOD)
2012 server_context.set_alpn_select_callback(select)
Cory Benfieldf1177e72015-04-12 09:11:49 -04002013
Cory Benfielde46fa842015-04-13 16:50:49 -04002014 # Necessary to actually accept the connection
2015 server_context.use_privatekey(
2016 load_privatekey(FILETYPE_PEM, server_key_pem))
2017 server_context.use_certificate(
2018 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfieldf1177e72015-04-12 09:11:49 -04002019
Cory Benfielde46fa842015-04-13 16:50:49 -04002020 # Do a little connection to trigger the logic
2021 server = Connection(server_context, None)
2022 server.set_accept_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002023
Cory Benfielde46fa842015-04-13 16:50:49 -04002024 client = Connection(client_context, None)
2025 client.set_connect_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002026
Alex Chanec1e32d2016-11-10 14:11:45 +00002027 with pytest.raises(TypeError):
2028 interact_in_memory(server, client)
2029 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfieldf1177e72015-04-12 09:11:49 -04002030
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002031 else:
2032 # No ALPN.
2033 def test_alpn_not_implemented(self):
Cory Benfieldef401452015-04-13 18:17:36 -04002034 """
2035 If ALPN is not in OpenSSL, we should raise NotImplementedError.
2036 """
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002037 # Test the context methods first.
2038 context = Context(TLSv1_METHOD)
Alex Chanec1e32d2016-11-10 14:11:45 +00002039 with pytest.raises(NotImplementedError):
2040 context.set_alpn_protos(None)
2041 with pytest.raises(NotImplementedError):
2042 context.set_alpn_select_callback(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002043
2044 # Now test a connection.
2045 conn = Connection(context)
Alex Chanec1e32d2016-11-10 14:11:45 +00002046 with pytest.raises(NotImplementedError):
2047 conn.set_alpn_protos(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002048
Cory Benfieldf1177e72015-04-12 09:11:49 -04002049
Alex Chanec1e32d2016-11-10 14:11:45 +00002050class TestSession(object):
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002051 """
2052 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2053 """
2054 def test_construction(self):
2055 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002056 :py:class:`Session` can be constructed with no arguments, creating
2057 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002058 """
2059 new_session = Session()
Alex Chanec1e32d2016-11-10 14:11:45 +00002060 assert isinstance(new_session, Session)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002061
2062
Alex Chan1c0cb662017-01-30 07:13:30 +00002063class TestConnection(object):
Rick Deane15b1472009-07-09 15:53:42 -05002064 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002065 Unit tests for `OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002066 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002067 # XXX get_peer_certificate -> None
2068 # XXX sock_shutdown
2069 # XXX master_key -> TypeError
2070 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002071 # XXX connect -> TypeError
2072 # XXX connect_ex -> TypeError
2073 # XXX set_connect_state -> TypeError
2074 # XXX set_accept_state -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002075 # XXX do_handshake -> TypeError
2076 # XXX bio_read -> TypeError
2077 # XXX recv -> TypeError
2078 # XXX send -> TypeError
2079 # XXX bio_write -> TypeError
2080
Rick Deane15b1472009-07-09 15:53:42 -05002081 def test_type(self):
2082 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002083 `Connection` and `ConnectionType` refer to the same type object and
2084 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002085 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002086 assert Connection is ConnectionType
Rick Deane15b1472009-07-09 15:53:42 -05002087 ctx = Context(TLSv1_METHOD)
Alex Chan1c0cb662017-01-30 07:13:30 +00002088 assert is_consistent_type(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002089
Alex Chanfb078d82017-04-20 11:16:15 +01002090 @pytest.mark.parametrize('bad_context', [object(), 'context', None, 1])
2091 def test_wrong_args(self, bad_context):
2092 """
2093 `Connection.__init__` raises `TypeError` if called with a non-`Context`
2094 instance argument.
2095 """
2096 with pytest.raises(TypeError):
2097 Connection(bad_context)
2098
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002099 def test_get_context(self):
2100 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002101 `Connection.get_context` returns the `Context` instance used to
2102 construct the `Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002103 """
2104 context = Context(TLSv1_METHOD)
2105 connection = Connection(context, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002106 assert connection.get_context() is context
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002107
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002108 def test_set_context_wrong_args(self):
2109 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002110 `Connection.set_context` raises `TypeError` if called with a
Alex Chanfb078d82017-04-20 11:16:15 +01002111 non-`Context` instance argument.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002112 """
2113 ctx = Context(TLSv1_METHOD)
2114 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002115 with pytest.raises(TypeError):
2116 connection.set_context(object())
2117 with pytest.raises(TypeError):
2118 connection.set_context("hello")
2119 with pytest.raises(TypeError):
2120 connection.set_context(1)
2121 assert ctx is connection.get_context()
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002122
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002123 def test_set_context(self):
2124 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002125 `Connection.set_context` specifies a new `Context` instance to be
2126 used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002127 """
2128 original = Context(SSLv23_METHOD)
2129 replacement = Context(TLSv1_METHOD)
2130 connection = Connection(original, None)
2131 connection.set_context(replacement)
Alex Chan1c0cb662017-01-30 07:13:30 +00002132 assert replacement is connection.get_context()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002133 # Lose our references to the contexts, just in case the Connection
2134 # isn't properly managing its own contributions to their reference
2135 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002136 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002137 collect()
2138
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002139 def test_set_tlsext_host_name_wrong_args(self):
2140 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002141 If `Connection.set_tlsext_host_name` is called with a non-byte string
2142 argument or a byte string with an embedded NUL, `TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002143 """
2144 conn = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002145 with pytest.raises(TypeError):
2146 conn.set_tlsext_host_name(object())
2147 with pytest.raises(TypeError):
2148 conn.set_tlsext_host_name(b"with\0null")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002149
Abraham Martinc5484ba2015-03-25 15:33:05 +00002150 if PY3:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002151 # On Python 3.x, don't accidentally implicitly convert from text.
Alex Chan1c0cb662017-01-30 07:13:30 +00002152 with pytest.raises(TypeError):
2153 conn.set_tlsext_host_name(b"example.com".decode("ascii"))
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002154
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002155 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002156 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002157 `Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002158 immediate read.
2159 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002160 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002161 assert connection.pending() == 0
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002162
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002163 def test_peek(self):
2164 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002165 `Connection.recv` peeks into the connection if `socket.MSG_PEEK` is
2166 passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002167 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002168 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002169 server.send(b'xy')
Alex Chan1c0cb662017-01-30 07:13:30 +00002170 assert client.recv(2, MSG_PEEK) == b'xy'
2171 assert client.recv(2, MSG_PEEK) == b'xy'
2172 assert client.recv(2) == b'xy'
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002173
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002174 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002175 """
Hynek Schlawack3bcf3152017-02-18 08:25:34 +01002176 `Connection.connect` raises `TypeError` if called with a non-address
2177 argument.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002178 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002179 connection = Connection(Context(TLSv1_METHOD), socket())
Alex Chan1c0cb662017-01-30 07:13:30 +00002180 with pytest.raises(TypeError):
2181 connection.connect(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002182
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002183 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002184 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002185 `Connection.connect` raises `socket.error` if the underlying socket
2186 connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002187 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002188 client = socket()
2189 context = Context(TLSv1_METHOD)
2190 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002191 # pytest.raises here doesn't work because of a bug in py.test on Python
2192 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002193 try:
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002194 clientSSL.connect(("127.0.0.1", 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002195 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002196 exc = e
2197 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002198
2199 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002200 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002201 `Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002202 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002203 port = socket()
2204 port.bind(('', 0))
2205 port.listen(3)
2206
2207 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002208 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
2209 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002210
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002211 @pytest.mark.skipif(
2212 platform == "darwin",
2213 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
2214 )
2215 def test_connect_ex(self):
2216 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002217 If there is a connection error, `Connection.connect_ex` returns the
2218 errno instead of raising an exception.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002219 """
2220 port = socket()
2221 port.bind(('', 0))
2222 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002223
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002224 clientSSL = Connection(Context(TLSv1_METHOD), socket())
2225 clientSSL.setblocking(False)
2226 result = clientSSL.connect_ex(port.getsockname())
2227 expected = (EINPROGRESS, EWOULDBLOCK)
Alex Chan1c0cb662017-01-30 07:13:30 +00002228 assert result in expected
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002229
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002230 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002231 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002232 `Connection.accept` accepts a pending connection attempt and returns a
2233 tuple of a new `Connection` (the accepted client) and the address the
2234 connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002235 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002236 ctx = Context(TLSv1_METHOD)
2237 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2238 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002239 port = socket()
2240 portSSL = Connection(ctx, port)
2241 portSSL.bind(('', 0))
2242 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002243
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002244 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002245
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002246 # Calling portSSL.getsockname() here to get the server IP address
2247 # sounds great, but frequently fails on Windows.
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002248 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002249
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002250 serverSSL, address = portSSL.accept()
2251
Alex Chan1c0cb662017-01-30 07:13:30 +00002252 assert isinstance(serverSSL, Connection)
2253 assert serverSSL.get_context() is ctx
2254 assert address == clientSSL.getsockname()
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002255
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002256 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002257 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002258 `Connection.set_shutdown` raises `TypeError` if called with arguments
2259 other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002260 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002261 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002262 with pytest.raises(TypeError):
2263 connection.set_shutdown(None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002264
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002265 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002266 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002267 `Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002268 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002269 server, client = loopback()
2270 assert not server.shutdown()
2271 assert server.get_shutdown() == SENT_SHUTDOWN
2272 with pytest.raises(ZeroReturnError):
2273 client.recv(1024)
2274 assert client.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002275 client.shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002276 assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
2277 with pytest.raises(ZeroReturnError):
2278 server.recv(1024)
2279 assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002280
Paul Aurichc85e0862015-01-08 08:34:33 -08002281 def test_shutdown_closed(self):
2282 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002283 If the underlying socket is closed, `Connection.shutdown` propagates
2284 the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002285 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002286 server, client = loopback()
Paul Aurichc85e0862015-01-08 08:34:33 -08002287 server.sock_shutdown(2)
Alex Chan1c0cb662017-01-30 07:13:30 +00002288 with pytest.raises(SysCallError) as exc:
2289 server.shutdown()
Alex Chanfb078d82017-04-20 11:16:15 +01002290 if platform == "win32":
2291 assert exc.value.args[0] == ESHUTDOWN
2292 else:
2293 assert exc.value.args[0] == EPIPE
Paul Aurichc85e0862015-01-08 08:34:33 -08002294
Glyph89389472015-04-14 17:29:26 -04002295 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002296 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002297 If the underlying connection is truncated, `Connection.shutdown`
2298 raises an `Error`.
Glyph6064ec32015-04-14 16:38:22 -04002299 """
Glyph89389472015-04-14 17:29:26 -04002300 server_ctx = Context(TLSv1_METHOD)
2301 client_ctx = Context(TLSv1_METHOD)
2302 server_ctx.use_privatekey(
2303 load_privatekey(FILETYPE_PEM, server_key_pem))
2304 server_ctx.use_certificate(
2305 load_certificate(FILETYPE_PEM, server_cert_pem))
2306 server = Connection(server_ctx, None)
2307 client = Connection(client_ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002308 handshake_in_memory(client, server)
2309 assert not server.shutdown()
2310 with pytest.raises(WantReadError):
2311 server.shutdown()
Glyph89389472015-04-14 17:29:26 -04002312 server.bio_shutdown()
Alex Chan1c0cb662017-01-30 07:13:30 +00002313 with pytest.raises(Error):
2314 server.shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002315
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002316 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002317 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002318 `Connection.set_shutdown` sets the state of the SSL connection
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002319 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002320 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002321 connection = Connection(Context(TLSv1_METHOD), socket())
2322 connection.set_shutdown(RECEIVED_SHUTDOWN)
Alex Chan1c0cb662017-01-30 07:13:30 +00002323 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002324
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002325 @skip_if_py3
2326 def test_set_shutdown_long(self):
2327 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002328 On Python 2 `Connection.set_shutdown` accepts an argument
2329 of type `long` as well as `int`.
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002330 """
2331 connection = Connection(Context(TLSv1_METHOD), socket())
2332 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
Alex Chan1c0cb662017-01-30 07:13:30 +00002333 assert connection.get_shutdown() == RECEIVED_SHUTDOWN
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002334
kjavaf248592015-09-07 12:14:01 +01002335 def test_state_string(self):
2336 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002337 `Connection.state_string` verbosely describes the current state of
2338 the `Connection`.
kjavaf248592015-09-07 12:14:01 +01002339 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002340 server, client = socket_pair()
Alex Chan1c0cb662017-01-30 07:13:30 +00002341 server = loopback_server_factory(server)
2342 client = loopback_client_factory(client)
kjavaf248592015-09-07 12:14:01 +01002343
Alex Gaynor5af32d02016-09-24 01:52:21 -04002344 assert server.get_state_string() in [
2345 b"before/accept initialization", b"before SSL initialization"
2346 ]
2347 assert client.get_state_string() in [
2348 b"before/connect initialization", b"before SSL initialization"
2349 ]
kjavaf248592015-09-07 12:14:01 +01002350
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002351 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002352 """
2353 Any object can be set as app data by passing it to
Alex Chan1c0cb662017-01-30 07:13:30 +00002354 `Connection.set_app_data` and later retrieved with
2355 `Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002356 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002357 conn = Connection(Context(TLSv1_METHOD), None)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002358 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002359 app_data = object()
2360 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002361 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002362
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002363 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002364 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002365 `Connection.makefile` is not implemented and calling that
2366 method raises `NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002367 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002368 conn = Connection(Context(TLSv1_METHOD), None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002369 with pytest.raises(NotImplementedError):
2370 conn.makefile()
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002371
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002372 def test_get_peer_cert_chain(self):
2373 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002374 `Connection.get_peer_cert_chain` returns a list of certificates
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002375 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002376 """
2377 chain = _create_certificate_chain()
2378 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2379
2380 serverContext = Context(TLSv1_METHOD)
2381 serverContext.use_privatekey(skey)
2382 serverContext.use_certificate(scert)
2383 serverContext.add_extra_chain_cert(icert)
2384 serverContext.add_extra_chain_cert(cacert)
2385 server = Connection(serverContext, None)
2386 server.set_accept_state()
2387
2388 # Create the client
2389 clientContext = Context(TLSv1_METHOD)
2390 clientContext.set_verify(VERIFY_NONE, verify_cb)
2391 client = Connection(clientContext, None)
2392 client.set_connect_state()
2393
Alex Chan1c0cb662017-01-30 07:13:30 +00002394 interact_in_memory(client, server)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002395
2396 chain = client.get_peer_cert_chain()
Alex Chan1c0cb662017-01-30 07:13:30 +00002397 assert len(chain) == 3
2398 assert "Server Certificate" == chain[0].get_subject().CN
2399 assert "Intermediate Certificate" == chain[1].get_subject().CN
2400 assert "Authority Certificate" == chain[2].get_subject().CN
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002401
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002402 def test_get_peer_cert_chain_none(self):
2403 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002404 `Connection.get_peer_cert_chain` returns `None` if the peer sends
2405 no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002406 """
2407 ctx = Context(TLSv1_METHOD)
2408 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2409 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2410 server = Connection(ctx, None)
2411 server.set_accept_state()
2412 client = Connection(Context(TLSv1_METHOD), None)
2413 client.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002414 interact_in_memory(client, server)
2415 assert None is server.get_peer_cert_chain()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002416
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002417 def test_get_session_unconnected(self):
2418 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002419 `Connection.get_session` returns `None` when used with an object
2420 which has not been connected.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002421 """
2422 ctx = Context(TLSv1_METHOD)
2423 server = Connection(ctx, None)
2424 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002425 assert None is session
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002426
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002427 def test_server_get_session(self):
2428 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002429 On the server side of a connection, `Connection.get_session` returns a
2430 `Session` instance representing the SSL session for that connection.
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002431 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002432 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002433 session = server.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002434 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002435
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002436 def test_client_get_session(self):
2437 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002438 On the client side of a connection, `Connection.get_session`
2439 returns a `Session` instance representing the SSL session for
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002440 that connection.
2441 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002442 server, client = loopback()
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002443 session = client.get_session()
Alex Chan1c0cb662017-01-30 07:13:30 +00002444 assert isinstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002445
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002446 def test_set_session_wrong_args(self):
2447 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002448 `Connection.set_session` raises `TypeError` if called with an object
2449 that is not an instance of `Session`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002450 """
2451 ctx = Context(TLSv1_METHOD)
2452 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002453 with pytest.raises(TypeError):
2454 connection.set_session(123)
2455 with pytest.raises(TypeError):
2456 connection.set_session("hello")
2457 with pytest.raises(TypeError):
2458 connection.set_session(object())
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002459
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002460 def test_client_set_session(self):
2461 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002462 `Connection.set_session`, when used prior to a connection being
2463 established, accepts a `Session` instance and causes an attempt to
2464 re-use the session it represents when the SSL handshake is performed.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002465 """
2466 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2467 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2468 ctx = Context(TLSv1_METHOD)
2469 ctx.use_privatekey(key)
2470 ctx.use_certificate(cert)
2471 ctx.set_session_id("unity-test")
2472
2473 def makeServer(socket):
2474 server = Connection(ctx, socket)
2475 server.set_accept_state()
2476 return server
2477
Alex Chan1c0cb662017-01-30 07:13:30 +00002478 originalServer, originalClient = loopback(
2479 server_factory=makeServer)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002480 originalSession = originalClient.get_session()
2481
2482 def makeClient(socket):
Alex Chan1c0cb662017-01-30 07:13:30 +00002483 client = loopback_client_factory(socket)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002484 client.set_session(originalSession)
2485 return client
Alex Chan1c0cb662017-01-30 07:13:30 +00002486 resumedServer, resumedClient = loopback(
2487 server_factory=makeServer,
2488 client_factory=makeClient)
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002489
2490 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002491 # identifier for the session (new enough versions of OpenSSL expose
2492 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002493 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002494 # session is re-used. As long as the master key for the two
2495 # connections is the same, the session was re-used!
Alex Chan1c0cb662017-01-30 07:13:30 +00002496 assert originalServer.master_key() == resumedServer.master_key()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002497
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002498 def test_set_session_wrong_method(self):
2499 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002500 If `Connection.set_session` is passed a `Session` instance associated
2501 with a context using a different SSL method than the `Connection`
2502 is using, a `OpenSSL.SSL.Error` is raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002503 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002504 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2505 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2506 # is a way to check for 1.1.0)
Alex Gaynoraa32e712017-06-29 20:56:12 -07002507 if SSL_ST_INIT is None:
2508 v1 = TLSv1_2_METHOD
2509 v2 = TLSv1_METHOD
2510 elif hasattr(_lib, "SSLv3_method"):
Alex Gaynor5af32d02016-09-24 01:52:21 -04002511 v1 = TLSv1_METHOD
2512 v2 = SSLv3_METHOD
2513 else:
Alex Gaynoraa32e712017-06-29 20:56:12 -07002514 pytest.skip("Test requires either OpenSSL 1.1.0 or SSLv3")
Alex Gaynor5af32d02016-09-24 01:52:21 -04002515
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002516 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2517 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002518 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002519 ctx.use_privatekey(key)
2520 ctx.use_certificate(cert)
2521 ctx.set_session_id("unity-test")
2522
2523 def makeServer(socket):
2524 server = Connection(ctx, socket)
2525 server.set_accept_state()
2526 return server
2527
Alex Gaynor5af32d02016-09-24 01:52:21 -04002528 def makeOriginalClient(socket):
2529 client = Connection(Context(v1), socket)
2530 client.set_connect_state()
2531 return client
2532
Alex Chan1c0cb662017-01-30 07:13:30 +00002533 originalServer, originalClient = loopback(
2534 server_factory=makeServer, client_factory=makeOriginalClient)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002535 originalSession = originalClient.get_session()
2536
2537 def makeClient(socket):
2538 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002539 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002540 client.set_connect_state()
2541 client.set_session(originalSession)
2542 return client
2543
Alex Chan1c0cb662017-01-30 07:13:30 +00002544 with pytest.raises(Error):
2545 loopback(client_factory=makeClient, server_factory=makeServer)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002546
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002547 def test_wantWriteError(self):
2548 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002549 `Connection` methods which generate output raise
2550 `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002551 fail indicating a should-write state.
2552 """
2553 client_socket, server_socket = socket_pair()
2554 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002555 # anything. Only write a single byte at a time so we can be sure we
2556 # completely fill the buffer. Even though the socket API is allowed to
2557 # signal a short write via its return value it seems this doesn't
2558 # always happen on all platforms (FreeBSD and OS X particular) for the
2559 # very last bit of available buffer space.
2560 msg = b"x"
2561 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002562 try:
2563 client_socket.send(msg)
2564 except error as e:
2565 if e.errno == EWOULDBLOCK:
2566 break
2567 raise
2568 else:
Alex Chan1c0cb662017-01-30 07:13:30 +00002569 pytest.fail(
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002570 "Failed to fill socket buffer, cannot test BIO want write")
2571
2572 ctx = Context(TLSv1_METHOD)
2573 conn = Connection(ctx, client_socket)
2574 # Client's speak first, so make it an SSL client
2575 conn.set_connect_state()
Alex Chan1c0cb662017-01-30 07:13:30 +00002576 with pytest.raises(WantWriteError):
2577 conn.do_handshake()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002578
2579 # XXX want_read
2580
Fedor Brunner416f4a12014-03-28 13:18:38 +01002581 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002582 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002583 `Connection.get_finished` returns `None` before TLS handshake
2584 is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002585 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002586 ctx = Context(TLSv1_METHOD)
2587 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002588 assert connection.get_finished() is None
Fedor Brunner416f4a12014-03-28 13:18:38 +01002589
2590 def test_get_peer_finished_before_connect(self):
2591 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002592 `Connection.get_peer_finished` returns `None` before TLS handshake
2593 is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002594 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002595 ctx = Context(TLSv1_METHOD)
2596 connection = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002597 assert connection.get_peer_finished() is None
Fedor Brunner5747b932014-03-05 14:22:34 +01002598
Fedor Brunner416f4a12014-03-28 13:18:38 +01002599 def test_get_finished(self):
2600 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002601 `Connection.get_finished` method returns the TLS Finished message send
2602 from client, or server. Finished messages are send during
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002603 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002604 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002605 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002606
Alex Chan1c0cb662017-01-30 07:13:30 +00002607 assert server.get_finished() is not None
2608 assert len(server.get_finished()) > 0
Fedor Brunner416f4a12014-03-28 13:18:38 +01002609
2610 def test_get_peer_finished(self):
2611 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002612 `Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002613 message received from client, or server. Finished messages are send
2614 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002615 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002616 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002617
Alex Chan1c0cb662017-01-30 07:13:30 +00002618 assert server.get_peer_finished() is not None
2619 assert len(server.get_peer_finished()) > 0
Fedor Brunner5747b932014-03-05 14:22:34 +01002620
Fedor Brunner416f4a12014-03-28 13:18:38 +01002621 def test_tls_finished_message_symmetry(self):
2622 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002623 The TLS Finished message send by server must be the TLS Finished
2624 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002625
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002626 The TLS Finished message send by client must be the TLS Finished
2627 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002628 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002629 server, client = loopback()
Fedor Brunner416f4a12014-03-28 13:18:38 +01002630
Alex Chan1c0cb662017-01-30 07:13:30 +00002631 assert server.get_finished() == client.get_peer_finished()
2632 assert client.get_finished() == server.get_peer_finished()
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002633
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002634 def test_get_cipher_name_before_connect(self):
2635 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002636 `Connection.get_cipher_name` returns `None` if no connection
2637 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002638 """
2639 ctx = Context(TLSv1_METHOD)
2640 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002641 assert conn.get_cipher_name() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002642
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002643 def test_get_cipher_name(self):
2644 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002645 `Connection.get_cipher_name` returns a `unicode` string giving the
2646 name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002647 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002648 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002649 server_cipher_name, client_cipher_name = \
2650 server.get_cipher_name(), client.get_cipher_name()
2651
Alex Chan1c0cb662017-01-30 07:13:30 +00002652 assert isinstance(server_cipher_name, text_type)
2653 assert isinstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002654
Alex Chan1c0cb662017-01-30 07:13:30 +00002655 assert server_cipher_name == client_cipher_name
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002656
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002657 def test_get_cipher_version_before_connect(self):
2658 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002659 `Connection.get_cipher_version` returns `None` if no connection
2660 has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002661 """
2662 ctx = Context(TLSv1_METHOD)
2663 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002664 assert conn.get_cipher_version() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002665
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002666 def test_get_cipher_version(self):
2667 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002668 `Connection.get_cipher_version` returns a `unicode` string giving
2669 the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002670 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002671 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002672 server_cipher_version, client_cipher_version = \
2673 server.get_cipher_version(), client.get_cipher_version()
2674
Alex Chan1c0cb662017-01-30 07:13:30 +00002675 assert isinstance(server_cipher_version, text_type)
2676 assert isinstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002677
Alex Chan1c0cb662017-01-30 07:13:30 +00002678 assert server_cipher_version == client_cipher_version
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002679
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002680 def test_get_cipher_bits_before_connect(self):
2681 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002682 `Connection.get_cipher_bits` returns `None` if no connection has
2683 been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002684 """
2685 ctx = Context(TLSv1_METHOD)
2686 conn = Connection(ctx, None)
Alex Chan1c0cb662017-01-30 07:13:30 +00002687 assert conn.get_cipher_bits() is None
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002688
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002689 def test_get_cipher_bits(self):
2690 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002691 `Connection.get_cipher_bits` returns the number of secret bits
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002692 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002693 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002694 server, client = loopback()
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002695 server_cipher_bits, client_cipher_bits = \
2696 server.get_cipher_bits(), client.get_cipher_bits()
2697
Alex Chan1c0cb662017-01-30 07:13:30 +00002698 assert isinstance(server_cipher_bits, int)
2699 assert isinstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002700
Alex Chan1c0cb662017-01-30 07:13:30 +00002701 assert server_cipher_bits == client_cipher_bits
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002702
Jim Shaverabff1882015-05-27 09:15:55 -04002703 def test_get_protocol_version_name(self):
2704 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002705 `Connection.get_protocol_version_name()` returns a string giving the
2706 protocol version of the current connection.
Jim Shaverabff1882015-05-27 09:15:55 -04002707 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002708 server, client = loopback()
Jim Shaverabff1882015-05-27 09:15:55 -04002709 client_protocol_version_name = client.get_protocol_version_name()
2710 server_protocol_version_name = server.get_protocol_version_name()
2711
Alex Chan1c0cb662017-01-30 07:13:30 +00002712 assert isinstance(server_protocol_version_name, text_type)
2713 assert isinstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002714
Alex Chan1c0cb662017-01-30 07:13:30 +00002715 assert server_protocol_version_name == client_protocol_version_name
Jim Shaverabff1882015-05-27 09:15:55 -04002716
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002717 def test_get_protocol_version(self):
2718 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002719 `Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002720 giving the protocol version of the current connection.
2721 """
Alex Chan1c0cb662017-01-30 07:13:30 +00002722 server, client = loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002723 client_protocol_version = client.get_protocol_version()
2724 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002725
Alex Chan1c0cb662017-01-30 07:13:30 +00002726 assert isinstance(server_protocol_version, int)
2727 assert isinstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002728
Alex Chan1c0cb662017-01-30 07:13:30 +00002729 assert server_protocol_version == client_protocol_version
2730
2731 def test_wantReadError(self):
2732 """
2733 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
2734 no bytes available to be read from the BIO.
2735 """
2736 ctx = Context(TLSv1_METHOD)
2737 conn = Connection(ctx, None)
2738 with pytest.raises(WantReadError):
2739 conn.bio_read(1024)
2740
Alex Chanfb078d82017-04-20 11:16:15 +01002741 @pytest.mark.parametrize('bufsize', [1.0, None, object(), 'bufsize'])
2742 def test_bio_read_wrong_args(self, bufsize):
2743 """
2744 `Connection.bio_read` raises `TypeError` if passed a non-integer
2745 argument.
2746 """
2747 ctx = Context(TLSv1_METHOD)
2748 conn = Connection(ctx, None)
2749 with pytest.raises(TypeError):
2750 conn.bio_read(bufsize)
2751
Alex Chan1c0cb662017-01-30 07:13:30 +00002752 def test_buffer_size(self):
2753 """
2754 `Connection.bio_read` accepts an integer giving the maximum number
2755 of bytes to read and return.
2756 """
2757 ctx = Context(TLSv1_METHOD)
2758 conn = Connection(ctx, None)
2759 conn.set_connect_state()
2760 try:
2761 conn.do_handshake()
2762 except WantReadError:
2763 pass
2764 data = conn.bio_read(2)
2765 assert 2 == len(data)
2766
2767 @skip_if_py3
2768 def test_buffer_size_long(self):
2769 """
2770 On Python 2 `Connection.bio_read` accepts values of type `long` as
2771 well as `int`.
2772 """
2773 ctx = Context(TLSv1_METHOD)
2774 conn = Connection(ctx, None)
2775 conn.set_connect_state()
2776 try:
2777 conn.do_handshake()
2778 except WantReadError:
2779 pass
2780 data = conn.bio_read(long(2))
2781 assert 2 == len(data)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002782
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002783
Alex Chanb7480992017-01-30 14:04:47 +00002784class TestConnectionGetCipherList(object):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002785 """
Alex Chanb7480992017-01-30 14:04:47 +00002786 Tests for `Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002787 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002788 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002789 """
Alex Chanb7480992017-01-30 14:04:47 +00002790 `Connection.get_cipher_list` returns a list of `bytes` giving the
2791 names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002792 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002793 connection = Connection(Context(TLSv1_METHOD), None)
2794 ciphers = connection.get_cipher_list()
Alex Chanb7480992017-01-30 14:04:47 +00002795 assert isinstance(ciphers, list)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002796 for cipher in ciphers:
Alex Chanb7480992017-01-30 14:04:47 +00002797 assert isinstance(cipher, str)
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002798
2799
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002800class VeryLarge(bytes):
2801 """
2802 Mock object so that we don't have to allocate 2**31 bytes
2803 """
2804 def __len__(self):
2805 return 2**31
2806
2807
Alex Chanb7480992017-01-30 14:04:47 +00002808class TestConnectionSend(object):
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002809 """
Alex Chanb7480992017-01-30 14:04:47 +00002810 Tests for `Connection.send`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002811 """
2812 def test_wrong_args(self):
2813 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002814 When called with arguments other than string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00002815 parameter, `Connection.send` raises `TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002816 """
2817 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00002818 with pytest.raises(TypeError):
2819 connection.send(object())
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002820
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002821 def test_short_bytes(self):
2822 """
Alex Chanb7480992017-01-30 14:04:47 +00002823 When passed a short byte string, `Connection.send` transmits all of it
2824 and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002825 """
Alex Chanb7480992017-01-30 14:04:47 +00002826 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002827 count = server.send(b'xy')
Alex Chanb7480992017-01-30 14:04:47 +00002828 assert count == 2
2829 assert client.recv(2) == b'xy'
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002830
Abraham Martinef063482015-03-25 14:06:24 +00002831 def test_text(self):
2832 """
Alex Chanb7480992017-01-30 14:04:47 +00002833 When passed a text, `Connection.send` transmits all of it and
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002834 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002835 """
Alex Chanb7480992017-01-30 14:04:47 +00002836 server, client = loopback()
2837 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00002838 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002839 count = server.send(b"xy".decode("ascii"))
Alex Chanb7480992017-01-30 14:04:47 +00002840 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002841 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002842 WARNING_TYPE_EXPECTED
Alex Chanb7480992017-01-30 14:04:47 +00002843 ) == str(w[-1].message))
2844 assert count == 2
2845 assert client.recv(2) == b'xy'
Abraham Martinef063482015-03-25 14:06:24 +00002846
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002847 @skip_if_py26
2848 def test_short_memoryview(self):
2849 """
2850 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002851 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002852 of bytes sent.
2853 """
Alex Chanb7480992017-01-30 14:04:47 +00002854 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002855 count = server.send(memoryview(b'xy'))
Alex Chanb7480992017-01-30 14:04:47 +00002856 assert count == 2
2857 assert client.recv(2) == b'xy'
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002858
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002859 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002860 def test_short_buffer(self):
2861 """
2862 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00002863 `Connection.send` transmits all of them and returns the number
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002864 of bytes sent.
2865 """
Alex Chanb7480992017-01-30 14:04:47 +00002866 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002867 count = server.send(buffer(b'xy'))
Alex Chanb7480992017-01-30 14:04:47 +00002868 assert count == 2
2869 assert client.recv(2) == b'xy'
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002870
Maximilian Hils868dc3c2017-02-10 14:56:55 +01002871 @pytest.mark.skipif(
2872 sys.maxsize < 2**31,
2873 reason="sys.maxsize < 2**31 - test requires 64 bit"
2874 )
2875 def test_buf_too_large(self):
2876 """
2877 When passed a buffer containing >= 2**31 bytes,
2878 `Connection.send` bails out as SSL_write only
2879 accepts an int for the buffer length.
2880 """
2881 connection = Connection(Context(TLSv1_METHOD), None)
2882 with pytest.raises(ValueError) as exc_info:
2883 connection.send(VeryLarge())
2884 exc_info.match(r"Cannot send more than .+ bytes at once")
2885
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002886
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002887def _make_memoryview(size):
2888 """
2889 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2890 size.
2891 """
2892 return memoryview(bytearray(size))
2893
2894
Alex Chanb7480992017-01-30 14:04:47 +00002895class TestConnectionRecvInto(object):
Cory Benfield62d10332014-06-15 10:03:41 +01002896 """
Alex Chanb7480992017-01-30 14:04:47 +00002897 Tests for `Connection.recv_into`.
Cory Benfield62d10332014-06-15 10:03:41 +01002898 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002899 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002900 """
Alex Chanb7480992017-01-30 14:04:47 +00002901 Assert that when the given buffer is passed to `Connection.recv_into`,
2902 whatever bytes are available to be received that fit into that buffer
2903 are written into that buffer.
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002904 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002905 output_buffer = factory(5)
2906
Alex Chanb7480992017-01-30 14:04:47 +00002907 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002908 server.send(b'xy')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002909
Alex Chanb7480992017-01-30 14:04:47 +00002910 assert client.recv_into(output_buffer) == 2
2911 assert output_buffer == bytearray(b'xy\x00\x00\x00')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002912
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002913 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002914 """
Alex Chanb7480992017-01-30 14:04:47 +00002915 `Connection.recv_into` can be passed a `bytearray` instance and data
2916 in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002917 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002918 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002919
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002920 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002921 """
Alex Chanb7480992017-01-30 14:04:47 +00002922 Assert that when the given buffer is passed to `Connection.recv_into`
2923 along with a value for `nbytes` that is less than the size of that
2924 buffer, only `nbytes` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002925 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002926 output_buffer = factory(10)
2927
Alex Chanb7480992017-01-30 14:04:47 +00002928 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002929 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002930
Alex Chanb7480992017-01-30 14:04:47 +00002931 assert client.recv_into(output_buffer, 5) == 5
2932 assert output_buffer == bytearray(b'abcde\x00\x00\x00\x00\x00')
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002933
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002934 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002935 """
Alex Chanb7480992017-01-30 14:04:47 +00002936 When called with a `bytearray` instance, `Connection.recv_into`
2937 respects the `nbytes` parameter and doesn't copy in more than that
2938 number of bytes.
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002939 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002940 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002941
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002942 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002943 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002944 Assert that if there are more bytes available to be read from the
2945 receive buffer than would fit into the buffer passed to
Alex Chanb7480992017-01-30 14:04:47 +00002946 `Connection.recv_into`, only as many as fit are written into it.
Cory Benfield62d10332014-06-15 10:03:41 +01002947 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002948 output_buffer = factory(5)
2949
Alex Chanb7480992017-01-30 14:04:47 +00002950 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002951 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002952
Alex Chanb7480992017-01-30 14:04:47 +00002953 assert client.recv_into(output_buffer) == 5
2954 assert output_buffer == bytearray(b'abcde')
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002955 rest = client.recv(5)
Alex Chanb7480992017-01-30 14:04:47 +00002956 assert b'fghij' == rest
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002957
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002958 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002959 """
Alex Chanb7480992017-01-30 14:04:47 +00002960 When called with a `bytearray` instance, `Connection.recv_into`
2961 respects the size of the array and doesn't write more bytes into it
2962 than will fit.
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002963 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002964 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002965
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002966 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002967 """
Alex Chanb7480992017-01-30 14:04:47 +00002968 When called with a `bytearray` instance and an `nbytes` value that is
2969 too large, `Connection.recv_into` respects the size of the array and
2970 not the `nbytes` value and doesn't write more bytes into the buffer
2971 than will fit.
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002972 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002973 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002974
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002975 def test_peek(self):
Alex Chanb7480992017-01-30 14:04:47 +00002976 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002977 server.send(b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002978
2979 for _ in range(2):
2980 output_buffer = bytearray(5)
Alex Chanb7480992017-01-30 14:04:47 +00002981 assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
2982 assert output_buffer == bytearray(b'xy\x00\x00\x00')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002983
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002984 @skip_if_py26
2985 def test_memoryview_no_length(self):
2986 """
Alex Chanb7480992017-01-30 14:04:47 +00002987 `Connection.recv_into` can be passed a `memoryview` instance and data
2988 in the receive buffer is written to it.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002989 """
2990 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002991
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002992 @skip_if_py26
2993 def test_memoryview_respects_length(self):
2994 """
Alex Chanb7480992017-01-30 14:04:47 +00002995 When called with a `memoryview` instance, `Connection.recv_into`
2996 respects the ``nbytes`` parameter and doesn't copy more than that
2997 number of bytes in.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002998 """
2999 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003000
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003001 @skip_if_py26
3002 def test_memoryview_doesnt_overfill(self):
3003 """
Alex Chanb7480992017-01-30 14:04:47 +00003004 When called with a `memoryview` instance, `Connection.recv_into`
3005 respects the size of the array and doesn't write more bytes into it
3006 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003007 """
3008 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003009
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003010 @skip_if_py26
3011 def test_memoryview_really_doesnt_overfill(self):
3012 """
Alex Chanb7480992017-01-30 14:04:47 +00003013 When called with a `memoryview` instance and an `nbytes` value that is
3014 too large, `Connection.recv_into` respects the size of the array and
3015 not the `nbytes` value and doesn't write more bytes into the buffer
3016 than will fit.
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003017 """
3018 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003019
Cory Benfield62d10332014-06-15 10:03:41 +01003020
Alex Chanb7480992017-01-30 14:04:47 +00003021class TestConnectionSendall(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003022 """
Alex Chanb7480992017-01-30 14:04:47 +00003023 Tests for `Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003024 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003025 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003026 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003027 When called with arguments other than a string argument for its first
Alex Chanb7480992017-01-30 14:04:47 +00003028 parameter, `Connection.sendall` raises `TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003029 """
3030 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003031 with pytest.raises(TypeError):
3032 connection.sendall(object())
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003033
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003034 def test_short(self):
3035 """
Alex Chanb7480992017-01-30 14:04:47 +00003036 `Connection.sendall` transmits all of the bytes in the string
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003037 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003038 """
Alex Chanb7480992017-01-30 14:04:47 +00003039 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003040 server.sendall(b'x')
Alex Chanb7480992017-01-30 14:04:47 +00003041 assert client.recv(1) == b'x'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003042
Abraham Martinef063482015-03-25 14:06:24 +00003043 def test_text(self):
3044 """
Alex Chanb7480992017-01-30 14:04:47 +00003045 `Connection.sendall` transmits all the content in the string passed
3046 to it, raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003047 """
Alex Chanb7480992017-01-30 14:04:47 +00003048 server, client = loopback()
3049 with pytest.warns(DeprecationWarning) as w:
Abraham Martinef063482015-03-25 14:06:24 +00003050 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003051 server.sendall(b"x".decode("ascii"))
Alex Chanb7480992017-01-30 14:04:47 +00003052 assert (
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003053 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003054 WARNING_TYPE_EXPECTED
Alex Chanb7480992017-01-30 14:04:47 +00003055 ) == str(w[-1].message))
3056 assert client.recv(1) == b"x"
Abraham Martinef063482015-03-25 14:06:24 +00003057
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003058 @skip_if_py26
3059 def test_short_memoryview(self):
3060 """
3061 When passed a memoryview onto a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003062 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003063 """
Alex Chanb7480992017-01-30 14:04:47 +00003064 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003065 server.sendall(memoryview(b'x'))
Alex Chanb7480992017-01-30 14:04:47 +00003066 assert client.recv(1) == b'x'
Abraham Martinef063482015-03-25 14:06:24 +00003067
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003068 @skip_if_py3
3069 def test_short_buffers(self):
3070 """
3071 When passed a buffer containing a small number of bytes,
Alex Chanb7480992017-01-30 14:04:47 +00003072 `Connection.sendall` transmits all of them.
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003073 """
Alex Chanb7480992017-01-30 14:04:47 +00003074 server, client = loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003075 server.sendall(buffer(b'x'))
Alex Chanb7480992017-01-30 14:04:47 +00003076 assert client.recv(1) == b'x'
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003077
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003078 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003079 """
Alex Chanb7480992017-01-30 14:04:47 +00003080 `Connection.sendall` transmits all the bytes in the string passed to it
3081 even if this requires multiple calls of an underlying write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003082 """
Alex Chanb7480992017-01-30 14:04:47 +00003083 server, client = loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003084 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003085 # On Windows, after 32k of bytes the write will block (forever
3086 # - because no one is yet reading).
Alex Gaynore7f51982016-09-11 11:48:14 -04003087 message = b'x' * (1024 * 32 - 1) + b'y'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003088 server.sendall(message)
3089 accum = []
3090 received = 0
3091 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003092 data = client.recv(1024)
3093 accum.append(data)
3094 received += len(data)
Alex Chanb7480992017-01-30 14:04:47 +00003095 assert message == b''.join(accum)
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003096
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003097 def test_closed(self):
3098 """
Alex Chanb7480992017-01-30 14:04:47 +00003099 If the underlying socket is closed, `Connection.sendall` propagates the
3100 write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003101 """
Alex Chanb7480992017-01-30 14:04:47 +00003102 server, client = loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003103 server.sock_shutdown(2)
Alex Chanb7480992017-01-30 14:04:47 +00003104 with pytest.raises(SysCallError) as err:
3105 server.sendall(b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003106 if platform == "win32":
Alex Chanb7480992017-01-30 14:04:47 +00003107 assert err.value.args[0] == ESHUTDOWN
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003108 else:
Alex Chanb7480992017-01-30 14:04:47 +00003109 assert err.value.args[0] == EPIPE
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003110
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003111
Alex Chanb7480992017-01-30 14:04:47 +00003112class TestConnectionRenegotiate(object):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003113 """
3114 Tests for SSL renegotiation APIs.
3115 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003116 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003117 """
Alex Chanb7480992017-01-30 14:04:47 +00003118 `Connection.total_renegotiations` returns `0` before any renegotiations
3119 have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003120 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003121 connection = Connection(Context(TLSv1_METHOD), None)
Alex Chanb7480992017-01-30 14:04:47 +00003122 assert connection.total_renegotiations() == 0
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003123
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003124 def test_renegotiate(self):
3125 """
3126 Go through a complete renegotiation cycle.
3127 """
Alex Chanb7480992017-01-30 14:04:47 +00003128 server, client = loopback()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003129
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003130 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003131
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003132 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003133
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003134 assert 0 == server.total_renegotiations()
3135 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003136
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003137 assert True is server.renegotiate()
3138
3139 assert True is server.renegotiate_pending()
3140
3141 server.setblocking(False)
3142 client.setblocking(False)
3143
3144 client.do_handshake()
3145 server.do_handshake()
3146
3147 assert 1 == server.total_renegotiations()
3148 while False is server.renegotiate_pending():
3149 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003150
3151
Alex Chanb7480992017-01-30 14:04:47 +00003152class TestError(object):
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003153 """
Alex Chanb7480992017-01-30 14:04:47 +00003154 Unit tests for `OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003155 """
3156 def test_type(self):
3157 """
Alex Chanb7480992017-01-30 14:04:47 +00003158 `Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003159 """
Alex Chanb7480992017-01-30 14:04:47 +00003160 assert issubclass(Error, Exception)
3161 assert Error.__name__ == 'Error'
Rick Deane15b1472009-07-09 15:53:42 -05003162
3163
Alex Chanb7480992017-01-30 14:04:47 +00003164class TestConstants(object):
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003165 """
Alex Chanb7480992017-01-30 14:04:47 +00003166 Tests for the values of constants exposed in `OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003167
3168 These are values defined by OpenSSL intended only to be used as flags to
3169 OpenSSL APIs. The only assertions it seems can be made about them is
3170 their values.
3171 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003172 @pytest.mark.skipif(
3173 OP_NO_QUERY_MTU is None,
3174 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3175 )
3176 def test_op_no_query_mtu(self):
3177 """
Alex Chanb7480992017-01-30 14:04:47 +00003178 The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3179 of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003180 """
Alex Chanb7480992017-01-30 14:04:47 +00003181 assert OP_NO_QUERY_MTU == 0x1000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003182
Hynek Schlawack35618382015-09-05 21:54:25 +02003183 @pytest.mark.skipif(
3184 OP_COOKIE_EXCHANGE is None,
3185 reason="OP_COOKIE_EXCHANGE unavailable - "
3186 "OpenSSL version may be too old"
3187 )
3188 def test_op_cookie_exchange(self):
3189 """
Alex Chanb7480992017-01-30 14:04:47 +00003190 The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3191 value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003192 """
Alex Chanb7480992017-01-30 14:04:47 +00003193 assert OP_COOKIE_EXCHANGE == 0x2000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003194
Hynek Schlawack35618382015-09-05 21:54:25 +02003195 @pytest.mark.skipif(
3196 OP_NO_TICKET is None,
3197 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3198 )
3199 def test_op_no_ticket(self):
3200 """
Alex Chanb7480992017-01-30 14:04:47 +00003201 The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3202 `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003203 """
Alex Chanb7480992017-01-30 14:04:47 +00003204 assert OP_NO_TICKET == 0x4000
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003205
Hynek Schlawack35618382015-09-05 21:54:25 +02003206 @pytest.mark.skipif(
3207 OP_NO_COMPRESSION is None,
3208 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3209 )
3210 def test_op_no_compression(self):
3211 """
Alex Chanb7480992017-01-30 14:04:47 +00003212 The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3213 value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003214 """
Alex Chanb7480992017-01-30 14:04:47 +00003215 assert OP_NO_COMPRESSION == 0x20000
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003216
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003217 def test_sess_cache_off(self):
3218 """
Alex Chanb7480992017-01-30 14:04:47 +00003219 The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3220 `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003221 """
Alex Chanb7480992017-01-30 14:04:47 +00003222 assert 0x0 == SESS_CACHE_OFF
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003223
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003224 def test_sess_cache_client(self):
3225 """
Alex Chanb7480992017-01-30 14:04:47 +00003226 The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3227 `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003228 """
Alex Chanb7480992017-01-30 14:04:47 +00003229 assert 0x1 == SESS_CACHE_CLIENT
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003230
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003231 def test_sess_cache_server(self):
3232 """
Alex Chanb7480992017-01-30 14:04:47 +00003233 The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3234 `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003235 """
Alex Chanb7480992017-01-30 14:04:47 +00003236 assert 0x2 == SESS_CACHE_SERVER
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003237
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003238 def test_sess_cache_both(self):
3239 """
Alex Chanb7480992017-01-30 14:04:47 +00003240 The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3241 `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003242 """
Alex Chanb7480992017-01-30 14:04:47 +00003243 assert 0x3 == SESS_CACHE_BOTH
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003244
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003245 def test_sess_cache_no_auto_clear(self):
3246 """
Alex Chanb7480992017-01-30 14:04:47 +00003247 The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3248 value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3249 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003250 """
Alex Chanb7480992017-01-30 14:04:47 +00003251 assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003252
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003253 def test_sess_cache_no_internal_lookup(self):
3254 """
Alex Chanb7480992017-01-30 14:04:47 +00003255 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3256 the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3257 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003258 """
Alex Chanb7480992017-01-30 14:04:47 +00003259 assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003260
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003261 def test_sess_cache_no_internal_store(self):
3262 """
Alex Chanb7480992017-01-30 14:04:47 +00003263 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3264 the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3265 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003266 """
Alex Chanb7480992017-01-30 14:04:47 +00003267 assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003268
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003269 def test_sess_cache_no_internal(self):
3270 """
Alex Chanb7480992017-01-30 14:04:47 +00003271 The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3272 value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
3273 `openssl/ssl.h`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003274 """
Alex Chanb7480992017-01-30 14:04:47 +00003275 assert 0x300 == SESS_CACHE_NO_INTERNAL
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003276
3277
Alex Chanb7480992017-01-30 14:04:47 +00003278class TestMemoryBIO(object):
Rick Deanb71c0d22009-04-01 14:09:23 -05003279 """
Alex Chanb7480992017-01-30 14:04:47 +00003280 Tests for `OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003281 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003282 def _server(self, sock):
3283 """
Alex Chanb7480992017-01-30 14:04:47 +00003284 Create a new server-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003285 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003286 # Create the server side Connection. This is mostly setup boilerplate
3287 # - use TLSv1, use a particular certificate, etc.
3288 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003289 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003290 server_ctx.set_verify(
3291 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3292 verify_cb
3293 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003294 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003295 server_ctx.use_privatekey(
3296 load_privatekey(FILETYPE_PEM, server_key_pem))
3297 server_ctx.use_certificate(
3298 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003299 server_ctx.check_privatekey()
3300 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003301 # Here the Connection is actually created. If None is passed as the
3302 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003303 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003304 server_conn.set_accept_state()
3305 return server_conn
3306
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003307 def _client(self, sock):
3308 """
Alex Chanb7480992017-01-30 14:04:47 +00003309 Create a new client-side SSL `Connection` object wrapped around `sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003310 """
3311 # Now create the client side Connection. Similar boilerplate to the
3312 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003313 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003314 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003315 client_ctx.set_verify(
3316 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3317 verify_cb
3318 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003319 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003320 client_ctx.use_privatekey(
3321 load_privatekey(FILETYPE_PEM, client_key_pem))
3322 client_ctx.use_certificate(
3323 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003324 client_ctx.check_privatekey()
3325 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003326 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003327 client_conn.set_connect_state()
3328 return client_conn
3329
Alex Chanb7480992017-01-30 14:04:47 +00003330 def test_memory_connect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003331 """
Alex Chanb7480992017-01-30 14:04:47 +00003332 Two `Connection`s which use memory BIOs can be manually connected by
3333 reading from the output of each and writing those bytes to the input of
3334 the other and in this way establish a connection and exchange
3335 application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003336 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003337 server_conn = self._server(None)
3338 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003339
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003340 # There should be no key or nonces yet.
Alex Chanb7480992017-01-30 14:04:47 +00003341 assert server_conn.master_key() is None
3342 assert server_conn.client_random() is None
3343 assert server_conn.server_random() is None
Rick Deanb71c0d22009-04-01 14:09:23 -05003344
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003345 # First, the handshake needs to happen. We'll deliver bytes back and
3346 # forth between the client and server until neither of them feels like
3347 # speaking any more.
Alex Chanb7480992017-01-30 14:04:47 +00003348 assert interact_in_memory(client_conn, server_conn) is None
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003349
3350 # Now that the handshake is done, there should be a key and nonces.
Alex Chanb7480992017-01-30 14:04:47 +00003351 assert server_conn.master_key() is not None
3352 assert server_conn.client_random() is not None
3353 assert server_conn.server_random() is not None
3354 assert server_conn.client_random() == client_conn.client_random()
3355 assert server_conn.server_random() == client_conn.server_random()
3356 assert server_conn.client_random() != server_conn.server_random()
3357 assert client_conn.client_random() != client_conn.server_random()
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003358
3359 # Here are the bytes we'll try to send.
Alex Gaynore7f51982016-09-11 11:48:14 -04003360 important_message = b'One if by land, two if by sea.'
Rick Deanb71c0d22009-04-01 14:09:23 -05003361
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003362 server_conn.write(important_message)
Alex Chanb7480992017-01-30 14:04:47 +00003363 assert (
3364 interact_in_memory(client_conn, server_conn) ==
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003365 (client_conn, important_message))
3366
3367 client_conn.write(important_message[::-1])
Alex Chanb7480992017-01-30 14:04:47 +00003368 assert (
3369 interact_in_memory(client_conn, server_conn) ==
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003370 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003371
Alex Chanb7480992017-01-30 14:04:47 +00003372 def test_socket_connect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003373 """
Alex Chanb7480992017-01-30 14:04:47 +00003374 Just like `test_memory_connect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003375
Hynek Schlawack35618382015-09-05 21:54:25 +02003376 This is primarily to rule out the memory BIO code as the source of any
Alex Chanb7480992017-01-30 14:04:47 +00003377 problems encountered while passing data over a `Connection` (if
Hynek Schlawack35618382015-09-05 21:54:25 +02003378 this test fails, there must be a problem outside the memory BIO code,
3379 as no memory BIO is involved here). Even though this isn't a memory
3380 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003381 """
Alex Chanb7480992017-01-30 14:04:47 +00003382 server_conn, client_conn = loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003383
Alex Gaynore7f51982016-09-11 11:48:14 -04003384 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003385 client_conn.send(important_message)
3386 msg = server_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003387 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003388
3389 # Again in the other direction, just for fun.
3390 important_message = important_message[::-1]
3391 server_conn.send(important_message)
3392 msg = client_conn.recv(1024)
Alex Chanb7480992017-01-30 14:04:47 +00003393 assert msg == important_message
Rick Deanb1ccd562009-07-09 23:52:39 -05003394
Alex Chanb7480992017-01-30 14:04:47 +00003395 def test_socket_overrides_memory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003396 """
Alex Chanb7480992017-01-30 14:04:47 +00003397 Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
3398 work on `OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003399 """
Alex Gaynor51d424c2016-09-10 14:50:11 -04003400 context = Context(TLSv1_METHOD)
Rick Deanb71c0d22009-04-01 14:09:23 -05003401 client = socket()
3402 clientSSL = Connection(context, client)
Alex Chanb7480992017-01-30 14:04:47 +00003403 with pytest.raises(TypeError):
3404 clientSSL.bio_read(100)
3405 with pytest.raises(TypeError):
3406 clientSSL.bio_write("foo")
3407 with pytest.raises(TypeError):
3408 clientSSL.bio_shutdown()
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003409
Alex Chanb7480992017-01-30 14:04:47 +00003410 def test_outgoing_overflow(self):
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003411 """
3412 If more bytes than can be written to the memory BIO are passed to
Alex Chanb7480992017-01-30 14:04:47 +00003413 `Connection.send` at once, the number of bytes which were written is
3414 returned and that many bytes from the beginning of the input can be
3415 read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003416 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003417 server = self._server(None)
3418 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003419
Alex Chanb7480992017-01-30 14:04:47 +00003420 interact_in_memory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003421
3422 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003423 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003424 # Sanity check. We're trying to test what happens when the entire
3425 # input can't be sent. If the entire input was sent, this test is
3426 # meaningless.
Alex Chanb7480992017-01-30 14:04:47 +00003427 assert sent < size
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003428
Alex Chanb7480992017-01-30 14:04:47 +00003429 receiver, received = interact_in_memory(client, server)
3430 assert receiver is server
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003431
3432 # We can rely on all of these bytes being received at once because
Alex Chanb7480992017-01-30 14:04:47 +00003433 # loopback passes 2 ** 16 to recv - more than 2 ** 15.
3434 assert len(received) == sent
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003435
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003436 def test_shutdown(self):
3437 """
Alex Chanb7480992017-01-30 14:04:47 +00003438 `Connection.bio_shutdown` signals the end of the data stream
3439 from which the `Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003440 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003441 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003442 server.bio_shutdown()
Alex Chanb7480992017-01-30 14:04:47 +00003443 with pytest.raises(Error) as err:
3444 server.recv(1024)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003445 # We don't want WantReadError or ZeroReturnError or anything - it's a
3446 # handshake failure.
Alex Chanb7480992017-01-30 14:04:47 +00003447 assert type(err.value) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003448
Alex Chanb7480992017-01-30 14:04:47 +00003449 def test_unexpected_EOF(self):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003450 """
3451 If the connection is lost before an orderly SSL shutdown occurs,
Alex Chanb7480992017-01-30 14:04:47 +00003452 `OpenSSL.SSL.SysCallError` is raised with a message of
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003453 "Unexpected EOF".
3454 """
Alex Chanb7480992017-01-30 14:04:47 +00003455 server_conn, client_conn = loopback()
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003456 client_conn.sock_shutdown(SHUT_RDWR)
Alex Chanb7480992017-01-30 14:04:47 +00003457 with pytest.raises(SysCallError) as err:
3458 server_conn.recv(1024)
3459 assert err.value.args == (-1, "Unexpected EOF")
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003460
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003461 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003462 """
Alex Chanb7480992017-01-30 14:04:47 +00003463 Verify the return value of the `get_client_ca_list` method for
Hynek Schlawack35618382015-09-05 21:54:25 +02003464 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003465
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003466 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003467 before the client and server are connected to each other. This
3468 function should specify a list of CAs for the server to send to the
3469 client and return that same list. The list will be used to verify
Alex Chanb7480992017-01-30 14:04:47 +00003470 that `get_client_ca_list` returns the proper value at
Hynek Schlawack35618382015-09-05 21:54:25 +02003471 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003472 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003473 server = self._server(None)
3474 client = self._client(None)
Alex Chanb7480992017-01-30 14:04:47 +00003475 assert client.get_client_ca_list() == []
3476 assert server.get_client_ca_list() == []
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003477 ctx = server.get_context()
3478 expected = func(ctx)
Alex Chanb7480992017-01-30 14:04:47 +00003479 assert client.get_client_ca_list() == []
3480 assert server.get_client_ca_list() == expected
3481 interact_in_memory(client, server)
3482 assert client.get_client_ca_list() == expected
3483 assert server.get_client_ca_list() == expected
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003484
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003485 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003486 """
Alex Chanb7480992017-01-30 14:04:47 +00003487 `Context.set_client_ca_list` raises a `TypeError` if called with a
3488 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003489 """
3490 ctx = Context(TLSv1_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003491 with pytest.raises(TypeError):
3492 ctx.set_client_ca_list("spam")
3493 with pytest.raises(TypeError):
3494 ctx.set_client_ca_list(["spam"])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003495
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003496 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003497 """
Alex Chanb7480992017-01-30 14:04:47 +00003498 If passed an empty list, `Context.set_client_ca_list` configures the
3499 context to send no CA names to the client and, on both the server and
3500 client sides, `Connection.get_client_ca_list` returns an empty list
3501 after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003502 """
3503 def no_ca(ctx):
3504 ctx.set_client_ca_list([])
3505 return []
3506 self._check_client_ca_list(no_ca)
3507
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003508 def test_set_one_ca_list(self):
3509 """
3510 If passed a list containing a single X509Name,
Alex Chanb7480992017-01-30 14:04:47 +00003511 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003512 that CA name to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003513 `Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003514 X509Name after the connection is set up.
3515 """
3516 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3517 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003518
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003519 def single_ca(ctx):
3520 ctx.set_client_ca_list([cadesc])
3521 return [cadesc]
3522 self._check_client_ca_list(single_ca)
3523
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003524 def test_set_multiple_ca_list(self):
3525 """
3526 If passed a list containing multiple X509Name objects,
Alex Chanb7480992017-01-30 14:04:47 +00003527 `Context.set_client_ca_list` configures the context to send
Hynek Schlawack35618382015-09-05 21:54:25 +02003528 those CA names to the client and, on both the server and client sides,
Alex Chanb7480992017-01-30 14:04:47 +00003529 `Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003530 X509Names after the connection is set up.
3531 """
3532 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3533 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3534
3535 sedesc = secert.get_subject()
3536 cldesc = clcert.get_subject()
3537
3538 def multiple_ca(ctx):
3539 L = [sedesc, cldesc]
3540 ctx.set_client_ca_list(L)
3541 return L
3542 self._check_client_ca_list(multiple_ca)
3543
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003544 def test_reset_ca_list(self):
3545 """
3546 If called multiple times, only the X509Names passed to the final call
Alex Chanb7480992017-01-30 14:04:47 +00003547 of `Context.set_client_ca_list` are used to configure the CA
Hynek Schlawack35618382015-09-05 21:54:25 +02003548 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003549 """
3550 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3551 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3552 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3553
3554 cadesc = cacert.get_subject()
3555 sedesc = secert.get_subject()
3556 cldesc = clcert.get_subject()
3557
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003558 def changed_ca(ctx):
3559 ctx.set_client_ca_list([sedesc, cldesc])
3560 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003561 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003562 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003563
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003564 def test_mutated_ca_list(self):
3565 """
Alex Chanb7480992017-01-30 14:04:47 +00003566 If the list passed to `Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003567 afterwards, this does not affect the list of CA names sent to the
3568 client.
3569 """
3570 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3571 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3572
3573 cadesc = cacert.get_subject()
3574 sedesc = secert.get_subject()
3575
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003576 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003577 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003578 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003579 L.append(sedesc)
3580 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003581 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003582
Alex Chanb7480992017-01-30 14:04:47 +00003583 def test_add_client_ca_wrong_args(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003584 """
Alex Chanb7480992017-01-30 14:04:47 +00003585 `Context.add_client_ca` raises `TypeError` if called with
3586 a non-X509 object.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003587 """
3588 ctx = Context(TLSv1_METHOD)
Alex Chanb7480992017-01-30 14:04:47 +00003589 with pytest.raises(TypeError):
3590 ctx.add_client_ca("spam")
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003591
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003592 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003593 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003594 A certificate's subject can be added as a CA to be sent to the client
Alex Chanb7480992017-01-30 14:04:47 +00003595 with `Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003596 """
3597 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3598 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003599
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003600 def single_ca(ctx):
3601 ctx.add_client_ca(cacert)
3602 return [cadesc]
3603 self._check_client_ca_list(single_ca)
3604
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003605 def test_multiple_add_client_ca(self):
3606 """
3607 Multiple CA names can be sent to the client by calling
Alex Chanb7480992017-01-30 14:04:47 +00003608 `Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003609 """
3610 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3611 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3612
3613 cadesc = cacert.get_subject()
3614 sedesc = secert.get_subject()
3615
3616 def multiple_ca(ctx):
3617 ctx.add_client_ca(cacert)
3618 ctx.add_client_ca(secert)
3619 return [cadesc, sedesc]
3620 self._check_client_ca_list(multiple_ca)
3621
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003622 def test_set_and_add_client_ca(self):
3623 """
Alex Chanb7480992017-01-30 14:04:47 +00003624 A call to `Context.set_client_ca_list` followed by a call to
3625 `Context.add_client_ca` results in using the CA names from the
Hynek Schlawack35618382015-09-05 21:54:25 +02003626 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003627 """
3628 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3629 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3630 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3631
3632 cadesc = cacert.get_subject()
3633 sedesc = secert.get_subject()
3634 cldesc = clcert.get_subject()
3635
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003636 def mixed_set_add_ca(ctx):
3637 ctx.set_client_ca_list([cadesc, sedesc])
3638 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003639 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003640 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003641
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003642 def test_set_after_add_client_ca(self):
3643 """
Alex Chanb7480992017-01-30 14:04:47 +00003644 A call to `Context.set_client_ca_list` after a call to
3645 `Context.add_client_ca` replaces the CA name specified by the
Hynek Schlawack35618382015-09-05 21:54:25 +02003646 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003647 """
3648 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3649 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3650 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3651
3652 cadesc = cacert.get_subject()
3653 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003654
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003655 def set_replaces_add_ca(ctx):
3656 ctx.add_client_ca(clcert)
3657 ctx.set_client_ca_list([cadesc])
3658 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003659 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003660 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003661
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003662
Alex Chanb7480992017-01-30 14:04:47 +00003663class TestInfoConstants(object):
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003664 """
3665 Tests for assorted constants exposed for use in info callbacks.
3666 """
3667 def test_integers(self):
3668 """
3669 All of the info constants are integers.
3670
3671 This is a very weak test. It would be nice to have one that actually
3672 verifies that as certain info events happen, the value passed to the
3673 info callback matches up with the constant exposed by OpenSSL.SSL.
3674 """
3675 for const in [
Alex Gaynor5af32d02016-09-24 01:52:21 -04003676 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003677 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3678 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3679 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003680 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3681 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003682 assert isinstance(const, int)
3683
3684 # These constants don't exist on OpenSSL 1.1.0
3685 for const in [
3686 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
3687 ]:
3688 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003689
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003690
Cory Benfield1d142142016-03-30 11:51:45 +01003691class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003692 """
3693 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003694 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003695 """
3696 def test_available(self):
3697 """
3698 When the OpenSSL functionality is available the decorated functions
3699 work appropriately.
3700 """
3701 feature_guard = _make_requires(True, "Error text")
3702 results = []
3703
3704 @feature_guard
3705 def inner():
3706 results.append(True)
3707 return True
3708
Cory Benfield2333e5e2016-03-30 14:24:16 +01003709 assert inner() is True
3710 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003711
3712 def test_unavailable(self):
3713 """
3714 When the OpenSSL functionality is not available the decorated function
3715 does not execute and NotImplementedError is raised.
3716 """
3717 feature_guard = _make_requires(False, "Error text")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003718
3719 @feature_guard
Alex Chanfb078d82017-04-20 11:16:15 +01003720 def inner(): # pragma: nocover
3721 pytest.fail("Should not be called")
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003722
Cory Benfield1d142142016-03-30 11:51:45 +01003723 with pytest.raises(NotImplementedError) as e:
3724 inner()
3725
3726 assert "Error text" in str(e.value)
Cory Benfield496652a2017-01-24 11:42:56 +00003727
3728
Alex Chanb7480992017-01-30 14:04:47 +00003729class TestOCSP(object):
Cory Benfield496652a2017-01-24 11:42:56 +00003730 """
3731 Tests for PyOpenSSL's OCSP stapling support.
3732 """
3733 sample_ocsp_data = b"this is totally ocsp data"
3734
3735 def _client_connection(self, callback, data, request_ocsp=True):
3736 """
3737 Builds a client connection suitable for using OCSP.
3738
3739 :param callback: The callback to register for OCSP.
3740 :param data: The opaque data object that will be handed to the
3741 OCSP callback.
3742 :param request_ocsp: Whether the client will actually ask for OCSP
3743 stapling. Useful for testing only.
3744 """
3745 ctx = Context(SSLv23_METHOD)
3746 ctx.set_ocsp_client_callback(callback, data)
3747 client = Connection(ctx)
3748
3749 if request_ocsp:
3750 client.request_ocsp()
3751
3752 client.set_connect_state()
3753 return client
3754
3755 def _server_connection(self, callback, data):
3756 """
3757 Builds a server connection suitable for using OCSP.
3758
3759 :param callback: The callback to register for OCSP.
3760 :param data: The opaque data object that will be handed to the
3761 OCSP callback.
3762 """
3763 ctx = Context(SSLv23_METHOD)
3764 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
3765 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
3766 ctx.set_ocsp_server_callback(callback, data)
3767 server = Connection(ctx)
3768 server.set_accept_state()
3769 return server
3770
3771 def test_callbacks_arent_called_by_default(self):
3772 """
3773 If both the client and the server have registered OCSP callbacks, but
3774 the client does not send the OCSP request, neither callback gets
3775 called.
3776 """
Alex Chanfb078d82017-04-20 11:16:15 +01003777 def ocsp_callback(*args, **kwargs): # pragma: nocover
3778 pytest.fail("Should not be called")
Cory Benfield496652a2017-01-24 11:42:56 +00003779
3780 client = self._client_connection(
3781 callback=ocsp_callback, data=None, request_ocsp=False
3782 )
3783 server = self._server_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003784 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003785
Cory Benfield496652a2017-01-24 11:42:56 +00003786 def test_client_negotiates_without_server(self):
3787 """
3788 If the client wants to do OCSP but the server does not, the handshake
3789 succeeds, and the client callback fires with an empty byte string.
3790 """
3791 called = []
3792
3793 def ocsp_callback(conn, ocsp_data, ignored):
3794 called.append(ocsp_data)
3795 return True
3796
3797 client = self._client_connection(callback=ocsp_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003798 server = loopback_server_factory(socket=None)
3799 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003800
3801 assert len(called) == 1
3802 assert called[0] == b''
3803
3804 def test_client_receives_servers_data(self):
3805 """
3806 The data the server sends in its callback is received by the client.
3807 """
3808 calls = []
3809
3810 def server_callback(*args, **kwargs):
3811 return self.sample_ocsp_data
3812
3813 def client_callback(conn, ocsp_data, ignored):
3814 calls.append(ocsp_data)
3815 return True
3816
3817 client = self._client_connection(callback=client_callback, data=None)
3818 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003819 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003820
3821 assert len(calls) == 1
3822 assert calls[0] == self.sample_ocsp_data
3823
3824 def test_callbacks_are_invoked_with_connections(self):
3825 """
3826 The first arguments to both callbacks are their respective connections.
3827 """
3828 client_calls = []
3829 server_calls = []
3830
3831 def client_callback(conn, *args, **kwargs):
3832 client_calls.append(conn)
3833 return True
3834
3835 def server_callback(conn, *args, **kwargs):
3836 server_calls.append(conn)
3837 return self.sample_ocsp_data
3838
3839 client = self._client_connection(callback=client_callback, data=None)
3840 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003841 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003842
3843 assert len(client_calls) == 1
3844 assert len(server_calls) == 1
3845 assert client_calls[0] is client
3846 assert server_calls[0] is server
3847
3848 def test_opaque_data_is_passed_through(self):
3849 """
3850 Both callbacks receive an opaque, user-provided piece of data in their
3851 callbacks as the final argument.
3852 """
3853 calls = []
3854
3855 def server_callback(*args):
3856 calls.append(args)
3857 return self.sample_ocsp_data
3858
3859 def client_callback(*args):
3860 calls.append(args)
3861 return True
3862
3863 sentinel = object()
3864
3865 client = self._client_connection(
3866 callback=client_callback, data=sentinel
3867 )
3868 server = self._server_connection(
3869 callback=server_callback, data=sentinel
3870 )
Alex Chanb7480992017-01-30 14:04:47 +00003871 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003872
3873 assert len(calls) == 2
3874 assert calls[0][-1] is sentinel
3875 assert calls[1][-1] is sentinel
3876
3877 def test_server_returns_empty_string(self):
3878 """
3879 If the server returns an empty bytestring from its callback, the
3880 client callback is called with the empty bytestring.
3881 """
3882 client_calls = []
3883
3884 def server_callback(*args):
3885 return b''
3886
3887 def client_callback(conn, ocsp_data, ignored):
3888 client_calls.append(ocsp_data)
3889 return True
3890
3891 client = self._client_connection(callback=client_callback, data=None)
3892 server = self._server_connection(callback=server_callback, data=None)
Alex Chanb7480992017-01-30 14:04:47 +00003893 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003894
3895 assert len(client_calls) == 1
3896 assert client_calls[0] == b''
3897
3898 def test_client_returns_false_terminates_handshake(self):
3899 """
3900 If the client returns False from its callback, the handshake fails.
3901 """
3902 def server_callback(*args):
3903 return self.sample_ocsp_data
3904
3905 def client_callback(*args):
3906 return False
3907
3908 client = self._client_connection(callback=client_callback, data=None)
3909 server = self._server_connection(callback=server_callback, data=None)
3910
3911 with pytest.raises(Error):
Alex Chanb7480992017-01-30 14:04:47 +00003912 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003913
3914 def test_exceptions_in_client_bubble_up(self):
3915 """
3916 The callbacks thrown in the client callback bubble up to the caller.
3917 """
3918 class SentinelException(Exception):
3919 pass
3920
3921 def server_callback(*args):
3922 return self.sample_ocsp_data
3923
3924 def client_callback(*args):
3925 raise SentinelException()
3926
3927 client = self._client_connection(callback=client_callback, data=None)
3928 server = self._server_connection(callback=server_callback, data=None)
3929
3930 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00003931 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003932
3933 def test_exceptions_in_server_bubble_up(self):
3934 """
3935 The callbacks thrown in the server callback bubble up to the caller.
3936 """
3937 class SentinelException(Exception):
3938 pass
3939
3940 def server_callback(*args):
3941 raise SentinelException()
3942
Alex Chanfb078d82017-04-20 11:16:15 +01003943 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00003944 pytest.fail("Should not be called")
3945
3946 client = self._client_connection(callback=client_callback, data=None)
3947 server = self._server_connection(callback=server_callback, data=None)
3948
3949 with pytest.raises(SentinelException):
Alex Chanb7480992017-01-30 14:04:47 +00003950 handshake_in_memory(client, server)
Cory Benfield496652a2017-01-24 11:42:56 +00003951
3952 def test_server_must_return_bytes(self):
3953 """
3954 The server callback must return a bytestring, or a TypeError is thrown.
3955 """
3956 def server_callback(*args):
3957 return self.sample_ocsp_data.decode('ascii')
3958
Alex Chanfb078d82017-04-20 11:16:15 +01003959 def client_callback(*args): # pragma: nocover
Cory Benfield496652a2017-01-24 11:42:56 +00003960 pytest.fail("Should not be called")
3961
3962 client = self._client_connection(callback=client_callback, data=None)
3963 server = self._server_connection(callback=server_callback, data=None)
3964
3965 with pytest.raises(TypeError):
Alex Chanb7480992017-01-30 14:04:47 +00003966 handshake_in_memory(client, server)