blob: 3db1f8f48c2bd332cf96542a1f64f38e10e2906a [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"""
Jonathan Ballet648875f2011-07-16 14:14:58 +09005Unit tests for :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -04006"""
7
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05008from gc import collect, get_referrers
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02009from errno import ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN
Hynek Schlawackf8979a52015-09-05 21:25:25 +020010from sys import platform, getfilesystemencoding, version_info
Maximilian Hils1d95dea2015-08-17 19:27:20 +020011from socket import MSG_PEEK, SHUT_RDWR, error, socket
Jean-Paul Calderonea65cf6c2009-07-19 10:26:52 -040012from os import makedirs
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040013from os.path import join
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -040014from unittest import main
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -040015from weakref import ref
Abraham Martinef063482015-03-25 14:06:24 +000016from warnings import catch_warnings, simplefilter
Jean-Paul Calderone460cc1f2009-03-07 11:31:12 -050017
Hynek Schlawack734d3022015-09-05 19:19:32 +020018import pytest
19
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -040020from six import PY3, text_type, u
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050021
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040022from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080023from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040024from OpenSSL.crypto import dump_privatekey, load_privatekey
25from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040026from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040027
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040028from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
29from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040030from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040031from OpenSSL.SSL import (
32 SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
33 TLSv1_1_METHOD, TLSv1_2_METHOD)
34from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040035from OpenSSL.SSL import (
36 VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040037
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040038from OpenSSL.SSL import (
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050039 SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
40 SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
41 SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
42
43from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070044 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050045from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070046 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040047
Cory Benfieldba1820d2015-04-13 17:39:12 -040048from OpenSSL._util import lib as _lib
49
Jean-Paul Calderone17eca482015-04-13 20:31:07 -040050from OpenSSL.test.util import WARNING_TYPE_EXPECTED, NON_ASCII, TestCase, b
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040051from OpenSSL.test.test_crypto import (
Jean-Paul Calderoneda6399a2015-04-13 20:52:29 -040052 cleartextCertificatePEM, cleartextPrivateKeyPEM,
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040053 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
54 root_cert_pem)
55
Jean-Paul Calderone4bccf5e2008-12-28 22:50:42 -050056try:
57 from OpenSSL.SSL import OP_NO_QUERY_MTU
58except ImportError:
59 OP_NO_QUERY_MTU = None
60try:
61 from OpenSSL.SSL import OP_COOKIE_EXCHANGE
62except ImportError:
63 OP_COOKIE_EXCHANGE = None
64try:
65 from OpenSSL.SSL import OP_NO_TICKET
66except ImportError:
67 OP_NO_TICKET = None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -040068
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040069try:
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -040070 from OpenSSL.SSL import OP_NO_COMPRESSION
71except ImportError:
72 OP_NO_COMPRESSION = None
73
74try:
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040075 from OpenSSL.SSL import MODE_RELEASE_BUFFERS
76except ImportError:
77 MODE_RELEASE_BUFFERS = None
78
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040079try:
80 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
81except ImportError:
82 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
83
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040084from OpenSSL.SSL import (
85 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
86 SSL_ST_OK, SSL_ST_RENEGOTIATE,
87 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
88 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
89 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
90 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040091
Hynek Schlawackde00dd52015-09-05 19:09:26 +020092
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040093# openssl dhparam 128 -out dh-128.pem (note that 128 is a small number of bits
94# to use)
95dhparam = """\
96-----BEGIN DH PARAMETERS-----
97MBYCEQCobsg29c9WZP/54oAPcwiDAgEC
98-----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.
Jean-Paul Calderone9e4eeae2010-08-22 21:32:52 -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 """
179 caext = X509Extension(b('basicConstraints'), False, b('CA:true'))
180
181 # Step 1
182 cakey = PKey()
183 cakey.generate_key(TYPE_RSA, 512)
184 cacert = X509()
185 cacert.get_subject().commonName = "Authority Certificate"
186 cacert.set_issuer(cacert.get_subject())
187 cacert.set_pubkey(cakey)
188 cacert.set_notBefore(b("20000101000000Z"))
189 cacert.set_notAfter(b("20200101000000Z"))
190 cacert.add_extensions([caext])
191 cacert.set_serial_number(0)
192 cacert.sign(cakey, "sha1")
193
194 # Step 2
195 ikey = PKey()
196 ikey.generate_key(TYPE_RSA, 512)
197 icert = X509()
198 icert.get_subject().commonName = "Intermediate Certificate"
199 icert.set_issuer(cacert.get_subject())
200 icert.set_pubkey(ikey)
201 icert.set_notBefore(b("20000101000000Z"))
202 icert.set_notAfter(b("20200101000000Z"))
203 icert.add_extensions([caext])
204 icert.set_serial_number(0)
205 icert.sign(cakey, "sha1")
206
207 # Step 3
208 skey = PKey()
209 skey.generate_key(TYPE_RSA, 512)
210 scert = X509()
211 scert.get_subject().commonName = "Server Certificate"
212 scert.set_issuer(icert.get_subject())
213 scert.set_pubkey(skey)
214 scert.set_notBefore(b("20000101000000Z"))
215 scert.set_notAfter(b("20200101000000Z"))
216 scert.add_extensions([
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200217 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
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400224class _LoopbackMixin:
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):
260 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900261 Try to read application bytes from each of the two :py:obj:`Connection`
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400262 objects. Copy bytes back and forth between their send/receive buffers
263 for as long as there is anything to copy. When there is nothing more
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200264 to copy, return :py:obj:`None`. If one of them actually manages to
265 deliver some application bytes, return a two-tuple of the connection
266 from which the bytes were read and the bytes themselves.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400267 """
268 wrote = True
269 while wrote:
270 # Loop until neither side has anything to say
271 wrote = False
272
273 # Copy stuff from each side's send buffer to the other side's
274 # receive buffer.
275 for (read, write) in [(client_conn, server_conn),
276 (server_conn, client_conn)]:
277
278 # Give the side a chance to generate some more bytes, or
279 # succeed.
280 try:
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400281 data = read.recv(2 ** 16)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400282 except WantReadError:
283 # It didn't succeed, so we'll hope it generated some
284 # output.
285 pass
286 else:
287 # It did succeed, so we'll stop now and let the caller deal
288 # with it.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400289 return (read, data)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400290
291 while True:
292 # Keep copying as long as there's more stuff there.
293 try:
294 dirty = read.bio_read(4096)
295 except WantReadError:
296 # Okay, nothing more waiting to be sent. Stop
297 # processing this send buffer.
298 break
299 else:
300 # Keep track of the fact that someone generated some
301 # output.
302 wrote = True
303 write.bio_write(dirty)
304
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400305 def _handshakeInMemory(self, client_conn, server_conn):
Jean-Paul Calderoneb2b40782014-05-06 08:47:40 -0400306 """
307 Perform the TLS handshake between two :py:class:`Connection` instances
308 connected to each other via memory BIOs.
309 """
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400310 client_conn.set_connect_state()
311 server_conn.set_accept_state()
312
313 for conn in [client_conn, server_conn]:
314 try:
315 conn.do_handshake()
316 except WantReadError:
317 pass
318
319 self._interactInMemory(client_conn, server_conn)
320
321
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400322class VersionTests(TestCase):
323 """
324 Tests for version information exposed by
Jonathan Ballet648875f2011-07-16 14:14:58 +0900325 :py:obj:`OpenSSL.SSL.SSLeay_version` and
326 :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400327 """
328 def test_OPENSSL_VERSION_NUMBER(self):
329 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900330 :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400331 byte and the patch, fix, minor, and major versions in the
332 nibbles above that.
333 """
334 self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
335
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400336 def test_SSLeay_version(self):
337 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900338 :py:obj:`SSLeay_version` takes a version type indicator and returns
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400339 one of a number of version strings based on that indicator.
340 """
341 versions = {}
342 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
343 SSLEAY_PLATFORM, SSLEAY_DIR]:
344 version = SSLeay_version(t)
345 versions[version] = t
346 self.assertTrue(isinstance(version, bytes))
347 self.assertEqual(len(versions), 5)
348
349
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400350class ContextTests(TestCase, _LoopbackMixin):
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400351 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900352 Unit tests for :py:obj:`OpenSSL.SSL.Context`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400353 """
354 def test_method(self):
355 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200356 :py:obj:`Context` can be instantiated with one of
357 :py:obj:`SSLv2_METHOD`, :py:obj:`SSLv3_METHOD`,
358 :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400359 :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400360 """
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400361 methods = [
362 SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]
363 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400364 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400365
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400366 maybe = [SSLv2_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
367 for meth in maybe:
368 try:
369 Context(meth)
370 except (Error, ValueError):
371 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
372 # don't. Difficult to say in advance.
373 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400374
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400375 self.assertRaises(TypeError, Context, "")
376 self.assertRaises(ValueError, Context, 10)
377
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200378 @skip_if_py3
379 def test_method_long(self):
380 """
381 On Python 2 :py:class:`Context` accepts values of type
382 :py:obj:`long` as well as :py:obj:`int`.
383 """
384 Context(long(TLSv1_METHOD))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500385
Rick Deane15b1472009-07-09 15:53:42 -0500386 def test_type(self):
387 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200388 :py:obj:`Context` and :py:obj:`ContextType` refer to the same type
389 object and can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500390 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400391 self.assertIdentical(Context, ContextType)
392 self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500393
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400394 def test_use_privatekey(self):
395 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200396 :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey`
397 instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400398 """
399 key = PKey()
400 key.generate_key(TYPE_RSA, 128)
401 ctx = Context(TLSv1_METHOD)
402 ctx.use_privatekey(key)
403 self.assertRaises(TypeError, ctx.use_privatekey, "")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400404
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800405 def test_use_privatekey_file_missing(self):
406 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200407 :py:obj:`Context.use_privatekey_file` raises
408 :py:obj:`OpenSSL.SSL.Error` when passed the name of a file which does
409 not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800410 """
411 ctx = Context(TLSv1_METHOD)
412 self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
413
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400414 def _use_privatekey_file_test(self, pemfile, filetype):
415 """
416 Verify that calling ``Context.use_privatekey_file`` with the given
417 arguments does not raise an exception.
418 """
419 key = PKey()
420 key.generate_key(TYPE_RSA, 128)
421
422 with open(pemfile, "wt") as pem:
423 pem.write(
424 dump_privatekey(FILETYPE_PEM, key).decode("ascii")
425 )
426
427 ctx = Context(TLSv1_METHOD)
428 ctx.use_privatekey_file(pemfile, filetype)
429
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400430 def test_use_privatekey_file_bytes(self):
431 """
432 A private key can be specified from a file by passing a ``bytes``
433 instance giving the file name to ``Context.use_privatekey_file``.
434 """
435 self._use_privatekey_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400436 self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400437 FILETYPE_PEM,
438 )
439
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400440 def test_use_privatekey_file_unicode(self):
441 """
442 A private key can be specified from a file by passing a ``unicode``
443 instance giving the file name to ``Context.use_privatekey_file``.
444 """
445 self._use_privatekey_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400446 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400447 FILETYPE_PEM,
448 )
449
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200450 @skip_if_py3
451 def test_use_privatekey_file_long(self):
452 """
453 On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
454 filetype of type :py:obj:`long` as well as :py:obj:`int`.
455 """
456 self._use_privatekey_file_test(self.mktemp(), long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500457
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800458 def test_use_certificate_wrong_args(self):
459 """
460 :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200461 when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as
462 an argument.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800463 """
464 ctx = Context(TLSv1_METHOD)
465 self.assertRaises(TypeError, ctx.use_certificate)
466 self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200467 self.assertRaises(
468 TypeError, ctx.use_certificate, X509(), "hello, world"
469 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800470
471 def test_use_certificate_uninitialized(self):
472 """
473 :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
474 when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
475 initialized (ie, which does not actually have any certificate data).
476 """
477 ctx = Context(TLSv1_METHOD)
478 self.assertRaises(Error, ctx.use_certificate, X509())
479
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800480 def test_use_certificate(self):
481 """
482 :py:obj:`Context.use_certificate` sets the certificate which will be
483 used to identify connections created using the context.
484 """
485 # TODO
486 # Hard to assert anything. But we could set a privatekey then ask
487 # OpenSSL if the cert and key agree using check_privatekey. Then as
488 # long as check_privatekey works right we're good...
489 ctx = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200490 ctx.use_certificate(
491 load_certificate(FILETYPE_PEM, cleartextCertificatePEM)
492 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800493
494 def test_use_certificate_file_wrong_args(self):
495 """
496 :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
497 called with zero arguments or more than two arguments, or if the first
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200498 argument is not a byte string or the second argumnent is not an
499 integer.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800500 """
501 ctx = Context(TLSv1_METHOD)
502 self.assertRaises(TypeError, ctx.use_certificate_file)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200503 self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile",
504 object())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800505 self.assertRaises(
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200506 TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM,
507 object())
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800508 self.assertRaises(
509 TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
510 self.assertRaises(
511 TypeError, ctx.use_certificate_file, b"somefile", object())
512
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800513 def test_use_certificate_file_missing(self):
514 """
515 :py:obj:`Context.use_certificate_file` raises
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200516 `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does
517 not exist.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800518 """
519 ctx = Context(TLSv1_METHOD)
520 self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
521
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400522 def _use_certificate_file_test(self, certificate_file):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800523 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400524 Verify that calling ``Context.use_certificate_file`` with the given
525 filename doesn't raise an exception.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800526 """
527 # TODO
528 # Hard to assert anything. But we could set a privatekey then ask
529 # OpenSSL if the cert and key agree using check_privatekey. Then as
530 # long as check_privatekey works right we're good...
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400531 with open(certificate_file, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800532 pem_file.write(cleartextCertificatePEM)
533
534 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400535 ctx.use_certificate_file(certificate_file)
536
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400537 def test_use_certificate_file_bytes(self):
538 """
539 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
540 ``bytes`` filename) which will be used to identify connections created
541 using the context.
542 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400543 filename = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400544 self._use_certificate_file_test(filename)
545
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400546 def test_use_certificate_file_unicode(self):
547 """
548 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
549 ``bytes`` filename) which will be used to identify connections created
550 using the context.
551 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400552 filename = self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400553 self._use_certificate_file_test(filename)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800554
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200555 @skip_if_py3
556 def test_use_certificate_file_long(self):
557 """
558 On Python 2 :py:obj:`Context.use_certificate_file` accepts a
559 filetype of type :py:obj:`long` as well as :py:obj:`int`.
560 """
561 pem_filename = self.mktemp()
562 with open(pem_filename, "wb") as pem_file:
563 pem_file.write(cleartextCertificatePEM)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500564
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200565 ctx = Context(TLSv1_METHOD)
566 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500567
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500568 def test_check_privatekey_valid(self):
569 """
570 :py:obj:`Context.check_privatekey` returns :py:obj:`None` if the
571 :py:obj:`Context` instance has been configured to use a matched key and
572 certificate pair.
573 """
574 key = load_privatekey(FILETYPE_PEM, client_key_pem)
575 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
576 context = Context(TLSv1_METHOD)
577 context.use_privatekey(key)
578 context.use_certificate(cert)
579 self.assertIs(None, context.check_privatekey())
580
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500581 def test_check_privatekey_invalid(self):
582 """
583 :py:obj:`Context.check_privatekey` raises :py:obj:`Error` if the
584 :py:obj:`Context` instance has been configured to use a key and
585 certificate pair which don't relate to each other.
586 """
587 key = load_privatekey(FILETYPE_PEM, client_key_pem)
588 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
589 context = Context(TLSv1_METHOD)
590 context.use_privatekey(key)
591 context.use_certificate(cert)
592 self.assertRaises(Error, context.check_privatekey)
593
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500594 def test_check_privatekey_wrong_args(self):
595 """
596 :py:obj:`Context.check_privatekey` raises :py:obj:`TypeError` if called
597 with other than no arguments.
598 """
599 context = Context(TLSv1_METHOD)
600 self.assertRaises(TypeError, context.check_privatekey, object())
601
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400602 def test_set_app_data_wrong_args(self):
603 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200604 :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called
605 with other than one argument.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400606 """
607 context = Context(TLSv1_METHOD)
608 self.assertRaises(TypeError, context.set_app_data)
609 self.assertRaises(TypeError, context.set_app_data, None, None)
610
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400611 def test_get_app_data_wrong_args(self):
612 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200613 :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called
614 with any arguments.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400615 """
616 context = Context(TLSv1_METHOD)
617 self.assertRaises(TypeError, context.get_app_data, None)
618
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400619 def test_app_data(self):
620 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200621 :py:obj:`Context.set_app_data` stores an object for later retrieval
622 using :py:obj:`Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400623 """
624 app_data = object()
625 context = Context(TLSv1_METHOD)
626 context.set_app_data(app_data)
627 self.assertIdentical(context.get_app_data(), app_data)
628
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400629 def test_set_options_wrong_args(self):
630 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200631 :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with
632 the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400633 """
634 context = Context(TLSv1_METHOD)
635 self.assertRaises(TypeError, context.set_options)
636 self.assertRaises(TypeError, context.set_options, None)
637 self.assertRaises(TypeError, context.set_options, 1, None)
638
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500639 def test_set_options(self):
640 """
641 :py:obj:`Context.set_options` returns the new options value.
642 """
643 context = Context(TLSv1_METHOD)
644 options = context.set_options(OP_NO_SSLv2)
645 self.assertTrue(OP_NO_SSLv2 & options)
646
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200647 @skip_if_py3
648 def test_set_options_long(self):
649 """
650 On Python 2 :py:obj:`Context.set_options` accepts values of type
651 :py:obj:`long` as well as :py:obj:`int`.
652 """
653 context = Context(TLSv1_METHOD)
654 options = context.set_options(long(OP_NO_SSLv2))
655 self.assertTrue(OP_NO_SSLv2 & options)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500656
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300657 def test_set_mode_wrong_args(self):
658 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200659 :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with
660 the wrong number of arguments or a non-:py:obj:`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300661 """
662 context = Context(TLSv1_METHOD)
663 self.assertRaises(TypeError, context.set_mode)
664 self.assertRaises(TypeError, context.set_mode, None)
665 self.assertRaises(TypeError, context.set_mode, 1, None)
666
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400667 if MODE_RELEASE_BUFFERS is not None:
668 def test_set_mode(self):
669 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200670 :py:obj:`Context.set_mode` accepts a mode bitvector and returns the
671 newly set mode.
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400672 """
673 context = Context(TLSv1_METHOD)
674 self.assertTrue(
675 MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500676
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200677 @skip_if_py3
678 def test_set_mode_long(self):
679 """
680 On Python 2 :py:obj:`Context.set_mode` accepts values of type
681 :py:obj:`long` as well as :py:obj:`int`.
682 """
683 context = Context(TLSv1_METHOD)
684 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
685 self.assertTrue(MODE_RELEASE_BUFFERS & mode)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400686 else:
687 "MODE_RELEASE_BUFFERS unavailable - OpenSSL version may be too old"
688
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400689 def test_set_timeout_wrong_args(self):
690 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200691 :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with
692 the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400693 """
694 context = Context(TLSv1_METHOD)
695 self.assertRaises(TypeError, context.set_timeout)
696 self.assertRaises(TypeError, context.set_timeout, None)
697 self.assertRaises(TypeError, context.set_timeout, 1, None)
698
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400699 def test_get_timeout_wrong_args(self):
700 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200701 :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with
702 any arguments.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400703 """
704 context = Context(TLSv1_METHOD)
705 self.assertRaises(TypeError, context.get_timeout, None)
706
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400707 def test_timeout(self):
708 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200709 :py:obj:`Context.set_timeout` sets the session timeout for all
710 connections created using the context object.
711 :py:obj:`Context.get_timeout` retrieves this value.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400712 """
713 context = Context(TLSv1_METHOD)
714 context.set_timeout(1234)
715 self.assertEquals(context.get_timeout(), 1234)
716
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200717 @skip_if_py3
718 def test_timeout_long(self):
719 """
720 On Python 2 :py:obj:`Context.set_timeout` accepts values of type
721 `long` as well as int.
722 """
723 context = Context(TLSv1_METHOD)
724 context.set_timeout(long(1234))
725 self.assertEquals(context.get_timeout(), 1234)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500726
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400727 def test_set_verify_depth_wrong_args(self):
728 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200729 :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called
730 with the wrong number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400731 """
732 context = Context(TLSv1_METHOD)
733 self.assertRaises(TypeError, context.set_verify_depth)
734 self.assertRaises(TypeError, context.set_verify_depth, None)
735 self.assertRaises(TypeError, context.set_verify_depth, 1, None)
736
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400737 def test_get_verify_depth_wrong_args(self):
738 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200739 :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called
740 with any arguments.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400741 """
742 context = Context(TLSv1_METHOD)
743 self.assertRaises(TypeError, context.get_verify_depth, None)
744
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400745 def test_verify_depth(self):
746 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200747 :py:obj:`Context.set_verify_depth` sets the number of certificates in
748 a chain to follow before giving up. The value can be retrieved with
Jonathan Ballet648875f2011-07-16 14:14:58 +0900749 :py:obj:`Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400750 """
751 context = Context(TLSv1_METHOD)
752 context.set_verify_depth(11)
753 self.assertEquals(context.get_verify_depth(), 11)
754
Hynek Schlawack97cf1a82015-09-05 20:40:19 +0200755 @skip_if_py3
756 def test_verify_depth_long(self):
757 """
758 On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
759 type `long` as well as int.
760 """
761 context = Context(TLSv1_METHOD)
762 context.set_verify_depth(long(11))
763 self.assertEquals(context.get_verify_depth(), 11)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500764
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400765 def _write_encrypted_pem(self, passphrase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400766 """
767 Write a new private key out to a new file, encrypted using the given
768 passphrase. Return the path to the new file.
769 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400770 key = PKey()
771 key.generate_key(TYPE_RSA, 128)
772 pemFile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400773 fObj = open(pemFile, 'w')
774 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
775 fObj.write(pem.decode('ascii'))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400776 fObj.close()
777 return pemFile
778
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400779 def test_set_passwd_cb_wrong_args(self):
780 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200781 :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called
782 with the wrong arguments or with a non-callable first argument.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400783 """
784 context = Context(TLSv1_METHOD)
785 self.assertRaises(TypeError, context.set_passwd_cb)
786 self.assertRaises(TypeError, context.set_passwd_cb, None)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200787 self.assertRaises(
788 TypeError, context.set_passwd_cb, lambda: None, None, None
Hynek Schlawack2c013a92015-09-05 19:33:05 +0200789 ) # pragma: nocover
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400790
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400791 def test_set_passwd_cb(self):
792 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200793 :py:obj:`Context.set_passwd_cb` accepts a callable which will be
794 invoked when a private key is loaded from an encrypted PEM.
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400795 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400796 passphrase = b("foobar")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400797 pemFile = self._write_encrypted_pem(passphrase)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400798 calledWith = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200799
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400800 def passphraseCallback(maxlen, verify, extra):
801 calledWith.append((maxlen, verify, extra))
802 return passphrase
803 context = Context(TLSv1_METHOD)
804 context.set_passwd_cb(passphraseCallback)
805 context.use_privatekey_file(pemFile)
806 self.assertTrue(len(calledWith), 1)
807 self.assertTrue(isinstance(calledWith[0][0], int))
808 self.assertTrue(isinstance(calledWith[0][1], int))
809 self.assertEqual(calledWith[0][2], None)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400810
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400811 def test_passwd_callback_exception(self):
812 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200813 :py:obj:`Context.use_privatekey_file` propagates any exception raised
814 by the passphrase callback.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400815 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400816 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200817
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400818 def passphraseCallback(maxlen, verify, extra):
819 raise RuntimeError("Sorry, I am a fail.")
820
821 context = Context(TLSv1_METHOD)
822 context.set_passwd_cb(passphraseCallback)
823 self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
824
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400825 def test_passwd_callback_false(self):
826 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200827 :py:obj:`Context.use_privatekey_file` raises
828 :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a false
829 value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400830 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400831 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200832
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400833 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500834 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400835
836 context = Context(TLSv1_METHOD)
837 context.set_passwd_cb(passphraseCallback)
838 self.assertRaises(Error, context.use_privatekey_file, pemFile)
839
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400840 def test_passwd_callback_non_string(self):
841 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200842 :py:obj:`Context.use_privatekey_file` raises
843 :py:obj:`OpenSSL.SSL.Error` if the passphrase callback returns a true
844 non-string value.
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400845 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400846 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200847
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400848 def passphraseCallback(maxlen, verify, extra):
849 return 10
850
851 context = Context(TLSv1_METHOD)
852 context.set_passwd_cb(passphraseCallback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800853 self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400854
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400855 def test_passwd_callback_too_long(self):
856 """
857 If the passphrase returned by the passphrase callback returns a string
858 longer than the indicated maximum length, it is truncated.
859 """
860 # A priori knowledge!
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400861 passphrase = b("x") * 1024
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400862 pemFile = self._write_encrypted_pem(passphrase)
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200863
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400864 def passphraseCallback(maxlen, verify, extra):
865 assert maxlen == 1024
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400866 return passphrase + b("y")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400867
868 context = Context(TLSv1_METHOD)
869 context.set_passwd_cb(passphraseCallback)
870 # This shall succeed because the truncated result is the correct
871 # passphrase.
872 context.use_privatekey_file(pemFile)
873
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400874 def test_set_info_callback(self):
875 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200876 :py:obj:`Context.set_info_callback` accepts a callable which will be
877 invoked when certain information about an SSL connection is available.
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400878 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500879 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400880
881 clientSSL = Connection(Context(TLSv1_METHOD), client)
882 clientSSL.set_connect_state()
883
884 called = []
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200885
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400886 def info(conn, where, ret):
887 called.append((conn, where, ret))
888 context = Context(TLSv1_METHOD)
889 context.set_info_callback(info)
890 context.use_certificate(
891 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
892 context.use_privatekey(
893 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
894
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400895 serverSSL = Connection(context, server)
896 serverSSL.set_accept_state()
897
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500898 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400899
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500900 # The callback must always be called with a Connection instance as the
901 # first argument. It would probably be better to split this into
902 # separate tests for client and server side info callbacks so we could
903 # assert it is called with the right Connection instance. It would
904 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500905 notConnections = [
906 conn for (conn, where, ret) in called
907 if not isinstance(conn, Connection)]
908 self.assertEqual(
909 [], notConnections,
910 "Some info callback arguments were not Connection instaces.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400911
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400912 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400913 """
914 Create a client context which will verify the peer certificate and call
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400915 its :py:obj:`load_verify_locations` method with the given arguments.
916 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400917 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500918 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400919
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400920 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400921 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400922 # Require that the server certificate verify properly or the
923 # connection will fail.
924 clientContext.set_verify(
925 VERIFY_PEER,
926 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
927
928 clientSSL = Connection(clientContext, client)
929 clientSSL.set_connect_state()
930
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400931 serverContext = Context(TLSv1_METHOD)
932 serverContext.use_certificate(
933 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
934 serverContext.use_privatekey(
935 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
936
937 serverSSL = Connection(serverContext, server)
938 serverSSL.set_accept_state()
939
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400940 # Without load_verify_locations above, the handshake
941 # will fail:
942 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
943 # 'certificate verify failed')]
944 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400945
946 cert = clientSSL.get_peer_certificate()
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400947 self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400948
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400949 def _load_verify_cafile(self, cafile):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400950 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400951 Verify that if path to a file containing a certificate is passed to
952 ``Context.load_verify_locations`` for the ``cafile`` parameter, that
953 certificate is used as a trust root for the purposes of verifying
954 connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400955 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400956 fObj = open(cafile, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400957 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400958 fObj.close()
959
960 self._load_verify_locations_test(cafile)
961
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400962 def test_load_verify_bytes_cafile(self):
963 """
964 :py:obj:`Context.load_verify_locations` accepts a file name as a
965 ``bytes`` instance and uses the certificates within for verification
966 purposes.
967 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400968 cafile = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400969 self._load_verify_cafile(cafile)
970
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400971 def test_load_verify_unicode_cafile(self):
972 """
973 :py:obj:`Context.load_verify_locations` accepts a file name as a
974 ``unicode`` instance and uses the certificates within for verification
975 purposes.
976 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -0400977 self._load_verify_cafile(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -0400978 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -0400979 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400980
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400981 def test_load_verify_invalid_file(self):
982 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +0200983 :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when
984 passed a non-existent cafile.
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400985 """
986 clientContext = Context(TLSv1_METHOD)
987 self.assertRaises(
988 Error, clientContext.load_verify_locations, self.mktemp())
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400989
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400990 def _load_verify_directory_locations_capath(self, capath):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400991 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400992 Verify that if path to a directory containing certificate files is
993 passed to ``Context.load_verify_locations`` for the ``capath``
994 parameter, those certificates are used as trust roots for the purposes
995 of verifying connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400996 """
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400997 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400998 # Hash values computed manually with c_rehash to avoid depending on
999 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
1000 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001001 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001002 cafile = join_bytes_or_unicode(capath, name)
1003 with open(cafile, 'w') as fObj:
1004 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001005
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001006 self._load_verify_locations_test(None, capath)
1007
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001008 def test_load_verify_directory_bytes_capath(self):
1009 """
1010 :py:obj:`Context.load_verify_locations` accepts a directory name as a
1011 ``bytes`` instance and uses the certificates within for verification
1012 purposes.
1013 """
1014 self._load_verify_directory_locations_capath(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001015 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001016 )
1017
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001018 def test_load_verify_directory_unicode_capath(self):
1019 """
1020 :py:obj:`Context.load_verify_locations` accepts a directory name as a
1021 ``unicode`` instance and uses the certificates within for verification
1022 purposes.
1023 """
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001024 self._load_verify_directory_locations_capath(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001025 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderone4f70c802015-04-12 11:26:47 -04001026 )
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -04001027
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001028 def test_load_verify_locations_wrong_args(self):
1029 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001030 :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if
1031 called with the wrong number of arguments or with non-:py:obj:`str`
1032 arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001033 """
1034 context = Context(TLSv1_METHOD)
1035 self.assertRaises(TypeError, context.load_verify_locations)
1036 self.assertRaises(TypeError, context.load_verify_locations, object())
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001037 self.assertRaises(
1038 TypeError, context.load_verify_locations, object(), object()
1039 )
1040 self.assertRaises(
1041 TypeError, context.load_verify_locations, None, None, None
1042 )
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001043
Hynek Schlawack734d3022015-09-05 19:19:32 +02001044 @pytest.mark.skipif(
1045 platform == "win32",
1046 reason="set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001047 "See LP#404343 and LP#404344."
Hynek Schlawack734d3022015-09-05 19:19:32 +02001048 )
1049 def test_set_default_verify_paths(self):
1050 """
1051 :py:obj:`Context.set_default_verify_paths` causes the
1052 platform-specific CA certificate locations to be used for
1053 verification purposes.
1054 """
1055 # Testing this requires a server with a certificate signed by one
1056 # of the CAs in the platform CA location. Getting one of those
1057 # costs money. Fortunately (or unfortunately, depending on your
1058 # perspective), it's easy to think of a public server on the
1059 # internet which has such a certificate. Connecting to the network
1060 # in a unit test is bad, but it's the only way I can think of to
1061 # really test this. -exarkun
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001062
Hynek Schlawack734d3022015-09-05 19:19:32 +02001063 # Arg, verisign.com doesn't speak anything newer than TLS 1.0
1064 context = Context(TLSv1_METHOD)
1065 context.set_default_verify_paths()
1066 context.set_verify(
1067 VERIFY_PEER,
1068 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001069
Hynek Schlawack734d3022015-09-05 19:19:32 +02001070 client = socket()
1071 client.connect(('verisign.com', 443))
1072 clientSSL = Connection(context, client)
1073 clientSSL.set_connect_state()
1074 clientSSL.do_handshake()
1075 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
1076 self.assertTrue(clientSSL.recv(1024))
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001077
1078 def test_set_default_verify_paths_signature(self):
1079 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001080 :py:obj:`Context.set_default_verify_paths` takes no arguments and
1081 raises :py:obj:`TypeError` if given any.
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001082 """
1083 context = Context(TLSv1_METHOD)
1084 self.assertRaises(TypeError, context.set_default_verify_paths, None)
1085 self.assertRaises(TypeError, context.set_default_verify_paths, 1)
1086 self.assertRaises(TypeError, context.set_default_verify_paths, "")
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001087
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001088 def test_add_extra_chain_cert_invalid_cert(self):
1089 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001090 :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if
1091 called with other than one argument or if called with an object which
1092 is not an instance of :py:obj:`X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001093 """
1094 context = Context(TLSv1_METHOD)
1095 self.assertRaises(TypeError, context.add_extra_chain_cert)
1096 self.assertRaises(TypeError, context.add_extra_chain_cert, object())
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001097 self.assertRaises(
1098 TypeError, context.add_extra_chain_cert, object(), object()
1099 )
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001100
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001101 def _handshake_test(self, serverContext, clientContext):
1102 """
1103 Verify that a client and server created with the given contexts can
1104 successfully handshake and communicate.
1105 """
1106 serverSocket, clientSocket = socket_pair()
1107
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001108 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001109 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001110
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001111 client = Connection(clientContext, clientSocket)
1112 client.set_connect_state()
1113
1114 # Make them talk to each other.
1115 # self._interactInMemory(client, server)
1116 for i in range(3):
1117 for s in [client, server]:
1118 try:
1119 s.do_handshake()
1120 except WantReadError:
1121 pass
1122
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001123 def test_set_verify_callback_connection_argument(self):
1124 """
1125 The first argument passed to the verify callback is the
1126 :py:class:`Connection` instance for which verification is taking place.
1127 """
1128 serverContext = Context(TLSv1_METHOD)
1129 serverContext.use_privatekey(
1130 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1131 serverContext.use_certificate(
1132 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1133 serverConnection = Connection(serverContext, None)
1134
1135 class VerifyCallback(object):
1136 def callback(self, connection, *args):
1137 self.connection = connection
1138 return 1
1139
1140 verify = VerifyCallback()
1141 clientContext = Context(TLSv1_METHOD)
1142 clientContext.set_verify(VERIFY_PEER, verify.callback)
1143 clientConnection = Connection(clientContext, None)
1144 clientConnection.set_connect_state()
1145
1146 self._handshakeInMemory(clientConnection, serverConnection)
1147
1148 self.assertIdentical(verify.connection, clientConnection)
1149
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001150 def test_set_verify_callback_exception(self):
1151 """
1152 If the verify callback passed to :py:obj:`Context.set_verify` raises an
1153 exception, verification fails and the exception is propagated to the
1154 caller of :py:obj:`Connection.do_handshake`.
1155 """
1156 serverContext = Context(TLSv1_METHOD)
1157 serverContext.use_privatekey(
1158 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1159 serverContext.use_certificate(
1160 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1161
1162 clientContext = Context(TLSv1_METHOD)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001163
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001164 def verify_callback(*args):
1165 raise Exception("silly verify failure")
1166 clientContext.set_verify(VERIFY_PEER, verify_callback)
1167
1168 exc = self.assertRaises(
1169 Exception, self._handshake_test, serverContext, clientContext)
1170 self.assertEqual("silly verify failure", str(exc))
1171
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001172 def test_add_extra_chain_cert(self):
1173 """
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001174 :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509`
1175 instance to add to the certificate chain.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001176
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001177 See :py:obj:`_create_certificate_chain` for the details of the
1178 certificate chain tested.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001179
1180 The chain is tested by starting a server with scert and connecting
1181 to it with a client which trusts cacert and requires verification to
1182 succeed.
1183 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001184 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001185 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1186
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001187 # Dump the CA certificate to a file because that's the only way to load
1188 # it as a trusted CA in the client context.
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001189 for cert, name in [(cacert, 'ca.pem'),
1190 (icert, 'i.pem'),
1191 (scert, 's.pem')]:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001192 with open(join(self.tmpdir, name), 'w') as f:
1193 f.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001194
Hynek Schlawack1902c012015-04-16 15:06:41 -04001195 for key, name in [(cakey, 'ca.key'),
1196 (ikey, 'i.key'),
1197 (skey, 's.key')]:
Hynek Schlawacke90680f2015-04-16 15:09:27 -04001198 with open(join(self.tmpdir, name), 'w') as f:
1199 f.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001200
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001201 # Create the server context
1202 serverContext = Context(TLSv1_METHOD)
1203 serverContext.use_privatekey(skey)
1204 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001205 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001206 serverContext.add_extra_chain_cert(icert)
1207
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001208 # Create the client
1209 clientContext = Context(TLSv1_METHOD)
1210 clientContext.set_verify(
1211 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001212 clientContext.load_verify_locations(join(self.tmpdir, "ca.pem"))
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001213
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001214 # Try it out.
1215 self._handshake_test(serverContext, clientContext)
1216
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001217 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001218 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001219 Verify that :py:obj:`Context.use_certificate_chain_file` reads a
1220 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001221
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001222 The chain is tested by starting a server with scert and connecting to
1223 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001224 succeed.
1225 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001226 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001227 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1228
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001229 makedirs(certdir)
1230
Jean-Paul Calderone05826732015-04-12 11:38:49 -04001231 chainFile = join_bytes_or_unicode(certdir, "chain.pem")
1232 caFile = join_bytes_or_unicode(certdir, "ca.pem")
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001233
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001234 # Write out the chain file.
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001235 with open(chainFile, 'wb') as fObj:
1236 # Most specific to least general.
1237 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1238 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1239 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1240
1241 with open(caFile, 'w') as fObj:
1242 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001243
1244 serverContext = Context(TLSv1_METHOD)
1245 serverContext.use_certificate_chain_file(chainFile)
1246 serverContext.use_privatekey(skey)
1247
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001248 clientContext = Context(TLSv1_METHOD)
1249 clientContext.set_verify(
1250 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001251 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001252
1253 self._handshake_test(serverContext, clientContext)
1254
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001255 def test_use_certificate_chain_file_bytes(self):
1256 """
1257 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1258 an instance of ``bytes``) to specify additional certificates to use to
1259 construct and verify a trust chain.
1260 """
1261 self._use_certificate_chain_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001262 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001263 )
1264
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001265 def test_use_certificate_chain_file_unicode(self):
1266 """
1267 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1268 an instance of ``unicode``) to specify additional certificates to use
1269 to construct and verify a trust chain.
1270 """
1271 self._use_certificate_chain_file_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001272 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001273 )
1274
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001275 def test_use_certificate_chain_file_wrong_args(self):
1276 """
1277 :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
1278 if passed zero or more than one argument or when passed a non-byte
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001279 string single argument. It also raises :py:obj:`OpenSSL.SSL.Error`
1280 when passed a bad chain file name (for example, the name of a file
1281 which does not exist).
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001282 """
1283 context = Context(TLSv1_METHOD)
1284 self.assertRaises(TypeError, context.use_certificate_chain_file)
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001285 self.assertRaises(
1286 TypeError, context.use_certificate_chain_file, object()
1287 )
1288 self.assertRaises(
1289 TypeError, context.use_certificate_chain_file, b"foo", object()
1290 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001291
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001292 self.assertRaises(
1293 Error, context.use_certificate_chain_file, self.mktemp()
1294 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295
Jean-Paul Calderonee0d79362010-08-03 18:46:46 -04001296 # XXX load_client_ca
1297 # XXX set_session_id
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001298
1299 def test_get_verify_mode_wrong_args(self):
1300 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001301 :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called
1302 with any arguments.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001303 """
1304 context = Context(TLSv1_METHOD)
1305 self.assertRaises(TypeError, context.get_verify_mode, None)
1306
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001307 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001308 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001309 :py:obj:`Context.get_verify_mode` returns the verify mode flags
1310 previously passed to :py:obj:`Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001311 """
1312 context = Context(TLSv1_METHOD)
1313 self.assertEquals(context.get_verify_mode(), 0)
1314 context.set_verify(
1315 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
1316 self.assertEquals(
1317 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1318
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001319 @skip_if_py3
1320 def test_set_verify_mode_long(self):
1321 """
1322 On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
1323 type :py:obj:`long` as well as :py:obj:`int`.
1324 """
1325 context = Context(TLSv1_METHOD)
1326 self.assertEquals(context.get_verify_mode(), 0)
1327 context.set_verify(
Hynek Schlawackb4ceed32015-09-05 20:55:19 +02001328 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None
1329 ) # pragma: nocover
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001330 self.assertEquals(
1331 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001332
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001333 def test_load_tmp_dh_wrong_args(self):
1334 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001335 :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with
1336 the wrong number of arguments or with a non-:py:obj:`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001337 """
1338 context = Context(TLSv1_METHOD)
1339 self.assertRaises(TypeError, context.load_tmp_dh)
1340 self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
1341 self.assertRaises(TypeError, context.load_tmp_dh, object())
1342
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001343 def test_load_tmp_dh_missing_file(self):
1344 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001345 :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the
1346 specified file does not exist.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001347 """
1348 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001349 self.assertRaises(Error, context.load_tmp_dh, b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001350
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001351 def _load_tmp_dh_test(self, dhfilename):
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001352 """
1353 Verify that calling ``Context.load_tmp_dh`` with the given filename
1354 does not raise an exception.
1355 """
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001356 context = Context(TLSv1_METHOD)
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001357 with open(dhfilename, "w") as dhfile:
1358 dhfile.write(dhparam)
1359
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001360 context.load_tmp_dh(dhfilename)
1361 # XXX What should I assert here? -exarkun
1362
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001363 def test_load_tmp_dh_bytes(self):
1364 """
1365 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1366 specified file (given as ``bytes``).
1367 """
1368 self._load_tmp_dh_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001369 self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001370 )
1371
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001372 def test_load_tmp_dh_unicode(self):
1373 """
1374 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
1375 specified file (given as ``unicode``).
1376 """
1377 self._load_tmp_dh_test(
Hynek Schlawack4813c0e2015-04-16 13:38:01 -04001378 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001379 )
1380
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001381 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001382 """
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001383 :py:obj:`Context.set_tmp_ecdh` sets the elliptic curve for
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001384 Diffie-Hellman to the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001385 """
1386 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001387 for curve in get_elliptic_curves():
Hynek Schlawacka07fa8c2015-10-17 10:15:28 +02001388 if curve.name.startswith(u"Oakley-"):
Hynek Schlawack7408aff2015-10-17 09:51:16 +02001389 # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
1390 # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
1391 # error queue on OpenSSL 1.0.2.
1392 continue
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001393 # The only easily "assertable" thing is that it does not raise an
1394 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001395 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001396
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001397 def test_set_cipher_list_bytes(self):
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001398 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001399 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
1400 ciphers which connections created with the context object will be able
1401 to choose from.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001402 """
1403 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001404 context.set_cipher_list(b"hello world:EXP-RC4-MD5")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001405 conn = Connection(context, None)
1406 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001407
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001408 def test_set_cipher_list_text(self):
1409 """
1410 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
1411 the ciphers which connections created with the context object will be
1412 able to choose from.
1413 """
1414 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -05001415 context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001416 conn = Connection(context, None)
1417 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
1418
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001419 def test_set_cipher_list_wrong_args(self):
1420 """
Jean-Paul Calderone17044832014-01-18 10:20:11 -05001421 :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
1422 passed zero arguments or more than one argument or when passed a
1423 non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001424 passed an incorrect cipher list string.
1425 """
1426 context = Context(TLSv1_METHOD)
1427 self.assertRaises(TypeError, context.set_cipher_list)
1428 self.assertRaises(TypeError, context.set_cipher_list, object())
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001429 self.assertRaises(
1430 TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object()
1431 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001432
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001433 self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001434
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001435 def test_set_session_cache_mode_wrong_args(self):
1436 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001437 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1438 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001439 """
1440 context = Context(TLSv1_METHOD)
1441 self.assertRaises(TypeError, context.set_session_cache_mode)
1442 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1443
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001444 def test_get_session_cache_mode_wrong_args(self):
1445 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001446 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1447 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001448 """
1449 context = Context(TLSv1_METHOD)
1450 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1451
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001452 def test_session_cache_mode(self):
1453 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001454 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1455 cached. The setting can be retrieved via
1456 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001457 """
1458 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001459 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001460 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1461 self.assertEqual(SESS_CACHE_OFF, off)
1462 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1463
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001464 @skip_if_py3
1465 def test_session_cache_mode_long(self):
1466 """
1467 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1468 of type :py:obj:`long` as well as :py:obj:`int`.
1469 """
1470 context = Context(TLSv1_METHOD)
1471 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1472 self.assertEqual(
1473 SESS_CACHE_BOTH, context.get_session_cache_mode())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001474
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001475 def test_get_cert_store(self):
1476 """
Hynek Schlawackde00dd52015-09-05 19:09:26 +02001477 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store`
1478 instance.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001479 """
1480 context = Context(TLSv1_METHOD)
1481 store = context.get_cert_store()
1482 self.assertIsInstance(store, X509Store)
1483
1484
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001485class ServerNameCallbackTests(TestCase, _LoopbackMixin):
1486 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001487 Tests for :py:obj:`Context.set_tlsext_servername_callback` and its
1488 interaction with :py:obj:`Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001489 """
1490 def test_wrong_args(self):
1491 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001492 :py:obj:`Context.set_tlsext_servername_callback` raises
1493 :py:obj:`TypeError` if called with other than one argument.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001494 """
1495 context = Context(TLSv1_METHOD)
1496 self.assertRaises(TypeError, context.set_tlsext_servername_callback)
1497 self.assertRaises(
1498 TypeError, context.set_tlsext_servername_callback, 1, 2)
1499
1500 def test_old_callback_forgotten(self):
1501 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001502 If :py:obj:`Context.set_tlsext_servername_callback` is used to specify
1503 a new callback, the one it replaces is dereferenced.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001504 """
1505 def callback(connection):
1506 pass
1507
1508 def replacement(connection):
1509 pass
1510
1511 context = Context(TLSv1_METHOD)
1512 context.set_tlsext_servername_callback(callback)
1513
1514 tracker = ref(callback)
1515 del callback
1516
1517 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001518
1519 # One run of the garbage collector happens to work on CPython. PyPy
1520 # doesn't collect the underlying object until a second run for whatever
1521 # reason. That's fine, it still demonstrates our code has properly
1522 # dropped the reference.
1523 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001524 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001525
1526 callback = tracker()
1527 if callback is not None:
1528 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001529 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001530 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001531
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001532 def test_no_servername(self):
1533 """
1534 When a client specifies no server name, the callback passed to
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001535 :py:obj:`Context.set_tlsext_servername_callback` is invoked and the
1536 result of :py:obj:`Connection.get_servername` is :py:obj:`None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001537 """
1538 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001539
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001540 def servername(conn):
1541 args.append((conn, conn.get_servername()))
1542 context = Context(TLSv1_METHOD)
1543 context.set_tlsext_servername_callback(servername)
1544
1545 # Lose our reference to it. The Context is responsible for keeping it
1546 # alive now.
1547 del servername
1548 collect()
1549
1550 # Necessary to actually accept the connection
1551 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001552 context.use_certificate(
1553 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001554
1555 # Do a little connection to trigger the logic
1556 server = Connection(context, None)
1557 server.set_accept_state()
1558
1559 client = Connection(Context(TLSv1_METHOD), None)
1560 client.set_connect_state()
1561
1562 self._interactInMemory(server, client)
1563
1564 self.assertEqual([(server, None)], args)
1565
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001566 def test_servername(self):
1567 """
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001568 When a client specifies a server name in its hello message, the
1569 callback passed to :py:obj:`Contexts.set_tlsext_servername_callback` is
1570 invoked and the result of :py:obj:`Connection.get_servername` is that
1571 server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001572 """
1573 args = []
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001574
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001575 def servername(conn):
1576 args.append((conn, conn.get_servername()))
1577 context = Context(TLSv1_METHOD)
1578 context.set_tlsext_servername_callback(servername)
1579
1580 # Necessary to actually accept the connection
1581 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
Hynek Schlawackafeffd22015-09-05 20:08:16 +02001582 context.use_certificate(
1583 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001584
1585 # Do a little connection to trigger the logic
1586 server = Connection(context, None)
1587 server.set_accept_state()
1588
1589 client = Connection(Context(TLSv1_METHOD), None)
1590 client.set_connect_state()
1591 client.set_tlsext_host_name(b("foo1.example.com"))
1592
1593 self._interactInMemory(server, client)
1594
1595 self.assertEqual([(server, b("foo1.example.com"))], args)
1596
1597
Cory Benfield84a121e2014-03-31 20:30:25 +01001598class NextProtoNegotiationTests(TestCase, _LoopbackMixin):
1599 """
1600 Test for Next Protocol Negotiation in PyOpenSSL.
1601 """
Cory Benfieldba1820d2015-04-13 17:39:12 -04001602 if _lib.Cryptography_HAS_NEXTPROTONEG:
1603 def test_npn_success(self):
1604 """
1605 Tests that clients and servers that agree on the negotiated next
1606 protocol can correct establish a connection, and that the agreed
1607 protocol is reported by the connections.
1608 """
1609 advertise_args = []
1610 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001611
Cory Benfieldba1820d2015-04-13 17:39:12 -04001612 def advertise(conn):
1613 advertise_args.append((conn,))
1614 return [b'http/1.1', b'spdy/2']
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001615
Cory Benfieldba1820d2015-04-13 17:39:12 -04001616 def select(conn, options):
1617 select_args.append((conn, options))
1618 return b'spdy/2'
Cory Benfield84a121e2014-03-31 20:30:25 +01001619
Cory Benfieldba1820d2015-04-13 17:39:12 -04001620 server_context = Context(TLSv1_METHOD)
1621 server_context.set_npn_advertise_callback(advertise)
Cory Benfield84a121e2014-03-31 20:30:25 +01001622
Cory Benfieldba1820d2015-04-13 17:39:12 -04001623 client_context = Context(TLSv1_METHOD)
1624 client_context.set_npn_select_callback(select)
Cory Benfield84a121e2014-03-31 20:30:25 +01001625
Cory Benfieldba1820d2015-04-13 17:39:12 -04001626 # Necessary to actually accept the connection
1627 server_context.use_privatekey(
1628 load_privatekey(FILETYPE_PEM, server_key_pem))
1629 server_context.use_certificate(
1630 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield84a121e2014-03-31 20:30:25 +01001631
Cory Benfieldba1820d2015-04-13 17:39:12 -04001632 # Do a little connection to trigger the logic
1633 server = Connection(server_context, None)
1634 server.set_accept_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001635
Cory Benfieldba1820d2015-04-13 17:39:12 -04001636 client = Connection(client_context, None)
1637 client.set_connect_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001638
Cory Benfieldba1820d2015-04-13 17:39:12 -04001639 self._interactInMemory(server, client)
Cory Benfield84a121e2014-03-31 20:30:25 +01001640
Cory Benfieldba1820d2015-04-13 17:39:12 -04001641 self.assertEqual([(server,)], advertise_args)
1642 self.assertEqual([(client, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield84a121e2014-03-31 20:30:25 +01001643
Cory Benfieldba1820d2015-04-13 17:39:12 -04001644 self.assertEqual(server.get_next_proto_negotiated(), b'spdy/2')
1645 self.assertEqual(client.get_next_proto_negotiated(), b'spdy/2')
Cory Benfield84a121e2014-03-31 20:30:25 +01001646
Cory Benfieldba1820d2015-04-13 17:39:12 -04001647 def test_npn_client_fail(self):
1648 """
1649 Tests that when clients and servers cannot agree on what protocol
1650 to use next that the TLS connection does not get established.
1651 """
1652 advertise_args = []
1653 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001654
Cory Benfieldba1820d2015-04-13 17:39:12 -04001655 def advertise(conn):
1656 advertise_args.append((conn,))
1657 return [b'http/1.1', b'spdy/2']
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001658
Cory Benfieldba1820d2015-04-13 17:39:12 -04001659 def select(conn, options):
1660 select_args.append((conn, options))
1661 return b''
Cory Benfield84a121e2014-03-31 20:30:25 +01001662
Cory Benfieldba1820d2015-04-13 17:39:12 -04001663 server_context = Context(TLSv1_METHOD)
1664 server_context.set_npn_advertise_callback(advertise)
Cory Benfield84a121e2014-03-31 20:30:25 +01001665
Cory Benfieldba1820d2015-04-13 17:39:12 -04001666 client_context = Context(TLSv1_METHOD)
1667 client_context.set_npn_select_callback(select)
Cory Benfield84a121e2014-03-31 20:30:25 +01001668
Cory Benfieldba1820d2015-04-13 17:39:12 -04001669 # Necessary to actually accept the connection
1670 server_context.use_privatekey(
1671 load_privatekey(FILETYPE_PEM, server_key_pem))
1672 server_context.use_certificate(
1673 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield84a121e2014-03-31 20:30:25 +01001674
Cory Benfieldba1820d2015-04-13 17:39:12 -04001675 # Do a little connection to trigger the logic
1676 server = Connection(server_context, None)
1677 server.set_accept_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001678
Cory Benfieldba1820d2015-04-13 17:39:12 -04001679 client = Connection(client_context, None)
1680 client.set_connect_state()
Cory Benfield84a121e2014-03-31 20:30:25 +01001681
Cory Benfieldba1820d2015-04-13 17:39:12 -04001682 # If the client doesn't return anything, the connection will fail.
1683 self.assertRaises(Error, self._interactInMemory, server, client)
Cory Benfield84a121e2014-03-31 20:30:25 +01001684
Cory Benfieldba1820d2015-04-13 17:39:12 -04001685 self.assertEqual([(server,)], advertise_args)
1686 self.assertEqual([(client, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield84a121e2014-03-31 20:30:25 +01001687
Cory Benfieldba1820d2015-04-13 17:39:12 -04001688 def test_npn_select_error(self):
1689 """
1690 Test that we can handle exceptions in the select callback. If
1691 select fails it should be fatal to the connection.
1692 """
1693 advertise_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001694
Cory Benfieldba1820d2015-04-13 17:39:12 -04001695 def advertise(conn):
1696 advertise_args.append((conn,))
1697 return [b'http/1.1', b'spdy/2']
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001698
Cory Benfieldba1820d2015-04-13 17:39:12 -04001699 def select(conn, options):
1700 raise TypeError
Cory Benfield0ea76e72015-03-22 09:05:28 +00001701
Cory Benfieldba1820d2015-04-13 17:39:12 -04001702 server_context = Context(TLSv1_METHOD)
1703 server_context.set_npn_advertise_callback(advertise)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001704
Cory Benfieldba1820d2015-04-13 17:39:12 -04001705 client_context = Context(TLSv1_METHOD)
1706 client_context.set_npn_select_callback(select)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001707
Cory Benfieldba1820d2015-04-13 17:39:12 -04001708 # Necessary to actually accept the connection
1709 server_context.use_privatekey(
1710 load_privatekey(FILETYPE_PEM, server_key_pem))
1711 server_context.use_certificate(
1712 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield0ea76e72015-03-22 09:05:28 +00001713
Cory Benfieldba1820d2015-04-13 17:39:12 -04001714 # Do a little connection to trigger the logic
1715 server = Connection(server_context, None)
1716 server.set_accept_state()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001717
Cory Benfieldba1820d2015-04-13 17:39:12 -04001718 client = Connection(client_context, None)
1719 client.set_connect_state()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001720
Cory Benfieldba1820d2015-04-13 17:39:12 -04001721 # If the callback throws an exception it should be raised here.
1722 self.assertRaises(
1723 TypeError, self._interactInMemory, server, client
1724 )
1725 self.assertEqual([(server,)], advertise_args)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001726
Cory Benfieldba1820d2015-04-13 17:39:12 -04001727 def test_npn_advertise_error(self):
1728 """
1729 Test that we can handle exceptions in the advertise callback. If
1730 advertise fails no NPN is advertised to the client.
1731 """
1732 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001733
Cory Benfieldba1820d2015-04-13 17:39:12 -04001734 def advertise(conn):
1735 raise TypeError
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001736
Hynek Schlawackb4ceed32015-09-05 20:55:19 +02001737 def select(conn, options): # pragma: nocover
1738 """
1739 Assert later that no args are actually appended.
1740 """
Cory Benfieldba1820d2015-04-13 17:39:12 -04001741 select_args.append((conn, options))
1742 return b''
Cory Benfield0ea76e72015-03-22 09:05:28 +00001743
Cory Benfieldba1820d2015-04-13 17:39:12 -04001744 server_context = Context(TLSv1_METHOD)
1745 server_context.set_npn_advertise_callback(advertise)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001746
Cory Benfieldba1820d2015-04-13 17:39:12 -04001747 client_context = Context(TLSv1_METHOD)
1748 client_context.set_npn_select_callback(select)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001749
Cory Benfieldba1820d2015-04-13 17:39:12 -04001750 # Necessary to actually accept the connection
1751 server_context.use_privatekey(
1752 load_privatekey(FILETYPE_PEM, server_key_pem))
1753 server_context.use_certificate(
1754 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield0ea76e72015-03-22 09:05:28 +00001755
Cory Benfieldba1820d2015-04-13 17:39:12 -04001756 # Do a little connection to trigger the logic
1757 server = Connection(server_context, None)
1758 server.set_accept_state()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001759
Cory Benfieldba1820d2015-04-13 17:39:12 -04001760 client = Connection(client_context, None)
1761 client.set_connect_state()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001762
Cory Benfieldba1820d2015-04-13 17:39:12 -04001763 # If the client doesn't return anything, the connection will fail.
1764 self.assertRaises(
1765 TypeError, self._interactInMemory, server, client
1766 )
1767 self.assertEqual([], select_args)
1768
1769 else:
1770 # No NPN.
1771 def test_npn_not_implemented(self):
1772 # Test the context methods first.
1773 context = Context(TLSv1_METHOD)
1774 fail_methods = [
1775 context.set_npn_advertise_callback,
1776 context.set_npn_select_callback,
1777 ]
1778 for method in fail_methods:
1779 self.assertRaises(
1780 NotImplementedError, method, None
1781 )
1782
1783 # Now test a connection.
1784 conn = Connection(context)
1785 fail_methods = [
1786 conn.get_next_proto_negotiated,
1787 ]
1788 for method in fail_methods:
1789 self.assertRaises(NotImplementedError, method)
Cory Benfield0ea76e72015-03-22 09:05:28 +00001790
1791
Cory Benfield12eae892014-06-07 15:42:56 +01001792class ApplicationLayerProtoNegotiationTests(TestCase, _LoopbackMixin):
1793 """
1794 Tests for ALPN in PyOpenSSL.
1795 """
Cory Benfielde46fa842015-04-13 16:50:49 -04001796 # Skip tests on versions that don't support ALPN.
1797 if _lib.Cryptography_HAS_ALPN:
Cory Benfield12eae892014-06-07 15:42:56 +01001798
Cory Benfielde46fa842015-04-13 16:50:49 -04001799 def test_alpn_success(self):
1800 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001801 Clients and servers that agree on the negotiated ALPN protocol can
1802 correct establish a connection, and the agreed protocol is reported
1803 by the connections.
Cory Benfielde46fa842015-04-13 16:50:49 -04001804 """
1805 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001806
Cory Benfielde46fa842015-04-13 16:50:49 -04001807 def select(conn, options):
1808 select_args.append((conn, options))
1809 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001810
Cory Benfielde46fa842015-04-13 16:50:49 -04001811 client_context = Context(TLSv1_METHOD)
1812 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001813
Cory Benfielde46fa842015-04-13 16:50:49 -04001814 server_context = Context(TLSv1_METHOD)
1815 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001816
Cory Benfielde46fa842015-04-13 16:50:49 -04001817 # Necessary to actually accept the connection
1818 server_context.use_privatekey(
1819 load_privatekey(FILETYPE_PEM, server_key_pem))
1820 server_context.use_certificate(
1821 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001822
Cory Benfielde46fa842015-04-13 16:50:49 -04001823 # Do a little connection to trigger the logic
1824 server = Connection(server_context, None)
1825 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001826
Cory Benfielde46fa842015-04-13 16:50:49 -04001827 client = Connection(client_context, None)
1828 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001829
Cory Benfielde46fa842015-04-13 16:50:49 -04001830 self._interactInMemory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001831
Cory Benfielde46fa842015-04-13 16:50:49 -04001832 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
1833
1834 self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
1835 self.assertEqual(client.get_alpn_proto_negotiated(), b'spdy/2')
Cory Benfield12eae892014-06-07 15:42:56 +01001836
Cory Benfielde46fa842015-04-13 16:50:49 -04001837 def test_alpn_set_on_connection(self):
1838 """
1839 The same as test_alpn_success, but setting the ALPN protocols on
1840 the connection rather than the context.
1841 """
1842 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001843
Cory Benfielde46fa842015-04-13 16:50:49 -04001844 def select(conn, options):
1845 select_args.append((conn, options))
1846 return b'spdy/2'
Cory Benfield12eae892014-06-07 15:42:56 +01001847
Cory Benfielde46fa842015-04-13 16:50:49 -04001848 # Setup the client context but don't set any ALPN protocols.
1849 client_context = Context(TLSv1_METHOD)
Cory Benfield12eae892014-06-07 15:42:56 +01001850
Cory Benfielde46fa842015-04-13 16:50:49 -04001851 server_context = Context(TLSv1_METHOD)
1852 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001853
Cory Benfielde46fa842015-04-13 16:50:49 -04001854 # Necessary to actually accept the connection
1855 server_context.use_privatekey(
1856 load_privatekey(FILETYPE_PEM, server_key_pem))
1857 server_context.use_certificate(
1858 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001859
Cory Benfielde46fa842015-04-13 16:50:49 -04001860 # Do a little connection to trigger the logic
1861 server = Connection(server_context, None)
1862 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001863
Cory Benfielde46fa842015-04-13 16:50:49 -04001864 # Set the ALPN protocols on the client connection.
1865 client = Connection(client_context, None)
1866 client.set_alpn_protos([b'http/1.1', b'spdy/2'])
1867 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001868
Cory Benfielde46fa842015-04-13 16:50:49 -04001869 self._interactInMemory(server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001870
Cory Benfielde46fa842015-04-13 16:50:49 -04001871 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield12eae892014-06-07 15:42:56 +01001872
Cory Benfielde46fa842015-04-13 16:50:49 -04001873 self.assertEqual(server.get_alpn_proto_negotiated(), b'spdy/2')
1874 self.assertEqual(client.get_alpn_proto_negotiated(), b'spdy/2')
Cory Benfield12eae892014-06-07 15:42:56 +01001875
Cory Benfielde46fa842015-04-13 16:50:49 -04001876 def test_alpn_server_fail(self):
1877 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001878 When clients and servers cannot agree on what protocol to use next
1879 the TLS connection does not get established.
Cory Benfielde46fa842015-04-13 16:50:49 -04001880 """
1881 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001882
Cory Benfielde46fa842015-04-13 16:50:49 -04001883 def select(conn, options):
1884 select_args.append((conn, options))
1885 return b''
Cory Benfield12eae892014-06-07 15:42:56 +01001886
Cory Benfielde46fa842015-04-13 16:50:49 -04001887 client_context = Context(TLSv1_METHOD)
1888 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfield12eae892014-06-07 15:42:56 +01001889
Cory Benfielde46fa842015-04-13 16:50:49 -04001890 server_context = Context(TLSv1_METHOD)
1891 server_context.set_alpn_select_callback(select)
Cory Benfield12eae892014-06-07 15:42:56 +01001892
Cory Benfielde46fa842015-04-13 16:50:49 -04001893 # Necessary to actually accept the connection
1894 server_context.use_privatekey(
1895 load_privatekey(FILETYPE_PEM, server_key_pem))
1896 server_context.use_certificate(
1897 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfield12eae892014-06-07 15:42:56 +01001898
Cory Benfielde46fa842015-04-13 16:50:49 -04001899 # Do a little connection to trigger the logic
1900 server = Connection(server_context, None)
1901 server.set_accept_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001902
Cory Benfielde46fa842015-04-13 16:50:49 -04001903 client = Connection(client_context, None)
1904 client.set_connect_state()
Cory Benfield12eae892014-06-07 15:42:56 +01001905
Cory Benfielde46fa842015-04-13 16:50:49 -04001906 # If the client doesn't return anything, the connection will fail.
1907 self.assertRaises(Error, self._interactInMemory, server, client)
Cory Benfield12eae892014-06-07 15:42:56 +01001908
Cory Benfielde46fa842015-04-13 16:50:49 -04001909 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfield12eae892014-06-07 15:42:56 +01001910
Cory Benfielde46fa842015-04-13 16:50:49 -04001911 def test_alpn_no_server(self):
1912 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001913 When clients and servers cannot agree on what protocol to use next
1914 because the server doesn't offer ALPN, no protocol is negotiated.
Cory Benfielde46fa842015-04-13 16:50:49 -04001915 """
1916 client_context = Context(TLSv1_METHOD)
1917 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfielde3d57152015-04-11 17:57:35 -04001918
Cory Benfielde46fa842015-04-13 16:50:49 -04001919 server_context = Context(TLSv1_METHOD)
Cory Benfielde3d57152015-04-11 17:57:35 -04001920
Cory Benfielde46fa842015-04-13 16:50:49 -04001921 # Necessary to actually accept the connection
1922 server_context.use_privatekey(
1923 load_privatekey(FILETYPE_PEM, server_key_pem))
1924 server_context.use_certificate(
1925 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfielde3d57152015-04-11 17:57:35 -04001926
Cory Benfielde46fa842015-04-13 16:50:49 -04001927 # Do a little connection to trigger the logic
1928 server = Connection(server_context, None)
1929 server.set_accept_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001930
Cory Benfielde46fa842015-04-13 16:50:49 -04001931 client = Connection(client_context, None)
1932 client.set_connect_state()
Cory Benfielde3d57152015-04-11 17:57:35 -04001933
Cory Benfielde46fa842015-04-13 16:50:49 -04001934 # Do the dance.
1935 self._interactInMemory(server, client)
Cory Benfielde3d57152015-04-11 17:57:35 -04001936
Cory Benfielde46fa842015-04-13 16:50:49 -04001937 self.assertEqual(client.get_alpn_proto_negotiated(), b'')
Cory Benfielde3d57152015-04-11 17:57:35 -04001938
Cory Benfielde46fa842015-04-13 16:50:49 -04001939 def test_alpn_callback_exception(self):
1940 """
Cory Benfieldbb8516b2015-04-13 18:12:53 -04001941 We can handle exceptions in the ALPN select callback.
Cory Benfielde46fa842015-04-13 16:50:49 -04001942 """
1943 select_args = []
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02001944
Cory Benfielde46fa842015-04-13 16:50:49 -04001945 def select(conn, options):
1946 select_args.append((conn, options))
Cory Benfieldef401452015-04-13 18:17:36 -04001947 raise TypeError()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001948
Cory Benfielde46fa842015-04-13 16:50:49 -04001949 client_context = Context(TLSv1_METHOD)
1950 client_context.set_alpn_protos([b'http/1.1', b'spdy/2'])
Cory Benfieldf1177e72015-04-12 09:11:49 -04001951
Cory Benfielde46fa842015-04-13 16:50:49 -04001952 server_context = Context(TLSv1_METHOD)
1953 server_context.set_alpn_select_callback(select)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001954
Cory Benfielde46fa842015-04-13 16:50:49 -04001955 # Necessary to actually accept the connection
1956 server_context.use_privatekey(
1957 load_privatekey(FILETYPE_PEM, server_key_pem))
1958 server_context.use_certificate(
1959 load_certificate(FILETYPE_PEM, server_cert_pem))
Cory Benfieldf1177e72015-04-12 09:11:49 -04001960
Cory Benfielde46fa842015-04-13 16:50:49 -04001961 # Do a little connection to trigger the logic
1962 server = Connection(server_context, None)
1963 server.set_accept_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001964
Cory Benfielde46fa842015-04-13 16:50:49 -04001965 client = Connection(client_context, None)
1966 client.set_connect_state()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001967
Cory Benfielde46fa842015-04-13 16:50:49 -04001968 self.assertRaises(
1969 TypeError, self._interactInMemory, server, client
1970 )
1971 self.assertEqual([(server, [b'http/1.1', b'spdy/2'])], select_args)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001972
Cory Benfield0f7b04c2015-04-13 17:51:12 -04001973 else:
1974 # No ALPN.
1975 def test_alpn_not_implemented(self):
Cory Benfieldef401452015-04-13 18:17:36 -04001976 """
1977 If ALPN is not in OpenSSL, we should raise NotImplementedError.
1978 """
Cory Benfield0f7b04c2015-04-13 17:51:12 -04001979 # Test the context methods first.
1980 context = Context(TLSv1_METHOD)
Cory Benfield307e9e62015-04-13 18:21:12 -04001981 self.assertRaises(
1982 NotImplementedError, context.set_alpn_protos, None
1983 )
1984 self.assertRaises(
1985 NotImplementedError, context.set_alpn_select_callback, None
1986 )
Cory Benfield0f7b04c2015-04-13 17:51:12 -04001987
1988 # Now test a connection.
1989 conn = Connection(context)
Cory Benfield307e9e62015-04-13 18:21:12 -04001990 self.assertRaises(
Alex Gaynor68417232015-09-04 07:56:29 -04001991 NotImplementedError, conn.set_alpn_protos, None
Cory Benfield307e9e62015-04-13 18:21:12 -04001992 )
Cory Benfield0f7b04c2015-04-13 17:51:12 -04001993
Cory Benfieldf1177e72015-04-12 09:11:49 -04001994
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05001995class SessionTests(TestCase):
1996 """
1997 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
1998 """
1999 def test_construction(self):
2000 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002001 :py:class:`Session` can be constructed with no arguments, creating
2002 a new instance of that type.
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002003 """
2004 new_session = Session()
2005 self.assertTrue(isinstance(new_session, Session))
2006
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05002007 def test_construction_wrong_args(self):
2008 """
2009 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
2010 is raised.
2011 """
2012 self.assertRaises(TypeError, Session, 123)
2013 self.assertRaises(TypeError, Session, "hello")
2014 self.assertRaises(TypeError, Session, object())
2015
2016
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002017class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05002018 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002019 Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05002020 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002021 # XXX get_peer_certificate -> None
2022 # XXX sock_shutdown
2023 # XXX master_key -> TypeError
2024 # XXX server_random -> TypeError
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04002025 # XXX connect -> TypeError
2026 # XXX connect_ex -> TypeError
2027 # XXX set_connect_state -> TypeError
2028 # XXX set_accept_state -> TypeError
2029 # XXX renegotiate_pending
2030 # XXX do_handshake -> TypeError
2031 # XXX bio_read -> TypeError
2032 # XXX recv -> TypeError
2033 # XXX send -> TypeError
2034 # XXX bio_write -> TypeError
2035
Rick Deane15b1472009-07-09 15:53:42 -05002036 def test_type(self):
2037 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002038 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same
2039 type object and can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05002040 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002041 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05002042 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002043 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05002044
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002045 def test_get_context(self):
2046 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002047 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance
2048 used to construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002049 """
2050 context = Context(TLSv1_METHOD)
2051 connection = Connection(context, None)
2052 self.assertIdentical(connection.get_context(), context)
2053
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002054 def test_get_context_wrong_args(self):
2055 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002056 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called
2057 with any arguments.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05002058 """
2059 connection = Connection(Context(TLSv1_METHOD), None)
2060 self.assertRaises(TypeError, connection.get_context, None)
2061
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002062 def test_set_context_wrong_args(self):
2063 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002064 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called
2065 with a non-:py:obj:`Context` instance argument or with any number of
2066 arguments other than 1.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002067 """
2068 ctx = Context(TLSv1_METHOD)
2069 connection = Connection(ctx, None)
2070 self.assertRaises(TypeError, connection.set_context)
2071 self.assertRaises(TypeError, connection.set_context, object())
2072 self.assertRaises(TypeError, connection.set_context, "hello")
2073 self.assertRaises(TypeError, connection.set_context, 1)
2074 self.assertRaises(TypeError, connection.set_context, 1, 2)
2075 self.assertRaises(
2076 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
2077 self.assertIdentical(ctx, connection.get_context())
2078
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002079 def test_set_context(self):
2080 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002081 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context`
2082 instance to be used for the connection.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002083 """
2084 original = Context(SSLv23_METHOD)
2085 replacement = Context(TLSv1_METHOD)
2086 connection = Connection(original, None)
2087 connection.set_context(replacement)
2088 self.assertIdentical(replacement, connection.get_context())
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002089 # Lose our references to the contexts, just in case the Connection
2090 # isn't properly managing its own contributions to their reference
2091 # counts.
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002092 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002093 collect()
2094
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002095 def test_set_tlsext_host_name_wrong_args(self):
2096 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002097 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte
2098 string argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09002099 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002100 """
2101 conn = Connection(Context(TLSv1_METHOD), None)
2102 self.assertRaises(TypeError, conn.set_tlsext_host_name)
2103 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
2104 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
2105 self.assertRaises(
2106 TypeError, conn.set_tlsext_host_name, b("with\0null"))
2107
Abraham Martinc5484ba2015-03-25 15:33:05 +00002108 if PY3:
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04002109 # On Python 3.x, don't accidentally implicitly convert from text.
2110 self.assertRaises(
2111 TypeError,
2112 conn.set_tlsext_host_name, b("example.com").decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04002113
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002114 def test_get_servername_wrong_args(self):
2115 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002116 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if
2117 called with any arguments.
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04002118 """
2119 connection = Connection(Context(TLSv1_METHOD), None)
2120 self.assertRaises(TypeError, connection.get_servername, object())
2121 self.assertRaises(TypeError, connection.get_servername, 1)
2122 self.assertRaises(TypeError, connection.get_servername, "hello")
2123
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002124 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002125 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002126 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002127 immediate read.
2128 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002129 connection = Connection(Context(TLSv1_METHOD), None)
2130 self.assertEquals(connection.pending(), 0)
2131
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002132 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002133 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002134 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with
2135 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002136 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002137 connection = Connection(Context(TLSv1_METHOD), None)
2138 self.assertRaises(TypeError, connection.pending, None)
2139
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002140 def test_peek(self):
2141 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002142 :py:obj:`Connection.recv` peeks into the connection if
2143 :py:obj:`socket.MSG_PEEK` is passed.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002144 """
2145 server, client = self._loopback()
2146 server.send(b('xy'))
2147 self.assertEqual(client.recv(2, MSG_PEEK), b('xy'))
2148 self.assertEqual(client.recv(2, MSG_PEEK), b('xy'))
2149 self.assertEqual(client.recv(2), b('xy'))
2150
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002151 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002152 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002153 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
2154 a non-address argument or with the wrong number of arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002155 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002156 connection = Connection(Context(TLSv1_METHOD), socket())
2157 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002158 self.assertRaises(TypeError, connection.connect)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002159 self.assertRaises(
2160 TypeError, connection.connect, ("127.0.0.1", 1), None
2161 )
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002162
kjavfe508d62015-09-02 12:20:35 +01002163 def test_connection_undefined_attr(self):
2164 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002165 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with
2166 a non-address argument or with the wrong number of arguments.
kjavfe508d62015-09-02 12:20:35 +01002167 """
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002168
kjavfe508d62015-09-02 12:20:35 +01002169 def attr_access_test(connection):
2170 return connection.an_attribute_which_is_not_defined
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002171
kjavfe508d62015-09-02 12:20:35 +01002172 connection = Connection(Context(TLSv1_METHOD), None)
2173 self.assertRaises(AttributeError, attr_access_test, connection)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002174
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002175 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002176 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002177 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the
2178 underlying socket connect method raises it.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002179 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002180 client = socket()
2181 context = Context(TLSv1_METHOD)
2182 clientSSL = Connection(context, client)
Alex Gaynor122717b2015-09-05 14:14:18 -04002183 # pytest.raises here doesn't work because of a bug in py.test on Python
2184 # 2.6: https://github.com/pytest-dev/pytest/issues/988
Alex Gaynore69c2782015-09-05 14:07:48 -04002185 try:
Alex Gaynor1aabb2e2015-09-05 13:35:18 -04002186 clientSSL.connect(("127.0.0.1", 1))
Alex Gaynore69c2782015-09-05 14:07:48 -04002187 except error as e:
Alex Gaynor20a4c082015-09-05 14:24:15 -04002188 exc = e
2189 assert exc.args[0] == ECONNREFUSED
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002190
2191 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002192 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002193 :py:obj:`Connection.connect` establishes a connection to the specified
2194 address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002195 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002196 port = socket()
2197 port.bind(('', 0))
2198 port.listen(3)
2199
2200 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002201 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
2202 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002203
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002204 @pytest.mark.skipif(
2205 platform == "darwin",
2206 reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4"
2207 )
2208 def test_connect_ex(self):
2209 """
2210 If there is a connection error, :py:obj:`Connection.connect_ex`
2211 returns the errno instead of raising an exception.
2212 """
2213 port = socket()
2214 port.bind(('', 0))
2215 port.listen(3)
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002216
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002217 clientSSL = Connection(Context(TLSv1_METHOD), socket())
2218 clientSSL.setblocking(False)
2219 result = clientSSL.connect_ex(port.getsockname())
2220 expected = (EINPROGRESS, EWOULDBLOCK)
2221 self.assertTrue(
2222 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04002223
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002224 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002225 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002226 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with
2227 any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002228 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002229 connection = Connection(Context(TLSv1_METHOD), socket())
2230 self.assertRaises(TypeError, connection.accept, None)
2231
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002232 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002233 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002234 :py:obj:`Connection.accept` accepts a pending connection attempt and
2235 returns a tuple of a new :py:obj:`Connection` (the accepted client) and
2236 the address the connection originated from.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002237 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002238 ctx = Context(TLSv1_METHOD)
2239 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2240 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002241 port = socket()
2242 portSSL = Connection(ctx, port)
2243 portSSL.bind(('', 0))
2244 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002245
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002246 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002247
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002248 # Calling portSSL.getsockname() here to get the server IP address
2249 # sounds great, but frequently fails on Windows.
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04002250 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002251
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04002252 serverSSL, address = portSSL.accept()
2253
2254 self.assertTrue(isinstance(serverSSL, Connection))
2255 self.assertIdentical(serverSSL.get_context(), ctx)
2256 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04002257
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002258 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002259 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002260 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with
2261 the wrong number of arguments or with arguments other than integers.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002262 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002263 connection = Connection(Context(TLSv1_METHOD), None)
2264 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04002265 self.assertRaises(TypeError, connection.get_shutdown, None)
2266 self.assertRaises(TypeError, connection.set_shutdown)
2267 self.assertRaises(TypeError, connection.set_shutdown, None)
2268 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002269
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002270 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002271 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002272 :py:obj:`Connection.shutdown` performs an SSL-level connection
2273 shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002274 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002275 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002276 self.assertFalse(server.shutdown())
2277 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002278 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002279 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
2280 client.shutdown()
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002281 self.assertEquals(
2282 client.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2283 )
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04002284 self.assertRaises(ZeroReturnError, server.recv, 1024)
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002285 self.assertEquals(
2286 server.get_shutdown(), SENT_SHUTDOWN | RECEIVED_SHUTDOWN
2287 )
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04002288
Paul Aurichc85e0862015-01-08 08:34:33 -08002289 def test_shutdown_closed(self):
2290 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002291 If the underlying socket is closed, :py:obj:`Connection.shutdown`
2292 propagates the write error from the low level write call.
Paul Aurichc85e0862015-01-08 08:34:33 -08002293 """
2294 server, client = self._loopback()
2295 server.sock_shutdown(2)
2296 exc = self.assertRaises(SysCallError, server.shutdown)
2297 if platform == "win32":
2298 self.assertEqual(exc.args[0], ESHUTDOWN)
2299 else:
2300 self.assertEqual(exc.args[0], EPIPE)
2301
Glyph89389472015-04-14 17:29:26 -04002302 def test_shutdown_truncated(self):
Glyph6064ec32015-04-14 16:38:22 -04002303 """
Glyph89389472015-04-14 17:29:26 -04002304 If the underlying connection is truncated, :obj:`Connection.shutdown`
2305 raises an :obj:`Error`.
Glyph6064ec32015-04-14 16:38:22 -04002306 """
Glyph89389472015-04-14 17:29:26 -04002307 server_ctx = Context(TLSv1_METHOD)
2308 client_ctx = Context(TLSv1_METHOD)
2309 server_ctx.use_privatekey(
2310 load_privatekey(FILETYPE_PEM, server_key_pem))
2311 server_ctx.use_certificate(
2312 load_certificate(FILETYPE_PEM, server_cert_pem))
2313 server = Connection(server_ctx, None)
2314 client = Connection(client_ctx, None)
2315 self._handshakeInMemory(client, server)
2316 self.assertEqual(server.shutdown(), False)
2317 self.assertRaises(WantReadError, server.shutdown)
2318 server.bio_shutdown()
Glyph6064ec32015-04-14 16:38:22 -04002319 self.assertRaises(Error, server.shutdown)
2320
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002321 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002322 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002323 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection
2324 shutdown process.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002325 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04002326 connection = Connection(Context(TLSv1_METHOD), socket())
2327 connection.set_shutdown(RECEIVED_SHUTDOWN)
2328 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
2329
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002330 @skip_if_py3
2331 def test_set_shutdown_long(self):
2332 """
2333 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
2334 of type :py:obj:`long` as well as :py:obj:`int`.
2335 """
2336 connection = Connection(Context(TLSv1_METHOD), socket())
2337 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
2338 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05002339
kjavaf248592015-09-07 12:14:01 +01002340 def test_state_string(self):
2341 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002342 :meth:`Connection.state_string` verbosely describes the current
2343 state of the :class:`Connection`.
kjavaf248592015-09-07 12:14:01 +01002344 """
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002345 server, client = socket_pair()
kjavaf248592015-09-07 12:14:01 +01002346 server = self._loopbackServerFactory(server)
2347 client = self._loopbackClientFactory(client)
2348
2349 self.assertEqual('before/accept initialization',
2350 server.state_string().decode())
2351 self.assertEqual('before/connect initialization',
2352 client.state_string().decode())
2353
2354 for conn in [server, client]:
2355 try:
2356 conn.do_handshake()
2357 except WantReadError:
2358 pass
2359
2360 self.assertEqual('SSLv3 read client hello B',
kjav3178c162015-09-07 12:23:09 +01002361 server.state_string().decode())
kjavaf248592015-09-07 12:14:01 +01002362 self.assertEqual('SSLv3 read server hello A',
2363 client.state_string().decode())
2364
2365 for conn in [server, client]:
2366 try:
2367 conn.do_handshake()
2368 except WantReadError:
2369 pass
2370
Hynek Schlawackb0274ce2015-10-16 19:56:26 +02002371 assert server.state_string().decode() in (
2372 "SSLv3 read client certificate A",
2373 "SSLv3 read client key exchange A", # 1.0.2d+
2374 )
kjavaf248592015-09-07 12:14:01 +01002375 self.assertEqual('SSLv3 read server session ticket A',
2376 client.state_string().decode())
2377
2378 for conn in [server, client]:
kjav92293472015-09-07 13:05:10 +01002379 conn.do_handshake()
kjavaf248592015-09-07 12:14:01 +01002380
2381 self.assertEqual('SSL negotiation finished successfully',
2382 server.state_string().decode())
2383 self.assertEqual('SSL negotiation finished successfully',
2384 client.state_string().decode())
2385
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002386 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002387 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002388 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called
2389 with other than one argument. :py:obj:`Connection.get_app_data` raises
2390 :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002391 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002392 conn = Connection(Context(TLSv1_METHOD), None)
2393 self.assertRaises(TypeError, conn.get_app_data, None)
2394 self.assertRaises(TypeError, conn.set_app_data)
2395 self.assertRaises(TypeError, conn.set_app_data, None, None)
2396
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002397 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002398 """
2399 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002400 :py:obj:`Connection.set_app_data` and later retrieved with
2401 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002402 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002403 conn = Connection(Context(TLSv1_METHOD), None)
2404 app_data = object()
2405 conn.set_app_data(app_data)
2406 self.assertIdentical(conn.get_app_data(), app_data)
2407
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002408 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002409 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002410 :py:obj:`Connection.makefile` is not implemented and calling that
2411 method raises :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002412 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002413 conn = Connection(Context(TLSv1_METHOD), None)
2414 self.assertRaises(NotImplementedError, conn.makefile)
2415
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002416 def test_get_peer_cert_chain_wrong_args(self):
2417 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002418 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if
2419 called with any arguments.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002420 """
2421 conn = Connection(Context(TLSv1_METHOD), None)
2422 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
2423 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
2424 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
2425 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
2426
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002427 def test_get_peer_cert_chain(self):
2428 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002429 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates
2430 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002431 """
2432 chain = _create_certificate_chain()
2433 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2434
2435 serverContext = Context(TLSv1_METHOD)
2436 serverContext.use_privatekey(skey)
2437 serverContext.use_certificate(scert)
2438 serverContext.add_extra_chain_cert(icert)
2439 serverContext.add_extra_chain_cert(cacert)
2440 server = Connection(serverContext, None)
2441 server.set_accept_state()
2442
2443 # Create the client
2444 clientContext = Context(TLSv1_METHOD)
2445 clientContext.set_verify(VERIFY_NONE, verify_cb)
2446 client = Connection(clientContext, None)
2447 client.set_connect_state()
2448
2449 self._interactInMemory(client, server)
2450
2451 chain = client.get_peer_cert_chain()
2452 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002453 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002454 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002455 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002456 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002457 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002458 "Authority Certificate", chain[2].get_subject().CN)
2459
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002460 def test_get_peer_cert_chain_none(self):
2461 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002462 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the
2463 peer sends no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002464 """
2465 ctx = Context(TLSv1_METHOD)
2466 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2467 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2468 server = Connection(ctx, None)
2469 server.set_accept_state()
2470 client = Connection(Context(TLSv1_METHOD), None)
2471 client.set_connect_state()
2472 self._interactInMemory(client, server)
2473 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002474
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002475 def test_get_session_wrong_args(self):
2476 """
2477 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
2478 with any arguments.
2479 """
2480 ctx = Context(TLSv1_METHOD)
2481 server = Connection(ctx, None)
2482 self.assertRaises(TypeError, server.get_session, 123)
2483 self.assertRaises(TypeError, server.get_session, "hello")
2484 self.assertRaises(TypeError, server.get_session, object())
2485
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002486 def test_get_session_unconnected(self):
2487 """
2488 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
2489 an object which has not been connected.
2490 """
2491 ctx = Context(TLSv1_METHOD)
2492 server = Connection(ctx, None)
2493 session = server.get_session()
2494 self.assertIdentical(None, session)
2495
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002496 def test_server_get_session(self):
2497 """
2498 On the server side of a connection, :py:obj:`Connection.get_session`
2499 returns a :py:class:`Session` instance representing the SSL session for
2500 that connection.
2501 """
2502 server, client = self._loopback()
2503 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002504 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002505
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002506 def test_client_get_session(self):
2507 """
2508 On the client side of a connection, :py:obj:`Connection.get_session`
2509 returns a :py:class:`Session` instance representing the SSL session for
2510 that connection.
2511 """
2512 server, client = self._loopback()
2513 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002514 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002515
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002516 def test_set_session_wrong_args(self):
2517 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002518 If called with an object that is not an instance of
2519 :py:class:`Session`, or with other than one argument,
2520 :py:obj:`Connection.set_session` raises :py:obj:`TypeError`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002521 """
2522 ctx = Context(TLSv1_METHOD)
2523 connection = Connection(ctx, None)
2524 self.assertRaises(TypeError, connection.set_session)
2525 self.assertRaises(TypeError, connection.set_session, 123)
2526 self.assertRaises(TypeError, connection.set_session, "hello")
2527 self.assertRaises(TypeError, connection.set_session, object())
2528 self.assertRaises(
2529 TypeError, connection.set_session, Session(), Session())
2530
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002531 def test_client_set_session(self):
2532 """
2533 :py:obj:`Connection.set_session`, when used prior to a connection being
2534 established, accepts a :py:class:`Session` instance and causes an
2535 attempt to re-use the session it represents when the SSL handshake is
2536 performed.
2537 """
2538 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2539 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2540 ctx = Context(TLSv1_METHOD)
2541 ctx.use_privatekey(key)
2542 ctx.use_certificate(cert)
2543 ctx.set_session_id("unity-test")
2544
2545 def makeServer(socket):
2546 server = Connection(ctx, socket)
2547 server.set_accept_state()
2548 return server
2549
2550 originalServer, originalClient = self._loopback(
2551 serverFactory=makeServer)
2552 originalSession = originalClient.get_session()
2553
2554 def makeClient(socket):
2555 client = self._loopbackClientFactory(socket)
2556 client.set_session(originalSession)
2557 return client
2558 resumedServer, resumedClient = self._loopback(
2559 serverFactory=makeServer,
2560 clientFactory=makeClient)
2561
2562 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002563 # identifier for the session (new enough versions of OpenSSL expose
2564 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002565 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002566 # session is re-used. As long as the master key for the two
2567 # connections is the same, the session was re-used!
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002568 self.assertEqual(
2569 originalServer.master_key(), resumedServer.master_key())
2570
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002571 def test_set_session_wrong_method(self):
2572 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002573 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002574 instance associated with a context using a different SSL method than
2575 the :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002576 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002577 """
2578 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2579 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2580 ctx = Context(TLSv1_METHOD)
2581 ctx.use_privatekey(key)
2582 ctx.use_certificate(cert)
2583 ctx.set_session_id("unity-test")
2584
2585 def makeServer(socket):
2586 server = Connection(ctx, socket)
2587 server.set_accept_state()
2588 return server
2589
2590 originalServer, originalClient = self._loopback(
2591 serverFactory=makeServer)
2592 originalSession = originalClient.get_session()
2593
2594 def makeClient(socket):
2595 # Intentionally use a different, incompatible method here.
2596 client = Connection(Context(SSLv3_METHOD), socket)
2597 client.set_connect_state()
2598 client.set_session(originalSession)
2599 return client
2600
2601 self.assertRaises(
2602 Error,
2603 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2604
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002605 def test_wantWriteError(self):
2606 """
2607 :py:obj:`Connection` methods which generate output raise
2608 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2609 fail indicating a should-write state.
2610 """
2611 client_socket, server_socket = socket_pair()
2612 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002613 # anything. Only write a single byte at a time so we can be sure we
2614 # completely fill the buffer. Even though the socket API is allowed to
2615 # signal a short write via its return value it seems this doesn't
2616 # always happen on all platforms (FreeBSD and OS X particular) for the
2617 # very last bit of available buffer space.
2618 msg = b"x"
2619 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002620 try:
2621 client_socket.send(msg)
2622 except error as e:
2623 if e.errno == EWOULDBLOCK:
2624 break
2625 raise
2626 else:
2627 self.fail(
2628 "Failed to fill socket buffer, cannot test BIO want write")
2629
2630 ctx = Context(TLSv1_METHOD)
2631 conn = Connection(ctx, client_socket)
2632 # Client's speak first, so make it an SSL client
2633 conn.set_connect_state()
2634 self.assertRaises(WantWriteError, conn.do_handshake)
2635
2636 # XXX want_read
2637
Fedor Brunner416f4a12014-03-28 13:18:38 +01002638 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002639 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002640 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2641 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002642 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002643 ctx = Context(TLSv1_METHOD)
2644 connection = Connection(ctx, None)
2645 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002646
2647 def test_get_peer_finished_before_connect(self):
2648 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002649 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2650 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002651 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002652 ctx = Context(TLSv1_METHOD)
2653 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002654 self.assertEqual(connection.get_peer_finished(), None)
2655
Fedor Brunner416f4a12014-03-28 13:18:38 +01002656 def test_get_finished(self):
2657 """
2658 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002659 message send from client, or server. Finished messages are send during
2660 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002661 """
2662
Fedor Brunner5747b932014-03-05 14:22:34 +01002663 server, client = self._loopback()
2664
2665 self.assertNotEqual(server.get_finished(), None)
2666 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002667
2668 def test_get_peer_finished(self):
2669 """
2670 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002671 message received from client, or server. Finished messages are send
2672 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002673 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002674 server, client = self._loopback()
2675
2676 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002677 self.assertTrue(len(server.get_peer_finished()) > 0)
2678
Fedor Brunner416f4a12014-03-28 13:18:38 +01002679 def test_tls_finished_message_symmetry(self):
2680 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002681 The TLS Finished message send by server must be the TLS Finished
2682 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002683
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002684 The TLS Finished message send by client must be the TLS Finished
2685 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002686 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002687 server, client = self._loopback()
2688
Fedor Brunner5747b932014-03-05 14:22:34 +01002689 self.assertEqual(server.get_finished(), client.get_peer_finished())
2690 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002691
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002692 def test_get_cipher_name_before_connect(self):
2693 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002694 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2695 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002696 """
2697 ctx = Context(TLSv1_METHOD)
2698 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002699 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002700
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002701 def test_get_cipher_name(self):
2702 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002703 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2704 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002705 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002706 server, client = self._loopback()
2707 server_cipher_name, client_cipher_name = \
2708 server.get_cipher_name(), client.get_cipher_name()
2709
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002710 self.assertIsInstance(server_cipher_name, text_type)
2711 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002712
2713 self.assertEqual(server_cipher_name, client_cipher_name)
2714
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002715 def test_get_cipher_version_before_connect(self):
2716 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002717 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2718 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002719 """
2720 ctx = Context(TLSv1_METHOD)
2721 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002722 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002723
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002724 def test_get_cipher_version(self):
2725 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002726 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2727 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002728 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002729 server, client = self._loopback()
2730 server_cipher_version, client_cipher_version = \
2731 server.get_cipher_version(), client.get_cipher_version()
2732
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002733 self.assertIsInstance(server_cipher_version, text_type)
2734 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002735
2736 self.assertEqual(server_cipher_version, client_cipher_version)
2737
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002738 def test_get_cipher_bits_before_connect(self):
2739 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002740 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2741 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002742 """
2743 ctx = Context(TLSv1_METHOD)
2744 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002745 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002746
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002747 def test_get_cipher_bits(self):
2748 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002749 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2750 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002751 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002752 server, client = self._loopback()
2753 server_cipher_bits, client_cipher_bits = \
2754 server.get_cipher_bits(), client.get_cipher_bits()
2755
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002756 self.assertIsInstance(server_cipher_bits, int)
2757 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002758
2759 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002760
Jim Shaverabff1882015-05-27 09:15:55 -04002761 def test_get_protocol_version_name(self):
2762 """
2763 :py:obj:`Connection.get_protocol_version_name()` returns a string
2764 giving the protocol version of the current connection.
2765 """
2766 server, client = self._loopback()
2767 client_protocol_version_name = client.get_protocol_version_name()
2768 server_protocol_version_name = server.get_protocol_version_name()
2769
Jim Shaver58d25732015-05-28 11:52:32 -04002770 self.assertIsInstance(server_protocol_version_name, text_type)
2771 self.assertIsInstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002772
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002773 self.assertEqual(
2774 server_protocol_version_name, client_protocol_version_name
2775 )
Jim Shaverabff1882015-05-27 09:15:55 -04002776
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002777 def test_get_protocol_version(self):
2778 """
Alex Gaynor43307782015-09-04 09:05:45 -04002779 :py:obj:`Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002780 giving the protocol version of the current connection.
2781 """
2782 server, client = self._loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002783 client_protocol_version = client.get_protocol_version()
2784 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002785
Jim Shaverabff1882015-05-27 09:15:55 -04002786 self.assertIsInstance(server_protocol_version, int)
2787 self.assertIsInstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002788
2789 self.assertEqual(server_protocol_version, client_protocol_version)
2790
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002791
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002792class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002793 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002794 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002795 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002796 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002797 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002798 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if
2799 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002800 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002801 connection = Connection(Context(TLSv1_METHOD), None)
2802 self.assertRaises(TypeError, connection.get_cipher_list, None)
2803
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002804 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002805 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002806 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2807 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002808 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002809 connection = Connection(Context(TLSv1_METHOD), None)
2810 ciphers = connection.get_cipher_list()
2811 self.assertTrue(isinstance(ciphers, list))
2812 for cipher in ciphers:
2813 self.assertTrue(isinstance(cipher, str))
2814
2815
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002816class ConnectionSendTests(TestCase, _LoopbackMixin):
2817 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002818 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002819 """
2820 def test_wrong_args(self):
2821 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002822 When called with arguments other than string argument for its first
2823 parameter or more than two arguments, :py:obj:`Connection.send` raises
2824 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002825 """
2826 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002827 self.assertRaises(TypeError, connection.send)
2828 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002829 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002830
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002831 def test_short_bytes(self):
2832 """
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002833 When passed a short byte string, :py:obj:`Connection.send` transmits
2834 all of it and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002835 """
2836 server, client = self._loopback()
2837 count = server.send(b('xy'))
2838 self.assertEquals(count, 2)
2839 self.assertEquals(client.recv(2), b('xy'))
2840
Abraham Martinef063482015-03-25 14:06:24 +00002841 def test_text(self):
2842 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002843 When passed a text, :py:obj:`Connection.send` transmits all of it and
2844 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002845 """
2846 server, client = self._loopback()
2847 with catch_warnings(record=True) as w:
2848 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002849 count = server.send(b"xy".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002850 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002851 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002852 WARNING_TYPE_EXPECTED
2853 ),
2854 str(w[-1].message)
2855 )
2856 self.assertIs(w[-1].category, DeprecationWarning)
Abraham Martinef063482015-03-25 14:06:24 +00002857 self.assertEquals(count, 2)
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002858 self.assertEquals(client.recv(2), b"xy")
Abraham Martinef063482015-03-25 14:06:24 +00002859
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002860 @skip_if_py26
2861 def test_short_memoryview(self):
2862 """
2863 When passed a memoryview onto a small number of bytes,
2864 :py:obj:`Connection.send` transmits all of them and returns the number
2865 of bytes sent.
2866 """
2867 server, client = self._loopback()
2868 count = server.send(memoryview(b('xy')))
2869 self.assertEquals(count, 2)
2870 self.assertEquals(client.recv(2), b('xy'))
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002871
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002872 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002873 def test_short_buffer(self):
2874 """
2875 When passed a buffer containing a small number of bytes,
2876 :py:obj:`Connection.send` transmits all of them and returns the number
2877 of bytes sent.
2878 """
2879 server, client = self._loopback()
2880 count = server.send(buffer(b('xy')))
2881 self.assertEquals(count, 2)
2882 self.assertEquals(client.recv(2), b('xy'))
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002883
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002884
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002885def _make_memoryview(size):
2886 """
2887 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2888 size.
2889 """
2890 return memoryview(bytearray(size))
2891
2892
Cory Benfield62d10332014-06-15 10:03:41 +01002893class ConnectionRecvIntoTests(TestCase, _LoopbackMixin):
2894 """
2895 Tests for :py:obj:`Connection.recv_into`
2896 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002897 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002898 """
2899 Assert that when the given buffer is passed to
2900 ``Connection.recv_into``, whatever bytes are available to be received
2901 that fit into that buffer are written into that buffer.
2902 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002903 output_buffer = factory(5)
2904
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002905 server, client = self._loopback()
2906 server.send(b('xy'))
2907
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002908 self.assertEqual(client.recv_into(output_buffer), 2)
2909 self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002910
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002911 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002912 """
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002913 :py:obj:`Connection.recv_into` can be passed a ``bytearray`` instance
2914 and data in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002915 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002916 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002917
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002918 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002919 """
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002920 Assert that when the given buffer is passed to ``Connection.recv_into``
2921 along with a value for ``nbytes`` that is less than the size of that
2922 buffer, only ``nbytes`` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002923 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002924 output_buffer = factory(10)
2925
Cory Benfield62d10332014-06-15 10:03:41 +01002926 server, client = self._loopback()
2927 server.send(b('abcdefghij'))
Cory Benfield62d10332014-06-15 10:03:41 +01002928
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002929 self.assertEqual(client.recv_into(output_buffer, 5), 5)
2930 self.assertEqual(
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002931 output_buffer, bytearray(b('abcde\x00\x00\x00\x00\x00'))
2932 )
2933
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002934 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002935 """
2936 When called with a ``bytearray`` instance,
2937 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter and
2938 doesn't copy in more than that number of bytes.
2939 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002940 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002941
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002942 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002943 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002944 Assert that if there are more bytes available to be read from the
2945 receive buffer than would fit into the buffer passed to
2946 :py:obj:`Connection.recv_into`, only as many as fit are written into
2947 it.
Cory Benfield62d10332014-06-15 10:03:41 +01002948 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002949 output_buffer = factory(5)
2950
Cory Benfield62d10332014-06-15 10:03:41 +01002951 server, client = self._loopback()
2952 server.send(b('abcdefghij'))
Cory Benfield62d10332014-06-15 10:03:41 +01002953
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002954 self.assertEqual(client.recv_into(output_buffer), 5)
2955 self.assertEqual(output_buffer, bytearray(b('abcde')))
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002956 rest = client.recv(5)
2957 self.assertEqual(b('fghij'), rest)
2958
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002959 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002960 """
2961 When called with a ``bytearray`` instance,
2962 :py:obj:`Connection.recv_into` respects the size of the array and
2963 doesn't write more bytes into it than will fit.
2964 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002965 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002966
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002967 def _really_doesnt_overfill_test(self, factory):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002968 """
2969 Assert that if the value given by ``nbytes`` is greater than the actual
2970 size of the output buffer passed to :py:obj:`Connection.recv_into`, the
2971 behavior is as if no value was given for ``nbytes`` at all.
2972 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002973 output_buffer = factory(5)
2974
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002975 server, client = self._loopback()
2976 server.send(b('abcdefghij'))
2977
2978 self.assertEqual(client.recv_into(output_buffer, 50), 5)
2979 self.assertEqual(output_buffer, bytearray(b('abcde')))
2980 rest = client.recv(5)
2981 self.assertEqual(b('fghij'), rest)
2982
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002983 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002984 """
2985 When called with a ``bytearray`` instance and an ``nbytes`` value that
2986 is too large, :py:obj:`Connection.recv_into` respects the size of the
2987 array and not the ``nbytes`` value and doesn't write more bytes into
2988 the buffer than will fit.
2989 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002990 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002991
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002992 def test_peek(self):
2993
2994 server, client = self._loopback()
2995 server.send(b('xy'))
2996
2997 for _ in range(2):
2998 output_buffer = bytearray(5)
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002999 self.assertEqual(
3000 client.recv_into(output_buffer, flags=MSG_PEEK), 2)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003001 self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
3002
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003003 @skip_if_py26
3004 def test_memoryview_no_length(self):
3005 """
3006 :py:obj:`Connection.recv_into` can be passed a ``memoryview``
3007 instance and data in the receive buffer is written to it.
3008 """
3009 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003010
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003011 @skip_if_py26
3012 def test_memoryview_respects_length(self):
3013 """
3014 When called with a ``memoryview`` instance,
3015 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter
3016 and doesn't copy more than that number of bytes in.
3017 """
3018 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003019
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003020 @skip_if_py26
3021 def test_memoryview_doesnt_overfill(self):
3022 """
3023 When called with a ``memoryview`` instance,
3024 :py:obj:`Connection.recv_into` respects the size of the array and
3025 doesn't write more bytes into it than will fit.
3026 """
3027 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003028
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003029 @skip_if_py26
3030 def test_memoryview_really_doesnt_overfill(self):
3031 """
3032 When called with a ``memoryview`` instance and an ``nbytes`` value
3033 that is too large, :py:obj:`Connection.recv_into` respects the size
3034 of the array and not the ``nbytes`` value and doesn't write more
3035 bytes into the buffer than will fit.
3036 """
3037 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003038
Cory Benfield62d10332014-06-15 10:03:41 +01003039
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003040class ConnectionSendallTests(TestCase, _LoopbackMixin):
3041 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003042 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003043 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003044 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003045 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003046 When called with arguments other than a string argument for its first
3047 parameter or with more than two arguments, :py:obj:`Connection.sendall`
3048 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003049 """
3050 connection = Connection(Context(TLSv1_METHOD), None)
3051 self.assertRaises(TypeError, connection.sendall)
3052 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003053 self.assertRaises(
3054 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003055
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003056 def test_short(self):
3057 """
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003058 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3059 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003060 """
3061 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04003062 server.sendall(b('x'))
3063 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003064
Abraham Martinef063482015-03-25 14:06:24 +00003065 def test_text(self):
3066 """
Jean-Paul Calderone93477422015-04-13 20:38:57 -04003067 :py:obj:`Connection.sendall` transmits all the content in the string
3068 passed to it raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003069 """
3070 server, client = self._loopback()
3071 with catch_warnings(record=True) as w:
3072 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003073 server.sendall(b"x".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003074 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003075 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003076 WARNING_TYPE_EXPECTED
3077 ),
3078 str(w[-1].message)
3079 )
3080 self.assertIs(w[-1].category, DeprecationWarning)
3081 self.assertEquals(client.recv(1), b"x")
Abraham Martinef063482015-03-25 14:06:24 +00003082
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003083 @skip_if_py26
3084 def test_short_memoryview(self):
3085 """
3086 When passed a memoryview onto a small number of bytes,
3087 :py:obj:`Connection.sendall` transmits all of them.
3088 """
3089 server, client = self._loopback()
3090 server.sendall(memoryview(b('x')))
3091 self.assertEquals(client.recv(1), b('x'))
Abraham Martinef063482015-03-25 14:06:24 +00003092
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003093 @skip_if_py3
3094 def test_short_buffers(self):
3095 """
3096 When passed a buffer containing a small number of bytes,
3097 :py:obj:`Connection.sendall` transmits all of them.
3098 """
3099 server, client = self._loopback()
3100 server.sendall(buffer(b('x')))
3101 self.assertEquals(client.recv(1), b('x'))
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003102
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003103 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003104 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003105 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3106 passed to it even if this requires multiple calls of an underlying
3107 write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003108 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003109 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003110 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003111 # On Windows, after 32k of bytes the write will block (forever
3112 # - because no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04003113 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003114 server.sendall(message)
3115 accum = []
3116 received = 0
3117 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003118 data = client.recv(1024)
3119 accum.append(data)
3120 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04003121 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003122
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003123 def test_closed(self):
3124 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003125 If the underlying socket is closed, :py:obj:`Connection.sendall`
3126 propagates the write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003127 """
3128 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003129 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003130 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003131 if platform == "win32":
3132 self.assertEqual(exc.args[0], ESHUTDOWN)
3133 else:
3134 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003135
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003136
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003137class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
3138 """
3139 Tests for SSL renegotiation APIs.
3140 """
3141 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003142 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003143 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called
3144 with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003145 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003146 connection = Connection(Context(TLSv1_METHOD), None)
3147 self.assertRaises(TypeError, connection.renegotiate, None)
3148
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003149 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003150 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003151 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if
3152 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003153 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003154 connection = Connection(Context(TLSv1_METHOD), None)
3155 self.assertRaises(TypeError, connection.total_renegotiations, None)
3156
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003157 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003158 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003159 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before
3160 any renegotiations have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003161 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003162 connection = Connection(Context(TLSv1_METHOD), None)
3163 self.assertEquals(connection.total_renegotiations(), 0)
3164
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003165# def test_renegotiate(self):
3166# """
3167# """
3168# server, client = self._loopback()
3169
3170# server.send("hello world")
3171# self.assertEquals(client.recv(len("hello world")), "hello world")
3172
3173# self.assertEquals(server.total_renegotiations(), 0)
3174# self.assertTrue(server.renegotiate())
3175
3176# server.setblocking(False)
3177# client.setblocking(False)
3178# while server.renegotiate_pending():
3179# client.do_handshake()
3180# server.do_handshake()
3181
3182# self.assertEquals(server.total_renegotiations(), 1)
3183
3184
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003185class ErrorTests(TestCase):
3186 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003187 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003188 """
3189 def test_type(self):
3190 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003191 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003192 """
3193 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05003194 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05003195
3196
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003197class ConstantsTests(TestCase):
3198 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003199 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003200
3201 These are values defined by OpenSSL intended only to be used as flags to
3202 OpenSSL APIs. The only assertions it seems can be made about them is
3203 their values.
3204 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003205 @pytest.mark.skipif(
3206 OP_NO_QUERY_MTU is None,
3207 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3208 )
3209 def test_op_no_query_mtu(self):
3210 """
3211 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3212 of :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
3213 """
3214 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003215
Hynek Schlawack35618382015-09-05 21:54:25 +02003216 @pytest.mark.skipif(
3217 OP_COOKIE_EXCHANGE is None,
3218 reason="OP_COOKIE_EXCHANGE unavailable - "
3219 "OpenSSL version may be too old"
3220 )
3221 def test_op_cookie_exchange(self):
3222 """
3223 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3224 value of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by
3225 :file:`openssl/ssl.h`.
3226 """
3227 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003228
Hynek Schlawack35618382015-09-05 21:54:25 +02003229 @pytest.mark.skipif(
3230 OP_NO_TICKET is None,
3231 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3232 )
3233 def test_op_no_ticket(self):
3234 """
3235 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3236 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
3237 """
3238 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003239
Hynek Schlawack35618382015-09-05 21:54:25 +02003240 @pytest.mark.skipif(
3241 OP_NO_COMPRESSION is None,
3242 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3243 )
3244 def test_op_no_compression(self):
3245 """
3246 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3247 value of :py:const:`SSL_OP_NO_COMPRESSION` defined by
3248 :file:`openssl/ssl.h`.
3249 """
3250 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003251
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003252 def test_sess_cache_off(self):
3253 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003254 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3255 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003256 """
3257 self.assertEqual(0x0, SESS_CACHE_OFF)
3258
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003259 def test_sess_cache_client(self):
3260 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003261 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3262 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003263 """
3264 self.assertEqual(0x1, SESS_CACHE_CLIENT)
3265
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003266 def test_sess_cache_server(self):
3267 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003268 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3269 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003270 """
3271 self.assertEqual(0x2, SESS_CACHE_SERVER)
3272
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003273 def test_sess_cache_both(self):
3274 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003275 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3276 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003277 """
3278 self.assertEqual(0x3, SESS_CACHE_BOTH)
3279
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003280 def test_sess_cache_no_auto_clear(self):
3281 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003282 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3283 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3284 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003285 """
3286 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
3287
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003288 def test_sess_cache_no_internal_lookup(self):
3289 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003290 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3291 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3292 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003293 """
3294 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
3295
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003296 def test_sess_cache_no_internal_store(self):
3297 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003298 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3299 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3300 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003301 """
3302 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
3303
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003304 def test_sess_cache_no_internal(self):
3305 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003306 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3307 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
3308 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003309 """
3310 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
3311
3312
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003313class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05003314 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003315 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003316 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003317 def _server(self, sock):
3318 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003319 Create a new server-side SSL :py:obj:`Connection` object wrapped around
3320 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003321 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003322 # Create the server side Connection. This is mostly setup boilerplate
3323 # - use TLSv1, use a particular certificate, etc.
3324 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003325 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003326 server_ctx.set_verify(
3327 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3328 verify_cb
3329 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003330 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003331 server_ctx.use_privatekey(
3332 load_privatekey(FILETYPE_PEM, server_key_pem))
3333 server_ctx.use_certificate(
3334 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003335 server_ctx.check_privatekey()
3336 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003337 # Here the Connection is actually created. If None is passed as the
3338 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003339 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003340 server_conn.set_accept_state()
3341 return server_conn
3342
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003343 def _client(self, sock):
3344 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003345 Create a new client-side SSL :py:obj:`Connection` object wrapped around
3346 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003347 """
3348 # Now create the client side Connection. Similar boilerplate to the
3349 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003350 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003351 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003352 client_ctx.set_verify(
3353 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3354 verify_cb
3355 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003356 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003357 client_ctx.use_privatekey(
3358 load_privatekey(FILETYPE_PEM, client_key_pem))
3359 client_ctx.use_certificate(
3360 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003361 client_ctx.check_privatekey()
3362 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003363 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003364 client_conn.set_connect_state()
3365 return client_conn
3366
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003367 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003368 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003369 Two :py:obj:`Connection`s which use memory BIOs can be manually
3370 connected by reading from the output of each and writing those bytes to
3371 the input of the other and in this way establish a connection and
3372 exchange application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003373 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003374 server_conn = self._server(None)
3375 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003376
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003377 # There should be no key or nonces yet.
3378 self.assertIdentical(server_conn.master_key(), None)
3379 self.assertIdentical(server_conn.client_random(), None)
3380 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003381
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003382 # First, the handshake needs to happen. We'll deliver bytes back and
3383 # forth between the client and server until neither of them feels like
3384 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003385 self.assertIdentical(
3386 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003387
3388 # Now that the handshake is done, there should be a key and nonces.
3389 self.assertNotIdentical(server_conn.master_key(), None)
3390 self.assertNotIdentical(server_conn.client_random(), None)
3391 self.assertNotIdentical(server_conn.server_random(), None)
Hynek Schlawack35618382015-09-05 21:54:25 +02003392 self.assertEquals(
3393 server_conn.client_random(), client_conn.client_random())
3394 self.assertEquals(
3395 server_conn.server_random(), client_conn.server_random())
3396 self.assertNotEquals(
3397 server_conn.client_random(), server_conn.server_random())
3398 self.assertNotEquals(
3399 client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003400
3401 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04003402 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05003403
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003404 server_conn.write(important_message)
3405 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003406 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003407 (client_conn, important_message))
3408
3409 client_conn.write(important_message[::-1])
3410 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003411 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003412 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003413
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003414 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003415 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003416 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003417
Hynek Schlawack35618382015-09-05 21:54:25 +02003418 This is primarily to rule out the memory BIO code as the source of any
3419 problems encountered while passing data over a :py:obj:`Connection` (if
3420 this test fails, there must be a problem outside the memory BIO code,
3421 as no memory BIO is involved here). Even though this isn't a memory
3422 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003423 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04003424 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003425
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04003426 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05003427 client_conn.send(important_message)
3428 msg = server_conn.recv(1024)
3429 self.assertEqual(msg, important_message)
3430
3431 # Again in the other direction, just for fun.
3432 important_message = important_message[::-1]
3433 server_conn.send(important_message)
3434 msg = client_conn.recv(1024)
3435 self.assertEqual(msg, important_message)
3436
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04003437 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003438 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003439 Test that :py:obj:`OpenSSL.SSL.bio_read` and
3440 :py:obj:`OpenSSL.SSL.bio_write` don't work on
3441 :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003442 """
3443 context = Context(SSLv3_METHOD)
3444 client = socket()
3445 clientSSL = Connection(context, client)
Alex Gaynor43307782015-09-04 09:05:45 -04003446 self.assertRaises(TypeError, clientSSL.bio_read, 100)
3447 self.assertRaises(TypeError, clientSSL.bio_write, "foo")
Alex Gaynor7e8b61e2015-09-04 13:13:05 -04003448 self.assertRaises(TypeError, clientSSL.bio_shutdown)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003449
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003450 def test_outgoingOverflow(self):
3451 """
3452 If more bytes than can be written to the memory BIO are passed to
Hynek Schlawack35618382015-09-05 21:54:25 +02003453 :py:obj:`Connection.send` at once, the number of bytes which were
3454 written is returned and that many bytes from the beginning of the input
3455 can be read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003456 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003457 server = self._server(None)
3458 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003459
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003460 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003461
3462 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003463 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003464 # Sanity check. We're trying to test what happens when the entire
3465 # input can't be sent. If the entire input was sent, this test is
3466 # meaningless.
3467 self.assertTrue(sent < size)
3468
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003469 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003470 self.assertIdentical(receiver, server)
3471
3472 # We can rely on all of these bytes being received at once because
3473 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
3474 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003475
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003476 def test_shutdown(self):
3477 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003478 :py:obj:`Connection.bio_shutdown` signals the end of the data stream
3479 from which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003480 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003481 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003482 server.bio_shutdown()
3483 e = self.assertRaises(Error, server.recv, 1024)
3484 # We don't want WantReadError or ZeroReturnError or anything - it's a
3485 # handshake failure.
3486 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003487
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003488 def test_unexpectedEndOfFile(self):
3489 """
3490 If the connection is lost before an orderly SSL shutdown occurs,
3491 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
3492 "Unexpected EOF".
3493 """
3494 server_conn, client_conn = self._loopback()
3495 client_conn.sock_shutdown(SHUT_RDWR)
3496 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
3497 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
3498
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003499 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003500 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003501 Verify the return value of the :py:obj:`get_client_ca_list` method for
3502 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003503
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003504 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003505 before the client and server are connected to each other. This
3506 function should specify a list of CAs for the server to send to the
3507 client and return that same list. The list will be used to verify
Hynek Schlawack35618382015-09-05 21:54:25 +02003508 that :py:obj:`get_client_ca_list` returns the proper value at
3509 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003510 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003511 server = self._server(None)
3512 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003513 self.assertEqual(client.get_client_ca_list(), [])
3514 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003515 ctx = server.get_context()
3516 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003517 self.assertEqual(client.get_client_ca_list(), [])
3518 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003519 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003520 self.assertEqual(client.get_client_ca_list(), expected)
3521 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003522
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003523 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003524 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003525 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if
3526 called with a non-list or a list that contains objects other than
3527 X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003528 """
3529 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003530 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
3531 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
3532 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003533
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003534 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003535 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003536 If passed an empty list, :py:obj:`Context.set_client_ca_list`
3537 configures the context to send no CA names to the client and, on both
3538 the server and client sides, :py:obj:`Connection.get_client_ca_list`
3539 returns an empty list after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003540 """
3541 def no_ca(ctx):
3542 ctx.set_client_ca_list([])
3543 return []
3544 self._check_client_ca_list(no_ca)
3545
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003546 def test_set_one_ca_list(self):
3547 """
3548 If passed a list containing a single X509Name,
Hynek Schlawack35618382015-09-05 21:54:25 +02003549 :py:obj:`Context.set_client_ca_list` configures the context to send
3550 that CA name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003551 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003552 X509Name after the connection is set up.
3553 """
3554 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3555 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003556
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003557 def single_ca(ctx):
3558 ctx.set_client_ca_list([cadesc])
3559 return [cadesc]
3560 self._check_client_ca_list(single_ca)
3561
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003562 def test_set_multiple_ca_list(self):
3563 """
3564 If passed a list containing multiple X509Name objects,
Hynek Schlawack35618382015-09-05 21:54:25 +02003565 :py:obj:`Context.set_client_ca_list` configures the context to send
3566 those CA names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003567 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003568 X509Names after the connection is set up.
3569 """
3570 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3571 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3572
3573 sedesc = secert.get_subject()
3574 cldesc = clcert.get_subject()
3575
3576 def multiple_ca(ctx):
3577 L = [sedesc, cldesc]
3578 ctx.set_client_ca_list(L)
3579 return L
3580 self._check_client_ca_list(multiple_ca)
3581
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003582 def test_reset_ca_list(self):
3583 """
3584 If called multiple times, only the X509Names passed to the final call
Hynek Schlawack35618382015-09-05 21:54:25 +02003585 of :py:obj:`Context.set_client_ca_list` are used to configure the CA
3586 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003587 """
3588 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3589 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3590 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3591
3592 cadesc = cacert.get_subject()
3593 sedesc = secert.get_subject()
3594 cldesc = clcert.get_subject()
3595
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003596 def changed_ca(ctx):
3597 ctx.set_client_ca_list([sedesc, cldesc])
3598 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003599 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003600 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003601
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003602 def test_mutated_ca_list(self):
3603 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003604 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003605 afterwards, this does not affect the list of CA names sent to the
3606 client.
3607 """
3608 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3609 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3610
3611 cadesc = cacert.get_subject()
3612 sedesc = secert.get_subject()
3613
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003614 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003615 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003616 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003617 L.append(sedesc)
3618 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003619 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003620
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003621 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003622 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003623 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called
3624 with a non-X509 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003625 """
3626 ctx = Context(TLSv1_METHOD)
3627 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003628 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003629 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003630 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003631
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003632 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003633 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003634 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09003635 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003636 """
3637 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3638 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003639
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003640 def single_ca(ctx):
3641 ctx.add_client_ca(cacert)
3642 return [cadesc]
3643 self._check_client_ca_list(single_ca)
3644
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003645 def test_multiple_add_client_ca(self):
3646 """
3647 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09003648 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003649 """
3650 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3651 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3652
3653 cadesc = cacert.get_subject()
3654 sedesc = secert.get_subject()
3655
3656 def multiple_ca(ctx):
3657 ctx.add_client_ca(cacert)
3658 ctx.add_client_ca(secert)
3659 return [cadesc, sedesc]
3660 self._check_client_ca_list(multiple_ca)
3661
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003662 def test_set_and_add_client_ca(self):
3663 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003664 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003665 :py:obj:`Context.add_client_ca` results in using the CA names from the
3666 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003667 """
3668 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3669 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3670 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3671
3672 cadesc = cacert.get_subject()
3673 sedesc = secert.get_subject()
3674 cldesc = clcert.get_subject()
3675
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003676 def mixed_set_add_ca(ctx):
3677 ctx.set_client_ca_list([cadesc, sedesc])
3678 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003679 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003680 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003681
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003682 def test_set_after_add_client_ca(self):
3683 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003684 A call to :py:obj:`Context.set_client_ca_list` after a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003685 :py:obj:`Context.add_client_ca` replaces the CA name specified by the
3686 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003687 """
3688 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3689 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3690 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3691
3692 cadesc = cacert.get_subject()
3693 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003694
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003695 def set_replaces_add_ca(ctx):
3696 ctx.add_client_ca(clcert)
3697 ctx.set_client_ca_list([cadesc])
3698 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003699 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003700 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003701
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003702
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003703class ConnectionBIOTests(TestCase):
3704 """
3705 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
3706 """
3707 def test_wantReadError(self):
3708 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003709 :py:obj:`Connection.bio_read` raises
3710 :py:obj:`OpenSSL.SSL.WantReadError` if there are no bytes available to
3711 be read from the BIO.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003712 """
3713 ctx = Context(TLSv1_METHOD)
3714 conn = Connection(ctx, None)
3715 self.assertRaises(WantReadError, conn.bio_read, 1024)
3716
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003717 def test_buffer_size(self):
3718 """
3719 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
3720 number of bytes to read and return.
3721 """
3722 ctx = Context(TLSv1_METHOD)
3723 conn = Connection(ctx, None)
3724 conn.set_connect_state()
3725 try:
3726 conn.do_handshake()
3727 except WantReadError:
3728 pass
3729 data = conn.bio_read(2)
3730 self.assertEqual(2, len(data))
3731
Hynek Schlawack35618382015-09-05 21:54:25 +02003732 @skip_if_py3
3733 def test_buffer_size_long(self):
3734 """
3735 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
3736 :py:obj:`long` as well as :py:obj:`int`.
3737 """
3738 ctx = Context(TLSv1_METHOD)
3739 conn = Connection(ctx, None)
3740 conn.set_connect_state()
3741 try:
3742 conn.do_handshake()
3743 except WantReadError:
3744 pass
3745 data = conn.bio_read(long(2))
3746 self.assertEqual(2, len(data))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003747
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003748
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003749class InfoConstantTests(TestCase):
3750 """
3751 Tests for assorted constants exposed for use in info callbacks.
3752 """
3753 def test_integers(self):
3754 """
3755 All of the info constants are integers.
3756
3757 This is a very weak test. It would be nice to have one that actually
3758 verifies that as certain info events happen, the value passed to the
3759 info callback matches up with the constant exposed by OpenSSL.SSL.
3760 """
3761 for const in [
3762 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
3763 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
3764 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3765 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3766 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003767 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3768 ]:
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003769 self.assertTrue(isinstance(const, int))
3770
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003771
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003772if __name__ == '__main__':
3773 main()