blob: c32ebab4e33544e1112e231a3ac10bf507dbd993 [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
9import uuid
10
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -050011from gc import collect, get_referrers
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +020012from errno import ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN
Hynek Schlawackf8979a52015-09-05 21:25:25 +020013from sys import platform, getfilesystemencoding, version_info
Maximilian Hils1d95dea2015-08-17 19:27:20 +020014from socket import MSG_PEEK, SHUT_RDWR, error, socket
Jean-Paul Calderonea65cf6c2009-07-19 10:26:52 -040015from os import makedirs
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040016from os.path import join
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -040017from weakref import ref
Abraham Martinef063482015-03-25 14:06:24 +000018from warnings import catch_warnings, simplefilter
Jean-Paul Calderone460cc1f2009-03-07 11:31:12 -050019
Hynek Schlawack734d3022015-09-05 19:19:32 +020020import pytest
21
Hynek Schlawackf90e3682016-03-11 11:21:13 +010022from six import PY3, text_type
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050023
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +010024from cryptography import x509
25from cryptography.hazmat.backends import default_backend
26from cryptography.hazmat.primitives import hashes
27from cryptography.hazmat.primitives import serialization
28from cryptography.hazmat.primitives.asymmetric import rsa
29from cryptography.x509.oid import NameOID
30
31
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040032from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080033from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040034from OpenSSL.crypto import dump_privatekey, load_privatekey
35from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040036from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040037
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040038from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
39from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040040from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040041from OpenSSL.SSL import (
42 SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
43 TLSv1_1_METHOD, TLSv1_2_METHOD)
44from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040045from OpenSSL.SSL import (
46 VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040047
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040048from OpenSSL.SSL import (
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050049 SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
50 SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
51 SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
52
53from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070054 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050055from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070056 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Cory Benfield0ba57ec2016-03-30 09:35:05 +010057from OpenSSL.SSL import _make_requires
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040058
Cory Benfieldba1820d2015-04-13 17:39:12 -040059from OpenSSL._util import lib as _lib
60
Alex Gaynord3b5d9b2016-07-31 10:54:24 -040061from OpenSSL.SSL import (
62 OP_NO_QUERY_MTU, OP_COOKIE_EXCHANGE, OP_NO_TICKET, OP_NO_COMPRESSION,
63 MODE_RELEASE_BUFFERS)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040064
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040065try:
66 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
67except ImportError:
68 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
69
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040070from OpenSSL.SSL import (
Alex Gaynor5af32d02016-09-24 01:52:21 -040071 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040072 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
73 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
74 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
75 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040076
Alex Gaynor5af32d02016-09-24 01:52:21 -040077try:
78 from OpenSSL.SSL import (
79 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
80 )
81except ImportError:
82 SSL_ST_INIT = SSL_ST_BEFORE = SSL_ST_OK = SSL_ST_RENEGOTIATE = None
83
Alex Gaynore7f51982016-09-11 11:48:14 -040084from .util import WARNING_TYPE_EXPECTED, NON_ASCII, TestCase
Hynek Schlawackf0e66852015-10-16 20:18:38 +020085from .test_crypto import (
86 cleartextCertificatePEM, cleartextPrivateKeyPEM,
87 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
88 root_cert_pem)
89
Hynek Schlawackde00dd52015-09-05 19:09:26 +020090
Alex Gaynord0bdd2d2016-09-10 14:23:46 -040091# openssl dhparam 1024 -out dh-1024.pem (note that 1024 is a small number of
92# bits to use)
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040093dhparam = """\
94-----BEGIN DH PARAMETERS-----
Alex Gaynord0bdd2d2016-09-10 14:23:46 -040095MIGHAoGBALdUMvn+C9MM+y5BWZs11mSeH6HHoEq0UVbzVq7UojC1hbsZUuGukQ3a
96Qh2/pwqb18BZFykrWB0zv/OkLa0kx4cuUgNrUVq1EFheBiX6YqryJ7t2sO09NQiO
97V7H54LmltOT/hEh6QWsJqb6BQgH65bswvV/XkYGja8/T0GzvbaVzAgEC
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040098-----END DH PARAMETERS-----
99"""
100
101
Hynek Schlawackb4f02402015-09-05 20:48:34 +0200102skip_if_py3 = pytest.mark.skipif(PY3, reason="Python 2 only")
Hynek Schlawackf8979a52015-09-05 21:25:25 +0200103skip_if_py26 = pytest.mark.skipif(
104 version_info[0:2] == (2, 6),
105 reason="Python 2.7 and later only"
106)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200107
108
Jean-Paul Calderone05826732015-04-12 11:38:49 -0400109def join_bytes_or_unicode(prefix, suffix):
110 """
111 Join two path components of either ``bytes`` or ``unicode``.
112
113 The return type is the same as the type of ``prefix``.
114 """
115 # If the types are the same, nothing special is necessary.
116 if type(prefix) == type(suffix):
117 return join(prefix, suffix)
118
119 # Otherwise, coerce suffix to the type of prefix.
120 if isinstance(prefix, text_type):
121 return join(prefix, suffix.decode(getfilesystemencoding()))
122 else:
123 return join(prefix, suffix.encode(getfilesystemencoding()))
124
125
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400126def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400127 return ok
128
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400129
Rick Deanb1ccd562009-07-09 23:52:39 -0500130def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400131 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400132 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400133 """
134 # Connect a pair of sockets
Rick Deanb1ccd562009-07-09 23:52:39 -0500135 port = socket()
136 port.bind(('', 0))
137 port.listen(1)
138 client = socket()
139 client.setblocking(False)
Jean-Paul Calderonef23c5d92009-07-23 17:58:15 -0400140 client.connect_ex(("127.0.0.1", port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400141 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500142 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500143
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400144 # Let's pass some unencrypted data to make sure our socket connection is
145 # fine. Just one byte, so we don't have to worry about buffers getting
146 # filled up or fragmentation.
Alex Gaynore7f51982016-09-11 11:48:14 -0400147 server.send(b"x")
148 assert client.recv(1024) == b"x"
149 client.send(b"y")
150 assert server.recv(1024) == b"y"
Rick Deanb1ccd562009-07-09 23:52:39 -0500151
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400152 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400153 server.setblocking(False)
154 client.setblocking(False)
Jim Shaver46f28912015-05-29 19:32:16 -0400155
Rick Deanb1ccd562009-07-09 23:52:39 -0500156 return (server, client)
157
158
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400159def handshake(client, server):
160 conns = [client, server]
161 while conns:
162 for conn in conns:
163 try:
164 conn.do_handshake()
165 except WantReadError:
166 pass
167 else:
168 conns.remove(conn)
169
170
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400171def _create_certificate_chain():
172 """
173 Construct and return a chain of certificates.
174
175 1. A new self-signed certificate authority certificate (cacert)
176 2. A new intermediate certificate signed by cacert (icert)
177 3. A new server certificate signed by icert (scert)
178 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400179 caext = X509Extension(b'basicConstraints', False, b'CA:true')
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400180
181 # Step 1
182 cakey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400183 cakey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400184 cacert = X509()
185 cacert.get_subject().commonName = "Authority Certificate"
186 cacert.set_issuer(cacert.get_subject())
187 cacert.set_pubkey(cakey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400188 cacert.set_notBefore(b"20000101000000Z")
189 cacert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400190 cacert.add_extensions([caext])
191 cacert.set_serial_number(0)
192 cacert.sign(cakey, "sha1")
193
194 # Step 2
195 ikey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400196 ikey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400197 icert = X509()
198 icert.get_subject().commonName = "Intermediate Certificate"
199 icert.set_issuer(cacert.get_subject())
200 icert.set_pubkey(ikey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400201 icert.set_notBefore(b"20000101000000Z")
202 icert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400203 icert.add_extensions([caext])
204 icert.set_serial_number(0)
205 icert.sign(cakey, "sha1")
206
207 # Step 3
208 skey = PKey()
Alex Gaynor0737a5e2016-09-10 14:35:09 -0400209 skey.generate_key(TYPE_RSA, 1024)
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400210 scert = X509()
211 scert.get_subject().commonName = "Server Certificate"
212 scert.set_issuer(icert.get_subject())
213 scert.set_pubkey(skey)
Alex Gaynore7f51982016-09-11 11:48:14 -0400214 scert.set_notBefore(b"20000101000000Z")
215 scert.set_notAfter(b"20200101000000Z")
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400216 scert.add_extensions([
Alex Gaynore7f51982016-09-11 11:48:14 -0400217 X509Extension(b'basicConstraints', True, b'CA:false')])
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400218 scert.set_serial_number(0)
219 scert.sign(ikey, "sha1")
220
221 return [(cakey, cacert), (ikey, icert), (skey, scert)]
222
223
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000224class _LoopbackMixin(object):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400225 """
226 Helper mixin which defines methods for creating a connected socket pair and
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200227 for forcing two connected SSL sockets to talk to each other via memory
228 BIOs.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400229 """
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500230 def _loopbackClientFactory(self, socket):
231 client = Connection(Context(TLSv1_METHOD), socket)
232 client.set_connect_state()
233 return client
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400234
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500235 def _loopbackServerFactory(self, socket):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400236 ctx = Context(TLSv1_METHOD)
237 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
238 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500239 server = Connection(ctx, socket)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400240 server.set_accept_state()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500241 return server
242
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500243 def _loopback(self, serverFactory=None, clientFactory=None):
244 if serverFactory is None:
245 serverFactory = self._loopbackServerFactory
246 if clientFactory is None:
247 clientFactory = self._loopbackClientFactory
248
249 (server, client) = socket_pair()
250 server = serverFactory(server)
251 client = clientFactory(client)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400252
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400253 handshake(client, server)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400254
255 server.setblocking(True)
256 client.setblocking(True)
257 return server, client
258
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400259 def _interactInMemory(self, client_conn, server_conn):
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000260 return interact_in_memory(client_conn, server_conn)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400261
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400262 def _handshakeInMemory(self, client_conn, server_conn):
Jean-Paul Calderoneb2b40782014-05-06 08:47:40 -0400263 """
264 Perform the TLS handshake between two :py:class:`Connection` instances
265 connected to each other via memory BIOs.
266 """
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400267 client_conn.set_connect_state()
268 server_conn.set_accept_state()
269
270 for conn in [client_conn, server_conn]:
271 try:
272 conn.do_handshake()
273 except WantReadError:
274 pass
275
276 self._interactInMemory(client_conn, server_conn)
277
278
Alex Chan1ca9e3a2016-11-05 13:01:51 +0000279def interact_in_memory(client_conn, server_conn):
280 """
281 Try to read application bytes from each of the two `Connection` objects.
282 Copy bytes back and forth between their send/receive buffers for as long
283 as there is anything to copy. When there is nothing more to copy,
284 return `None`. If one of them actually manages to deliver some application
285 bytes, return a two-tuple of the connection from which the bytes were read
286 and the bytes themselves.
287 """
288 wrote = True
289 while wrote:
290 # Loop until neither side has anything to say
291 wrote = False
292
293 # Copy stuff from each side's send buffer to the other side's
294 # receive buffer.
295 for (read, write) in [(client_conn, server_conn),
296 (server_conn, client_conn)]:
297
298 # Give the side a chance to generate some more bytes, or succeed.
299 try:
300 data = read.recv(2 ** 16)
301 except WantReadError:
302 # It didn't succeed, so we'll hope it generated some output.
303 pass
304 else:
305 # It did succeed, so we'll stop now and let the caller deal
306 # with it.
307 return (read, data)
308
309 while True:
310 # Keep copying as long as there's more stuff there.
311 try:
312 dirty = read.bio_read(4096)
313 except WantReadError:
314 # Okay, nothing more waiting to be sent. Stop
315 # processing this send buffer.
316 break
317 else:
318 # Keep track of the fact that someone generated some
319 # output.
320 wrote = True
321 write.bio_write(dirty)
322
323
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400324class VersionTests(TestCase):
325 """
326 Tests for version information exposed by
Jonathan Ballet648875f2011-07-16 14:14:58 +0900327 :py:obj:`OpenSSL.SSL.SSLeay_version` and
328 :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400329 """
330 def test_OPENSSL_VERSION_NUMBER(self):
331 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900332 :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400333 byte and the patch, fix, minor, and major versions in the
334 nibbles above that.
335 """
336 self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
337
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400338 def test_SSLeay_version(self):
339 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900340 :py:obj:`SSLeay_version` takes a version type indicator and returns
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400341 one of a number of version strings based on that indicator.
342 """
343 versions = {}
344 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
345 SSLEAY_PLATFORM, SSLEAY_DIR]:
346 version = SSLeay_version(t)
347 versions[version] = t
348 self.assertTrue(isinstance(version, bytes))
349 self.assertEqual(len(versions), 5)
350
351
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100352@pytest.fixture
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100353def ca_file(tmpdir):
354 """
355 Create a valid PEM file with CA certificates and return the path.
356 """
357 key = rsa.generate_private_key(
358 public_exponent=65537,
359 key_size=2048,
360 backend=default_backend()
361 )
362 public_key = key.public_key()
363
364 builder = x509.CertificateBuilder()
365 builder = builder.subject_name(x509.Name([
366 x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
367 ]))
368 builder = builder.issuer_name(x509.Name([
369 x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
370 ]))
371 one_day = datetime.timedelta(1, 0, 0)
372 builder = builder.not_valid_before(datetime.datetime.today() - one_day)
373 builder = builder.not_valid_after(datetime.datetime.today() + one_day)
374 builder = builder.serial_number(int(uuid.uuid4()))
375 builder = builder.public_key(public_key)
376 builder = builder.add_extension(
377 x509.BasicConstraints(ca=True, path_length=None), critical=True,
378 )
379
380 certificate = builder.sign(
381 private_key=key, algorithm=hashes.SHA256(),
382 backend=default_backend()
383 )
384
385 ca_file = tmpdir.join("test.pem")
386 ca_file.write_binary(
387 certificate.public_bytes(
388 encoding=serialization.Encoding.PEM,
389 )
390 )
391
392 return str(ca_file).encode("ascii")
393
394
395@pytest.fixture
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100396def context():
397 """
398 A simple TLS 1.0 context.
399 """
400 return Context(TLSv1_METHOD)
401
402
403class TestContext(object):
Hynek Schlawackaa861212016-03-13 13:53:48 +0100404 """
405 py.test-based tests for :class:`OpenSSL.SSL.Context`.
406
407 If possible, add new tests here.
408 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100409 @pytest.mark.parametrize("cipher_string", [
410 b"hello world:AES128-SHA",
411 u"hello world:AES128-SHA",
412 ])
413 def test_set_cipher_list(self, context, cipher_string):
414 """
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100415 :meth:`Context.set_cipher_list` accepts both byte and unicode strings
416 for naming the ciphers which connections created with the context
417 object will be able to choose from.
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100418 """
419 context.set_cipher_list(cipher_string)
420 conn = Connection(context, None)
421
422 assert "AES128-SHA" in conn.get_cipher_list()
423
424 @pytest.mark.parametrize("cipher_list,error", [
425 (object(), TypeError),
426 ("imaginary-cipher", Error),
427 ])
428 def test_set_cipher_list_wrong_args(self, context, cipher_list, error):
429 """
430 :meth:`Context.set_cipher_list` raises :exc:`TypeError` when passed a
431 non-string argument and raises :exc:`OpenSSL.SSL.Error` when passed an
432 incorrect cipher list string.
433 """
434 with pytest.raises(error):
435 context.set_cipher_list(cipher_list)
436
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100437 def test_load_client_ca(self, context, ca_file):
438 """
439 :meth:`Context.load_client_ca` works as far as we can tell.
440 """
441 context.load_client_ca(ca_file)
442
443 def test_load_client_ca_invalid(self, context, tmpdir):
444 """
445 :meth:`Context.load_client_ca` raises an Error if the ca file is
446 invalid.
447 """
448 ca_file = tmpdir.join("test.pem")
449 ca_file.write("")
450
451 with pytest.raises(Error) as e:
452 context.load_client_ca(str(ca_file).encode("ascii"))
453
454 assert "PEM routines" == e.value.args[0][0][0]
455
456 def test_load_client_ca_unicode(self, context, ca_file):
457 """
458 Passing the path as unicode raises a warning but works.
459 """
460 pytest.deprecated_call(
461 context.load_client_ca, ca_file.decode("ascii")
462 )
463
464 def test_set_session_id(self, context):
465 """
466 :meth:`Context.set_session_id` works as far as we can tell.
467 """
468 context.set_session_id(b"abc")
469
470 def test_set_session_id_fail(self, context):
471 """
472 :meth:`Context.set_session_id` errors are propagated.
473 """
474 with pytest.raises(Error) as e:
475 context.set_session_id(b"abc" * 1000)
476
477 assert [
478 ("SSL routines",
479 "SSL_CTX_set_session_id_context",
480 "ssl session id context too long")
481 ] == e.value.args[0]
482
483 def test_set_session_id_unicode(self, context):
484 """
485 :meth:`Context.set_session_id` raises a warning if a unicode string is
486 passed.
487 """
488 pytest.deprecated_call(context.set_session_id, u"abc")
489
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100490
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400491class ContextTests(TestCase, _LoopbackMixin):
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400492 """
Hynek Schlawackaa861212016-03-13 13:53:48 +0100493 Unit tests for :class:`OpenSSL.SSL.Context`.
494
495 If possible, add new tests to :class:`TestContext` above.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400496 """
497 def test_method(self):
498 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200499 :py:obj:`Context` can be instantiated with one of
500 :py:obj:`SSLv2_METHOD`, :py:obj:`SSLv3_METHOD`,
501 :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400502 :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400503 """
Alex Gaynor5af32d02016-09-24 01:52:21 -0400504 methods = [SSLv23_METHOD, TLSv1_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400505 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400506 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400507
Alex Gaynor5af32d02016-09-24 01:52:21 -0400508 maybe = [SSLv2_METHOD, SSLv3_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400509 for meth in maybe:
510 try:
511 Context(meth)
512 except (Error, ValueError):
513 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
514 # don't. Difficult to say in advance.
515 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400516
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400517 self.assertRaises(TypeError, Context, "")
518 self.assertRaises(ValueError, Context, 10)
519
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200520 @skip_if_py3
521 def test_method_long(self):
522 """
523 On Python 2 :py:class:`Context` accepts values of type
524 :py:obj:`long` as well as :py:obj:`int`.
525 """
526 Context(long(TLSv1_METHOD))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500527
Rick Deane15b1472009-07-09 15:53:42 -0500528 def test_type(self):
529 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200530 :py:obj:`Context` and :py:obj:`ContextType` refer to the same type
531 object and can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500532 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400533 self.assertIdentical(Context, ContextType)
534 self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500535
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400536 def test_use_privatekey(self):
537 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200538 :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey`
539 instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400540 """
541 key = PKey()
542 key.generate_key(TYPE_RSA, 128)
543 ctx = Context(TLSv1_METHOD)
544 ctx.use_privatekey(key)
545 self.assertRaises(TypeError, ctx.use_privatekey, "")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400546
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800547 def test_use_privatekey_file_missing(self):
548 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200549 :py:obj:`Context.use_privatekey_file` raises
550 :py:obj:`OpenSSL.SSL.Error` when passed the name of a file which does
551 not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800552 """
553 ctx = Context(TLSv1_METHOD)
554 self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
555
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400556 def _use_privatekey_file_test(self, pemfile, filetype):
557 """
558 Verify that calling ``Context.use_privatekey_file`` with the given
559 arguments does not raise an exception.
560 """
561 key = PKey()
562 key.generate_key(TYPE_RSA, 128)
563
564 with open(pemfile, "wt") as pem:
565 pem.write(
566 dump_privatekey(FILETYPE_PEM, key).decode("ascii")
567 )
568
569 ctx = Context(TLSv1_METHOD)
570 ctx.use_privatekey_file(pemfile, filetype)
571
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400572 def test_use_privatekey_file_bytes(self):
573 """
574 A private key can be specified from a file by passing a ``bytes``
575 instance giving the file name to ``Context.use_privatekey_file``.
576 """
577 self._use_privatekey_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400578 self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400579 FILETYPE_PEM,
580 )
581
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400582 def test_use_privatekey_file_unicode(self):
583 """
584 A private key can be specified from a file by passing a ``unicode``
585 instance giving the file name to ``Context.use_privatekey_file``.
586 """
587 self._use_privatekey_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400588 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400589 FILETYPE_PEM,
590 )
591
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200592 @skip_if_py3
593 def test_use_privatekey_file_long(self):
594 """
595 On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
596 filetype of type :py:obj:`long` as well as :py:obj:`int`.
597 """
598 self._use_privatekey_file_test(self.mktemp(), long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500599
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800600 def test_use_certificate_wrong_args(self):
601 """
602 :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200603 when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as
604 an argument.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800605 """
606 ctx = Context(TLSv1_METHOD)
607 self.assertRaises(TypeError, ctx.use_certificate)
608 self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200609 self.assertRaises(
610 TypeError, ctx.use_certificate, X509(), "hello, world"
611 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800612
613 def test_use_certificate_uninitialized(self):
614 """
615 :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
616 when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
617 initialized (ie, which does not actually have any certificate data).
618 """
619 ctx = Context(TLSv1_METHOD)
620 self.assertRaises(Error, ctx.use_certificate, X509())
621
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800622 def test_use_certificate(self):
623 """
624 :py:obj:`Context.use_certificate` sets the certificate which will be
625 used to identify connections created using the context.
626 """
627 # TODO
628 # Hard to assert anything. But we could set a privatekey then ask
629 # OpenSSL if the cert and key agree using check_privatekey. Then as
630 # long as check_privatekey works right we're good...
631 ctx = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200632 ctx.use_certificate(
633 load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
634 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800635
636 def test_use_certificate_file_wrong_args(self):
637 """
638 :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
639 called with zero arguments or more than two arguments, or if the first
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200640 argument is not a byte string or the second argumnent is not an
641 integer.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800642 """
643 ctx = Context(TLSv1_METHOD)
644 self.assertRaises(TypeError, ctx.use_certificate_file)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200645 self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile",
646 object())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800647 self.assertRaises(
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200648 TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM,
649 object())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800650 self.assertRaises(
651 TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
652 self.assertRaises(
653 TypeError, ctx.use_certificate_file, b"somefile", object())
654
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800655 def test_use_certificate_file_missing(self):
656 """
657 :py:obj:`Context.use_certificate_file` raises
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200658 `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does
659 not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800660 """
661 ctx = Context(TLSv1_METHOD)
662 self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
663
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400664 def _use_certificate_file_test(self, certificate_file):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800665 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400666 Verify that calling ``Context.use_certificate_file`` with the given
667 filename doesn't raise an exception.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800668 """
669 # TODO
670 # Hard to assert anything. But we could set a privatekey then ask
671 # OpenSSL if the cert and key agree using check_privatekey. Then as
672 # long as check_privatekey works right we're good...
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400673 with open(certificate_file, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800674 pem_file.write(cleartextCertificatePEM)
675
676 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400677 ctx.use_certificate_file(certificate_file)
678
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400679 def test_use_certificate_file_bytes(self):
680 """
681 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
682 ``bytes`` filename) which will be used to identify connections created
683 using the context.
684 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400685 filename = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400686 self._use_certificate_file_test(filename)
687
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400688 def test_use_certificate_file_unicode(self):
689 """
690 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
691 ``bytes`` filename) which will be used to identify connections created
692 using the context.
693 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400694 filename = self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400695 self._use_certificate_file_test(filename)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800696
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200697 @skip_if_py3
698 def test_use_certificate_file_long(self):
699 """
700 On Python 2 :py:obj:`Context.use_certificate_file` accepts a
701 filetype of type :py:obj:`long` as well as :py:obj:`int`.
702 """
703 pem_filename = self.mktemp()
704 with open(pem_filename, "wb") as pem_file:
705 pem_file.write(cleartextCertificatePEM)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500706
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200707 ctx = Context(TLSv1_METHOD)
708 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500709
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500710 def test_check_privatekey_valid(self):
711 """
712 :py:obj:`Context.check_privatekey` returns :py:obj:`None` if the
713 :py:obj:`Context` instance has been configured to use a matched key and
714 certificate pair.
715 """
716 key = load_privatekey(FILETYPE_PEM, client_key_pem)
717 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
718 context = Context(TLSv1_METHOD)
719 context.use_privatekey(key)
720 context.use_certificate(cert)
721 self.assertIs(None, context.check_privatekey())
722
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500723 def test_check_privatekey_invalid(self):
724 """
725 :py:obj:`Context.check_privatekey` raises :py:obj:`Error` if the
726 :py:obj:`Context` instance has been configured to use a key and
727 certificate pair which don't relate to each other.
728 """
729 key = load_privatekey(FILETYPE_PEM, client_key_pem)
730 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
731 context = Context(TLSv1_METHOD)
732 context.use_privatekey(key)
733 context.use_certificate(cert)
734 self.assertRaises(Error, context.check_privatekey)
735
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500736 def test_check_privatekey_wrong_args(self):
737 """
738 :py:obj:`Context.check_privatekey` raises :py:obj:`TypeError` if called
739 with other than no arguments.
740 """
741 context = Context(TLSv1_METHOD)
742 self.assertRaises(TypeError, context.check_privatekey, object())
743
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400744 def test_set_app_data_wrong_args(self):
745 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200746 :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called
747 with other than one argument.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400748 """
749 context = Context(TLSv1_METHOD)
750 self.assertRaises(TypeError, context.set_app_data)
751 self.assertRaises(TypeError, context.set_app_data, None, None)
752
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400753 def test_get_app_data_wrong_args(self):
754 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200755 :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called
756 with any arguments.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400757 """
758 context = Context(TLSv1_METHOD)
759 self.assertRaises(TypeError, context.get_app_data, None)
760
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400761 def test_app_data(self):
762 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200763 :py:obj:`Context.set_app_data` stores an object for later retrieval
764 using :py:obj:`Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400765 """
766 app_data = object()
767 context = Context(TLSv1_METHOD)
768 context.set_app_data(app_data)
769 self.assertIdentical(context.get_app_data(), app_data)
770
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400771 def test_set_options_wrong_args(self):
772 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200773 :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with
774 the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400775 """
776 context = Context(TLSv1_METHOD)
777 self.assertRaises(TypeError, context.set_options)
778 self.assertRaises(TypeError, context.set_options, None)
779 self.assertRaises(TypeError, context.set_options, 1, None)
780
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500781 def test_set_options(self):
782 """
783 :py:obj:`Context.set_options` returns the new options value.
784 """
785 context = Context(TLSv1_METHOD)
786 options = context.set_options(OP_NO_SSLv2)
Alex Gaynor2310f8b2016-09-10 14:39:32 -0400787 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500788
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200789 @skip_if_py3
790 def test_set_options_long(self):
791 """
792 On Python 2 :py:obj:`Context.set_options` accepts values of type
793 :py:obj:`long` as well as :py:obj:`int`.
794 """
795 context = Context(TLSv1_METHOD)
796 options = context.set_options(long(OP_NO_SSLv2))
Alex Gaynor2310f8b2016-09-10 14:39:32 -0400797 assert options & OP_NO_SSLv2 == OP_NO_SSLv2
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500798
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300799 def test_set_mode_wrong_args(self):
800 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200801 :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with
802 the wrong number of arguments or a non-:py:obj:`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300803 """
804 context = Context(TLSv1_METHOD)
805 self.assertRaises(TypeError, context.set_mode)
806 self.assertRaises(TypeError, context.set_mode, None)
807 self.assertRaises(TypeError, context.set_mode, 1, None)
808
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400809 def test_set_mode(self):
810 """
811 :py:obj:`Context.set_mode` accepts a mode bitvector and returns the
812 newly set mode.
813 """
814 context = Context(TLSv1_METHOD)
815 self.assertTrue(
816 MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500817
Alex Gaynord3b5d9b2016-07-31 10:54:24 -0400818 @skip_if_py3
819 def test_set_mode_long(self):
820 """
821 On Python 2 :py:obj:`Context.set_mode` accepts values of type
822 :py:obj:`long` as well as :py:obj:`int`.
823 """
824 context = Context(TLSv1_METHOD)
825 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
826 self.assertTrue(MODE_RELEASE_BUFFERS & mode)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400827
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400828 def test_set_timeout_wrong_args(self):
829 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200830 :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with
831 the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400832 """
833 context = Context(TLSv1_METHOD)
834 self.assertRaises(TypeError, context.set_timeout)
835 self.assertRaises(TypeError, context.set_timeout, None)
836 self.assertRaises(TypeError, context.set_timeout, 1, None)
837
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400838 def test_get_timeout_wrong_args(self):
839 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200840 :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with
841 any arguments.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400842 """
843 context = Context(TLSv1_METHOD)
844 self.assertRaises(TypeError, context.get_timeout, None)
845
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400846 def test_timeout(self):
847 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200848 :py:obj:`Context.set_timeout` sets the session timeout for all
849 connections created using the context object.
850 :py:obj:`Context.get_timeout` retrieves this value.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400851 """
852 context = Context(TLSv1_METHOD)
853 context.set_timeout(1234)
854 self.assertEquals(context.get_timeout(), 1234)
855
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200856 @skip_if_py3
857 def test_timeout_long(self):
858 """
859 On Python 2 :py:obj:`Context.set_timeout` accepts values of type
860 `long` as well as int.
861 """
862 context = Context(TLSv1_METHOD)
863 context.set_timeout(long(1234))
864 self.assertEquals(context.get_timeout(), 1234)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500865
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400866 def test_set_verify_depth_wrong_args(self):
867 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200868 :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called
869 with the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400870 """
871 context = Context(TLSv1_METHOD)
872 self.assertRaises(TypeError, context.set_verify_depth)
873 self.assertRaises(TypeError, context.set_verify_depth, None)
874 self.assertRaises(TypeError, context.set_verify_depth, 1, None)
875
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400876 def test_get_verify_depth_wrong_args(self):
877 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200878 :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called
879 with any arguments.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400880 """
881 context = Context(TLSv1_METHOD)
882 self.assertRaises(TypeError, context.get_verify_depth, None)
883
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400884 def test_verify_depth(self):
885 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200886 :py:obj:`Context.set_verify_depth` sets the number of certificates in
887 a chain to follow before giving up. The value can be retrieved with
Jonathan Ballet648875f2011-07-16 14:14:58 +0900888 :py:obj:`Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400889 """
890 context = Context(TLSv1_METHOD)
891 context.set_verify_depth(11)
892 self.assertEquals(context.get_verify_depth(), 11)
893
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200894 @skip_if_py3
895 def test_verify_depth_long(self):
896 """
897 On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
898 type `long` as well as int.
899 """
900 context = Context(TLSv1_METHOD)
901 context.set_verify_depth(long(11))
902 self.assertEquals(context.get_verify_depth(), 11)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500903
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400904 def _write_encrypted_pem(self, passphrase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400905 """
906 Write a new private key out to a new file, encrypted using the given
907 passphrase. Return the path to the new file.
908 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400909 key = PKey()
910 key.generate_key(TYPE_RSA, 128)
911 pemFile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400912 fObj = open(pemFile, 'w')
913 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
914 fObj.write(pem.decode('ascii'))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400915 fObj.close()
916 return pemFile
917
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400918 def test_set_passwd_cb_wrong_args(self):
919 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200920 :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called
921 with the wrong arguments or with a non-callable first argument.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400922 """
923 context = Context(TLSv1_METHOD)
924 self.assertRaises(TypeError, context.set_passwd_cb)
925 self.assertRaises(TypeError, context.set_passwd_cb, None)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200926 self.assertRaises(
927 TypeError, context.set_passwd_cb, lambda: None, None, None
Hynek Schlawack2c013a92015-09-05 19:33:05 +0200928 ) # pragma: nocover
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400929
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400930 def test_set_passwd_cb(self):
931 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200932 :py:obj:`Context.set_passwd_cb` accepts a callable which will be
933 invoked when a private key is loaded from an encrypted PEM.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400934 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400935 passphrase = b"foobar"
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400936 pemFile = self._write_encrypted_pem(passphrase)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400937 calledWith = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200938
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400939 def passphraseCallback(maxlen, verify, extra):
940 calledWith.append((maxlen, verify, extra))
941 return passphrase
942 context = Context(TLSv1_METHOD)
943 context.set_passwd_cb(passphraseCallback)
944 context.use_privatekey_file(pemFile)
945 self.assertTrue(len(calledWith), 1)
946 self.assertTrue(isinstance(calledWith[0][0], int))
947 self.assertTrue(isinstance(calledWith[0][1], int))
948 self.assertEqual(calledWith[0][2], None)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400949
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400950 def test_passwd_callback_exception(self):
951 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200952 :py:obj:`Context.use_privatekey_file` propagates any exception raised
953 by the passphrase callback.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400954 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400955 pemFile = self._write_encrypted_pem(b"monkeys are nice")
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200956
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400957 def passphraseCallback(maxlen, verify, extra):
958 raise RuntimeError("Sorry, I am a fail.")
959
960 context = Context(TLSv1_METHOD)
961 context.set_passwd_cb(passphraseCallback)
962 self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
963
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400964 def test_passwd_callback_false(self):
965 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200966 :py:obj:`Context.use_privatekey_file` raises
967 :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a false
968 value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400969 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400970 pemFile = self._write_encrypted_pem(b"monkeys are nice")
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200971
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400972 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500973 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400974
975 context = Context(TLSv1_METHOD)
976 context.set_passwd_cb(passphraseCallback)
977 self.assertRaises(Error, context.use_privatekey_file, pemFile)
978
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400979 def test_passwd_callback_non_string(self):
980 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200981 :py:obj:`Context.use_privatekey_file` raises
982 :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a true
983 non-string value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400984 """
Alex Gaynore7f51982016-09-11 11:48:14 -0400985 pemFile = self._write_encrypted_pem(b"monkeys are nice")
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200986
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400987 def passphraseCallback(maxlen, verify, extra):
988 return 10
989
990 context = Context(TLSv1_METHOD)
991 context.set_passwd_cb(passphraseCallback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992 self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400993
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400994 def test_passwd_callback_too_long(self):
995 """
996 If the passphrase returned by the passphrase callback returns a string
997 longer than the indicated maximum length, it is truncated.
998 """
999 # A priori knowledge!
Alex Gaynore7f51982016-09-11 11:48:14 -04001000 passphrase = b"x" * 1024
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -04001001 pemFile = self._write_encrypted_pem(passphrase)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001002
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -04001003 def passphraseCallback(maxlen, verify, extra):
1004 assert maxlen == 1024
Alex Gaynore7f51982016-09-11 11:48:14 -04001005 return passphrase + b"y"
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -04001006
1007 context = Context(TLSv1_METHOD)
1008 context.set_passwd_cb(passphraseCallback)
1009 # This shall succeed because the truncated result is the correct
1010 # passphrase.
1011 context.use_privatekey_file(pemFile)
1012
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001013 def test_set_info_callback(self):
1014 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001015 :py:obj:`Context.set_info_callback` accepts a callable which will be
1016 invoked when certain information about an SSL connection is available.
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001017 """
Rick Deanb1ccd562009-07-09 23:52:39 -05001018 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001019
1020 clientSSL = Connection(Context(TLSv1_METHOD), client)
1021 clientSSL.set_connect_state()
1022
1023 called = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001024
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001025 def info(conn, where, ret):
1026 called.append((conn, where, ret))
1027 context = Context(TLSv1_METHOD)
1028 context.set_info_callback(info)
1029 context.use_certificate(
1030 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1031 context.use_privatekey(
1032 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1033
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001034 serverSSL = Connection(context, server)
1035 serverSSL.set_accept_state()
1036
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001037 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -04001038
Jean-Paul Calderone3835e522014-02-02 11:12:30 -05001039 # The callback must always be called with a Connection instance as the
1040 # first argument. It would probably be better to split this into
1041 # separate tests for client and server side info callbacks so we could
1042 # assert it is called with the right Connection instance. It would
1043 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001044 notConnections = [
1045 conn for (conn, where, ret) in called
1046 if not isinstance(conn, Connection)]
1047 self.assertEqual(
1048 [], notConnections,
1049 "Some info callback arguments were not Connection instaces.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001050
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001051 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04001052 """
1053 Create a client context which will verify the peer certificate and call
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04001054 its :py:obj:`load_verify_locations` method with the given arguments.
1055 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04001056 """
Rick Deanb1ccd562009-07-09 23:52:39 -05001057 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001058
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001059 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001060 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001061 # Require that the server certificate verify properly or the
1062 # connection will fail.
1063 clientContext.set_verify(
1064 VERIFY_PEER,
1065 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
1066
1067 clientSSL = Connection(clientContext, client)
1068 clientSSL.set_connect_state()
1069
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001070 serverContext = Context(TLSv1_METHOD)
1071 serverContext.use_certificate(
1072 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1073 serverContext.use_privatekey(
1074 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1075
1076 serverSSL = Connection(serverContext, server)
1077 serverSSL.set_accept_state()
1078
Jean-Paul Calderonef8742032010-09-25 00:00:32 -04001079 # Without load_verify_locations above, the handshake
1080 # will fail:
1081 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
1082 # 'certificate verify failed')]
1083 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -04001084
1085 cert = clientSSL.get_peer_certificate()
Jean-Paul Calderone20131f52009-04-01 12:05:45 -04001086 self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001087
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001088 def _load_verify_cafile(self, cafile):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001089 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001090 Verify that if path to a file containing a certificate is passed to
1091 ``Context.load_verify_locations`` for the ``cafile`` parameter, that
1092 certificate is used as a trust root for the purposes of verifying
1093 connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001094 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001095 fObj = open(cafile, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001096 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001097 fObj.close()
1098
1099 self._load_verify_locations_test(cafile)
1100
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001101 def test_load_verify_bytes_cafile(self):
1102 """
1103 :py:obj:`Context.load_verify_locations` accepts a file name as a
1104 ``bytes`` instance and uses the certificates within for verification
1105 purposes.
1106 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001107 cafile = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001108 self._load_verify_cafile(cafile)
1109
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001110 def test_load_verify_unicode_cafile(self):
1111 """
1112 :py:obj:`Context.load_verify_locations` accepts a file name as a
1113 ``unicode`` instance and uses the certificates within for verification
1114 purposes.
1115 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001116 self._load_verify_cafile(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001117 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001118 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001119
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001120 def test_load_verify_invalid_file(self):
1121 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001122 :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when
1123 passed a non-existent cafile.
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -04001124 """
1125 clientContext = Context(TLSv1_METHOD)
1126 self.assertRaises(
1127 Error, clientContext.load_verify_locations, self.mktemp())
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001128
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001129 def _load_verify_directory_locations_capath(self, capath):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001130 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001131 Verify that if path to a directory containing certificate files is
1132 passed to ``Context.load_verify_locations`` for the ``capath``
1133 parameter, those certificates are used as trust roots for the purposes
1134 of verifying connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001135 """
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001136 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -04001137 # Hash values computed manually with c_rehash to avoid depending on
1138 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
1139 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001140 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001141 cafile = join_bytes_or_unicode(capath, name)
1142 with open(cafile, 'w') as fObj:
1143 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001144
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001145 self._load_verify_locations_test(None, capath)
1146
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001147 def test_load_verify_directory_bytes_capath(self):
1148 """
1149 :py:obj:`Context.load_verify_locations` accepts a directory name as a
1150 ``bytes`` instance and uses the certificates within for verification
1151 purposes.
1152 """
1153 self._load_verify_directory_locations_capath(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001154 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001155 )
1156
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001157 def test_load_verify_directory_unicode_capath(self):
1158 """
1159 :py:obj:`Context.load_verify_locations` accepts a directory name as a
1160 ``unicode`` instance and uses the certificates within for verification
1161 purposes.
1162 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001163 self._load_verify_directory_locations_capath(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001164 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001165 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001166
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001167 def test_load_verify_locations_wrong_args(self):
1168 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001169 :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if
1170 called with the wrong number of arguments or with non-:py:obj:`str`
1171 arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001172 """
1173 context = Context(TLSv1_METHOD)
1174 self.assertRaises(TypeError, context.load_verify_locations)
1175 self.assertRaises(TypeError, context.load_verify_locations, object())
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001176 self.assertRaises(
1177 TypeError, context.load_verify_locations, object(), object()
1178 )
1179 self.assertRaises(
1180 TypeError, context.load_verify_locations, None, None, None
1181 )
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001182
Hynek Schlawack734d3022015-09-05 19:19:32 +02001183 @pytest.mark.skipif(
1184 platform == "win32",
1185 reason="set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001186 "See LP#404343 and LP#404344."
Hynek Schlawack734d3022015-09-05 19:19:32 +02001187 )
1188 def test_set_default_verify_paths(self):
1189 """
1190 :py:obj:`Context.set_default_verify_paths` causes the
1191 platform-specific CA certificate locations to be used for
1192 verification purposes.
1193 """
1194 # Testing this requires a server with a certificate signed by one
1195 # of the CAs in the platform CA location. Getting one of those
1196 # costs money. Fortunately (or unfortunately, depending on your
1197 # perspective), it's easy to think of a public server on the
1198 # internet which has such a certificate. Connecting to the network
1199 # in a unit test is bad, but it's the only way I can think of to
1200 # really test this. -exarkun
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001201
Hynek Schlawack734d3022015-09-05 19:19:32 +02001202 # Arg, verisign.com doesn't speak anything newer than TLS 1.0
Hynek Schlawackbf887932015-10-21 17:13:47 +02001203 context = Context(SSLv23_METHOD)
Hynek Schlawack734d3022015-09-05 19:19:32 +02001204 context.set_default_verify_paths()
1205 context.set_verify(
1206 VERIFY_PEER,
1207 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001208
Hynek Schlawack734d3022015-09-05 19:19:32 +02001209 client = socket()
Hynek Schlawackbf887932015-10-21 17:13:47 +02001210 client.connect(("encrypted.google.com", 443))
Hynek Schlawack734d3022015-09-05 19:19:32 +02001211 clientSSL = Connection(context, client)
1212 clientSSL.set_connect_state()
1213 clientSSL.do_handshake()
1214 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
1215 self.assertTrue(clientSSL.recv(1024))
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001216
1217 def test_set_default_verify_paths_signature(self):
1218 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001219 :py:obj:`Context.set_default_verify_paths` takes no arguments and
1220 raises :py:obj:`TypeError` if given any.
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001221 """
1222 context = Context(TLSv1_METHOD)
1223 self.assertRaises(TypeError, context.set_default_verify_paths, None)
1224 self.assertRaises(TypeError, context.set_default_verify_paths, 1)
1225 self.assertRaises(TypeError, context.set_default_verify_paths, "")
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001226
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001227 def test_add_extra_chain_cert_invalid_cert(self):
1228 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001229 :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if
1230 called with other than one argument or if called with an object which
1231 is not an instance of :py:obj:`X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001232 """
1233 context = Context(TLSv1_METHOD)
1234 self.assertRaises(TypeError, context.add_extra_chain_cert)
1235 self.assertRaises(TypeError, context.add_extra_chain_cert, object())
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001236 self.assertRaises(
1237 TypeError, context.add_extra_chain_cert, object(), object()
1238 )
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001239
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001240 def _handshake_test(self, serverContext, clientContext):
1241 """
1242 Verify that a client and server created with the given contexts can
1243 successfully handshake and communicate.
1244 """
1245 serverSocket, clientSocket = socket_pair()
1246
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001247 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001248 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001249
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001250 client = Connection(clientContext, clientSocket)
1251 client.set_connect_state()
1252
1253 # Make them talk to each other.
1254 # self._interactInMemory(client, server)
1255 for i in range(3):
1256 for s in [client, server]:
1257 try:
1258 s.do_handshake()
1259 except WantReadError:
1260 pass
1261
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001262 def test_set_verify_callback_connection_argument(self):
1263 """
1264 The first argument passed to the verify callback is the
1265 :py:class:`Connection` instance for which verification is taking place.
1266 """
1267 serverContext = Context(TLSv1_METHOD)
1268 serverContext.use_privatekey(
1269 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1270 serverContext.use_certificate(
1271 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1272 serverConnection = Connection(serverContext, None)
1273
1274 class VerifyCallback(object):
1275 def callback(self, connection, *args):
1276 self.connection = connection
1277 return 1
1278
1279 verify = VerifyCallback()
1280 clientContext = Context(TLSv1_METHOD)
1281 clientContext.set_verify(VERIFY_PEER, verify.callback)
1282 clientConnection = Connection(clientContext, None)
1283 clientConnection.set_connect_state()
1284
1285 self._handshakeInMemory(clientConnection, serverConnection)
1286
1287 self.assertIdentical(verify.connection, clientConnection)
1288
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001289 def test_set_verify_callback_exception(self):
1290 """
1291 If the verify callback passed to :py:obj:`Context.set_verify` raises an
1292 exception, verification fails and the exception is propagated to the
1293 caller of :py:obj:`Connection.do_handshake`.
1294 """
1295 serverContext = Context(TLSv1_METHOD)
1296 serverContext.use_privatekey(
1297 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1298 serverContext.use_certificate(
1299 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1300
1301 clientContext = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001302
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001303 def verify_callback(*args):
1304 raise Exception("silly verify failure")
1305 clientContext.set_verify(VERIFY_PEER, verify_callback)
1306
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001307 with pytest.raises(Exception) as exc:
1308 self._handshake_test(serverContext, clientContext)
1309
1310 self.assertEqual("silly verify failure", str(exc.value))
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001311
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001312 def test_add_extra_chain_cert(self):
1313 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001314 :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509`
1315 instance to add to the certificate chain.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001316
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001317 See :py:obj:`_create_certificate_chain` for the details of the
1318 certificate chain tested.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001319
1320 The chain is tested by starting a server with scert and connecting
1321 to it with a client which trusts cacert and requires verification to
1322 succeed.
1323 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001324 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001325 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1326
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001327 # Dump the CA certificate to a file because that's the only way to load
1328 # it as a trusted CA in the client context.
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001329 for cert, name in [(cacert, 'ca.pem'),
1330 (icert, 'i.pem'),
1331 (scert, 's.pem')]:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001332 with open(join(self.tmpdir, name), 'w') as f:
1333 f.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001334
Hynek Schlawack1902c012015-04-16 15:06:41 -04001335 for key, name in [(cakey, 'ca.key'),
1336 (ikey, 'i.key'),
1337 (skey, 's.key')]:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001338 with open(join(self.tmpdir, name), 'w') as f:
1339 f.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001340
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001341 # Create the server context
1342 serverContext = Context(TLSv1_METHOD)
1343 serverContext.use_privatekey(skey)
1344 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001345 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001346 serverContext.add_extra_chain_cert(icert)
1347
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001348 # Create the client
1349 clientContext = Context(TLSv1_METHOD)
1350 clientContext.set_verify(
1351 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001352 clientContext.load_verify_locations(join(self.tmpdir, "ca.pem"))
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001353
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001354 # Try it out.
1355 self._handshake_test(serverContext, clientContext)
1356
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001357 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001358 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001359 Verify that :py:obj:`Context.use_certificate_chain_file` reads a
1360 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001361
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001362 The chain is tested by starting a server with scert and connecting to
1363 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001364 succeed.
1365 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001366 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001367 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1368
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001369 makedirs(certdir)
1370
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001371 chainFile = join_bytes_or_unicode(certdir, "chain.pem")
1372 caFile = join_bytes_or_unicode(certdir, "ca.pem")
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001373
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001374 # Write out the chain file.
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001375 with open(chainFile, 'wb') as fObj:
1376 # Most specific to least general.
1377 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1378 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1379 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1380
1381 with open(caFile, 'w') as fObj:
1382 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001383
1384 serverContext = Context(TLSv1_METHOD)
1385 serverContext.use_certificate_chain_file(chainFile)
1386 serverContext.use_privatekey(skey)
1387
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001388 clientContext = Context(TLSv1_METHOD)
1389 clientContext.set_verify(
1390 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001391 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001392
1393 self._handshake_test(serverContext, clientContext)
1394
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001395 def test_use_certificate_chain_file_bytes(self):
1396 """
1397 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1398 an instance of ``bytes``) to specify additional certificates to use to
1399 construct and verify a trust chain.
1400 """
1401 self._use_certificate_chain_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001402 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001403 )
1404
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001405 def test_use_certificate_chain_file_unicode(self):
1406 """
1407 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1408 an instance of ``unicode``) to specify additional certificates to use
1409 to construct and verify a trust chain.
1410 """
1411 self._use_certificate_chain_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001412 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001413 )
1414
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001415 def test_use_certificate_chain_file_wrong_args(self):
1416 """
1417 :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
1418 if passed zero or more than one argument or when passed a non-byte
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001419 string single argument. It also raises :py:obj:`OpenSSL.SSL.Error`
1420 when passed a bad chain file name (for example, the name of a file
1421 which does not exist).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001422 """
1423 context = Context(TLSv1_METHOD)
1424 self.assertRaises(TypeError, context.use_certificate_chain_file)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001425 self.assertRaises(
1426 TypeError, context.use_certificate_chain_file, object()
1427 )
1428 self.assertRaises(
1429 TypeError, context.use_certificate_chain_file, b"foo", object()
1430 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001431
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001432 self.assertRaises(
1433 Error, context.use_certificate_chain_file, self.mktemp()
1434 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001435
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001436 def test_get_verify_mode_wrong_args(self):
1437 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001438 :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called
1439 with any arguments.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001440 """
1441 context = Context(TLSv1_METHOD)
1442 self.assertRaises(TypeError, context.get_verify_mode, None)
1443
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001444 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001445 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001446 :py:obj:`Context.get_verify_mode` returns the verify mode flags
1447 previously passed to :py:obj:`Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001448 """
1449 context = Context(TLSv1_METHOD)
1450 self.assertEquals(context.get_verify_mode(), 0)
1451 context.set_verify(
1452 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
1453 self.assertEquals(
1454 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1455
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001456 @skip_if_py3
1457 def test_set_verify_mode_long(self):
1458 """
1459 On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
1460 type :py:obj:`long` as well as :py:obj:`int`.
1461 """
1462 context = Context(TLSv1_METHOD)
1463 self.assertEquals(context.get_verify_mode(), 0)
1464 context.set_verify(
Hynek Schlawackb4ceed32015-09-05 20:55:19 +02001465 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None
1466 ) # pragma: nocover
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001467 self.assertEquals(
1468 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001469
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001470 def test_load_tmp_dh_wrong_args(self):
1471 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001472 :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with
1473 the wrong number of arguments or with a non-:py:obj:`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001474 """
1475 context = Context(TLSv1_METHOD)
1476 self.assertRaises(TypeError, context.load_tmp_dh)
1477 self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
1478 self.assertRaises(TypeError, context.load_tmp_dh, object())
1479
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001480 def test_load_tmp_dh_missing_file(self):
1481 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001482 :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the
1483 specified file does not exist.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001484 """
1485 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001486 self.assertRaises(Error, context.load_tmp_dh, b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001487
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001488 def _load_tmp_dh_test(self, dhfilename):
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001489 """
1490 Verify that calling ``Context.load_tmp_dh`` with the given filename
1491 does not raise an exception.
1492 """
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001493 context = Context(TLSv1_METHOD)
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001494 with open(dhfilename, "w") as dhfile:
1495 dhfile.write(dhparam)
1496
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001497 context.load_tmp_dh(dhfilename)
1498 # XXX What should I assert here? -exarkun
1499
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001500 def test_load_tmp_dh_bytes(self):
1501 """
1502 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1503 specified file (given as ``bytes``).
1504 """
1505 self._load_tmp_dh_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001506 self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001507 )
1508
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001509 def test_load_tmp_dh_unicode(self):
1510 """
1511 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1512 specified file (given as ``unicode``).
1513 """
1514 self._load_tmp_dh_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001515 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001516 )
1517
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001518 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001519 """
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001520 :py:obj:`Context.set_tmp_ecdh` sets the elliptic curve for
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001521 Diffie-Hellman to the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001522 """
1523 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001524 for curve in get_elliptic_curves():
Hynek Schlawacka07fa8c2015-10-17 10:15:28 +02001525 if curve.name.startswith(u"Oakley-"):
Hynek Schlawack7408aff2015-10-17 09:51:16 +02001526 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1527 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1528 # error queue on OpenSSL 1.0.2.
1529 continue
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001530 # The only easily "assertable" thing is that it does not raise an
1531 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001532 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001533
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001534 def test_set_session_cache_mode_wrong_args(self):
1535 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001536 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1537 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001538 """
1539 context = Context(TLSv1_METHOD)
1540 self.assertRaises(TypeError, context.set_session_cache_mode)
1541 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1542
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001543 def test_get_session_cache_mode_wrong_args(self):
1544 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001545 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1546 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001547 """
1548 context = Context(TLSv1_METHOD)
1549 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1550
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001551 def test_session_cache_mode(self):
1552 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001553 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1554 cached. The setting can be retrieved via
1555 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001556 """
1557 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001558 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001559 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1560 self.assertEqual(SESS_CACHE_OFF, off)
1561 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1562
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001563 @skip_if_py3
1564 def test_session_cache_mode_long(self):
1565 """
1566 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1567 of type :py:obj:`long` as well as :py:obj:`int`.
1568 """
1569 context = Context(TLSv1_METHOD)
1570 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1571 self.assertEqual(
1572 SESS_CACHE_BOTH, context.get_session_cache_mode())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001573
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001574 def test_get_cert_store(self):
1575 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001576 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store`
1577 instance.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001578 """
1579 context = Context(TLSv1_METHOD)
1580 store = context.get_cert_store()
1581 self.assertIsInstance(store, X509Store)
1582
1583
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001584class TestServerNameCallback(object):
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001585 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001586 Tests for `Context.set_tlsext_servername_callback` and its
1587 interaction with `Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001588 """
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001589 def test_old_callback_forgotten(self):
1590 """
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001591 If `Context.set_tlsext_servername_callback` is used to specify
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001592 a new callback, the one it replaces is dereferenced.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001593 """
1594 def callback(connection):
1595 pass
1596
1597 def replacement(connection):
1598 pass
1599
1600 context = Context(TLSv1_METHOD)
1601 context.set_tlsext_servername_callback(callback)
1602
1603 tracker = ref(callback)
1604 del callback
1605
1606 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001607
1608 # One run of the garbage collector happens to work on CPython. PyPy
1609 # doesn't collect the underlying object until a second run for whatever
1610 # reason. That's fine, it still demonstrates our code has properly
1611 # dropped the reference.
1612 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001613 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001614
1615 callback = tracker()
1616 if callback is not None:
1617 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001618 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001619 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001620
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001621 def test_no_servername(self):
1622 """
1623 When a client specifies no server name, the callback passed to
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001624 `Context.set_tlsext_servername_callback` is invoked and the
1625 result of `Connection.get_servername` is `None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001626 """
1627 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001628
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001629 def servername(conn):
1630 args.append((conn, conn.get_servername()))
1631 context = Context(TLSv1_METHOD)
1632 context.set_tlsext_servername_callback(servername)
1633
1634 # Lose our reference to it. The Context is responsible for keeping it
1635 # alive now.
1636 del servername
1637 collect()
1638
1639 # Necessary to actually accept the connection
1640 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001641 context.use_certificate(
1642 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001643
1644 # Do a little connection to trigger the logic
1645 server = Connection(context, None)
1646 server.set_accept_state()
1647
1648 client = Connection(Context(TLSv1_METHOD), None)
1649 client.set_connect_state()
1650
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001651 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001652
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001653 assert args == [(server, None)]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001654
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001655 def test_servername(self):
1656 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001657 When a client specifies a server name in its hello message, the
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001658 callback passed to `Contexts.set_tlsext_servername_callback` is
1659 invoked and the result of `Connection.get_servername` is that
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001660 server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001661 """
1662 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001663
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001664 def servername(conn):
1665 args.append((conn, conn.get_servername()))
1666 context = Context(TLSv1_METHOD)
1667 context.set_tlsext_servername_callback(servername)
1668
1669 # Necessary to actually accept the connection
1670 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001671 context.use_certificate(
1672 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001673
1674 # Do a little connection to trigger the logic
1675 server = Connection(context, None)
1676 server.set_accept_state()
1677
1678 client = Connection(Context(TLSv1_METHOD), None)
1679 client.set_connect_state()
Alex Gaynore7f51982016-09-11 11:48:14 -04001680 client.set_tlsext_host_name(b"foo1.example.com")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001681
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001682 interact_in_memory(server, client)
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001683
Alex Chan1ca9e3a2016-11-05 13:01:51 +00001684 assert args == [(server, b"foo1.example.com")]
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001685
1686
Alex Chan9e08b3e2016-11-10 12:18:54 +00001687class TestNextProtoNegotiation(object):
Cory Benfield84a121e2014-03-31 20:30:25 +01001688 """
1689 Test for Next Protocol Negotiation in PyOpenSSL.
1690 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001691 def test_npn_success(self):
1692 """
1693 Tests that clients and servers that agree on the negotiated next
1694 protocol can correct establish a connection, and that the agreed
1695 protocol is reported by the connections.
1696 """
1697 advertise_args = []
1698 select_args = []
1699
1700 def advertise(conn):
1701 advertise_args.append((conn,))
1702 return [b'http/1.1', b'spdy/2']
1703
1704 def select(conn, options):
1705 select_args.append((conn, options))
1706 return b'spdy/2'
1707
1708 server_context = Context(TLSv1_METHOD)
1709 server_context.set_npn_advertise_callback(advertise)
1710
1711 client_context = Context(TLSv1_METHOD)
1712 client_context.set_npn_select_callback(select)
1713
1714 # Necessary to actually accept the connection
1715 server_context.use_privatekey(
1716 load_privatekey(FILETYPE_PEM, server_key_pem))
1717 server_context.use_certificate(
1718 load_certificate(FILETYPE_PEM, server_cert_pem))
1719
1720 # Do a little connection to trigger the logic
1721 server = Connection(server_context, None)
1722 server.set_accept_state()
1723
1724 client = Connection(client_context, None)
1725 client.set_connect_state()
1726
1727 interact_in_memory(server, client)
1728
1729 assert advertise_args == [(server,)]
1730 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1731
1732 assert server.get_next_proto_negotiated() == b'spdy/2'
1733 assert client.get_next_proto_negotiated() == b'spdy/2'
1734
1735 def test_npn_client_fail(self):
1736 """
1737 Tests that when clients and servers cannot agree on what protocol
1738 to use next that the TLS connection does not get established.
1739 """
1740 advertise_args = []
1741 select_args = []
1742
1743 def advertise(conn):
1744 advertise_args.append((conn,))
1745 return [b'http/1.1', b'spdy/2']
1746
1747 def select(conn, options):
1748 select_args.append((conn, options))
1749 return b''
1750
1751 server_context = Context(TLSv1_METHOD)
1752 server_context.set_npn_advertise_callback(advertise)
1753
1754 client_context = Context(TLSv1_METHOD)
1755 client_context.set_npn_select_callback(select)
1756
1757 # Necessary to actually accept the connection
1758 server_context.use_privatekey(
1759 load_privatekey(FILETYPE_PEM, server_key_pem))
1760 server_context.use_certificate(
1761 load_certificate(FILETYPE_PEM, server_cert_pem))
1762
1763 # Do a little connection to trigger the logic
1764 server = Connection(server_context, None)
1765 server.set_accept_state()
1766
1767 client = Connection(client_context, None)
1768 client.set_connect_state()
1769
1770 # If the client doesn't return anything, the connection will fail.
1771 with pytest.raises(Error):
1772 interact_in_memory(server, client)
1773
1774 assert advertise_args == [(server,)]
1775 assert select_args == [(client, [b'http/1.1', b'spdy/2'])]
1776
1777 def test_npn_select_error(self):
1778 """
1779 Test that we can handle exceptions in the select callback. If
1780 select fails it should be fatal to the connection.
1781 """
1782 advertise_args = []
1783
1784 def advertise(conn):
1785 advertise_args.append((conn,))
1786 return [b'http/1.1', b'spdy/2']
1787
1788 def select(conn, options):
1789 raise TypeError
1790
1791 server_context = Context(TLSv1_METHOD)
1792 server_context.set_npn_advertise_callback(advertise)
1793
1794 client_context = Context(TLSv1_METHOD)
1795 client_context.set_npn_select_callback(select)
1796
1797 # Necessary to actually accept the connection
1798 server_context.use_privatekey(
1799 load_privatekey(FILETYPE_PEM, server_key_pem))
1800 server_context.use_certificate(
1801 load_certificate(FILETYPE_PEM, server_cert_pem))
1802
1803 # Do a little connection to trigger the logic
1804 server = Connection(server_context, None)
1805 server.set_accept_state()
1806
1807 client = Connection(client_context, None)
1808 client.set_connect_state()
1809
1810 # If the callback throws an exception it should be raised here.
1811 with pytest.raises(TypeError):
1812 interact_in_memory(server, client)
1813 assert advertise_args == [(server,), ]
1814
1815 def test_npn_advertise_error(self):
1816 """
1817 Test that we can handle exceptions in the advertise callback. If
1818 advertise fails no NPN is advertised to the client.
1819 """
1820 select_args = []
1821
1822 def advertise(conn):
1823 raise TypeError
1824
1825 def select(conn, options): # pragma: nocover
Cory Benfieldba1820d2015-04-13 17:39:12 -04001826 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001827 Assert later that no args are actually appended.
Cory Benfieldba1820d2015-04-13 17:39:12 -04001828 """
Alex Chan9e08b3e2016-11-10 12:18:54 +00001829 select_args.append((conn, options))
1830 return b''
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001831
Alex Chan9e08b3e2016-11-10 12:18:54 +00001832 server_context = Context(TLSv1_METHOD)
1833 server_context.set_npn_advertise_callback(advertise)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001834
Alex Chan9e08b3e2016-11-10 12:18:54 +00001835 client_context = Context(TLSv1_METHOD)
1836 client_context.set_npn_select_callback(select)
Cory Benfield84a121e2014-03-31 20:30:25 +01001837
Alex Chan9e08b3e2016-11-10 12:18:54 +00001838 # Necessary to actually accept the connection
1839 server_context.use_privatekey(
1840 load_privatekey(FILETYPE_PEM, server_key_pem))
1841 server_context.use_certificate(
1842 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield84a121e2014-03-31 20:30:25 +01001843
Alex Chan9e08b3e2016-11-10 12:18:54 +00001844 # Do a little connection to trigger the logic
1845 server = Connection(server_context, None)
1846 server.set_accept_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001847
Alex Chan9e08b3e2016-11-10 12:18:54 +00001848 client = Connection(client_context, None)
1849 client.set_connect_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001850
Alex Chan9e08b3e2016-11-10 12:18:54 +00001851 # If the client doesn't return anything, the connection will fail.
1852 with pytest.raises(TypeError):
1853 interact_in_memory(server, client)
1854 assert select_args == []
Cory Benfield0ea76e72015-03-22 09:05:28 +00001855
1856
Alex Chanec1e32d2016-11-10 14:11:45 +00001857class TestApplicationLayerProtoNegotiation(object):
Cory Benfield12eae892014-06-07 15:42:56 +01001858 """
1859 Tests for ALPN in PyOpenSSL.
1860 """
Cory Benfielde46fa842015-04-13 16:50:49 -04001861 # Skip tests on versions that don't support ALPN.
1862 if _lib.Cryptography_HAS_ALPN:
Cory Benfield12eae892014-06-07 15:42:56 +01001863
Cory Benfielde46fa842015-04-13 16:50:49 -04001864 def test_alpn_success(self):
1865 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001866 Clients and servers that agree on the negotiated ALPN protocol can
1867 correct establish a connection, and the agreed protocol is reported
1868 by the connections.
Cory Benfielde46fa842015-04-13 16:50:49 -04001869 """
1870 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001871
Cory Benfielde46fa842015-04-13 16:50:49 -04001872 def select(conn, options):
1873 select_args.append((conn, options))
1874 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001875
Cory Benfielde46fa842015-04-13 16:50:49 -04001876 client_context = Context(TLSv1_METHOD)
1877 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001878
Cory Benfielde46fa842015-04-13 16:50:49 -04001879 server_context = Context(TLSv1_METHOD)
1880 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001881
Cory Benfielde46fa842015-04-13 16:50:49 -04001882 # Necessary to actually accept the connection
1883 server_context.use_privatekey(
1884 load_privatekey(FILETYPE_PEM, server_key_pem))
1885 server_context.use_certificate(
1886 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001887
Cory Benfielde46fa842015-04-13 16:50:49 -04001888 # Do a little connection to trigger the logic
1889 server = Connection(server_context, None)
1890 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001891
Cory Benfielde46fa842015-04-13 16:50:49 -04001892 client = Connection(client_context, None)
1893 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001894
Alex Chanec1e32d2016-11-10 14:11:45 +00001895 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001896
Alex Chanec1e32d2016-11-10 14:11:45 +00001897 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfielde46fa842015-04-13 16:50:49 -04001898
Alex Chanec1e32d2016-11-10 14:11:45 +00001899 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1900 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001901
Cory Benfielde46fa842015-04-13 16:50:49 -04001902 def test_alpn_set_on_connection(self):
1903 """
1904 The same as test_alpn_success, but setting the ALPN protocols on
1905 the connection rather than the context.
1906 """
1907 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001908
Cory Benfielde46fa842015-04-13 16:50:49 -04001909 def select(conn, options):
1910 select_args.append((conn, options))
1911 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001912
Cory Benfielde46fa842015-04-13 16:50:49 -04001913 # Setup the client context but don't set any ALPN protocols.
1914 client_context = Context(TLSv1_METHOD)
Cory Benfield12eae892014-06-07 15:42:56 +01001915
Cory Benfielde46fa842015-04-13 16:50:49 -04001916 server_context = Context(TLSv1_METHOD)
1917 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001918
Cory Benfielde46fa842015-04-13 16:50:49 -04001919 # Necessary to actually accept the connection
1920 server_context.use_privatekey(
1921 load_privatekey(FILETYPE_PEM, server_key_pem))
1922 server_context.use_certificate(
1923 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001924
Cory Benfielde46fa842015-04-13 16:50:49 -04001925 # Do a little connection to trigger the logic
1926 server = Connection(server_context, None)
1927 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001928
Cory Benfielde46fa842015-04-13 16:50:49 -04001929 # Set the ALPN protocols on the client connection.
1930 client = Connection(client_context, None)
1931 client.set_alpn_protos([b'http/1.1', b'spdy/2'])
1932 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001933
Alex Chanec1e32d2016-11-10 14:11:45 +00001934 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001935
Alex Chanec1e32d2016-11-10 14:11:45 +00001936 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001937
Alex Chanec1e32d2016-11-10 14:11:45 +00001938 assert server.get_alpn_proto_negotiated() == b'spdy/2'
1939 assert client.get_alpn_proto_negotiated() == b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001940
Cory Benfielde46fa842015-04-13 16:50:49 -04001941 def test_alpn_server_fail(self):
1942 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001943 When clients and servers cannot agree on what protocol to use next
1944 the TLS connection does not get established.
Cory Benfielde46fa842015-04-13 16:50:49 -04001945 """
1946 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001947
Cory Benfielde46fa842015-04-13 16:50:49 -04001948 def select(conn, options):
1949 select_args.append((conn, options))
1950 return b''
Cory Benfield12eae892014-06-07 15:42:56 +01001951
Cory Benfielde46fa842015-04-13 16:50:49 -04001952 client_context = Context(TLSv1_METHOD)
1953 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001954
Cory Benfielde46fa842015-04-13 16:50:49 -04001955 server_context = Context(TLSv1_METHOD)
1956 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001957
Cory Benfielde46fa842015-04-13 16:50:49 -04001958 # Necessary to actually accept the connection
1959 server_context.use_privatekey(
1960 load_privatekey(FILETYPE_PEM, server_key_pem))
1961 server_context.use_certificate(
1962 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001963
Cory Benfielde46fa842015-04-13 16:50:49 -04001964 # Do a little connection to trigger the logic
1965 server = Connection(server_context, None)
1966 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001967
Cory Benfielde46fa842015-04-13 16:50:49 -04001968 client = Connection(client_context, None)
1969 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001970
Cory Benfielde46fa842015-04-13 16:50:49 -04001971 # If the client doesn't return anything, the connection will fail.
Alex Chanec1e32d2016-11-10 14:11:45 +00001972 with pytest.raises(Error):
1973 interact_in_memory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001974
Alex Chanec1e32d2016-11-10 14:11:45 +00001975 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfield12eae892014-06-07 15:42:56 +01001976
Cory Benfielde46fa842015-04-13 16:50:49 -04001977 def test_alpn_no_server(self):
1978 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001979 When clients and servers cannot agree on what protocol to use next
1980 because the server doesn't offer ALPN, no protocol is negotiated.
Cory Benfielde46fa842015-04-13 16:50:49 -04001981 """
1982 client_context = Context(TLSv1_METHOD)
1983 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfielde3d57152015-04-11 17:57:35 -04001984
Cory Benfielde46fa842015-04-13 16:50:49 -04001985 server_context = Context(TLSv1_METHOD)
Cory Benfielde3d57152015-04-11 17:57:35 -04001986
Cory Benfielde46fa842015-04-13 16:50:49 -04001987 # Necessary to actually accept the connection
1988 server_context.use_privatekey(
1989 load_privatekey(FILETYPE_PEM, server_key_pem))
1990 server_context.use_certificate(
1991 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfielde3d57152015-04-11 17:57:35 -04001992
Cory Benfielde46fa842015-04-13 16:50:49 -04001993 # Do a little connection to trigger the logic
1994 server = Connection(server_context, None)
1995 server.set_accept_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001996
Cory Benfielde46fa842015-04-13 16:50:49 -04001997 client = Connection(client_context, None)
1998 client.set_connect_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001999
Cory Benfielde46fa842015-04-13 16:50:49 -04002000 # Do the dance.
Alex Chanec1e32d2016-11-10 14:11:45 +00002001 interact_in_memory(server, client)
Cory Benfielde3d57152015-04-11 17:57:35 -04002002
Alex Chanec1e32d2016-11-10 14:11:45 +00002003 assert client.get_alpn_proto_negotiated() == b''
Cory Benfielde3d57152015-04-11 17:57:35 -04002004
Cory Benfielde46fa842015-04-13 16:50:49 -04002005 def test_alpn_callback_exception(self):
2006 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04002007 We can handle exceptions in the ALPN select callback.
Cory Benfielde46fa842015-04-13 16:50:49 -04002008 """
2009 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002010
Cory Benfielde46fa842015-04-13 16:50:49 -04002011 def select(conn, options):
2012 select_args.append((conn, options))
Cory Benfieldef401452015-04-13 18:17:36 -04002013 raise TypeError()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002014
Cory Benfielde46fa842015-04-13 16:50:49 -04002015 client_context = Context(TLSv1_METHOD)
2016 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfieldf1177e72015-04-12 09:11:49 -04002017
Cory Benfielde46fa842015-04-13 16:50:49 -04002018 server_context = Context(TLSv1_METHOD)
2019 server_context.set_alpn_select_callback(select)
Cory Benfieldf1177e72015-04-12 09:11:49 -04002020
Cory Benfielde46fa842015-04-13 16:50:49 -04002021 # Necessary to actually accept the connection
2022 server_context.use_privatekey(
2023 load_privatekey(FILETYPE_PEM, server_key_pem))
2024 server_context.use_certificate(
2025 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfieldf1177e72015-04-12 09:11:49 -04002026
Cory Benfielde46fa842015-04-13 16:50:49 -04002027 # Do a little connection to trigger the logic
2028 server = Connection(server_context, None)
2029 server.set_accept_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002030
Cory Benfielde46fa842015-04-13 16:50:49 -04002031 client = Connection(client_context, None)
2032 client.set_connect_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002033
Alex Chanec1e32d2016-11-10 14:11:45 +00002034 with pytest.raises(TypeError):
2035 interact_in_memory(server, client)
2036 assert select_args == [(server, [b'http/1.1', b'spdy/2'])]
Cory Benfieldf1177e72015-04-12 09:11:49 -04002037
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002038 else:
2039 # No ALPN.
2040 def test_alpn_not_implemented(self):
Cory Benfieldef401452015-04-13 18:17:36 -04002041 """
2042 If ALPN is not in OpenSSL, we should raise NotImplementedError.
2043 """
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002044 # Test the context methods first.
2045 context = Context(TLSv1_METHOD)
Alex Chanec1e32d2016-11-10 14:11:45 +00002046 with pytest.raises(NotImplementedError):
2047 context.set_alpn_protos(None)
2048 with pytest.raises(NotImplementedError):
2049 context.set_alpn_select_callback(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002050
2051 # Now test a connection.
2052 conn = Connection(context)
Alex Chanec1e32d2016-11-10 14:11:45 +00002053 with pytest.raises(NotImplementedError):
2054 conn.set_alpn_protos(None)
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002055
Cory Benfieldf1177e72015-04-12 09:11:49 -04002056
Alex Chanec1e32d2016-11-10 14:11:45 +00002057class TestSession(object):
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002058 """
2059 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2060 """
2061 def test_construction(self):
2062 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002063 :py:class:`Session` can be constructed with no arguments, creating
2064 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002065 """
2066 new_session = Session()
Alex Chanec1e32d2016-11-10 14:11:45 +00002067 assert isinstance(new_session, Session)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002068
2069
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002070class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05002071 """
Hynek Schlawackaa861212016-03-13 13:53:48 +01002072 Unit tests for :class:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002073 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002074 # XXX get_peer_certificate -> None
2075 # XXX sock_shutdown
2076 # XXX master_key -> TypeError
2077 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002078 # XXX connect -> TypeError
2079 # XXX connect_ex -> TypeError
2080 # XXX set_connect_state -> TypeError
2081 # XXX set_accept_state -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002082 # XXX do_handshake -> TypeError
2083 # XXX bio_read -> TypeError
2084 # XXX recv -> TypeError
2085 # XXX send -> TypeError
2086 # XXX bio_write -> TypeError
2087
Rick Deane15b1472009-07-09 15:53:42 -05002088 def test_type(self):
2089 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002090 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same
2091 type object and can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002092 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002093 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05002094 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002095 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002096
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002097 def test_get_context(self):
2098 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002099 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance
2100 used to construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002101 """
2102 context = Context(TLSv1_METHOD)
2103 connection = Connection(context, None)
2104 self.assertIdentical(connection.get_context(), context)
2105
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002106 def test_get_context_wrong_args(self):
2107 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002108 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called
2109 with any arguments.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002110 """
2111 connection = Connection(Context(TLSv1_METHOD), None)
2112 self.assertRaises(TypeError, connection.get_context, None)
2113
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002114 def test_set_context_wrong_args(self):
2115 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002116 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called
2117 with a non-:py:obj:`Context` instance argument or with any number of
2118 arguments other than 1.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002119 """
2120 ctx = Context(TLSv1_METHOD)
2121 connection = Connection(ctx, None)
2122 self.assertRaises(TypeError, connection.set_context)
2123 self.assertRaises(TypeError, connection.set_context, object())
2124 self.assertRaises(TypeError, connection.set_context, "hello")
2125 self.assertRaises(TypeError, connection.set_context, 1)
2126 self.assertRaises(TypeError, connection.set_context, 1, 2)
2127 self.assertRaises(
2128 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
2129 self.assertIdentical(ctx, connection.get_context())
2130
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002131 def test_set_context(self):
2132 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002133 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context`
2134 instance to be used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002135 """
2136 original = Context(SSLv23_METHOD)
2137 replacement = Context(TLSv1_METHOD)
2138 connection = Connection(original, None)
2139 connection.set_context(replacement)
2140 self.assertIdentical(replacement, connection.get_context())
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002141 # Lose our references to the contexts, just in case the Connection
2142 # isn't properly managing its own contributions to their reference
2143 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002144 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002145 collect()
2146
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002147 def test_set_tlsext_host_name_wrong_args(self):
2148 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002149 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte
2150 string argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09002151 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002152 """
2153 conn = Connection(Context(TLSv1_METHOD), None)
2154 self.assertRaises(TypeError, conn.set_tlsext_host_name)
2155 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
2156 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
2157 self.assertRaises(
Alex Gaynore7f51982016-09-11 11:48:14 -04002158 TypeError, conn.set_tlsext_host_name, b"with\0null")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002159
Abraham Martinc5484ba2015-03-25 15:33:05 +00002160 if PY3:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002161 # On Python 3.x, don't accidentally implicitly convert from text.
2162 self.assertRaises(
2163 TypeError,
Alex Gaynore7f51982016-09-11 11:48:14 -04002164 conn.set_tlsext_host_name, b"example.com".decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002165
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002166 def test_get_servername_wrong_args(self):
2167 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002168 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if
2169 called with any arguments.
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002170 """
2171 connection = Connection(Context(TLSv1_METHOD), None)
2172 self.assertRaises(TypeError, connection.get_servername, object())
2173 self.assertRaises(TypeError, connection.get_servername, 1)
2174 self.assertRaises(TypeError, connection.get_servername, "hello")
2175
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002176 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002177 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002178 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002179 immediate read.
2180 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002181 connection = Connection(Context(TLSv1_METHOD), None)
2182 self.assertEquals(connection.pending(), 0)
2183
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002184 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002185 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002186 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with
2187 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002188 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002189 connection = Connection(Context(TLSv1_METHOD), None)
2190 self.assertRaises(TypeError, connection.pending, None)
2191
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002192 def test_peek(self):
2193 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002194 :py:obj:`Connection.recv` peeks into the connection if
2195 :py:obj:`socket.MSG_PEEK` is passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002196 """
2197 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002198 server.send(b'xy')
2199 self.assertEqual(client.recv(2, MSG_PEEK), b'xy')
2200 self.assertEqual(client.recv(2, MSG_PEEK), b'xy')
2201 self.assertEqual(client.recv(2), b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002202
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002203 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002204 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002205 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
2206 a non-address argument or with the wrong number of arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002207 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002208 connection = Connection(Context(TLSv1_METHOD), socket())
2209 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002210 self.assertRaises(TypeError, connection.connect)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002211 self.assertRaises(
2212 TypeError, connection.connect, ("127.0.0.1", 1), None
2213 )
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002214
kjavfe508d62015-09-02 12:20:35 +01002215 def test_connection_undefined_attr(self):
2216 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002217 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
2218 a non-address argument or with the wrong number of arguments.
kjavfe508d62015-09-02 12:20:35 +01002219 """
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002220
kjavfe508d62015-09-02 12:20:35 +01002221 def attr_access_test(connection):
2222 return connection.an_attribute_which_is_not_defined
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002223
kjavfe508d62015-09-02 12:20:35 +01002224 connection = Connection(Context(TLSv1_METHOD), None)
2225 self.assertRaises(AttributeError, attr_access_test, connection)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002226
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002227 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002228 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002229 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the
2230 underlying socket connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002231 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002232 client = socket()
2233 context = Context(TLSv1_METHOD)
2234 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002235 # pytest.raises here doesn't work because of a bug in py.test on Python
2236 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002237 try:
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002238 clientSSL.connect(("127.0.0.1", 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002239 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002240 exc = e
2241 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002242
2243 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002244 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002245 :py:obj:`Connection.connect` establishes a connection to the specified
2246 address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002247 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002248 port = socket()
2249 port.bind(('', 0))
2250 port.listen(3)
2251
2252 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002253 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
2254 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002255
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002256 @pytest.mark.skipif(
2257 platform == "darwin",
2258 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
2259 )
2260 def test_connect_ex(self):
2261 """
2262 If there is a connection error, :py:obj:`Connection.connect_ex`
2263 returns the errno instead of raising an exception.
2264 """
2265 port = socket()
2266 port.bind(('', 0))
2267 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002268
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002269 clientSSL = Connection(Context(TLSv1_METHOD), socket())
2270 clientSSL.setblocking(False)
2271 result = clientSSL.connect_ex(port.getsockname())
2272 expected = (EINPROGRESS, EWOULDBLOCK)
2273 self.assertTrue(
2274 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04002275
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002276 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002277 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002278 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with
2279 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002280 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002281 connection = Connection(Context(TLSv1_METHOD), socket())
2282 self.assertRaises(TypeError, connection.accept, None)
2283
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002284 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002285 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002286 :py:obj:`Connection.accept` accepts a pending connection attempt and
2287 returns a tuple of a new :py:obj:`Connection` (the accepted client) and
2288 the address the connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002289 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002290 ctx = Context(TLSv1_METHOD)
2291 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2292 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002293 port = socket()
2294 portSSL = Connection(ctx, port)
2295 portSSL.bind(('', 0))
2296 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002297
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002298 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002299
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002300 # Calling portSSL.getsockname() here to get the server IP address
2301 # sounds great, but frequently fails on Windows.
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002302 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002303
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002304 serverSSL, address = portSSL.accept()
2305
2306 self.assertTrue(isinstance(serverSSL, Connection))
2307 self.assertIdentical(serverSSL.get_context(), ctx)
2308 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002309
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002310 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002311 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002312 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with
2313 the wrong number of arguments or with arguments other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002314 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002315 connection = Connection(Context(TLSv1_METHOD), None)
2316 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04002317 self.assertRaises(TypeError, connection.get_shutdown, None)
2318 self.assertRaises(TypeError, connection.set_shutdown)
2319 self.assertRaises(TypeError, connection.set_shutdown, None)
2320 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002321
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002322 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002323 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002324 :py:obj:`Connection.shutdown` performs an SSL-level connection
2325 shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002326 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002327 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002328 self.assertFalse(server.shutdown())
2329 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002330 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002331 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
2332 client.shutdown()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002333 self.assertEquals(
2334 client.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2335 )
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002336 self.assertRaises(ZeroReturnError, server.recv, 1024)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002337 self.assertEquals(
2338 server.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2339 )
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002340
Paul Aurichc85e0862015-01-08 08:34:33 -08002341 def test_shutdown_closed(self):
2342 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002343 If the underlying socket is closed, :py:obj:`Connection.shutdown`
2344 propagates the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002345 """
2346 server, client = self._loopback()
2347 server.sock_shutdown(2)
2348 exc = self.assertRaises(SysCallError, server.shutdown)
2349 if platform == "win32":
2350 self.assertEqual(exc.args[0], ESHUTDOWN)
2351 else:
2352 self.assertEqual(exc.args[0], EPIPE)
2353
Glyph89389472015-04-14 17:29:26 -04002354 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002355 """
Glyph89389472015-04-14 17:29:26 -04002356 If the underlying connection is truncated, :obj:`Connection.shutdown`
2357 raises an :obj:`Error`.
Glyph6064ec32015-04-14 16:38:22 -04002358 """
Glyph89389472015-04-14 17:29:26 -04002359 server_ctx = Context(TLSv1_METHOD)
2360 client_ctx = Context(TLSv1_METHOD)
2361 server_ctx.use_privatekey(
2362 load_privatekey(FILETYPE_PEM, server_key_pem))
2363 server_ctx.use_certificate(
2364 load_certificate(FILETYPE_PEM, server_cert_pem))
2365 server = Connection(server_ctx, None)
2366 client = Connection(client_ctx, None)
2367 self._handshakeInMemory(client, server)
2368 self.assertEqual(server.shutdown(), False)
2369 self.assertRaises(WantReadError, server.shutdown)
2370 server.bio_shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002371 self.assertRaises(Error, server.shutdown)
2372
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002373 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002374 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002375 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection
2376 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002377 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002378 connection = Connection(Context(TLSv1_METHOD), socket())
2379 connection.set_shutdown(RECEIVED_SHUTDOWN)
2380 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
2381
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002382 @skip_if_py3
2383 def test_set_shutdown_long(self):
2384 """
2385 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
2386 of type :py:obj:`long` as well as :py:obj:`int`.
2387 """
2388 connection = Connection(Context(TLSv1_METHOD), socket())
2389 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
2390 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002391
kjavaf248592015-09-07 12:14:01 +01002392 def test_state_string(self):
2393 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002394 :meth:`Connection.state_string` verbosely describes the current
2395 state of the :class:`Connection`.
kjavaf248592015-09-07 12:14:01 +01002396 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002397 server, client = socket_pair()
kjavaf248592015-09-07 12:14:01 +01002398 server = self._loopbackServerFactory(server)
2399 client = self._loopbackClientFactory(client)
2400
Alex Gaynor5af32d02016-09-24 01:52:21 -04002401 assert server.get_state_string() in [
2402 b"before/accept initialization", b"before SSL initialization"
2403 ]
2404 assert client.get_state_string() in [
2405 b"before/connect initialization", b"before SSL initialization"
2406 ]
kjavaf248592015-09-07 12:14:01 +01002407
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002408 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002409 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002410 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called
2411 with other than one argument. :py:obj:`Connection.get_app_data` raises
2412 :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002413 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002414 conn = Connection(Context(TLSv1_METHOD), None)
2415 self.assertRaises(TypeError, conn.get_app_data, None)
2416 self.assertRaises(TypeError, conn.set_app_data)
2417 self.assertRaises(TypeError, conn.set_app_data, None, None)
2418
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002419 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002420 """
2421 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002422 :py:obj:`Connection.set_app_data` and later retrieved with
2423 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002424 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002425 conn = Connection(Context(TLSv1_METHOD), None)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002426 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002427 app_data = object()
2428 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002429 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002430
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002431 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002432 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002433 :py:obj:`Connection.makefile` is not implemented and calling that
2434 method raises :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002435 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002436 conn = Connection(Context(TLSv1_METHOD), None)
2437 self.assertRaises(NotImplementedError, conn.makefile)
2438
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002439 def test_get_peer_cert_chain_wrong_args(self):
2440 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002441 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if
2442 called with any arguments.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002443 """
2444 conn = Connection(Context(TLSv1_METHOD), None)
2445 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
2446 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
2447 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
2448 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
2449
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002450 def test_get_peer_cert_chain(self):
2451 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002452 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates
2453 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002454 """
2455 chain = _create_certificate_chain()
2456 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2457
2458 serverContext = Context(TLSv1_METHOD)
2459 serverContext.use_privatekey(skey)
2460 serverContext.use_certificate(scert)
2461 serverContext.add_extra_chain_cert(icert)
2462 serverContext.add_extra_chain_cert(cacert)
2463 server = Connection(serverContext, None)
2464 server.set_accept_state()
2465
2466 # Create the client
2467 clientContext = Context(TLSv1_METHOD)
2468 clientContext.set_verify(VERIFY_NONE, verify_cb)
2469 client = Connection(clientContext, None)
2470 client.set_connect_state()
2471
2472 self._interactInMemory(client, server)
2473
2474 chain = client.get_peer_cert_chain()
2475 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002476 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002477 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002478 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002479 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002480 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002481 "Authority Certificate", chain[2].get_subject().CN)
2482
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002483 def test_get_peer_cert_chain_none(self):
2484 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002485 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the
2486 peer sends no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002487 """
2488 ctx = Context(TLSv1_METHOD)
2489 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2490 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2491 server = Connection(ctx, None)
2492 server.set_accept_state()
2493 client = Connection(Context(TLSv1_METHOD), None)
2494 client.set_connect_state()
2495 self._interactInMemory(client, server)
2496 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002497
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002498 def test_get_session_wrong_args(self):
2499 """
2500 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
2501 with any arguments.
2502 """
2503 ctx = Context(TLSv1_METHOD)
2504 server = Connection(ctx, None)
2505 self.assertRaises(TypeError, server.get_session, 123)
2506 self.assertRaises(TypeError, server.get_session, "hello")
2507 self.assertRaises(TypeError, server.get_session, object())
2508
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002509 def test_get_session_unconnected(self):
2510 """
2511 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
2512 an object which has not been connected.
2513 """
2514 ctx = Context(TLSv1_METHOD)
2515 server = Connection(ctx, None)
2516 session = server.get_session()
2517 self.assertIdentical(None, session)
2518
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002519 def test_server_get_session(self):
2520 """
2521 On the server side of a connection, :py:obj:`Connection.get_session`
2522 returns a :py:class:`Session` instance representing the SSL session for
2523 that connection.
2524 """
2525 server, client = self._loopback()
2526 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002527 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002528
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002529 def test_client_get_session(self):
2530 """
2531 On the client side of a connection, :py:obj:`Connection.get_session`
2532 returns a :py:class:`Session` instance representing the SSL session for
2533 that connection.
2534 """
2535 server, client = self._loopback()
2536 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002537 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002538
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002539 def test_set_session_wrong_args(self):
2540 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002541 If called with an object that is not an instance of
2542 :py:class:`Session`, or with other than one argument,
2543 :py:obj:`Connection.set_session` raises :py:obj:`TypeError`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002544 """
2545 ctx = Context(TLSv1_METHOD)
2546 connection = Connection(ctx, None)
2547 self.assertRaises(TypeError, connection.set_session)
2548 self.assertRaises(TypeError, connection.set_session, 123)
2549 self.assertRaises(TypeError, connection.set_session, "hello")
2550 self.assertRaises(TypeError, connection.set_session, object())
2551 self.assertRaises(
2552 TypeError, connection.set_session, Session(), Session())
2553
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002554 def test_client_set_session(self):
2555 """
2556 :py:obj:`Connection.set_session`, when used prior to a connection being
2557 established, accepts a :py:class:`Session` instance and causes an
2558 attempt to re-use the session it represents when the SSL handshake is
2559 performed.
2560 """
2561 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2562 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2563 ctx = Context(TLSv1_METHOD)
2564 ctx.use_privatekey(key)
2565 ctx.use_certificate(cert)
2566 ctx.set_session_id("unity-test")
2567
2568 def makeServer(socket):
2569 server = Connection(ctx, socket)
2570 server.set_accept_state()
2571 return server
2572
2573 originalServer, originalClient = self._loopback(
2574 serverFactory=makeServer)
2575 originalSession = originalClient.get_session()
2576
2577 def makeClient(socket):
2578 client = self._loopbackClientFactory(socket)
2579 client.set_session(originalSession)
2580 return client
2581 resumedServer, resumedClient = self._loopback(
2582 serverFactory=makeServer,
2583 clientFactory=makeClient)
2584
2585 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002586 # identifier for the session (new enough versions of OpenSSL expose
2587 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002588 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002589 # session is re-used. As long as the master key for the two
2590 # connections is the same, the session was re-used!
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002591 self.assertEqual(
2592 originalServer.master_key(), resumedServer.master_key())
2593
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002594 def test_set_session_wrong_method(self):
2595 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002596 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002597 instance associated with a context using a different SSL method than
2598 the :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002599 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002600 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002601 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2602 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2603 # is a way to check for 1.1.0)
2604 if SSL_ST_INIT is not None:
2605 v1 = TLSv1_METHOD
2606 v2 = SSLv3_METHOD
2607 else:
2608 v1 = TLSv1_2_METHOD
2609 v2 = TLSv1_METHOD
2610
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002611 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2612 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002613 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002614 ctx.use_privatekey(key)
2615 ctx.use_certificate(cert)
2616 ctx.set_session_id("unity-test")
2617
2618 def makeServer(socket):
2619 server = Connection(ctx, socket)
2620 server.set_accept_state()
2621 return server
2622
Alex Gaynor5af32d02016-09-24 01:52:21 -04002623 def makeOriginalClient(socket):
2624 client = Connection(Context(v1), socket)
2625 client.set_connect_state()
2626 return client
2627
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002628 originalServer, originalClient = self._loopback(
Alex Gaynor5af32d02016-09-24 01:52:21 -04002629 serverFactory=makeServer, clientFactory=makeOriginalClient)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002630 originalSession = originalClient.get_session()
2631
2632 def makeClient(socket):
2633 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002634 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002635 client.set_connect_state()
2636 client.set_session(originalSession)
2637 return client
2638
2639 self.assertRaises(
2640 Error,
2641 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2642
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002643 def test_wantWriteError(self):
2644 """
2645 :py:obj:`Connection` methods which generate output raise
2646 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2647 fail indicating a should-write state.
2648 """
2649 client_socket, server_socket = socket_pair()
2650 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002651 # anything. Only write a single byte at a time so we can be sure we
2652 # completely fill the buffer. Even though the socket API is allowed to
2653 # signal a short write via its return value it seems this doesn't
2654 # always happen on all platforms (FreeBSD and OS X particular) for the
2655 # very last bit of available buffer space.
2656 msg = b"x"
2657 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002658 try:
2659 client_socket.send(msg)
2660 except error as e:
2661 if e.errno == EWOULDBLOCK:
2662 break
2663 raise
2664 else:
2665 self.fail(
2666 "Failed to fill socket buffer, cannot test BIO want write")
2667
2668 ctx = Context(TLSv1_METHOD)
2669 conn = Connection(ctx, client_socket)
2670 # Client's speak first, so make it an SSL client
2671 conn.set_connect_state()
2672 self.assertRaises(WantWriteError, conn.do_handshake)
2673
2674 # XXX want_read
2675
Fedor Brunner416f4a12014-03-28 13:18:38 +01002676 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002677 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002678 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2679 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002680 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002681 ctx = Context(TLSv1_METHOD)
2682 connection = Connection(ctx, None)
2683 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002684
2685 def test_get_peer_finished_before_connect(self):
2686 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002687 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2688 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002689 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002690 ctx = Context(TLSv1_METHOD)
2691 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002692 self.assertEqual(connection.get_peer_finished(), None)
2693
Fedor Brunner416f4a12014-03-28 13:18:38 +01002694 def test_get_finished(self):
2695 """
2696 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002697 message send from client, or server. Finished messages are send during
2698 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002699 """
2700
Fedor Brunner5747b932014-03-05 14:22:34 +01002701 server, client = self._loopback()
2702
2703 self.assertNotEqual(server.get_finished(), None)
2704 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002705
2706 def test_get_peer_finished(self):
2707 """
2708 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002709 message received from client, or server. Finished messages are send
2710 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002711 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002712 server, client = self._loopback()
2713
2714 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002715 self.assertTrue(len(server.get_peer_finished()) > 0)
2716
Fedor Brunner416f4a12014-03-28 13:18:38 +01002717 def test_tls_finished_message_symmetry(self):
2718 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002719 The TLS Finished message send by server must be the TLS Finished
2720 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002721
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002722 The TLS Finished message send by client must be the TLS Finished
2723 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002724 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002725 server, client = self._loopback()
2726
Fedor Brunner5747b932014-03-05 14:22:34 +01002727 self.assertEqual(server.get_finished(), client.get_peer_finished())
2728 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002729
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002730 def test_get_cipher_name_before_connect(self):
2731 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002732 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2733 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002734 """
2735 ctx = Context(TLSv1_METHOD)
2736 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002737 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002738
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002739 def test_get_cipher_name(self):
2740 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002741 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2742 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002743 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002744 server, client = self._loopback()
2745 server_cipher_name, client_cipher_name = \
2746 server.get_cipher_name(), client.get_cipher_name()
2747
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002748 self.assertIsInstance(server_cipher_name, text_type)
2749 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002750
2751 self.assertEqual(server_cipher_name, client_cipher_name)
2752
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002753 def test_get_cipher_version_before_connect(self):
2754 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002755 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2756 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002757 """
2758 ctx = Context(TLSv1_METHOD)
2759 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002760 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002761
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002762 def test_get_cipher_version(self):
2763 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002764 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2765 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002766 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002767 server, client = self._loopback()
2768 server_cipher_version, client_cipher_version = \
2769 server.get_cipher_version(), client.get_cipher_version()
2770
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002771 self.assertIsInstance(server_cipher_version, text_type)
2772 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002773
2774 self.assertEqual(server_cipher_version, client_cipher_version)
2775
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002776 def test_get_cipher_bits_before_connect(self):
2777 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002778 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2779 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002780 """
2781 ctx = Context(TLSv1_METHOD)
2782 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002783 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002784
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002785 def test_get_cipher_bits(self):
2786 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002787 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2788 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002789 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002790 server, client = self._loopback()
2791 server_cipher_bits, client_cipher_bits = \
2792 server.get_cipher_bits(), client.get_cipher_bits()
2793
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002794 self.assertIsInstance(server_cipher_bits, int)
2795 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002796
2797 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002798
Jim Shaverabff1882015-05-27 09:15:55 -04002799 def test_get_protocol_version_name(self):
2800 """
2801 :py:obj:`Connection.get_protocol_version_name()` returns a string
2802 giving the protocol version of the current connection.
2803 """
2804 server, client = self._loopback()
2805 client_protocol_version_name = client.get_protocol_version_name()
2806 server_protocol_version_name = server.get_protocol_version_name()
2807
Jim Shaver58d25732015-05-28 11:52:32 -04002808 self.assertIsInstance(server_protocol_version_name, text_type)
2809 self.assertIsInstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002810
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002811 self.assertEqual(
2812 server_protocol_version_name, client_protocol_version_name
2813 )
Jim Shaverabff1882015-05-27 09:15:55 -04002814
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002815 def test_get_protocol_version(self):
2816 """
Alex Gaynor43307782015-09-04 09:05:45 -04002817 :py:obj:`Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002818 giving the protocol version of the current connection.
2819 """
2820 server, client = self._loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002821 client_protocol_version = client.get_protocol_version()
2822 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002823
Jim Shaverabff1882015-05-27 09:15:55 -04002824 self.assertIsInstance(server_protocol_version, int)
2825 self.assertIsInstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002826
2827 self.assertEqual(server_protocol_version, client_protocol_version)
2828
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002829
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002830class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002831 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002832 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002833 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002834 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002835 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002836 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if
2837 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002838 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002839 connection = Connection(Context(TLSv1_METHOD), None)
2840 self.assertRaises(TypeError, connection.get_cipher_list, None)
2841
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002842 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002843 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002844 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2845 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002846 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002847 connection = Connection(Context(TLSv1_METHOD), None)
2848 ciphers = connection.get_cipher_list()
2849 self.assertTrue(isinstance(ciphers, list))
2850 for cipher in ciphers:
2851 self.assertTrue(isinstance(cipher, str))
2852
2853
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002854class ConnectionSendTests(TestCase, _LoopbackMixin):
2855 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002856 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002857 """
2858 def test_wrong_args(self):
2859 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002860 When called with arguments other than string argument for its first
2861 parameter or more than two arguments, :py:obj:`Connection.send` raises
2862 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002863 """
2864 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002865 self.assertRaises(TypeError, connection.send)
2866 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002867 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002868
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002869 def test_short_bytes(self):
2870 """
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002871 When passed a short byte string, :py:obj:`Connection.send` transmits
2872 all of it and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002873 """
2874 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002875 count = server.send(b'xy')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002876 self.assertEquals(count, 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002877 self.assertEquals(client.recv(2), b'xy')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002878
Abraham Martinef063482015-03-25 14:06:24 +00002879 def test_text(self):
2880 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002881 When passed a text, :py:obj:`Connection.send` transmits all of it and
2882 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002883 """
2884 server, client = self._loopback()
2885 with catch_warnings(record=True) as w:
2886 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002887 count = server.send(b"xy".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002888 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002889 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002890 WARNING_TYPE_EXPECTED
2891 ),
2892 str(w[-1].message)
2893 )
2894 self.assertIs(w[-1].category, DeprecationWarning)
Abraham Martinef063482015-03-25 14:06:24 +00002895 self.assertEquals(count, 2)
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002896 self.assertEquals(client.recv(2), b"xy")
Abraham Martinef063482015-03-25 14:06:24 +00002897
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002898 @skip_if_py26
2899 def test_short_memoryview(self):
2900 """
2901 When passed a memoryview onto a small number of bytes,
2902 :py:obj:`Connection.send` transmits all of them and returns the number
2903 of bytes sent.
2904 """
2905 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002906 count = server.send(memoryview(b'xy'))
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002907 self.assertEquals(count, 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002908 self.assertEquals(client.recv(2), b'xy')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002909
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002910 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002911 def test_short_buffer(self):
2912 """
2913 When passed a buffer containing a small number of bytes,
2914 :py:obj:`Connection.send` transmits all of them and returns the number
2915 of bytes sent.
2916 """
2917 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002918 count = server.send(buffer(b'xy'))
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002919 self.assertEquals(count, 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002920 self.assertEquals(client.recv(2), b'xy')
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002921
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002922
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002923def _make_memoryview(size):
2924 """
2925 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2926 size.
2927 """
2928 return memoryview(bytearray(size))
2929
2930
Cory Benfield62d10332014-06-15 10:03:41 +01002931class ConnectionRecvIntoTests(TestCase, _LoopbackMixin):
2932 """
2933 Tests for :py:obj:`Connection.recv_into`
2934 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002935 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002936 """
2937 Assert that when the given buffer is passed to
2938 ``Connection.recv_into``, whatever bytes are available to be received
2939 that fit into that buffer are written into that buffer.
2940 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002941 output_buffer = factory(5)
2942
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002943 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002944 server.send(b'xy')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002945
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002946 self.assertEqual(client.recv_into(output_buffer), 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002947 self.assertEqual(output_buffer, bytearray(b'xy\x00\x00\x00'))
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002948
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002949 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002950 """
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002951 :py:obj:`Connection.recv_into` can be passed a ``bytearray`` instance
2952 and data in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002953 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002954 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002955
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002956 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002957 """
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002958 Assert that when the given buffer is passed to ``Connection.recv_into``
2959 along with a value for ``nbytes`` that is less than the size of that
2960 buffer, only ``nbytes`` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002961 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002962 output_buffer = factory(10)
2963
Cory Benfield62d10332014-06-15 10:03:41 +01002964 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002965 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002966
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002967 self.assertEqual(client.recv_into(output_buffer, 5), 5)
2968 self.assertEqual(
Alex Gaynore7f51982016-09-11 11:48:14 -04002969 output_buffer, bytearray(b'abcde\x00\x00\x00\x00\x00')
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002970 )
2971
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002972 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002973 """
2974 When called with a ``bytearray`` instance,
2975 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter and
2976 doesn't copy in more than that number of bytes.
2977 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002978 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002979
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002980 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002981 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002982 Assert that if there are more bytes available to be read from the
2983 receive buffer than would fit into the buffer passed to
2984 :py:obj:`Connection.recv_into`, only as many as fit are written into
2985 it.
Cory Benfield62d10332014-06-15 10:03:41 +01002986 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002987 output_buffer = factory(5)
2988
Cory Benfield62d10332014-06-15 10:03:41 +01002989 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002990 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002991
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002992 self.assertEqual(client.recv_into(output_buffer), 5)
Alex Gaynore7f51982016-09-11 11:48:14 -04002993 self.assertEqual(output_buffer, bytearray(b'abcde'))
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002994 rest = client.recv(5)
Alex Gaynore7f51982016-09-11 11:48:14 -04002995 self.assertEqual(b'fghij', rest)
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002996
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002997 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002998 """
2999 When called with a ``bytearray`` instance,
3000 :py:obj:`Connection.recv_into` respects the size of the array and
3001 doesn't write more bytes into it than will fit.
3002 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003003 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003004
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003005 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003006 """
3007 When called with a ``bytearray`` instance and an ``nbytes`` value that
3008 is too large, :py:obj:`Connection.recv_into` respects the size of the
3009 array and not the ``nbytes`` value and doesn't write more bytes into
3010 the buffer than will fit.
3011 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003012 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003013
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003014 def test_peek(self):
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003015 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003016 server.send(b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003017
3018 for _ in range(2):
3019 output_buffer = bytearray(5)
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003020 self.assertEqual(
3021 client.recv_into(output_buffer, flags=MSG_PEEK), 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04003022 self.assertEqual(output_buffer, bytearray(b'xy\x00\x00\x00'))
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003023
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003024 @skip_if_py26
3025 def test_memoryview_no_length(self):
3026 """
3027 :py:obj:`Connection.recv_into` can be passed a ``memoryview``
3028 instance and data in the receive buffer is written to it.
3029 """
3030 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003031
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003032 @skip_if_py26
3033 def test_memoryview_respects_length(self):
3034 """
3035 When called with a ``memoryview`` instance,
3036 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter
3037 and doesn't copy more than that number of bytes in.
3038 """
3039 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003040
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003041 @skip_if_py26
3042 def test_memoryview_doesnt_overfill(self):
3043 """
3044 When called with a ``memoryview`` instance,
3045 :py:obj:`Connection.recv_into` respects the size of the array and
3046 doesn't write more bytes into it than will fit.
3047 """
3048 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003049
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003050 @skip_if_py26
3051 def test_memoryview_really_doesnt_overfill(self):
3052 """
3053 When called with a ``memoryview`` instance and an ``nbytes`` value
3054 that is too large, :py:obj:`Connection.recv_into` respects the size
3055 of the array and not the ``nbytes`` value and doesn't write more
3056 bytes into the buffer than will fit.
3057 """
3058 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003059
Cory Benfield62d10332014-06-15 10:03:41 +01003060
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003061class ConnectionSendallTests(TestCase, _LoopbackMixin):
3062 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003063 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003064 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003065 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003066 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003067 When called with arguments other than a string argument for its first
3068 parameter or with more than two arguments, :py:obj:`Connection.sendall`
3069 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003070 """
3071 connection = Connection(Context(TLSv1_METHOD), None)
3072 self.assertRaises(TypeError, connection.sendall)
3073 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003074 self.assertRaises(
3075 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003076
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003077 def test_short(self):
3078 """
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003079 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3080 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003081 """
3082 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003083 server.sendall(b'x')
3084 self.assertEquals(client.recv(1), b'x')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003085
Abraham Martinef063482015-03-25 14:06:24 +00003086 def test_text(self):
3087 """
Jean-Paul Calderone93477422015-04-13 20:38:57 -04003088 :py:obj:`Connection.sendall` transmits all the content in the string
3089 passed to it raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003090 """
3091 server, client = self._loopback()
3092 with catch_warnings(record=True) as w:
3093 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003094 server.sendall(b"x".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003095 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003096 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003097 WARNING_TYPE_EXPECTED
3098 ),
3099 str(w[-1].message)
3100 )
3101 self.assertIs(w[-1].category, DeprecationWarning)
3102 self.assertEquals(client.recv(1), b"x")
Abraham Martinef063482015-03-25 14:06:24 +00003103
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003104 @skip_if_py26
3105 def test_short_memoryview(self):
3106 """
3107 When passed a memoryview onto a small number of bytes,
3108 :py:obj:`Connection.sendall` transmits all of them.
3109 """
3110 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003111 server.sendall(memoryview(b'x'))
3112 self.assertEquals(client.recv(1), b'x')
Abraham Martinef063482015-03-25 14:06:24 +00003113
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003114 @skip_if_py3
3115 def test_short_buffers(self):
3116 """
3117 When passed a buffer containing a small number of bytes,
3118 :py:obj:`Connection.sendall` transmits all of them.
3119 """
3120 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003121 server.sendall(buffer(b'x'))
3122 self.assertEquals(client.recv(1), b'x')
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003123
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003124 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003125 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003126 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3127 passed to it even if this requires multiple calls of an underlying
3128 write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003129 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003130 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003131 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003132 # On Windows, after 32k of bytes the write will block (forever
3133 # - because no one is yet reading).
Alex Gaynore7f51982016-09-11 11:48:14 -04003134 message = b'x' * (1024 * 32 - 1) + b'y'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003135 server.sendall(message)
3136 accum = []
3137 received = 0
3138 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003139 data = client.recv(1024)
3140 accum.append(data)
3141 received += len(data)
Alex Gaynore7f51982016-09-11 11:48:14 -04003142 self.assertEquals(message, b''.join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003143
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003144 def test_closed(self):
3145 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003146 If the underlying socket is closed, :py:obj:`Connection.sendall`
3147 propagates the write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003148 """
3149 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003150 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003151 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003152 if platform == "win32":
3153 self.assertEqual(exc.args[0], ESHUTDOWN)
3154 else:
3155 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003156
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003157
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003158class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
3159 """
3160 Tests for SSL renegotiation APIs.
3161 """
3162 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003163 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003164 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called
3165 with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003166 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003167 connection = Connection(Context(TLSv1_METHOD), None)
3168 self.assertRaises(TypeError, connection.renegotiate, None)
3169
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003170 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003171 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003172 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if
3173 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003174 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003175 connection = Connection(Context(TLSv1_METHOD), None)
3176 self.assertRaises(TypeError, connection.total_renegotiations, None)
3177
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003178 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003179 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003180 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before
3181 any renegotiations have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003182 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003183 connection = Connection(Context(TLSv1_METHOD), None)
3184 self.assertEquals(connection.total_renegotiations(), 0)
3185
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003186 def test_renegotiate(self):
3187 """
3188 Go through a complete renegotiation cycle.
3189 """
3190 server, client = self._loopback()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003191
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003192 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003193
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003194 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003195
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003196 assert 0 == server.total_renegotiations()
3197 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003198
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003199 assert True is server.renegotiate()
3200
3201 assert True is server.renegotiate_pending()
3202
3203 server.setblocking(False)
3204 client.setblocking(False)
3205
3206 client.do_handshake()
3207 server.do_handshake()
3208
3209 assert 1 == server.total_renegotiations()
3210 while False is server.renegotiate_pending():
3211 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003212
3213
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003214class ErrorTests(TestCase):
3215 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003216 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003217 """
3218 def test_type(self):
3219 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003220 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003221 """
3222 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05003223 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05003224
3225
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003226class ConstantsTests(TestCase):
3227 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003228 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003229
3230 These are values defined by OpenSSL intended only to be used as flags to
3231 OpenSSL APIs. The only assertions it seems can be made about them is
3232 their values.
3233 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003234 @pytest.mark.skipif(
3235 OP_NO_QUERY_MTU is None,
3236 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3237 )
3238 def test_op_no_query_mtu(self):
3239 """
3240 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3241 of :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
3242 """
3243 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003244
Hynek Schlawack35618382015-09-05 21:54:25 +02003245 @pytest.mark.skipif(
3246 OP_COOKIE_EXCHANGE is None,
3247 reason="OP_COOKIE_EXCHANGE unavailable - "
3248 "OpenSSL version may be too old"
3249 )
3250 def test_op_cookie_exchange(self):
3251 """
3252 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3253 value of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by
3254 :file:`openssl/ssl.h`.
3255 """
3256 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003257
Hynek Schlawack35618382015-09-05 21:54:25 +02003258 @pytest.mark.skipif(
3259 OP_NO_TICKET is None,
3260 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3261 )
3262 def test_op_no_ticket(self):
3263 """
3264 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3265 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
3266 """
3267 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003268
Hynek Schlawack35618382015-09-05 21:54:25 +02003269 @pytest.mark.skipif(
3270 OP_NO_COMPRESSION is None,
3271 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3272 )
3273 def test_op_no_compression(self):
3274 """
3275 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3276 value of :py:const:`SSL_OP_NO_COMPRESSION` defined by
3277 :file:`openssl/ssl.h`.
3278 """
3279 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003280
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003281 def test_sess_cache_off(self):
3282 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003283 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3284 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003285 """
3286 self.assertEqual(0x0, SESS_CACHE_OFF)
3287
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003288 def test_sess_cache_client(self):
3289 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003290 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3291 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003292 """
3293 self.assertEqual(0x1, SESS_CACHE_CLIENT)
3294
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003295 def test_sess_cache_server(self):
3296 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003297 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3298 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003299 """
3300 self.assertEqual(0x2, SESS_CACHE_SERVER)
3301
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003302 def test_sess_cache_both(self):
3303 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003304 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3305 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003306 """
3307 self.assertEqual(0x3, SESS_CACHE_BOTH)
3308
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003309 def test_sess_cache_no_auto_clear(self):
3310 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003311 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3312 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3313 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003314 """
3315 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
3316
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003317 def test_sess_cache_no_internal_lookup(self):
3318 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003319 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3320 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3321 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003322 """
3323 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
3324
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003325 def test_sess_cache_no_internal_store(self):
3326 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003327 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3328 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3329 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003330 """
3331 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
3332
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003333 def test_sess_cache_no_internal(self):
3334 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003335 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3336 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
3337 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003338 """
3339 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
3340
3341
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003342class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05003343 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003344 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003345 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003346 def _server(self, sock):
3347 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003348 Create a new server-side SSL :py:obj:`Connection` object wrapped around
3349 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003350 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003351 # Create the server side Connection. This is mostly setup boilerplate
3352 # - use TLSv1, use a particular certificate, etc.
3353 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003354 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003355 server_ctx.set_verify(
3356 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3357 verify_cb
3358 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003359 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003360 server_ctx.use_privatekey(
3361 load_privatekey(FILETYPE_PEM, server_key_pem))
3362 server_ctx.use_certificate(
3363 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003364 server_ctx.check_privatekey()
3365 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003366 # Here the Connection is actually created. If None is passed as the
3367 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003368 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003369 server_conn.set_accept_state()
3370 return server_conn
3371
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003372 def _client(self, sock):
3373 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003374 Create a new client-side SSL :py:obj:`Connection` object wrapped around
3375 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003376 """
3377 # Now create the client side Connection. Similar boilerplate to the
3378 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003379 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003380 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003381 client_ctx.set_verify(
3382 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3383 verify_cb
3384 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003385 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003386 client_ctx.use_privatekey(
3387 load_privatekey(FILETYPE_PEM, client_key_pem))
3388 client_ctx.use_certificate(
3389 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003390 client_ctx.check_privatekey()
3391 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003392 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003393 client_conn.set_connect_state()
3394 return client_conn
3395
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003396 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003397 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003398 Two :py:obj:`Connection`s which use memory BIOs can be manually
3399 connected by reading from the output of each and writing those bytes to
3400 the input of the other and in this way establish a connection and
3401 exchange application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003402 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003403 server_conn = self._server(None)
3404 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003405
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003406 # There should be no key or nonces yet.
3407 self.assertIdentical(server_conn.master_key(), None)
3408 self.assertIdentical(server_conn.client_random(), None)
3409 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003410
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003411 # First, the handshake needs to happen. We'll deliver bytes back and
3412 # forth between the client and server until neither of them feels like
3413 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003414 self.assertIdentical(
3415 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003416
3417 # Now that the handshake is done, there should be a key and nonces.
3418 self.assertNotIdentical(server_conn.master_key(), None)
3419 self.assertNotIdentical(server_conn.client_random(), None)
3420 self.assertNotIdentical(server_conn.server_random(), None)
Hynek Schlawack35618382015-09-05 21:54:25 +02003421 self.assertEquals(
3422 server_conn.client_random(), client_conn.client_random())
3423 self.assertEquals(
3424 server_conn.server_random(), client_conn.server_random())
3425 self.assertNotEquals(
3426 server_conn.client_random(), server_conn.server_random())
3427 self.assertNotEquals(
3428 client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003429
3430 # Here are the bytes we'll try to send.
Alex Gaynore7f51982016-09-11 11:48:14 -04003431 important_message = b'One if by land, two if by sea.'
Rick Deanb71c0d22009-04-01 14:09:23 -05003432
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003433 server_conn.write(important_message)
3434 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003435 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003436 (client_conn, important_message))
3437
3438 client_conn.write(important_message[::-1])
3439 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003440 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003441 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003442
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003443 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003444 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003445 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003446
Hynek Schlawack35618382015-09-05 21:54:25 +02003447 This is primarily to rule out the memory BIO code as the source of any
3448 problems encountered while passing data over a :py:obj:`Connection` (if
3449 this test fails, there must be a problem outside the memory BIO code,
3450 as no memory BIO is involved here). Even though this isn't a memory
3451 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003452 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04003453 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003454
Alex Gaynore7f51982016-09-11 11:48:14 -04003455 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003456 client_conn.send(important_message)
3457 msg = server_conn.recv(1024)
3458 self.assertEqual(msg, important_message)
3459
3460 # Again in the other direction, just for fun.
3461 important_message = important_message[::-1]
3462 server_conn.send(important_message)
3463 msg = client_conn.recv(1024)
3464 self.assertEqual(msg, important_message)
3465
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04003466 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003467 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003468 Test that :py:obj:`OpenSSL.SSL.bio_read` and
3469 :py:obj:`OpenSSL.SSL.bio_write` don't work on
3470 :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003471 """
Alex Gaynor51d424c2016-09-10 14:50:11 -04003472 context = Context(TLSv1_METHOD)
Rick Deanb71c0d22009-04-01 14:09:23 -05003473 client = socket()
3474 clientSSL = Connection(context, client)
Alex Gaynor43307782015-09-04 09:05:45 -04003475 self.assertRaises(TypeError, clientSSL.bio_read, 100)
3476 self.assertRaises(TypeError, clientSSL.bio_write, "foo")
Alex Gaynor7e8b61e2015-09-04 13:13:05 -04003477 self.assertRaises(TypeError, clientSSL.bio_shutdown)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003478
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003479 def test_outgoingOverflow(self):
3480 """
3481 If more bytes than can be written to the memory BIO are passed to
Hynek Schlawack35618382015-09-05 21:54:25 +02003482 :py:obj:`Connection.send` at once, the number of bytes which were
3483 written is returned and that many bytes from the beginning of the input
3484 can be read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003485 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003486 server = self._server(None)
3487 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003488
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003489 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003490
3491 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003492 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003493 # Sanity check. We're trying to test what happens when the entire
3494 # input can't be sent. If the entire input was sent, this test is
3495 # meaningless.
3496 self.assertTrue(sent < size)
3497
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003498 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003499 self.assertIdentical(receiver, server)
3500
3501 # We can rely on all of these bytes being received at once because
3502 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
3503 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003504
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003505 def test_shutdown(self):
3506 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003507 :py:obj:`Connection.bio_shutdown` signals the end of the data stream
3508 from which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003509 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003510 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003511 server.bio_shutdown()
3512 e = self.assertRaises(Error, server.recv, 1024)
3513 # We don't want WantReadError or ZeroReturnError or anything - it's a
3514 # handshake failure.
Alex Gaynor5af32d02016-09-24 01:52:21 -04003515 assert type(e) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003516
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003517 def test_unexpectedEndOfFile(self):
3518 """
3519 If the connection is lost before an orderly SSL shutdown occurs,
3520 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
3521 "Unexpected EOF".
3522 """
3523 server_conn, client_conn = self._loopback()
3524 client_conn.sock_shutdown(SHUT_RDWR)
3525 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
3526 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
3527
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003528 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003529 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003530 Verify the return value of the :py:obj:`get_client_ca_list` method for
3531 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003532
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003533 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003534 before the client and server are connected to each other. This
3535 function should specify a list of CAs for the server to send to the
3536 client and return that same list. The list will be used to verify
Hynek Schlawack35618382015-09-05 21:54:25 +02003537 that :py:obj:`get_client_ca_list` returns the proper value at
3538 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003539 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003540 server = self._server(None)
3541 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003542 self.assertEqual(client.get_client_ca_list(), [])
3543 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003544 ctx = server.get_context()
3545 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003546 self.assertEqual(client.get_client_ca_list(), [])
3547 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003548 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003549 self.assertEqual(client.get_client_ca_list(), expected)
3550 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003551
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003552 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003553 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003554 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if
3555 called with a non-list or a list that contains objects other than
3556 X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003557 """
3558 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003559 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
3560 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
3561 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003562
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003563 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003564 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003565 If passed an empty list, :py:obj:`Context.set_client_ca_list`
3566 configures the context to send no CA names to the client and, on both
3567 the server and client sides, :py:obj:`Connection.get_client_ca_list`
3568 returns an empty list after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003569 """
3570 def no_ca(ctx):
3571 ctx.set_client_ca_list([])
3572 return []
3573 self._check_client_ca_list(no_ca)
3574
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003575 def test_set_one_ca_list(self):
3576 """
3577 If passed a list containing a single X509Name,
Hynek Schlawack35618382015-09-05 21:54:25 +02003578 :py:obj:`Context.set_client_ca_list` configures the context to send
3579 that CA name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003580 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003581 X509Name after the connection is set up.
3582 """
3583 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3584 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003585
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003586 def single_ca(ctx):
3587 ctx.set_client_ca_list([cadesc])
3588 return [cadesc]
3589 self._check_client_ca_list(single_ca)
3590
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003591 def test_set_multiple_ca_list(self):
3592 """
3593 If passed a list containing multiple X509Name objects,
Hynek Schlawack35618382015-09-05 21:54:25 +02003594 :py:obj:`Context.set_client_ca_list` configures the context to send
3595 those CA names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003596 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003597 X509Names after the connection is set up.
3598 """
3599 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3600 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3601
3602 sedesc = secert.get_subject()
3603 cldesc = clcert.get_subject()
3604
3605 def multiple_ca(ctx):
3606 L = [sedesc, cldesc]
3607 ctx.set_client_ca_list(L)
3608 return L
3609 self._check_client_ca_list(multiple_ca)
3610
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003611 def test_reset_ca_list(self):
3612 """
3613 If called multiple times, only the X509Names passed to the final call
Hynek Schlawack35618382015-09-05 21:54:25 +02003614 of :py:obj:`Context.set_client_ca_list` are used to configure the CA
3615 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003616 """
3617 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3618 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3619 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3620
3621 cadesc = cacert.get_subject()
3622 sedesc = secert.get_subject()
3623 cldesc = clcert.get_subject()
3624
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003625 def changed_ca(ctx):
3626 ctx.set_client_ca_list([sedesc, cldesc])
3627 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003628 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003629 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003630
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003631 def test_mutated_ca_list(self):
3632 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003633 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003634 afterwards, this does not affect the list of CA names sent to the
3635 client.
3636 """
3637 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3638 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3639
3640 cadesc = cacert.get_subject()
3641 sedesc = secert.get_subject()
3642
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003643 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003644 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003645 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003646 L.append(sedesc)
3647 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003648 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003649
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003650 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003651 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003652 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called
3653 with a non-X509 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003654 """
3655 ctx = Context(TLSv1_METHOD)
3656 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003657 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003658 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003659 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003660
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003661 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003662 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003663 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09003664 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003665 """
3666 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3667 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003668
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003669 def single_ca(ctx):
3670 ctx.add_client_ca(cacert)
3671 return [cadesc]
3672 self._check_client_ca_list(single_ca)
3673
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003674 def test_multiple_add_client_ca(self):
3675 """
3676 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09003677 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003678 """
3679 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3680 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3681
3682 cadesc = cacert.get_subject()
3683 sedesc = secert.get_subject()
3684
3685 def multiple_ca(ctx):
3686 ctx.add_client_ca(cacert)
3687 ctx.add_client_ca(secert)
3688 return [cadesc, sedesc]
3689 self._check_client_ca_list(multiple_ca)
3690
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003691 def test_set_and_add_client_ca(self):
3692 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003693 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003694 :py:obj:`Context.add_client_ca` results in using the CA names from the
3695 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003696 """
3697 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3698 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3699 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3700
3701 cadesc = cacert.get_subject()
3702 sedesc = secert.get_subject()
3703 cldesc = clcert.get_subject()
3704
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003705 def mixed_set_add_ca(ctx):
3706 ctx.set_client_ca_list([cadesc, sedesc])
3707 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003708 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003709 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003710
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003711 def test_set_after_add_client_ca(self):
3712 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003713 A call to :py:obj:`Context.set_client_ca_list` after a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003714 :py:obj:`Context.add_client_ca` replaces the CA name specified by the
3715 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003716 """
3717 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3718 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3719 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3720
3721 cadesc = cacert.get_subject()
3722 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003723
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003724 def set_replaces_add_ca(ctx):
3725 ctx.add_client_ca(clcert)
3726 ctx.set_client_ca_list([cadesc])
3727 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003728 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003729 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003730
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003731
Alex Chandeec9342016-12-19 22:00:38 +00003732class TestConnection(object):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003733 """
Alex Chandeec9342016-12-19 22:00:38 +00003734 Tests for `Connection.bio_read` and `Connection.bio_write`.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003735 """
3736 def test_wantReadError(self):
3737 """
Alex Chandeec9342016-12-19 22:00:38 +00003738 `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
3739 no bytes available to be read from the BIO.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003740 """
3741 ctx = Context(TLSv1_METHOD)
3742 conn = Connection(ctx, None)
Alex Chandeec9342016-12-19 22:00:38 +00003743 with pytest.raises(WantReadError):
3744 conn.bio_read(1024)
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003745
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003746 def test_buffer_size(self):
3747 """
Alex Chandeec9342016-12-19 22:00:38 +00003748 `Connection.bio_read` accepts an integer giving the maximum number
3749 of bytes to read and return.
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003750 """
3751 ctx = Context(TLSv1_METHOD)
3752 conn = Connection(ctx, None)
3753 conn.set_connect_state()
3754 try:
3755 conn.do_handshake()
3756 except WantReadError:
3757 pass
3758 data = conn.bio_read(2)
Alex Chandeec9342016-12-19 22:00:38 +00003759 assert 2 == len(data)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003760
Hynek Schlawack35618382015-09-05 21:54:25 +02003761 @skip_if_py3
3762 def test_buffer_size_long(self):
3763 """
Alex Chandeec9342016-12-19 22:00:38 +00003764 On Python 2 `Connection.bio_read` accepts values of type `long` as
3765 well as `int`.
Hynek Schlawack35618382015-09-05 21:54:25 +02003766 """
3767 ctx = Context(TLSv1_METHOD)
3768 conn = Connection(ctx, None)
3769 conn.set_connect_state()
3770 try:
3771 conn.do_handshake()
3772 except WantReadError:
3773 pass
3774 data = conn.bio_read(long(2))
Alex Chandeec9342016-12-19 22:00:38 +00003775 assert 2 == len(data)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003776
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003777
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003778class InfoConstantTests(TestCase):
3779 """
3780 Tests for assorted constants exposed for use in info callbacks.
3781 """
3782 def test_integers(self):
3783 """
3784 All of the info constants are integers.
3785
3786 This is a very weak test. It would be nice to have one that actually
3787 verifies that as certain info events happen, the value passed to the
3788 info callback matches up with the constant exposed by OpenSSL.SSL.
3789 """
3790 for const in [
Alex Gaynor5af32d02016-09-24 01:52:21 -04003791 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003792 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3793 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3794 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003795 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3796 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003797 assert isinstance(const, int)
3798
3799 # These constants don't exist on OpenSSL 1.1.0
3800 for const in [
3801 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
3802 ]:
3803 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003804
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003805
Cory Benfield1d142142016-03-30 11:51:45 +01003806class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003807 """
3808 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003809 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003810 """
3811 def test_available(self):
3812 """
3813 When the OpenSSL functionality is available the decorated functions
3814 work appropriately.
3815 """
3816 feature_guard = _make_requires(True, "Error text")
3817 results = []
3818
3819 @feature_guard
3820 def inner():
3821 results.append(True)
3822 return True
3823
Cory Benfield2333e5e2016-03-30 14:24:16 +01003824 assert inner() is True
3825 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003826
3827 def test_unavailable(self):
3828 """
3829 When the OpenSSL functionality is not available the decorated function
3830 does not execute and NotImplementedError is raised.
3831 """
3832 feature_guard = _make_requires(False, "Error text")
3833 results = []
3834
3835 @feature_guard
3836 def inner():
3837 results.append(True)
3838 return True
3839
Cory Benfield1d142142016-03-30 11:51:45 +01003840 with pytest.raises(NotImplementedError) as e:
3841 inner()
3842
3843 assert "Error text" in str(e.value)
Cory Benfield2333e5e2016-03-30 14:24:16 +01003844 assert results == []