blob: 62bbbf7c52b242ac2acb9e1cd008bec369982581 [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
Cory Benfield12eae892014-06-07 15:42:56 +01001857class ApplicationLayerProtoNegotiationTests(TestCase, _LoopbackMixin):
1858 """
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
Cory Benfielde46fa842015-04-13 16:50:49 -04001895 self._interactInMemory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001896
Cory Benfielde46fa842015-04-13 16:50:49 -04001897 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
1898
1899 self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
1900 self.assertEqual(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
Cory Benfielde46fa842015-04-13 16:50:49 -04001934 self._interactInMemory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001935
Cory Benfielde46fa842015-04-13 16:50:49 -04001936 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield12eae892014-06-07 15:42:56 +01001937
Cory Benfielde46fa842015-04-13 16:50:49 -04001938 self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
1939 self.assertEqual(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.
1972 self.assertRaises(Error, self._interactInMemory, server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001973
Cory Benfielde46fa842015-04-13 16:50:49 -04001974 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield12eae892014-06-07 15:42:56 +01001975
Cory Benfielde46fa842015-04-13 16:50:49 -04001976 def test_alpn_no_server(self):
1977 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001978 When clients and servers cannot agree on what protocol to use next
1979 because the server doesn't offer ALPN, no protocol is negotiated.
Cory Benfielde46fa842015-04-13 16:50:49 -04001980 """
1981 client_context = Context(TLSv1_METHOD)
1982 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfielde3d57152015-04-11 17:57:35 -04001983
Cory Benfielde46fa842015-04-13 16:50:49 -04001984 server_context = Context(TLSv1_METHOD)
Cory Benfielde3d57152015-04-11 17:57:35 -04001985
Cory Benfielde46fa842015-04-13 16:50:49 -04001986 # Necessary to actually accept the connection
1987 server_context.use_privatekey(
1988 load_privatekey(FILETYPE_PEM, server_key_pem))
1989 server_context.use_certificate(
1990 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfielde3d57152015-04-11 17:57:35 -04001991
Cory Benfielde46fa842015-04-13 16:50:49 -04001992 # Do a little connection to trigger the logic
1993 server = Connection(server_context, None)
1994 server.set_accept_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001995
Cory Benfielde46fa842015-04-13 16:50:49 -04001996 client = Connection(client_context, None)
1997 client.set_connect_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001998
Cory Benfielde46fa842015-04-13 16:50:49 -04001999 # Do the dance.
2000 self._interactInMemory(server, client)
Cory Benfielde3d57152015-04-11 17:57:35 -04002001
Cory Benfielde46fa842015-04-13 16:50:49 -04002002 self.assertEqual(client.get_alpn_proto_negotiated(), b'')
Cory Benfielde3d57152015-04-11 17:57:35 -04002003
Cory Benfielde46fa842015-04-13 16:50:49 -04002004 def test_alpn_callback_exception(self):
2005 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04002006 We can handle exceptions in the ALPN select callback.
Cory Benfielde46fa842015-04-13 16:50:49 -04002007 """
2008 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002009
Cory Benfielde46fa842015-04-13 16:50:49 -04002010 def select(conn, options):
2011 select_args.append((conn, options))
Cory Benfieldef401452015-04-13 18:17:36 -04002012 raise TypeError()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002013
Cory Benfielde46fa842015-04-13 16:50:49 -04002014 client_context = Context(TLSv1_METHOD)
2015 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfieldf1177e72015-04-12 09:11:49 -04002016
Cory Benfielde46fa842015-04-13 16:50:49 -04002017 server_context = Context(TLSv1_METHOD)
2018 server_context.set_alpn_select_callback(select)
Cory Benfieldf1177e72015-04-12 09:11:49 -04002019
Cory Benfielde46fa842015-04-13 16:50:49 -04002020 # Necessary to actually accept the connection
2021 server_context.use_privatekey(
2022 load_privatekey(FILETYPE_PEM, server_key_pem))
2023 server_context.use_certificate(
2024 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfieldf1177e72015-04-12 09:11:49 -04002025
Cory Benfielde46fa842015-04-13 16:50:49 -04002026 # Do a little connection to trigger the logic
2027 server = Connection(server_context, None)
2028 server.set_accept_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002029
Cory Benfielde46fa842015-04-13 16:50:49 -04002030 client = Connection(client_context, None)
2031 client.set_connect_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04002032
Cory Benfielde46fa842015-04-13 16:50:49 -04002033 self.assertRaises(
2034 TypeError, self._interactInMemory, server, client
2035 )
2036 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
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)
Cory Benfield307e9e62015-04-13 18:21:12 -04002046 self.assertRaises(
2047 NotImplementedError, context.set_alpn_protos, None
2048 )
2049 self.assertRaises(
2050 NotImplementedError, context.set_alpn_select_callback, None
2051 )
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002052
2053 # Now test a connection.
2054 conn = Connection(context)
Cory Benfield307e9e62015-04-13 18:21:12 -04002055 self.assertRaises(
Alex Gaynor68417232015-09-04 07:56:29 -04002056 NotImplementedError, conn.set_alpn_protos, None
Cory Benfield307e9e62015-04-13 18:21:12 -04002057 )
Cory Benfield0f7b04c2015-04-13 17:51:12 -04002058
Cory Benfieldf1177e72015-04-12 09:11:49 -04002059
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002060class SessionTests(TestCase):
2061 """
2062 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
2063 """
2064 def test_construction(self):
2065 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002066 :py:class:`Session` can be constructed with no arguments, creating
2067 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002068 """
2069 new_session = Session()
2070 self.assertTrue(isinstance(new_session, Session))
2071
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002072 def test_construction_wrong_args(self):
2073 """
2074 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
2075 is raised.
2076 """
2077 self.assertRaises(TypeError, Session, 123)
2078 self.assertRaises(TypeError, Session, "hello")
2079 self.assertRaises(TypeError, Session, object())
2080
2081
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002082class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05002083 """
Hynek Schlawackaa861212016-03-13 13:53:48 +01002084 Unit tests for :class:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002085 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002086 # XXX get_peer_certificate -> None
2087 # XXX sock_shutdown
2088 # XXX master_key -> TypeError
2089 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002090 # XXX connect -> TypeError
2091 # XXX connect_ex -> TypeError
2092 # XXX set_connect_state -> TypeError
2093 # XXX set_accept_state -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002094 # XXX do_handshake -> TypeError
2095 # XXX bio_read -> TypeError
2096 # XXX recv -> TypeError
2097 # XXX send -> TypeError
2098 # XXX bio_write -> TypeError
2099
Rick Deane15b1472009-07-09 15:53:42 -05002100 def test_type(self):
2101 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002102 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same
2103 type object and can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002104 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002105 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05002106 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002107 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002108
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002109 def test_get_context(self):
2110 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002111 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance
2112 used to construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002113 """
2114 context = Context(TLSv1_METHOD)
2115 connection = Connection(context, None)
2116 self.assertIdentical(connection.get_context(), context)
2117
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002118 def test_get_context_wrong_args(self):
2119 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002120 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called
2121 with any arguments.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002122 """
2123 connection = Connection(Context(TLSv1_METHOD), None)
2124 self.assertRaises(TypeError, connection.get_context, None)
2125
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002126 def test_set_context_wrong_args(self):
2127 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002128 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called
2129 with a non-:py:obj:`Context` instance argument or with any number of
2130 arguments other than 1.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002131 """
2132 ctx = Context(TLSv1_METHOD)
2133 connection = Connection(ctx, None)
2134 self.assertRaises(TypeError, connection.set_context)
2135 self.assertRaises(TypeError, connection.set_context, object())
2136 self.assertRaises(TypeError, connection.set_context, "hello")
2137 self.assertRaises(TypeError, connection.set_context, 1)
2138 self.assertRaises(TypeError, connection.set_context, 1, 2)
2139 self.assertRaises(
2140 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
2141 self.assertIdentical(ctx, connection.get_context())
2142
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002143 def test_set_context(self):
2144 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002145 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context`
2146 instance to be used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002147 """
2148 original = Context(SSLv23_METHOD)
2149 replacement = Context(TLSv1_METHOD)
2150 connection = Connection(original, None)
2151 connection.set_context(replacement)
2152 self.assertIdentical(replacement, connection.get_context())
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002153 # Lose our references to the contexts, just in case the Connection
2154 # isn't properly managing its own contributions to their reference
2155 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002156 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002157 collect()
2158
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002159 def test_set_tlsext_host_name_wrong_args(self):
2160 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002161 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte
2162 string argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09002163 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002164 """
2165 conn = Connection(Context(TLSv1_METHOD), None)
2166 self.assertRaises(TypeError, conn.set_tlsext_host_name)
2167 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
2168 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
2169 self.assertRaises(
Alex Gaynore7f51982016-09-11 11:48:14 -04002170 TypeError, conn.set_tlsext_host_name, b"with\0null")
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002171
Abraham Martinc5484ba2015-03-25 15:33:05 +00002172 if PY3:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002173 # On Python 3.x, don't accidentally implicitly convert from text.
2174 self.assertRaises(
2175 TypeError,
Alex Gaynore7f51982016-09-11 11:48:14 -04002176 conn.set_tlsext_host_name, b"example.com".decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002177
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002178 def test_get_servername_wrong_args(self):
2179 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002180 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if
2181 called with any arguments.
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002182 """
2183 connection = Connection(Context(TLSv1_METHOD), None)
2184 self.assertRaises(TypeError, connection.get_servername, object())
2185 self.assertRaises(TypeError, connection.get_servername, 1)
2186 self.assertRaises(TypeError, connection.get_servername, "hello")
2187
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002188 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002189 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002190 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002191 immediate read.
2192 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002193 connection = Connection(Context(TLSv1_METHOD), None)
2194 self.assertEquals(connection.pending(), 0)
2195
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002196 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002197 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002198 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with
2199 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002200 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002201 connection = Connection(Context(TLSv1_METHOD), None)
2202 self.assertRaises(TypeError, connection.pending, None)
2203
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002204 def test_peek(self):
2205 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002206 :py:obj:`Connection.recv` peeks into the connection if
2207 :py:obj:`socket.MSG_PEEK` is passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002208 """
2209 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002210 server.send(b'xy')
2211 self.assertEqual(client.recv(2, MSG_PEEK), b'xy')
2212 self.assertEqual(client.recv(2, MSG_PEEK), b'xy')
2213 self.assertEqual(client.recv(2), b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002214
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002215 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002216 """
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.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002219 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002220 connection = Connection(Context(TLSv1_METHOD), socket())
2221 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002222 self.assertRaises(TypeError, connection.connect)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002223 self.assertRaises(
2224 TypeError, connection.connect, ("127.0.0.1", 1), None
2225 )
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002226
kjavfe508d62015-09-02 12:20:35 +01002227 def test_connection_undefined_attr(self):
2228 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002229 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
2230 a non-address argument or with the wrong number of arguments.
kjavfe508d62015-09-02 12:20:35 +01002231 """
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002232
kjavfe508d62015-09-02 12:20:35 +01002233 def attr_access_test(connection):
2234 return connection.an_attribute_which_is_not_defined
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002235
kjavfe508d62015-09-02 12:20:35 +01002236 connection = Connection(Context(TLSv1_METHOD), None)
2237 self.assertRaises(AttributeError, attr_access_test, connection)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002238
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002239 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002240 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002241 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the
2242 underlying socket connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002243 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002244 client = socket()
2245 context = Context(TLSv1_METHOD)
2246 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002247 # pytest.raises here doesn't work because of a bug in py.test on Python
2248 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002249 try:
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002250 clientSSL.connect(("127.0.0.1", 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002251 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002252 exc = e
2253 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002254
2255 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002256 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002257 :py:obj:`Connection.connect` establishes a connection to the specified
2258 address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002259 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002260 port = socket()
2261 port.bind(('', 0))
2262 port.listen(3)
2263
2264 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002265 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
2266 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002267
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002268 @pytest.mark.skipif(
2269 platform == "darwin",
2270 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
2271 )
2272 def test_connect_ex(self):
2273 """
2274 If there is a connection error, :py:obj:`Connection.connect_ex`
2275 returns the errno instead of raising an exception.
2276 """
2277 port = socket()
2278 port.bind(('', 0))
2279 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002280
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002281 clientSSL = Connection(Context(TLSv1_METHOD), socket())
2282 clientSSL.setblocking(False)
2283 result = clientSSL.connect_ex(port.getsockname())
2284 expected = (EINPROGRESS, EWOULDBLOCK)
2285 self.assertTrue(
2286 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04002287
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002288 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002289 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002290 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with
2291 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002292 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002293 connection = Connection(Context(TLSv1_METHOD), socket())
2294 self.assertRaises(TypeError, connection.accept, None)
2295
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002296 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002297 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002298 :py:obj:`Connection.accept` accepts a pending connection attempt and
2299 returns a tuple of a new :py:obj:`Connection` (the accepted client) and
2300 the address the connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002301 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002302 ctx = Context(TLSv1_METHOD)
2303 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2304 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002305 port = socket()
2306 portSSL = Connection(ctx, port)
2307 portSSL.bind(('', 0))
2308 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002309
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002310 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002311
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002312 # Calling portSSL.getsockname() here to get the server IP address
2313 # sounds great, but frequently fails on Windows.
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002314 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002315
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002316 serverSSL, address = portSSL.accept()
2317
2318 self.assertTrue(isinstance(serverSSL, Connection))
2319 self.assertIdentical(serverSSL.get_context(), ctx)
2320 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002321
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002322 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002323 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002324 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with
2325 the wrong number of arguments or with arguments other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002326 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002327 connection = Connection(Context(TLSv1_METHOD), None)
2328 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04002329 self.assertRaises(TypeError, connection.get_shutdown, None)
2330 self.assertRaises(TypeError, connection.set_shutdown)
2331 self.assertRaises(TypeError, connection.set_shutdown, None)
2332 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002333
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002334 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002335 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002336 :py:obj:`Connection.shutdown` performs an SSL-level connection
2337 shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002338 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002339 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002340 self.assertFalse(server.shutdown())
2341 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002342 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002343 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
2344 client.shutdown()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002345 self.assertEquals(
2346 client.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2347 )
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002348 self.assertRaises(ZeroReturnError, server.recv, 1024)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002349 self.assertEquals(
2350 server.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2351 )
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002352
Paul Aurichc85e0862015-01-08 08:34:33 -08002353 def test_shutdown_closed(self):
2354 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002355 If the underlying socket is closed, :py:obj:`Connection.shutdown`
2356 propagates the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002357 """
2358 server, client = self._loopback()
2359 server.sock_shutdown(2)
2360 exc = self.assertRaises(SysCallError, server.shutdown)
2361 if platform == "win32":
2362 self.assertEqual(exc.args[0], ESHUTDOWN)
2363 else:
2364 self.assertEqual(exc.args[0], EPIPE)
2365
Glyph89389472015-04-14 17:29:26 -04002366 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002367 """
Glyph89389472015-04-14 17:29:26 -04002368 If the underlying connection is truncated, :obj:`Connection.shutdown`
2369 raises an :obj:`Error`.
Glyph6064ec32015-04-14 16:38:22 -04002370 """
Glyph89389472015-04-14 17:29:26 -04002371 server_ctx = Context(TLSv1_METHOD)
2372 client_ctx = Context(TLSv1_METHOD)
2373 server_ctx.use_privatekey(
2374 load_privatekey(FILETYPE_PEM, server_key_pem))
2375 server_ctx.use_certificate(
2376 load_certificate(FILETYPE_PEM, server_cert_pem))
2377 server = Connection(server_ctx, None)
2378 client = Connection(client_ctx, None)
2379 self._handshakeInMemory(client, server)
2380 self.assertEqual(server.shutdown(), False)
2381 self.assertRaises(WantReadError, server.shutdown)
2382 server.bio_shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002383 self.assertRaises(Error, server.shutdown)
2384
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002385 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002386 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002387 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection
2388 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002389 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002390 connection = Connection(Context(TLSv1_METHOD), socket())
2391 connection.set_shutdown(RECEIVED_SHUTDOWN)
2392 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
2393
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002394 @skip_if_py3
2395 def test_set_shutdown_long(self):
2396 """
2397 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
2398 of type :py:obj:`long` as well as :py:obj:`int`.
2399 """
2400 connection = Connection(Context(TLSv1_METHOD), socket())
2401 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
2402 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002403
kjavaf248592015-09-07 12:14:01 +01002404 def test_state_string(self):
2405 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002406 :meth:`Connection.state_string` verbosely describes the current
2407 state of the :class:`Connection`.
kjavaf248592015-09-07 12:14:01 +01002408 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002409 server, client = socket_pair()
kjavaf248592015-09-07 12:14:01 +01002410 server = self._loopbackServerFactory(server)
2411 client = self._loopbackClientFactory(client)
2412
Alex Gaynor5af32d02016-09-24 01:52:21 -04002413 assert server.get_state_string() in [
2414 b"before/accept initialization", b"before SSL initialization"
2415 ]
2416 assert client.get_state_string() in [
2417 b"before/connect initialization", b"before SSL initialization"
2418 ]
kjavaf248592015-09-07 12:14:01 +01002419
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002420 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002421 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002422 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called
2423 with other than one argument. :py:obj:`Connection.get_app_data` raises
2424 :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002425 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002426 conn = Connection(Context(TLSv1_METHOD), None)
2427 self.assertRaises(TypeError, conn.get_app_data, None)
2428 self.assertRaises(TypeError, conn.set_app_data)
2429 self.assertRaises(TypeError, conn.set_app_data, None, None)
2430
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002431 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002432 """
2433 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002434 :py:obj:`Connection.set_app_data` and later retrieved with
2435 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002436 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002437 conn = Connection(Context(TLSv1_METHOD), None)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002438 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002439 app_data = object()
2440 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002441 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002442
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002443 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002444 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002445 :py:obj:`Connection.makefile` is not implemented and calling that
2446 method raises :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002447 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002448 conn = Connection(Context(TLSv1_METHOD), None)
2449 self.assertRaises(NotImplementedError, conn.makefile)
2450
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002451 def test_get_peer_cert_chain_wrong_args(self):
2452 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002453 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if
2454 called with any arguments.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002455 """
2456 conn = Connection(Context(TLSv1_METHOD), None)
2457 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
2458 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
2459 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
2460 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
2461
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002462 def test_get_peer_cert_chain(self):
2463 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002464 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates
2465 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002466 """
2467 chain = _create_certificate_chain()
2468 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2469
2470 serverContext = Context(TLSv1_METHOD)
2471 serverContext.use_privatekey(skey)
2472 serverContext.use_certificate(scert)
2473 serverContext.add_extra_chain_cert(icert)
2474 serverContext.add_extra_chain_cert(cacert)
2475 server = Connection(serverContext, None)
2476 server.set_accept_state()
2477
2478 # Create the client
2479 clientContext = Context(TLSv1_METHOD)
2480 clientContext.set_verify(VERIFY_NONE, verify_cb)
2481 client = Connection(clientContext, None)
2482 client.set_connect_state()
2483
2484 self._interactInMemory(client, server)
2485
2486 chain = client.get_peer_cert_chain()
2487 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002488 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002489 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002490 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002491 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002492 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002493 "Authority Certificate", chain[2].get_subject().CN)
2494
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002495 def test_get_peer_cert_chain_none(self):
2496 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002497 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the
2498 peer sends no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002499 """
2500 ctx = Context(TLSv1_METHOD)
2501 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2502 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2503 server = Connection(ctx, None)
2504 server.set_accept_state()
2505 client = Connection(Context(TLSv1_METHOD), None)
2506 client.set_connect_state()
2507 self._interactInMemory(client, server)
2508 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002509
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002510 def test_get_session_wrong_args(self):
2511 """
2512 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
2513 with any arguments.
2514 """
2515 ctx = Context(TLSv1_METHOD)
2516 server = Connection(ctx, None)
2517 self.assertRaises(TypeError, server.get_session, 123)
2518 self.assertRaises(TypeError, server.get_session, "hello")
2519 self.assertRaises(TypeError, server.get_session, object())
2520
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002521 def test_get_session_unconnected(self):
2522 """
2523 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
2524 an object which has not been connected.
2525 """
2526 ctx = Context(TLSv1_METHOD)
2527 server = Connection(ctx, None)
2528 session = server.get_session()
2529 self.assertIdentical(None, session)
2530
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002531 def test_server_get_session(self):
2532 """
2533 On the server side of a connection, :py:obj:`Connection.get_session`
2534 returns a :py:class:`Session` instance representing the SSL session for
2535 that connection.
2536 """
2537 server, client = self._loopback()
2538 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002539 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002540
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002541 def test_client_get_session(self):
2542 """
2543 On the client side of a connection, :py:obj:`Connection.get_session`
2544 returns a :py:class:`Session` instance representing the SSL session for
2545 that connection.
2546 """
2547 server, client = self._loopback()
2548 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002549 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002550
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002551 def test_set_session_wrong_args(self):
2552 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002553 If called with an object that is not an instance of
2554 :py:class:`Session`, or with other than one argument,
2555 :py:obj:`Connection.set_session` raises :py:obj:`TypeError`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002556 """
2557 ctx = Context(TLSv1_METHOD)
2558 connection = Connection(ctx, None)
2559 self.assertRaises(TypeError, connection.set_session)
2560 self.assertRaises(TypeError, connection.set_session, 123)
2561 self.assertRaises(TypeError, connection.set_session, "hello")
2562 self.assertRaises(TypeError, connection.set_session, object())
2563 self.assertRaises(
2564 TypeError, connection.set_session, Session(), Session())
2565
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002566 def test_client_set_session(self):
2567 """
2568 :py:obj:`Connection.set_session`, when used prior to a connection being
2569 established, accepts a :py:class:`Session` instance and causes an
2570 attempt to re-use the session it represents when the SSL handshake is
2571 performed.
2572 """
2573 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2574 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2575 ctx = Context(TLSv1_METHOD)
2576 ctx.use_privatekey(key)
2577 ctx.use_certificate(cert)
2578 ctx.set_session_id("unity-test")
2579
2580 def makeServer(socket):
2581 server = Connection(ctx, socket)
2582 server.set_accept_state()
2583 return server
2584
2585 originalServer, originalClient = self._loopback(
2586 serverFactory=makeServer)
2587 originalSession = originalClient.get_session()
2588
2589 def makeClient(socket):
2590 client = self._loopbackClientFactory(socket)
2591 client.set_session(originalSession)
2592 return client
2593 resumedServer, resumedClient = self._loopback(
2594 serverFactory=makeServer,
2595 clientFactory=makeClient)
2596
2597 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002598 # identifier for the session (new enough versions of OpenSSL expose
2599 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002600 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002601 # session is re-used. As long as the master key for the two
2602 # connections is the same, the session was re-used!
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002603 self.assertEqual(
2604 originalServer.master_key(), resumedServer.master_key())
2605
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002606 def test_set_session_wrong_method(self):
2607 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002608 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002609 instance associated with a context using a different SSL method than
2610 the :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002611 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002612 """
Alex Gaynor5af32d02016-09-24 01:52:21 -04002613 # Make this work on both OpenSSL 1.0.0, which doesn't support TLSv1.2
2614 # and also on OpenSSL 1.1.0 which doesn't support SSLv3. (SSL_ST_INIT
2615 # is a way to check for 1.1.0)
2616 if SSL_ST_INIT is not None:
2617 v1 = TLSv1_METHOD
2618 v2 = SSLv3_METHOD
2619 else:
2620 v1 = TLSv1_2_METHOD
2621 v2 = TLSv1_METHOD
2622
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002623 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2624 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
Alex Gaynor5af32d02016-09-24 01:52:21 -04002625 ctx = Context(v1)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002626 ctx.use_privatekey(key)
2627 ctx.use_certificate(cert)
2628 ctx.set_session_id("unity-test")
2629
2630 def makeServer(socket):
2631 server = Connection(ctx, socket)
2632 server.set_accept_state()
2633 return server
2634
Alex Gaynor5af32d02016-09-24 01:52:21 -04002635 def makeOriginalClient(socket):
2636 client = Connection(Context(v1), socket)
2637 client.set_connect_state()
2638 return client
2639
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002640 originalServer, originalClient = self._loopback(
Alex Gaynor5af32d02016-09-24 01:52:21 -04002641 serverFactory=makeServer, clientFactory=makeOriginalClient)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002642 originalSession = originalClient.get_session()
2643
2644 def makeClient(socket):
2645 # Intentionally use a different, incompatible method here.
Alex Gaynor5af32d02016-09-24 01:52:21 -04002646 client = Connection(Context(v2), socket)
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002647 client.set_connect_state()
2648 client.set_session(originalSession)
2649 return client
2650
2651 self.assertRaises(
2652 Error,
2653 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2654
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002655 def test_wantWriteError(self):
2656 """
2657 :py:obj:`Connection` methods which generate output raise
2658 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2659 fail indicating a should-write state.
2660 """
2661 client_socket, server_socket = socket_pair()
2662 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002663 # anything. Only write a single byte at a time so we can be sure we
2664 # completely fill the buffer. Even though the socket API is allowed to
2665 # signal a short write via its return value it seems this doesn't
2666 # always happen on all platforms (FreeBSD and OS X particular) for the
2667 # very last bit of available buffer space.
2668 msg = b"x"
2669 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002670 try:
2671 client_socket.send(msg)
2672 except error as e:
2673 if e.errno == EWOULDBLOCK:
2674 break
2675 raise
2676 else:
2677 self.fail(
2678 "Failed to fill socket buffer, cannot test BIO want write")
2679
2680 ctx = Context(TLSv1_METHOD)
2681 conn = Connection(ctx, client_socket)
2682 # Client's speak first, so make it an SSL client
2683 conn.set_connect_state()
2684 self.assertRaises(WantWriteError, conn.do_handshake)
2685
2686 # XXX want_read
2687
Fedor Brunner416f4a12014-03-28 13:18:38 +01002688 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002689 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002690 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2691 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002692 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002693 ctx = Context(TLSv1_METHOD)
2694 connection = Connection(ctx, None)
2695 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002696
2697 def test_get_peer_finished_before_connect(self):
2698 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002699 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2700 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002701 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002702 ctx = Context(TLSv1_METHOD)
2703 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002704 self.assertEqual(connection.get_peer_finished(), None)
2705
Fedor Brunner416f4a12014-03-28 13:18:38 +01002706 def test_get_finished(self):
2707 """
2708 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002709 message send from client, or server. Finished messages are send during
2710 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002711 """
2712
Fedor Brunner5747b932014-03-05 14:22:34 +01002713 server, client = self._loopback()
2714
2715 self.assertNotEqual(server.get_finished(), None)
2716 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002717
2718 def test_get_peer_finished(self):
2719 """
2720 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002721 message received from client, or server. Finished messages are send
2722 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002723 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002724 server, client = self._loopback()
2725
2726 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002727 self.assertTrue(len(server.get_peer_finished()) > 0)
2728
Fedor Brunner416f4a12014-03-28 13:18:38 +01002729 def test_tls_finished_message_symmetry(self):
2730 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002731 The TLS Finished message send by server must be the TLS Finished
2732 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002733
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002734 The TLS Finished message send by client must be the TLS Finished
2735 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002736 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002737 server, client = self._loopback()
2738
Fedor Brunner5747b932014-03-05 14:22:34 +01002739 self.assertEqual(server.get_finished(), client.get_peer_finished())
2740 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002741
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002742 def test_get_cipher_name_before_connect(self):
2743 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002744 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2745 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002746 """
2747 ctx = Context(TLSv1_METHOD)
2748 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002749 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002750
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002751 def test_get_cipher_name(self):
2752 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002753 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2754 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002755 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002756 server, client = self._loopback()
2757 server_cipher_name, client_cipher_name = \
2758 server.get_cipher_name(), client.get_cipher_name()
2759
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002760 self.assertIsInstance(server_cipher_name, text_type)
2761 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002762
2763 self.assertEqual(server_cipher_name, client_cipher_name)
2764
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002765 def test_get_cipher_version_before_connect(self):
2766 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002767 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2768 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002769 """
2770 ctx = Context(TLSv1_METHOD)
2771 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002772 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002773
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002774 def test_get_cipher_version(self):
2775 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002776 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2777 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002778 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002779 server, client = self._loopback()
2780 server_cipher_version, client_cipher_version = \
2781 server.get_cipher_version(), client.get_cipher_version()
2782
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002783 self.assertIsInstance(server_cipher_version, text_type)
2784 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002785
2786 self.assertEqual(server_cipher_version, client_cipher_version)
2787
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002788 def test_get_cipher_bits_before_connect(self):
2789 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002790 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2791 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002792 """
2793 ctx = Context(TLSv1_METHOD)
2794 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002795 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002796
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002797 def test_get_cipher_bits(self):
2798 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002799 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2800 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002801 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002802 server, client = self._loopback()
2803 server_cipher_bits, client_cipher_bits = \
2804 server.get_cipher_bits(), client.get_cipher_bits()
2805
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002806 self.assertIsInstance(server_cipher_bits, int)
2807 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002808
2809 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002810
Jim Shaverabff1882015-05-27 09:15:55 -04002811 def test_get_protocol_version_name(self):
2812 """
2813 :py:obj:`Connection.get_protocol_version_name()` returns a string
2814 giving the protocol version of the current connection.
2815 """
2816 server, client = self._loopback()
2817 client_protocol_version_name = client.get_protocol_version_name()
2818 server_protocol_version_name = server.get_protocol_version_name()
2819
Jim Shaver58d25732015-05-28 11:52:32 -04002820 self.assertIsInstance(server_protocol_version_name, text_type)
2821 self.assertIsInstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002822
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002823 self.assertEqual(
2824 server_protocol_version_name, client_protocol_version_name
2825 )
Jim Shaverabff1882015-05-27 09:15:55 -04002826
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002827 def test_get_protocol_version(self):
2828 """
Alex Gaynor43307782015-09-04 09:05:45 -04002829 :py:obj:`Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002830 giving the protocol version of the current connection.
2831 """
2832 server, client = self._loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002833 client_protocol_version = client.get_protocol_version()
2834 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002835
Jim Shaverabff1882015-05-27 09:15:55 -04002836 self.assertIsInstance(server_protocol_version, int)
2837 self.assertIsInstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002838
2839 self.assertEqual(server_protocol_version, client_protocol_version)
2840
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002841
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002842class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002843 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002844 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002845 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002846 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002847 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002848 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if
2849 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002850 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002851 connection = Connection(Context(TLSv1_METHOD), None)
2852 self.assertRaises(TypeError, connection.get_cipher_list, None)
2853
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002854 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002855 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002856 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2857 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002858 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002859 connection = Connection(Context(TLSv1_METHOD), None)
2860 ciphers = connection.get_cipher_list()
2861 self.assertTrue(isinstance(ciphers, list))
2862 for cipher in ciphers:
2863 self.assertTrue(isinstance(cipher, str))
2864
2865
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002866class ConnectionSendTests(TestCase, _LoopbackMixin):
2867 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002868 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002869 """
2870 def test_wrong_args(self):
2871 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002872 When called with arguments other than string argument for its first
2873 parameter or more than two arguments, :py:obj:`Connection.send` raises
2874 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002875 """
2876 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002877 self.assertRaises(TypeError, connection.send)
2878 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002879 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002880
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002881 def test_short_bytes(self):
2882 """
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002883 When passed a short byte string, :py:obj:`Connection.send` transmits
2884 all of it and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002885 """
2886 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002887 count = server.send(b'xy')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002888 self.assertEquals(count, 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002889 self.assertEquals(client.recv(2), b'xy')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002890
Abraham Martinef063482015-03-25 14:06:24 +00002891 def test_text(self):
2892 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002893 When passed a text, :py:obj:`Connection.send` transmits all of it and
2894 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002895 """
2896 server, client = self._loopback()
2897 with catch_warnings(record=True) as w:
2898 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002899 count = server.send(b"xy".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002900 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002901 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002902 WARNING_TYPE_EXPECTED
2903 ),
2904 str(w[-1].message)
2905 )
2906 self.assertIs(w[-1].category, DeprecationWarning)
Abraham Martinef063482015-03-25 14:06:24 +00002907 self.assertEquals(count, 2)
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002908 self.assertEquals(client.recv(2), b"xy")
Abraham Martinef063482015-03-25 14:06:24 +00002909
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002910 @skip_if_py26
2911 def test_short_memoryview(self):
2912 """
2913 When passed a memoryview onto 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(memoryview(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')
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002921
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002922 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002923 def test_short_buffer(self):
2924 """
2925 When passed a buffer containing a small number of bytes,
2926 :py:obj:`Connection.send` transmits all of them and returns the number
2927 of bytes sent.
2928 """
2929 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002930 count = server.send(buffer(b'xy'))
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002931 self.assertEquals(count, 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002932 self.assertEquals(client.recv(2), b'xy')
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002933
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002934
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002935def _make_memoryview(size):
2936 """
2937 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2938 size.
2939 """
2940 return memoryview(bytearray(size))
2941
2942
Cory Benfield62d10332014-06-15 10:03:41 +01002943class ConnectionRecvIntoTests(TestCase, _LoopbackMixin):
2944 """
2945 Tests for :py:obj:`Connection.recv_into`
2946 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002947 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002948 """
2949 Assert that when the given buffer is passed to
2950 ``Connection.recv_into``, whatever bytes are available to be received
2951 that fit into that buffer are written into that buffer.
2952 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002953 output_buffer = factory(5)
2954
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002955 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002956 server.send(b'xy')
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002957
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002958 self.assertEqual(client.recv_into(output_buffer), 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04002959 self.assertEqual(output_buffer, bytearray(b'xy\x00\x00\x00'))
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002960
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002961 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002962 """
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002963 :py:obj:`Connection.recv_into` can be passed a ``bytearray`` instance
2964 and data in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002965 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002966 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002967
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002968 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002969 """
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002970 Assert that when the given buffer is passed to ``Connection.recv_into``
2971 along with a value for ``nbytes`` that is less than the size of that
2972 buffer, only ``nbytes`` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002973 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002974 output_buffer = factory(10)
2975
Cory Benfield62d10332014-06-15 10:03:41 +01002976 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04002977 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01002978
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002979 self.assertEqual(client.recv_into(output_buffer, 5), 5)
2980 self.assertEqual(
Alex Gaynore7f51982016-09-11 11:48:14 -04002981 output_buffer, bytearray(b'abcde\x00\x00\x00\x00\x00')
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002982 )
2983
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002984 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002985 """
2986 When called with a ``bytearray`` instance,
2987 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter and
2988 doesn't copy in more than that number of bytes.
2989 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002990 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002991
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002992 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002993 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002994 Assert that if there are more bytes available to be read from the
2995 receive buffer than would fit into the buffer passed to
2996 :py:obj:`Connection.recv_into`, only as many as fit are written into
2997 it.
Cory Benfield62d10332014-06-15 10:03:41 +01002998 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002999 output_buffer = factory(5)
3000
Cory Benfield62d10332014-06-15 10:03:41 +01003001 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003002 server.send(b'abcdefghij')
Cory Benfield62d10332014-06-15 10:03:41 +01003003
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04003004 self.assertEqual(client.recv_into(output_buffer), 5)
Alex Gaynore7f51982016-09-11 11:48:14 -04003005 self.assertEqual(output_buffer, bytearray(b'abcde'))
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003006 rest = client.recv(5)
Alex Gaynore7f51982016-09-11 11:48:14 -04003007 self.assertEqual(b'fghij', rest)
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003008
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003009 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04003010 """
3011 When called with a ``bytearray`` instance,
3012 :py:obj:`Connection.recv_into` respects the size of the array and
3013 doesn't write more bytes into it than will fit.
3014 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003015 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01003016
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04003017 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003018 """
3019 When called with a ``bytearray`` instance and an ``nbytes`` value that
3020 is too large, :py:obj:`Connection.recv_into` respects the size of the
3021 array and not the ``nbytes`` value and doesn't write more bytes into
3022 the buffer than will fit.
3023 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04003024 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003025
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003026 def test_peek(self):
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003027 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003028 server.send(b'xy')
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003029
3030 for _ in range(2):
3031 output_buffer = bytearray(5)
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003032 self.assertEqual(
3033 client.recv_into(output_buffer, flags=MSG_PEEK), 2)
Alex Gaynore7f51982016-09-11 11:48:14 -04003034 self.assertEqual(output_buffer, bytearray(b'xy\x00\x00\x00'))
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003035
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003036 @skip_if_py26
3037 def test_memoryview_no_length(self):
3038 """
3039 :py:obj:`Connection.recv_into` can be passed a ``memoryview``
3040 instance and data in the receive buffer is written to it.
3041 """
3042 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003043
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003044 @skip_if_py26
3045 def test_memoryview_respects_length(self):
3046 """
3047 When called with a ``memoryview`` instance,
3048 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter
3049 and doesn't copy more than that number of bytes in.
3050 """
3051 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003052
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003053 @skip_if_py26
3054 def test_memoryview_doesnt_overfill(self):
3055 """
3056 When called with a ``memoryview`` instance,
3057 :py:obj:`Connection.recv_into` respects the size of the array and
3058 doesn't write more bytes into it than will fit.
3059 """
3060 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003061
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003062 @skip_if_py26
3063 def test_memoryview_really_doesnt_overfill(self):
3064 """
3065 When called with a ``memoryview`` instance and an ``nbytes`` value
3066 that is too large, :py:obj:`Connection.recv_into` respects the size
3067 of the array and not the ``nbytes`` value and doesn't write more
3068 bytes into the buffer than will fit.
3069 """
3070 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003071
Cory Benfield62d10332014-06-15 10:03:41 +01003072
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003073class ConnectionSendallTests(TestCase, _LoopbackMixin):
3074 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003075 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003076 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003077 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003078 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003079 When called with arguments other than a string argument for its first
3080 parameter or with more than two arguments, :py:obj:`Connection.sendall`
3081 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003082 """
3083 connection = Connection(Context(TLSv1_METHOD), None)
3084 self.assertRaises(TypeError, connection.sendall)
3085 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003086 self.assertRaises(
3087 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003088
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003089 def test_short(self):
3090 """
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003091 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3092 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003093 """
3094 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003095 server.sendall(b'x')
3096 self.assertEquals(client.recv(1), b'x')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003097
Abraham Martinef063482015-03-25 14:06:24 +00003098 def test_text(self):
3099 """
Jean-Paul Calderone93477422015-04-13 20:38:57 -04003100 :py:obj:`Connection.sendall` transmits all the content in the string
3101 passed to it raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003102 """
3103 server, client = self._loopback()
3104 with catch_warnings(record=True) as w:
3105 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003106 server.sendall(b"x".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003107 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003108 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003109 WARNING_TYPE_EXPECTED
3110 ),
3111 str(w[-1].message)
3112 )
3113 self.assertIs(w[-1].category, DeprecationWarning)
3114 self.assertEquals(client.recv(1), b"x")
Abraham Martinef063482015-03-25 14:06:24 +00003115
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003116 @skip_if_py26
3117 def test_short_memoryview(self):
3118 """
3119 When passed a memoryview onto a small number of bytes,
3120 :py:obj:`Connection.sendall` transmits all of them.
3121 """
3122 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003123 server.sendall(memoryview(b'x'))
3124 self.assertEquals(client.recv(1), b'x')
Abraham Martinef063482015-03-25 14:06:24 +00003125
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003126 @skip_if_py3
3127 def test_short_buffers(self):
3128 """
3129 When passed a buffer containing a small number of bytes,
3130 :py:obj:`Connection.sendall` transmits all of them.
3131 """
3132 server, client = self._loopback()
Alex Gaynore7f51982016-09-11 11:48:14 -04003133 server.sendall(buffer(b'x'))
3134 self.assertEquals(client.recv(1), b'x')
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003135
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003136 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003137 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003138 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3139 passed to it even if this requires multiple calls of an underlying
3140 write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003141 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003142 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003143 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003144 # On Windows, after 32k of bytes the write will block (forever
3145 # - because no one is yet reading).
Alex Gaynore7f51982016-09-11 11:48:14 -04003146 message = b'x' * (1024 * 32 - 1) + b'y'
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003147 server.sendall(message)
3148 accum = []
3149 received = 0
3150 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003151 data = client.recv(1024)
3152 accum.append(data)
3153 received += len(data)
Alex Gaynore7f51982016-09-11 11:48:14 -04003154 self.assertEquals(message, b''.join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003155
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003156 def test_closed(self):
3157 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003158 If the underlying socket is closed, :py:obj:`Connection.sendall`
3159 propagates the write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003160 """
3161 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003162 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003163 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003164 if platform == "win32":
3165 self.assertEqual(exc.args[0], ESHUTDOWN)
3166 else:
3167 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003168
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003169
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003170class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
3171 """
3172 Tests for SSL renegotiation APIs.
3173 """
3174 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003175 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003176 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called
3177 with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003178 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003179 connection = Connection(Context(TLSv1_METHOD), None)
3180 self.assertRaises(TypeError, connection.renegotiate, None)
3181
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003182 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003183 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003184 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if
3185 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003186 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003187 connection = Connection(Context(TLSv1_METHOD), None)
3188 self.assertRaises(TypeError, connection.total_renegotiations, None)
3189
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003190 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003191 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003192 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before
3193 any renegotiations have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003194 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003195 connection = Connection(Context(TLSv1_METHOD), None)
3196 self.assertEquals(connection.total_renegotiations(), 0)
3197
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003198 def test_renegotiate(self):
3199 """
3200 Go through a complete renegotiation cycle.
3201 """
3202 server, client = self._loopback()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003203
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003204 server.send(b"hello world")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003205
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003206 assert b"hello world" == client.recv(len(b"hello world"))
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003207
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003208 assert 0 == server.total_renegotiations()
3209 assert False is server.renegotiate_pending()
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003210
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01003211 assert True is server.renegotiate()
3212
3213 assert True is server.renegotiate_pending()
3214
3215 server.setblocking(False)
3216 client.setblocking(False)
3217
3218 client.do_handshake()
3219 server.do_handshake()
3220
3221 assert 1 == server.total_renegotiations()
3222 while False is server.renegotiate_pending():
3223 pass
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003224
3225
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003226class ErrorTests(TestCase):
3227 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003228 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003229 """
3230 def test_type(self):
3231 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003232 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003233 """
3234 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05003235 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05003236
3237
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003238class ConstantsTests(TestCase):
3239 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003240 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003241
3242 These are values defined by OpenSSL intended only to be used as flags to
3243 OpenSSL APIs. The only assertions it seems can be made about them is
3244 their values.
3245 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003246 @pytest.mark.skipif(
3247 OP_NO_QUERY_MTU is None,
3248 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3249 )
3250 def test_op_no_query_mtu(self):
3251 """
3252 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3253 of :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
3254 """
3255 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003256
Hynek Schlawack35618382015-09-05 21:54:25 +02003257 @pytest.mark.skipif(
3258 OP_COOKIE_EXCHANGE is None,
3259 reason="OP_COOKIE_EXCHANGE unavailable - "
3260 "OpenSSL version may be too old"
3261 )
3262 def test_op_cookie_exchange(self):
3263 """
3264 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3265 value of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by
3266 :file:`openssl/ssl.h`.
3267 """
3268 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003269
Hynek Schlawack35618382015-09-05 21:54:25 +02003270 @pytest.mark.skipif(
3271 OP_NO_TICKET is None,
3272 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3273 )
3274 def test_op_no_ticket(self):
3275 """
3276 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3277 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
3278 """
3279 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003280
Hynek Schlawack35618382015-09-05 21:54:25 +02003281 @pytest.mark.skipif(
3282 OP_NO_COMPRESSION is None,
3283 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3284 )
3285 def test_op_no_compression(self):
3286 """
3287 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3288 value of :py:const:`SSL_OP_NO_COMPRESSION` defined by
3289 :file:`openssl/ssl.h`.
3290 """
3291 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003292
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003293 def test_sess_cache_off(self):
3294 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003295 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3296 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003297 """
3298 self.assertEqual(0x0, SESS_CACHE_OFF)
3299
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003300 def test_sess_cache_client(self):
3301 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003302 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3303 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003304 """
3305 self.assertEqual(0x1, SESS_CACHE_CLIENT)
3306
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003307 def test_sess_cache_server(self):
3308 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003309 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3310 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003311 """
3312 self.assertEqual(0x2, SESS_CACHE_SERVER)
3313
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003314 def test_sess_cache_both(self):
3315 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003316 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3317 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003318 """
3319 self.assertEqual(0x3, SESS_CACHE_BOTH)
3320
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003321 def test_sess_cache_no_auto_clear(self):
3322 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003323 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3324 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3325 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003326 """
3327 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
3328
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003329 def test_sess_cache_no_internal_lookup(self):
3330 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003331 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3332 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3333 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003334 """
3335 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
3336
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003337 def test_sess_cache_no_internal_store(self):
3338 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003339 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3340 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3341 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003342 """
3343 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
3344
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003345 def test_sess_cache_no_internal(self):
3346 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003347 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3348 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
3349 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003350 """
3351 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
3352
3353
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003354class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05003355 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003356 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003357 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003358 def _server(self, sock):
3359 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003360 Create a new server-side SSL :py:obj:`Connection` object wrapped around
3361 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003362 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003363 # Create the server side Connection. This is mostly setup boilerplate
3364 # - use TLSv1, use a particular certificate, etc.
3365 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003366 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003367 server_ctx.set_verify(
3368 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3369 verify_cb
3370 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003371 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003372 server_ctx.use_privatekey(
3373 load_privatekey(FILETYPE_PEM, server_key_pem))
3374 server_ctx.use_certificate(
3375 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003376 server_ctx.check_privatekey()
3377 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003378 # Here the Connection is actually created. If None is passed as the
3379 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003380 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003381 server_conn.set_accept_state()
3382 return server_conn
3383
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003384 def _client(self, sock):
3385 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003386 Create a new client-side SSL :py:obj:`Connection` object wrapped around
3387 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003388 """
3389 # Now create the client side Connection. Similar boilerplate to the
3390 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003391 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003392 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003393 client_ctx.set_verify(
3394 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3395 verify_cb
3396 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003397 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003398 client_ctx.use_privatekey(
3399 load_privatekey(FILETYPE_PEM, client_key_pem))
3400 client_ctx.use_certificate(
3401 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003402 client_ctx.check_privatekey()
3403 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003404 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003405 client_conn.set_connect_state()
3406 return client_conn
3407
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003408 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003409 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003410 Two :py:obj:`Connection`s which use memory BIOs can be manually
3411 connected by reading from the output of each and writing those bytes to
3412 the input of the other and in this way establish a connection and
3413 exchange application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003414 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003415 server_conn = self._server(None)
3416 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003417
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003418 # There should be no key or nonces yet.
3419 self.assertIdentical(server_conn.master_key(), None)
3420 self.assertIdentical(server_conn.client_random(), None)
3421 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003422
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003423 # First, the handshake needs to happen. We'll deliver bytes back and
3424 # forth between the client and server until neither of them feels like
3425 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003426 self.assertIdentical(
3427 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003428
3429 # Now that the handshake is done, there should be a key and nonces.
3430 self.assertNotIdentical(server_conn.master_key(), None)
3431 self.assertNotIdentical(server_conn.client_random(), None)
3432 self.assertNotIdentical(server_conn.server_random(), None)
Hynek Schlawack35618382015-09-05 21:54:25 +02003433 self.assertEquals(
3434 server_conn.client_random(), client_conn.client_random())
3435 self.assertEquals(
3436 server_conn.server_random(), client_conn.server_random())
3437 self.assertNotEquals(
3438 server_conn.client_random(), server_conn.server_random())
3439 self.assertNotEquals(
3440 client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003441
3442 # Here are the bytes we'll try to send.
Alex Gaynore7f51982016-09-11 11:48:14 -04003443 important_message = b'One if by land, two if by sea.'
Rick Deanb71c0d22009-04-01 14:09:23 -05003444
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003445 server_conn.write(important_message)
3446 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003447 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003448 (client_conn, important_message))
3449
3450 client_conn.write(important_message[::-1])
3451 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003452 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003453 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003454
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003455 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003456 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003457 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003458
Hynek Schlawack35618382015-09-05 21:54:25 +02003459 This is primarily to rule out the memory BIO code as the source of any
3460 problems encountered while passing data over a :py:obj:`Connection` (if
3461 this test fails, there must be a problem outside the memory BIO code,
3462 as no memory BIO is involved here). Even though this isn't a memory
3463 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003464 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04003465 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003466
Alex Gaynore7f51982016-09-11 11:48:14 -04003467 important_message = b"Help me Obi Wan Kenobi, you're my only hope."
Rick Deanb1ccd562009-07-09 23:52:39 -05003468 client_conn.send(important_message)
3469 msg = server_conn.recv(1024)
3470 self.assertEqual(msg, important_message)
3471
3472 # Again in the other direction, just for fun.
3473 important_message = important_message[::-1]
3474 server_conn.send(important_message)
3475 msg = client_conn.recv(1024)
3476 self.assertEqual(msg, important_message)
3477
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04003478 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003479 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003480 Test that :py:obj:`OpenSSL.SSL.bio_read` and
3481 :py:obj:`OpenSSL.SSL.bio_write` don't work on
3482 :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003483 """
Alex Gaynor51d424c2016-09-10 14:50:11 -04003484 context = Context(TLSv1_METHOD)
Rick Deanb71c0d22009-04-01 14:09:23 -05003485 client = socket()
3486 clientSSL = Connection(context, client)
Alex Gaynor43307782015-09-04 09:05:45 -04003487 self.assertRaises(TypeError, clientSSL.bio_read, 100)
3488 self.assertRaises(TypeError, clientSSL.bio_write, "foo")
Alex Gaynor7e8b61e2015-09-04 13:13:05 -04003489 self.assertRaises(TypeError, clientSSL.bio_shutdown)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003490
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003491 def test_outgoingOverflow(self):
3492 """
3493 If more bytes than can be written to the memory BIO are passed to
Hynek Schlawack35618382015-09-05 21:54:25 +02003494 :py:obj:`Connection.send` at once, the number of bytes which were
3495 written is returned and that many bytes from the beginning of the input
3496 can be read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003497 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003498 server = self._server(None)
3499 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003500
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003501 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003502
3503 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003504 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003505 # Sanity check. We're trying to test what happens when the entire
3506 # input can't be sent. If the entire input was sent, this test is
3507 # meaningless.
3508 self.assertTrue(sent < size)
3509
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003510 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003511 self.assertIdentical(receiver, server)
3512
3513 # We can rely on all of these bytes being received at once because
3514 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
3515 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003516
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003517 def test_shutdown(self):
3518 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003519 :py:obj:`Connection.bio_shutdown` signals the end of the data stream
3520 from which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003521 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003522 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003523 server.bio_shutdown()
3524 e = self.assertRaises(Error, server.recv, 1024)
3525 # We don't want WantReadError or ZeroReturnError or anything - it's a
3526 # handshake failure.
Alex Gaynor5af32d02016-09-24 01:52:21 -04003527 assert type(e) in [Error, SysCallError]
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003528
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003529 def test_unexpectedEndOfFile(self):
3530 """
3531 If the connection is lost before an orderly SSL shutdown occurs,
3532 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
3533 "Unexpected EOF".
3534 """
3535 server_conn, client_conn = self._loopback()
3536 client_conn.sock_shutdown(SHUT_RDWR)
3537 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
3538 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
3539
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003540 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003541 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003542 Verify the return value of the :py:obj:`get_client_ca_list` method for
3543 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003544
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003545 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003546 before the client and server are connected to each other. This
3547 function should specify a list of CAs for the server to send to the
3548 client and return that same list. The list will be used to verify
Hynek Schlawack35618382015-09-05 21:54:25 +02003549 that :py:obj:`get_client_ca_list` returns the proper value at
3550 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003551 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003552 server = self._server(None)
3553 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003554 self.assertEqual(client.get_client_ca_list(), [])
3555 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003556 ctx = server.get_context()
3557 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003558 self.assertEqual(client.get_client_ca_list(), [])
3559 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003560 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003561 self.assertEqual(client.get_client_ca_list(), expected)
3562 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003563
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003564 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003565 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003566 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if
3567 called with a non-list or a list that contains objects other than
3568 X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003569 """
3570 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003571 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
3572 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
3573 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003574
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003575 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003576 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003577 If passed an empty list, :py:obj:`Context.set_client_ca_list`
3578 configures the context to send no CA names to the client and, on both
3579 the server and client sides, :py:obj:`Connection.get_client_ca_list`
3580 returns an empty list after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003581 """
3582 def no_ca(ctx):
3583 ctx.set_client_ca_list([])
3584 return []
3585 self._check_client_ca_list(no_ca)
3586
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003587 def test_set_one_ca_list(self):
3588 """
3589 If passed a list containing a single X509Name,
Hynek Schlawack35618382015-09-05 21:54:25 +02003590 :py:obj:`Context.set_client_ca_list` configures the context to send
3591 that CA name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003592 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003593 X509Name after the connection is set up.
3594 """
3595 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3596 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003597
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003598 def single_ca(ctx):
3599 ctx.set_client_ca_list([cadesc])
3600 return [cadesc]
3601 self._check_client_ca_list(single_ca)
3602
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003603 def test_set_multiple_ca_list(self):
3604 """
3605 If passed a list containing multiple X509Name objects,
Hynek Schlawack35618382015-09-05 21:54:25 +02003606 :py:obj:`Context.set_client_ca_list` configures the context to send
3607 those CA names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003608 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003609 X509Names after the connection is set up.
3610 """
3611 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3612 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3613
3614 sedesc = secert.get_subject()
3615 cldesc = clcert.get_subject()
3616
3617 def multiple_ca(ctx):
3618 L = [sedesc, cldesc]
3619 ctx.set_client_ca_list(L)
3620 return L
3621 self._check_client_ca_list(multiple_ca)
3622
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003623 def test_reset_ca_list(self):
3624 """
3625 If called multiple times, only the X509Names passed to the final call
Hynek Schlawack35618382015-09-05 21:54:25 +02003626 of :py:obj:`Context.set_client_ca_list` are used to configure the CA
3627 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003628 """
3629 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3630 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3631 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3632
3633 cadesc = cacert.get_subject()
3634 sedesc = secert.get_subject()
3635 cldesc = clcert.get_subject()
3636
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003637 def changed_ca(ctx):
3638 ctx.set_client_ca_list([sedesc, cldesc])
3639 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003640 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003641 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003642
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003643 def test_mutated_ca_list(self):
3644 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003645 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003646 afterwards, this does not affect the list of CA names sent to the
3647 client.
3648 """
3649 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3650 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3651
3652 cadesc = cacert.get_subject()
3653 sedesc = secert.get_subject()
3654
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003655 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003656 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003657 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003658 L.append(sedesc)
3659 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003660 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003661
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003662 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003663 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003664 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called
3665 with a non-X509 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003666 """
3667 ctx = Context(TLSv1_METHOD)
3668 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003669 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003670 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003671 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003672
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003673 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003674 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003675 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09003676 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003677 """
3678 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3679 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003680
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003681 def single_ca(ctx):
3682 ctx.add_client_ca(cacert)
3683 return [cadesc]
3684 self._check_client_ca_list(single_ca)
3685
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003686 def test_multiple_add_client_ca(self):
3687 """
3688 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09003689 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003690 """
3691 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3692 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3693
3694 cadesc = cacert.get_subject()
3695 sedesc = secert.get_subject()
3696
3697 def multiple_ca(ctx):
3698 ctx.add_client_ca(cacert)
3699 ctx.add_client_ca(secert)
3700 return [cadesc, sedesc]
3701 self._check_client_ca_list(multiple_ca)
3702
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003703 def test_set_and_add_client_ca(self):
3704 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003705 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003706 :py:obj:`Context.add_client_ca` results in using the CA names from the
3707 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003708 """
3709 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3710 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3711 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3712
3713 cadesc = cacert.get_subject()
3714 sedesc = secert.get_subject()
3715 cldesc = clcert.get_subject()
3716
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003717 def mixed_set_add_ca(ctx):
3718 ctx.set_client_ca_list([cadesc, sedesc])
3719 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003720 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003721 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003722
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003723 def test_set_after_add_client_ca(self):
3724 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003725 A call to :py:obj:`Context.set_client_ca_list` after a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003726 :py:obj:`Context.add_client_ca` replaces the CA name specified by the
3727 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003728 """
3729 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3730 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3731 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3732
3733 cadesc = cacert.get_subject()
3734 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003735
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003736 def set_replaces_add_ca(ctx):
3737 ctx.add_client_ca(clcert)
3738 ctx.set_client_ca_list([cadesc])
3739 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003740 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003741 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003742
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003743
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003744class ConnectionBIOTests(TestCase):
3745 """
3746 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
3747 """
3748 def test_wantReadError(self):
3749 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003750 :py:obj:`Connection.bio_read` raises
3751 :py:obj:`OpenSSL.SSL.WantReadError` if there are no bytes available to
3752 be read from the BIO.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003753 """
3754 ctx = Context(TLSv1_METHOD)
3755 conn = Connection(ctx, None)
3756 self.assertRaises(WantReadError, conn.bio_read, 1024)
3757
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003758 def test_buffer_size(self):
3759 """
3760 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
3761 number of bytes to read and return.
3762 """
3763 ctx = Context(TLSv1_METHOD)
3764 conn = Connection(ctx, None)
3765 conn.set_connect_state()
3766 try:
3767 conn.do_handshake()
3768 except WantReadError:
3769 pass
3770 data = conn.bio_read(2)
3771 self.assertEqual(2, len(data))
3772
Hynek Schlawack35618382015-09-05 21:54:25 +02003773 @skip_if_py3
3774 def test_buffer_size_long(self):
3775 """
3776 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
3777 :py:obj:`long` as well as :py:obj:`int`.
3778 """
3779 ctx = Context(TLSv1_METHOD)
3780 conn = Connection(ctx, None)
3781 conn.set_connect_state()
3782 try:
3783 conn.do_handshake()
3784 except WantReadError:
3785 pass
3786 data = conn.bio_read(long(2))
3787 self.assertEqual(2, len(data))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003788
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003789
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003790class InfoConstantTests(TestCase):
3791 """
3792 Tests for assorted constants exposed for use in info callbacks.
3793 """
3794 def test_integers(self):
3795 """
3796 All of the info constants are integers.
3797
3798 This is a very weak test. It would be nice to have one that actually
3799 verifies that as certain info events happen, the value passed to the
3800 info callback matches up with the constant exposed by OpenSSL.SSL.
3801 """
3802 for const in [
Alex Gaynor5af32d02016-09-24 01:52:21 -04003803 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK,
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003804 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3805 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3806 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003807 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3808 ]:
Alex Gaynor5af32d02016-09-24 01:52:21 -04003809 assert isinstance(const, int)
3810
3811 # These constants don't exist on OpenSSL 1.1.0
3812 for const in [
3813 SSL_ST_INIT, SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE
3814 ]:
3815 assert const is None or isinstance(const, int)
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003816
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003817
Cory Benfield1d142142016-03-30 11:51:45 +01003818class TestRequires(object):
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003819 """
3820 Tests for the decorator factory used to conditionally raise
Cory Benfield1d142142016-03-30 11:51:45 +01003821 NotImplementedError when older OpenSSLs are used.
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003822 """
3823 def test_available(self):
3824 """
3825 When the OpenSSL functionality is available the decorated functions
3826 work appropriately.
3827 """
3828 feature_guard = _make_requires(True, "Error text")
3829 results = []
3830
3831 @feature_guard
3832 def inner():
3833 results.append(True)
3834 return True
3835
Cory Benfield2333e5e2016-03-30 14:24:16 +01003836 assert inner() is True
3837 assert [True] == results
Cory Benfield0ba57ec2016-03-30 09:35:05 +01003838
3839 def test_unavailable(self):
3840 """
3841 When the OpenSSL functionality is not available the decorated function
3842 does not execute and NotImplementedError is raised.
3843 """
3844 feature_guard = _make_requires(False, "Error text")
3845 results = []
3846
3847 @feature_guard
3848 def inner():
3849 results.append(True)
3850 return True
3851
Cory Benfield1d142142016-03-30 11:51:45 +01003852 with pytest.raises(NotImplementedError) as e:
3853 inner()
3854
3855 assert "Error text" in str(e.value)
Cory Benfield2333e5e2016-03-30 14:24:16 +01003856 assert results == []