blob: de144ce5c3e3da4b59fcf15d86f53c03fd78b2e5 [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 Calderone4bccf5e2008-12-28 22:50:42 -050050try:
51 from OpenSSL.SSL import OP_NO_QUERY_MTU
52except ImportError:
53 OP_NO_QUERY_MTU = None
54try:
55 from OpenSSL.SSL import OP_COOKIE_EXCHANGE
56except ImportError:
57 OP_COOKIE_EXCHANGE = None
58try:
59 from OpenSSL.SSL import OP_NO_TICKET
60except ImportError:
61 OP_NO_TICKET = None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -040062
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040063try:
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -040064 from OpenSSL.SSL import OP_NO_COMPRESSION
65except ImportError:
66 OP_NO_COMPRESSION = None
67
68try:
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040069 from OpenSSL.SSL import MODE_RELEASE_BUFFERS
70except ImportError:
71 MODE_RELEASE_BUFFERS = None
72
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040073try:
74 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
75except ImportError:
76 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
77
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040078from OpenSSL.SSL import (
79 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
80 SSL_ST_OK, SSL_ST_RENEGOTIATE,
81 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
82 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
83 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
84 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040085
Hynek Schlawackf0e66852015-10-16 20:18:38 +020086from .util import WARNING_TYPE_EXPECTED, NON_ASCII, TestCase, b
87from .test_crypto import (
88 cleartextCertificatePEM, cleartextPrivateKeyPEM,
89 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
90 root_cert_pem)
91
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
Hynek Schlawackbf887932015-10-21 17:13:47 +02001064 context = Context(SSLv23_METHOD)
Hynek Schlawack734d3022015-09-05 19:19:32 +02001065 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()
Hynek Schlawackbf887932015-10-21 17:13:47 +02001071 client.connect(("encrypted.google.com", 443))
Hynek Schlawack734d3022015-09-05 19:19:32 +02001072 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)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002404 assert None is conn.get_app_data()
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002405 app_data = object()
2406 conn.set_app_data(app_data)
Todd Chapman4f73e4f2015-08-27 11:26:43 -04002407 assert conn.get_app_data() is app_data
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04002408
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002409 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002410 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002411 :py:obj:`Connection.makefile` is not implemented and calling that
2412 method raises :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04002413 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002414 conn = Connection(Context(TLSv1_METHOD), None)
2415 self.assertRaises(NotImplementedError, conn.makefile)
2416
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002417 def test_get_peer_cert_chain_wrong_args(self):
2418 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002419 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if
2420 called with any arguments.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002421 """
2422 conn = Connection(Context(TLSv1_METHOD), None)
2423 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
2424 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
2425 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
2426 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
2427
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002428 def test_get_peer_cert_chain(self):
2429 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002430 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates
2431 which the connected server returned for the certification verification.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002432 """
2433 chain = _create_certificate_chain()
2434 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
2435
2436 serverContext = Context(TLSv1_METHOD)
2437 serverContext.use_privatekey(skey)
2438 serverContext.use_certificate(scert)
2439 serverContext.add_extra_chain_cert(icert)
2440 serverContext.add_extra_chain_cert(cacert)
2441 server = Connection(serverContext, None)
2442 server.set_accept_state()
2443
2444 # Create the client
2445 clientContext = Context(TLSv1_METHOD)
2446 clientContext.set_verify(VERIFY_NONE, verify_cb)
2447 client = Connection(clientContext, None)
2448 client.set_connect_state()
2449
2450 self._interactInMemory(client, server)
2451
2452 chain = client.get_peer_cert_chain()
2453 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002454 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002455 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002456 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002457 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04002458 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002459 "Authority Certificate", chain[2].get_subject().CN)
2460
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002461 def test_get_peer_cert_chain_none(self):
2462 """
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002463 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the
2464 peer sends no certificate chain.
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04002465 """
2466 ctx = Context(TLSv1_METHOD)
2467 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2468 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2469 server = Connection(ctx, None)
2470 server.set_accept_state()
2471 client = Connection(Context(TLSv1_METHOD), None)
2472 client.set_connect_state()
2473 self._interactInMemory(client, server)
2474 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04002475
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002476 def test_get_session_wrong_args(self):
2477 """
2478 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
2479 with any arguments.
2480 """
2481 ctx = Context(TLSv1_METHOD)
2482 server = Connection(ctx, None)
2483 self.assertRaises(TypeError, server.get_session, 123)
2484 self.assertRaises(TypeError, server.get_session, "hello")
2485 self.assertRaises(TypeError, server.get_session, object())
2486
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002487 def test_get_session_unconnected(self):
2488 """
2489 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
2490 an object which has not been connected.
2491 """
2492 ctx = Context(TLSv1_METHOD)
2493 server = Connection(ctx, None)
2494 session = server.get_session()
2495 self.assertIdentical(None, session)
2496
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002497 def test_server_get_session(self):
2498 """
2499 On the server side of a connection, :py:obj:`Connection.get_session`
2500 returns a :py:class:`Session` instance representing the SSL session for
2501 that connection.
2502 """
2503 server, client = self._loopback()
2504 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002505 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002506
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002507 def test_client_get_session(self):
2508 """
2509 On the client side of a connection, :py:obj:`Connection.get_session`
2510 returns a :py:class:`Session` instance representing the SSL session for
2511 that connection.
2512 """
2513 server, client = self._loopback()
2514 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002515 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05002516
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002517 def test_set_session_wrong_args(self):
2518 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002519 If called with an object that is not an instance of
2520 :py:class:`Session`, or with other than one argument,
2521 :py:obj:`Connection.set_session` raises :py:obj:`TypeError`.
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002522 """
2523 ctx = Context(TLSv1_METHOD)
2524 connection = Connection(ctx, None)
2525 self.assertRaises(TypeError, connection.set_session)
2526 self.assertRaises(TypeError, connection.set_session, 123)
2527 self.assertRaises(TypeError, connection.set_session, "hello")
2528 self.assertRaises(TypeError, connection.set_session, object())
2529 self.assertRaises(
2530 TypeError, connection.set_session, Session(), Session())
2531
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002532 def test_client_set_session(self):
2533 """
2534 :py:obj:`Connection.set_session`, when used prior to a connection being
2535 established, accepts a :py:class:`Session` instance and causes an
2536 attempt to re-use the session it represents when the SSL handshake is
2537 performed.
2538 """
2539 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2540 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2541 ctx = Context(TLSv1_METHOD)
2542 ctx.use_privatekey(key)
2543 ctx.use_certificate(cert)
2544 ctx.set_session_id("unity-test")
2545
2546 def makeServer(socket):
2547 server = Connection(ctx, socket)
2548 server.set_accept_state()
2549 return server
2550
2551 originalServer, originalClient = self._loopback(
2552 serverFactory=makeServer)
2553 originalSession = originalClient.get_session()
2554
2555 def makeClient(socket):
2556 client = self._loopbackClientFactory(socket)
2557 client.set_session(originalSession)
2558 return client
2559 resumedServer, resumedClient = self._loopback(
2560 serverFactory=makeServer,
2561 clientFactory=makeClient)
2562
2563 # This is a proxy: in general, we have no access to any unique
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002564 # identifier for the session (new enough versions of OpenSSL expose
2565 # a hash which could be usable, but "new enough" is very, very new).
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002566 # Instead, exploit the fact that the master key is re-used if the
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002567 # session is re-used. As long as the master key for the two
2568 # connections is the same, the session was re-used!
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05002569 self.assertEqual(
2570 originalServer.master_key(), resumedServer.master_key())
2571
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002572 def test_set_session_wrong_method(self):
2573 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002574 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002575 instance associated with a context using a different SSL method than
2576 the :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002577 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002578 """
2579 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2580 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2581 ctx = Context(TLSv1_METHOD)
2582 ctx.use_privatekey(key)
2583 ctx.use_certificate(cert)
2584 ctx.set_session_id("unity-test")
2585
2586 def makeServer(socket):
2587 server = Connection(ctx, socket)
2588 server.set_accept_state()
2589 return server
2590
2591 originalServer, originalClient = self._loopback(
2592 serverFactory=makeServer)
2593 originalSession = originalClient.get_session()
2594
2595 def makeClient(socket):
2596 # Intentionally use a different, incompatible method here.
2597 client = Connection(Context(SSLv3_METHOD), socket)
2598 client.set_connect_state()
2599 client.set_session(originalSession)
2600 return client
2601
2602 self.assertRaises(
2603 Error,
2604 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2605
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002606 def test_wantWriteError(self):
2607 """
2608 :py:obj:`Connection` methods which generate output raise
2609 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2610 fail indicating a should-write state.
2611 """
2612 client_socket, server_socket = socket_pair()
2613 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002614 # anything. Only write a single byte at a time so we can be sure we
2615 # completely fill the buffer. Even though the socket API is allowed to
2616 # signal a short write via its return value it seems this doesn't
2617 # always happen on all platforms (FreeBSD and OS X particular) for the
2618 # very last bit of available buffer space.
2619 msg = b"x"
2620 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002621 try:
2622 client_socket.send(msg)
2623 except error as e:
2624 if e.errno == EWOULDBLOCK:
2625 break
2626 raise
2627 else:
2628 self.fail(
2629 "Failed to fill socket buffer, cannot test BIO want write")
2630
2631 ctx = Context(TLSv1_METHOD)
2632 conn = Connection(ctx, client_socket)
2633 # Client's speak first, so make it an SSL client
2634 conn.set_connect_state()
2635 self.assertRaises(WantWriteError, conn.do_handshake)
2636
2637 # XXX want_read
2638
Fedor Brunner416f4a12014-03-28 13:18:38 +01002639 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002640 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002641 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2642 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002643 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002644 ctx = Context(TLSv1_METHOD)
2645 connection = Connection(ctx, None)
2646 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002647
2648 def test_get_peer_finished_before_connect(self):
2649 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002650 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2651 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002652 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002653 ctx = Context(TLSv1_METHOD)
2654 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002655 self.assertEqual(connection.get_peer_finished(), None)
2656
Fedor Brunner416f4a12014-03-28 13:18:38 +01002657 def test_get_finished(self):
2658 """
2659 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002660 message send from client, or server. Finished messages are send during
2661 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002662 """
2663
Fedor Brunner5747b932014-03-05 14:22:34 +01002664 server, client = self._loopback()
2665
2666 self.assertNotEqual(server.get_finished(), None)
2667 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002668
2669 def test_get_peer_finished(self):
2670 """
2671 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002672 message received from client, or server. Finished messages are send
2673 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002674 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002675 server, client = self._loopback()
2676
2677 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002678 self.assertTrue(len(server.get_peer_finished()) > 0)
2679
Fedor Brunner416f4a12014-03-28 13:18:38 +01002680 def test_tls_finished_message_symmetry(self):
2681 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002682 The TLS Finished message send by server must be the TLS Finished
2683 message received by client.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002684
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002685 The TLS Finished message send by client must be the TLS Finished
2686 message received by server.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002687 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002688 server, client = self._loopback()
2689
Fedor Brunner5747b932014-03-05 14:22:34 +01002690 self.assertEqual(server.get_finished(), client.get_peer_finished())
2691 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002692
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002693 def test_get_cipher_name_before_connect(self):
2694 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002695 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2696 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002697 """
2698 ctx = Context(TLSv1_METHOD)
2699 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002700 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002701
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002702 def test_get_cipher_name(self):
2703 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002704 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2705 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002706 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002707 server, client = self._loopback()
2708 server_cipher_name, client_cipher_name = \
2709 server.get_cipher_name(), client.get_cipher_name()
2710
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002711 self.assertIsInstance(server_cipher_name, text_type)
2712 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002713
2714 self.assertEqual(server_cipher_name, client_cipher_name)
2715
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002716 def test_get_cipher_version_before_connect(self):
2717 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002718 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2719 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002720 """
2721 ctx = Context(TLSv1_METHOD)
2722 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002723 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002724
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002725 def test_get_cipher_version(self):
2726 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002727 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2728 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002729 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002730 server, client = self._loopback()
2731 server_cipher_version, client_cipher_version = \
2732 server.get_cipher_version(), client.get_cipher_version()
2733
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002734 self.assertIsInstance(server_cipher_version, text_type)
2735 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002736
2737 self.assertEqual(server_cipher_version, client_cipher_version)
2738
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002739 def test_get_cipher_bits_before_connect(self):
2740 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002741 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2742 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002743 """
2744 ctx = Context(TLSv1_METHOD)
2745 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002746 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002747
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002748 def test_get_cipher_bits(self):
2749 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002750 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2751 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002752 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002753 server, client = self._loopback()
2754 server_cipher_bits, client_cipher_bits = \
2755 server.get_cipher_bits(), client.get_cipher_bits()
2756
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002757 self.assertIsInstance(server_cipher_bits, int)
2758 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002759
2760 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002761
Jim Shaverabff1882015-05-27 09:15:55 -04002762 def test_get_protocol_version_name(self):
2763 """
2764 :py:obj:`Connection.get_protocol_version_name()` returns a string
2765 giving the protocol version of the current connection.
2766 """
2767 server, client = self._loopback()
2768 client_protocol_version_name = client.get_protocol_version_name()
2769 server_protocol_version_name = server.get_protocol_version_name()
2770
Jim Shaver58d25732015-05-28 11:52:32 -04002771 self.assertIsInstance(server_protocol_version_name, text_type)
2772 self.assertIsInstance(client_protocol_version_name, text_type)
Jim Shaverabff1882015-05-27 09:15:55 -04002773
Hynek Schlawack97cf1a82015-09-05 20:40:19 +02002774 self.assertEqual(
2775 server_protocol_version_name, client_protocol_version_name
2776 )
Jim Shaverabff1882015-05-27 09:15:55 -04002777
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002778 def test_get_protocol_version(self):
2779 """
Alex Gaynor43307782015-09-04 09:05:45 -04002780 :py:obj:`Connection.get_protocol_version()` returns an integer
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002781 giving the protocol version of the current connection.
2782 """
2783 server, client = self._loopback()
Jim Shaver85a4dff2015-04-27 17:42:46 -04002784 client_protocol_version = client.get_protocol_version()
2785 server_protocol_version = server.get_protocol_version()
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002786
Jim Shaverabff1882015-05-27 09:15:55 -04002787 self.assertIsInstance(server_protocol_version, int)
2788 self.assertIsInstance(client_protocol_version, int)
Richard J. Moore5d85fca2015-01-11 17:04:43 +00002789
2790 self.assertEqual(server_protocol_version, client_protocol_version)
2791
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002792
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002793class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002794 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002795 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002796 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002797 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002798 """
Hynek Schlawackdddd1112015-09-05 21:12:30 +02002799 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if
2800 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002801 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002802 connection = Connection(Context(TLSv1_METHOD), None)
2803 self.assertRaises(TypeError, connection.get_cipher_list, None)
2804
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002805 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002806 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002807 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2808 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002809 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002810 connection = Connection(Context(TLSv1_METHOD), None)
2811 ciphers = connection.get_cipher_list()
2812 self.assertTrue(isinstance(ciphers, list))
2813 for cipher in ciphers:
2814 self.assertTrue(isinstance(cipher, str))
2815
2816
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002817class ConnectionSendTests(TestCase, _LoopbackMixin):
2818 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002819 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002820 """
2821 def test_wrong_args(self):
2822 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002823 When called with arguments other than string argument for its first
2824 parameter or more than two arguments, :py:obj:`Connection.send` raises
2825 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002826 """
2827 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002828 self.assertRaises(TypeError, connection.send)
2829 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002830 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002831
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002832 def test_short_bytes(self):
2833 """
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002834 When passed a short byte string, :py:obj:`Connection.send` transmits
2835 all of it and returns the number of bytes sent.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002836 """
2837 server, client = self._loopback()
2838 count = server.send(b('xy'))
2839 self.assertEquals(count, 2)
2840 self.assertEquals(client.recv(2), b('xy'))
2841
Abraham Martinef063482015-03-25 14:06:24 +00002842 def test_text(self):
2843 """
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002844 When passed a text, :py:obj:`Connection.send` transmits all of it and
2845 returns the number of bytes sent. It also raises a DeprecationWarning.
Abraham Martinef063482015-03-25 14:06:24 +00002846 """
2847 server, client = self._loopback()
2848 with catch_warnings(record=True) as w:
2849 simplefilter("always")
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002850 count = server.send(b"xy".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002851 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04002852 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002853 WARNING_TYPE_EXPECTED
2854 ),
2855 str(w[-1].message)
2856 )
2857 self.assertIs(w[-1].category, DeprecationWarning)
Abraham Martinef063482015-03-25 14:06:24 +00002858 self.assertEquals(count, 2)
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04002859 self.assertEquals(client.recv(2), b"xy")
Abraham Martinef063482015-03-25 14:06:24 +00002860
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002861 @skip_if_py26
2862 def test_short_memoryview(self):
2863 """
2864 When passed a memoryview onto a small number of bytes,
2865 :py:obj:`Connection.send` transmits all of them and returns the number
2866 of bytes sent.
2867 """
2868 server, client = self._loopback()
2869 count = server.send(memoryview(b('xy')))
2870 self.assertEquals(count, 2)
2871 self.assertEquals(client.recv(2), b('xy'))
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002872
Hynek Schlawack8e94f1b2015-09-05 21:31:00 +02002873 @skip_if_py3
Hynek Schlawackf8979a52015-09-05 21:25:25 +02002874 def test_short_buffer(self):
2875 """
2876 When passed a buffer containing a small number of bytes,
2877 :py:obj:`Connection.send` transmits all of them and returns the number
2878 of bytes sent.
2879 """
2880 server, client = self._loopback()
2881 count = server.send(buffer(b('xy')))
2882 self.assertEquals(count, 2)
2883 self.assertEquals(client.recv(2), b('xy'))
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002884
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002885
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002886def _make_memoryview(size):
2887 """
2888 Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
2889 size.
2890 """
2891 return memoryview(bytearray(size))
2892
2893
Cory Benfield62d10332014-06-15 10:03:41 +01002894class ConnectionRecvIntoTests(TestCase, _LoopbackMixin):
2895 """
2896 Tests for :py:obj:`Connection.recv_into`
2897 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002898 def _no_length_test(self, factory):
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002899 """
2900 Assert that when the given buffer is passed to
2901 ``Connection.recv_into``, whatever bytes are available to be received
2902 that fit into that buffer are written into that buffer.
2903 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002904 output_buffer = factory(5)
2905
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002906 server, client = self._loopback()
2907 server.send(b('xy'))
2908
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002909 self.assertEqual(client.recv_into(output_buffer), 2)
2910 self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
Jean-Paul Calderone332a85e2015-03-15 17:02:40 -04002911
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002912 def test_bytearray_no_length(self):
Cory Benfield62d10332014-06-15 10:03:41 +01002913 """
Jean-Paul Calderone61559d82015-03-15 17:04:50 -04002914 :py:obj:`Connection.recv_into` can be passed a ``bytearray`` instance
2915 and data in the receive buffer is written to it.
Cory Benfield62d10332014-06-15 10:03:41 +01002916 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002917 self._no_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002918
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002919 def _respects_length_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002920 """
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002921 Assert that when the given buffer is passed to ``Connection.recv_into``
2922 along with a value for ``nbytes`` that is less than the size of that
2923 buffer, only ``nbytes`` bytes are written into the buffer.
Cory Benfield62d10332014-06-15 10:03:41 +01002924 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002925 output_buffer = factory(10)
2926
Cory Benfield62d10332014-06-15 10:03:41 +01002927 server, client = self._loopback()
2928 server.send(b('abcdefghij'))
Cory Benfield62d10332014-06-15 10:03:41 +01002929
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002930 self.assertEqual(client.recv_into(output_buffer, 5), 5)
2931 self.assertEqual(
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002932 output_buffer, bytearray(b('abcde\x00\x00\x00\x00\x00'))
2933 )
2934
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002935 def test_bytearray_respects_length(self):
Jean-Paul Calderonec295a2f2015-03-15 17:11:18 -04002936 """
2937 When called with a ``bytearray`` instance,
2938 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter and
2939 doesn't copy in more than that number of bytes.
2940 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002941 self._respects_length_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002942
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002943 def _doesnt_overfill_test(self, factory):
Cory Benfield62d10332014-06-15 10:03:41 +01002944 """
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002945 Assert that if there are more bytes available to be read from the
2946 receive buffer than would fit into the buffer passed to
2947 :py:obj:`Connection.recv_into`, only as many as fit are written into
2948 it.
Cory Benfield62d10332014-06-15 10:03:41 +01002949 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002950 output_buffer = factory(5)
2951
Cory Benfield62d10332014-06-15 10:03:41 +01002952 server, client = self._loopback()
2953 server.send(b('abcdefghij'))
Cory Benfield62d10332014-06-15 10:03:41 +01002954
Jean-Paul Calderone320af1e2015-03-15 17:20:13 -04002955 self.assertEqual(client.recv_into(output_buffer), 5)
2956 self.assertEqual(output_buffer, bytearray(b('abcde')))
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002957 rest = client.recv(5)
2958 self.assertEqual(b('fghij'), rest)
2959
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002960 def test_bytearray_doesnt_overfill(self):
Jean-Paul Calderone2b41ad32015-03-15 17:19:39 -04002961 """
2962 When called with a ``bytearray`` instance,
2963 :py:obj:`Connection.recv_into` respects the size of the array and
2964 doesn't write more bytes into it than will fit.
2965 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002966 self._doesnt_overfill_test(bytearray)
Cory Benfield62d10332014-06-15 10:03:41 +01002967
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002968 def _really_doesnt_overfill_test(self, factory):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002969 """
2970 Assert that if the value given by ``nbytes`` is greater than the actual
2971 size of the output buffer passed to :py:obj:`Connection.recv_into`, the
2972 behavior is as if no value was given for ``nbytes`` at all.
2973 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002974 output_buffer = factory(5)
2975
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002976 server, client = self._loopback()
2977 server.send(b('abcdefghij'))
2978
2979 self.assertEqual(client.recv_into(output_buffer, 50), 5)
2980 self.assertEqual(output_buffer, bytearray(b('abcde')))
2981 rest = client.recv(5)
2982 self.assertEqual(b('fghij'), rest)
2983
Jean-Paul Calderoned335b272015-03-15 17:26:38 -04002984 def test_bytearray_really_doesnt_overfill(self):
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002985 """
2986 When called with a ``bytearray`` instance and an ``nbytes`` value that
2987 is too large, :py:obj:`Connection.recv_into` respects the size of the
2988 array and not the ``nbytes`` value and doesn't write more bytes into
2989 the buffer than will fit.
2990 """
Jean-Paul Calderone6c840102015-03-15 17:32:15 -04002991 self._doesnt_overfill_test(bytearray)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04002992
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002993 def test_peek(self):
2994
2995 server, client = self._loopback()
2996 server.send(b('xy'))
2997
2998 for _ in range(2):
2999 output_buffer = bytearray(5)
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003000 self.assertEqual(
3001 client.recv_into(output_buffer, flags=MSG_PEEK), 2)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003002 self.assertEqual(output_buffer, bytearray(b('xy\x00\x00\x00')))
3003
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003004 @skip_if_py26
3005 def test_memoryview_no_length(self):
3006 """
3007 :py:obj:`Connection.recv_into` can be passed a ``memoryview``
3008 instance and data in the receive buffer is written to it.
3009 """
3010 self._no_length_test(_make_memoryview)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02003011
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003012 @skip_if_py26
3013 def test_memoryview_respects_length(self):
3014 """
3015 When called with a ``memoryview`` instance,
3016 :py:obj:`Connection.recv_into` respects the ``nbytes`` parameter
3017 and doesn't copy more than that number of bytes in.
3018 """
3019 self._respects_length_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003020
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003021 @skip_if_py26
3022 def test_memoryview_doesnt_overfill(self):
3023 """
3024 When called with a ``memoryview`` instance,
3025 :py:obj:`Connection.recv_into` respects the size of the array and
3026 doesn't write more bytes into it than will fit.
3027 """
3028 self._doesnt_overfill_test(_make_memoryview)
Cory Benfield62d10332014-06-15 10:03:41 +01003029
Hynek Schlawackf8979a52015-09-05 21:25:25 +02003030 @skip_if_py26
3031 def test_memoryview_really_doesnt_overfill(self):
3032 """
3033 When called with a ``memoryview`` instance and an ``nbytes`` value
3034 that is too large, :py:obj:`Connection.recv_into` respects the size
3035 of the array and not the ``nbytes`` value and doesn't write more
3036 bytes into the buffer than will fit.
3037 """
3038 self._doesnt_overfill_test(_make_memoryview)
Jean-Paul Calderone4bec59a2015-03-15 17:25:57 -04003039
Cory Benfield62d10332014-06-15 10:03:41 +01003040
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003041class ConnectionSendallTests(TestCase, _LoopbackMixin):
3042 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003043 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003044 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003045 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003046 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003047 When called with arguments other than a string argument for its first
3048 parameter or with more than two arguments, :py:obj:`Connection.sendall`
3049 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003050 """
3051 connection = Connection(Context(TLSv1_METHOD), None)
3052 self.assertRaises(TypeError, connection.sendall)
3053 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003054 self.assertRaises(
3055 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003056
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003057 def test_short(self):
3058 """
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003059 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3060 passed to it.
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003061 """
3062 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04003063 server.sendall(b('x'))
3064 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003065
Abraham Martinef063482015-03-25 14:06:24 +00003066 def test_text(self):
3067 """
Jean-Paul Calderone93477422015-04-13 20:38:57 -04003068 :py:obj:`Connection.sendall` transmits all the content in the string
3069 passed to it raising a DeprecationWarning in case of this being a text.
Abraham Martinef063482015-03-25 14:06:24 +00003070 """
3071 server, client = self._loopback()
3072 with catch_warnings(record=True) as w:
3073 simplefilter("always")
Jean-Paul Calderone8dc37a12015-03-29 08:16:52 -04003074 server.sendall(b"x".decode("ascii"))
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003075 self.assertEqual(
Jean-Paul Calderone13a0e652015-03-29 07:58:51 -04003076 "{0} for buf is no longer accepted, use bytes".format(
Jean-Paul Calderone6462b072015-03-29 07:03:11 -04003077 WARNING_TYPE_EXPECTED
3078 ),
3079 str(w[-1].message)
3080 )
3081 self.assertIs(w[-1].category, DeprecationWarning)
3082 self.assertEquals(client.recv(1), b"x")
Abraham Martinef063482015-03-25 14:06:24 +00003083
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003084 @skip_if_py26
3085 def test_short_memoryview(self):
3086 """
3087 When passed a memoryview onto a small number of bytes,
3088 :py:obj:`Connection.sendall` transmits all of them.
3089 """
3090 server, client = self._loopback()
3091 server.sendall(memoryview(b('x')))
3092 self.assertEquals(client.recv(1), b('x'))
Abraham Martinef063482015-03-25 14:06:24 +00003093
Hynek Schlawacke2f8a092015-09-05 21:39:50 +02003094 @skip_if_py3
3095 def test_short_buffers(self):
3096 """
3097 When passed a buffer containing a small number of bytes,
3098 :py:obj:`Connection.sendall` transmits all of them.
3099 """
3100 server, client = self._loopback()
3101 server.sendall(buffer(b('x')))
3102 self.assertEquals(client.recv(1), b('x'))
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02003103
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003104 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003105 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003106 :py:obj:`Connection.sendall` transmits all of the bytes in the string
3107 passed to it even if this requires multiple calls of an underlying
3108 write function.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003109 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003110 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04003111 # Should be enough, underlying SSL_write should only do 16k at a time.
Hynek Schlawack35618382015-09-05 21:54:25 +02003112 # On Windows, after 32k of bytes the write will block (forever
3113 # - because no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04003114 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003115 server.sendall(message)
3116 accum = []
3117 received = 0
3118 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04003119 data = client.recv(1024)
3120 accum.append(data)
3121 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04003122 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003123
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003124 def test_closed(self):
3125 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003126 If the underlying socket is closed, :py:obj:`Connection.sendall`
3127 propagates the write error from the low level write call.
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003128 """
3129 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04003130 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003131 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003132 if platform == "win32":
3133 self.assertEqual(exc.args[0], ESHUTDOWN)
3134 else:
3135 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04003136
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04003137
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003138class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
3139 """
3140 Tests for SSL renegotiation APIs.
3141 """
3142 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003143 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003144 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called
3145 with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003146 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003147 connection = Connection(Context(TLSv1_METHOD), None)
3148 self.assertRaises(TypeError, connection.renegotiate, None)
3149
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003150 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003151 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003152 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if
3153 called with any arguments.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003154 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003155 connection = Connection(Context(TLSv1_METHOD), None)
3156 self.assertRaises(TypeError, connection.total_renegotiations, None)
3157
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003158 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003159 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003160 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before
3161 any renegotiations have happened.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04003162 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04003163 connection = Connection(Context(TLSv1_METHOD), None)
3164 self.assertEquals(connection.total_renegotiations(), 0)
3165
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04003166# def test_renegotiate(self):
3167# """
3168# """
3169# server, client = self._loopback()
3170
3171# server.send("hello world")
3172# self.assertEquals(client.recv(len("hello world")), "hello world")
3173
3174# self.assertEquals(server.total_renegotiations(), 0)
3175# self.assertTrue(server.renegotiate())
3176
3177# server.setblocking(False)
3178# client.setblocking(False)
3179# while server.renegotiate_pending():
3180# client.do_handshake()
3181# server.do_handshake()
3182
3183# self.assertEquals(server.total_renegotiations(), 1)
3184
3185
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003186class ErrorTests(TestCase):
3187 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003188 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003189 """
3190 def test_type(self):
3191 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003192 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04003193 """
3194 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05003195 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05003196
3197
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003198class ConstantsTests(TestCase):
3199 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003200 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003201
3202 These are values defined by OpenSSL intended only to be used as flags to
3203 OpenSSL APIs. The only assertions it seems can be made about them is
3204 their values.
3205 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003206 @pytest.mark.skipif(
3207 OP_NO_QUERY_MTU is None,
3208 reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
3209 )
3210 def test_op_no_query_mtu(self):
3211 """
3212 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
3213 of :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
3214 """
3215 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003216
Hynek Schlawack35618382015-09-05 21:54:25 +02003217 @pytest.mark.skipif(
3218 OP_COOKIE_EXCHANGE is None,
3219 reason="OP_COOKIE_EXCHANGE unavailable - "
3220 "OpenSSL version may be too old"
3221 )
3222 def test_op_cookie_exchange(self):
3223 """
3224 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
3225 value of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by
3226 :file:`openssl/ssl.h`.
3227 """
3228 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003229
Hynek Schlawack35618382015-09-05 21:54:25 +02003230 @pytest.mark.skipif(
3231 OP_NO_TICKET is None,
3232 reason="OP_NO_TICKET unavailable - OpenSSL version may be too old"
3233 )
3234 def test_op_no_ticket(self):
3235 """
3236 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
3237 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
3238 """
3239 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05003240
Hynek Schlawack35618382015-09-05 21:54:25 +02003241 @pytest.mark.skipif(
3242 OP_NO_COMPRESSION is None,
3243 reason="OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
3244 )
3245 def test_op_no_compression(self):
3246 """
3247 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
3248 value of :py:const:`SSL_OP_NO_COMPRESSION` defined by
3249 :file:`openssl/ssl.h`.
3250 """
3251 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04003252
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003253 def test_sess_cache_off(self):
3254 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003255 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
3256 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003257 """
3258 self.assertEqual(0x0, SESS_CACHE_OFF)
3259
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003260 def test_sess_cache_client(self):
3261 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003262 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
3263 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003264 """
3265 self.assertEqual(0x1, SESS_CACHE_CLIENT)
3266
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003267 def test_sess_cache_server(self):
3268 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003269 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
3270 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003271 """
3272 self.assertEqual(0x2, SESS_CACHE_SERVER)
3273
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003274 def test_sess_cache_both(self):
3275 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003276 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
3277 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003278 """
3279 self.assertEqual(0x3, SESS_CACHE_BOTH)
3280
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003281 def test_sess_cache_no_auto_clear(self):
3282 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003283 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
3284 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
3285 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003286 """
3287 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
3288
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003289 def test_sess_cache_no_internal_lookup(self):
3290 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003291 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
3292 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
3293 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003294 """
3295 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
3296
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003297 def test_sess_cache_no_internal_store(self):
3298 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003299 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
3300 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
3301 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003302 """
3303 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
3304
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003305 def test_sess_cache_no_internal(self):
3306 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003307 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
3308 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
3309 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05003310 """
3311 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
3312
3313
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003314class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05003315 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003316 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05003317 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003318 def _server(self, sock):
3319 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003320 Create a new server-side SSL :py:obj:`Connection` object wrapped around
3321 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003322 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003323 # Create the server side Connection. This is mostly setup boilerplate
3324 # - use TLSv1, use a particular certificate, etc.
3325 server_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003326 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003327 server_ctx.set_verify(
3328 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3329 verify_cb
3330 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003331 server_store = server_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003332 server_ctx.use_privatekey(
3333 load_privatekey(FILETYPE_PEM, server_key_pem))
3334 server_ctx.use_certificate(
3335 load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003336 server_ctx.check_privatekey()
3337 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Hynek Schlawack35618382015-09-05 21:54:25 +02003338 # Here the Connection is actually created. If None is passed as the
3339 # 2nd parameter, it indicates a memory BIO should be created.
Rick Deanb1ccd562009-07-09 23:52:39 -05003340 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003341 server_conn.set_accept_state()
3342 return server_conn
3343
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003344 def _client(self, sock):
3345 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003346 Create a new client-side SSL :py:obj:`Connection` object wrapped around
3347 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003348 """
3349 # Now create the client side Connection. Similar boilerplate to the
3350 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003351 client_ctx = Context(TLSv1_METHOD)
Alex Gaynor43307782015-09-04 09:05:45 -04003352 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
Hynek Schlawack35618382015-09-05 21:54:25 +02003353 client_ctx.set_verify(
3354 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
3355 verify_cb
3356 )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003357 client_store = client_ctx.get_cert_store()
Hynek Schlawack35618382015-09-05 21:54:25 +02003358 client_ctx.use_privatekey(
3359 load_privatekey(FILETYPE_PEM, client_key_pem))
3360 client_ctx.use_certificate(
3361 load_certificate(FILETYPE_PEM, client_cert_pem))
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003362 client_ctx.check_privatekey()
3363 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05003364 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003365 client_conn.set_connect_state()
3366 return client_conn
3367
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003368 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003369 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003370 Two :py:obj:`Connection`s which use memory BIOs can be manually
3371 connected by reading from the output of each and writing those bytes to
3372 the input of the other and in this way establish a connection and
3373 exchange application-level bytes with each other.
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003374 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003375 server_conn = self._server(None)
3376 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003377
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003378 # There should be no key or nonces yet.
3379 self.assertIdentical(server_conn.master_key(), None)
3380 self.assertIdentical(server_conn.client_random(), None)
3381 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05003382
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003383 # First, the handshake needs to happen. We'll deliver bytes back and
3384 # forth between the client and server until neither of them feels like
3385 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003386 self.assertIdentical(
3387 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003388
3389 # Now that the handshake is done, there should be a key and nonces.
3390 self.assertNotIdentical(server_conn.master_key(), None)
3391 self.assertNotIdentical(server_conn.client_random(), None)
3392 self.assertNotIdentical(server_conn.server_random(), None)
Hynek Schlawack35618382015-09-05 21:54:25 +02003393 self.assertEquals(
3394 server_conn.client_random(), client_conn.client_random())
3395 self.assertEquals(
3396 server_conn.server_random(), client_conn.server_random())
3397 self.assertNotEquals(
3398 server_conn.client_random(), server_conn.server_random())
3399 self.assertNotEquals(
3400 client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003401
3402 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04003403 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05003404
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003405 server_conn.write(important_message)
3406 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003407 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003408 (client_conn, important_message))
3409
3410 client_conn.write(important_message[::-1])
3411 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003412 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04003413 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05003414
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003415 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05003416 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003417 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003418
Hynek Schlawack35618382015-09-05 21:54:25 +02003419 This is primarily to rule out the memory BIO code as the source of any
3420 problems encountered while passing data over a :py:obj:`Connection` (if
3421 this test fails, there must be a problem outside the memory BIO code,
3422 as no memory BIO is involved here). Even though this isn't a memory
3423 BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05003424 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04003425 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05003426
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04003427 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05003428 client_conn.send(important_message)
3429 msg = server_conn.recv(1024)
3430 self.assertEqual(msg, important_message)
3431
3432 # Again in the other direction, just for fun.
3433 important_message = important_message[::-1]
3434 server_conn.send(important_message)
3435 msg = client_conn.recv(1024)
3436 self.assertEqual(msg, important_message)
3437
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04003438 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05003439 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003440 Test that :py:obj:`OpenSSL.SSL.bio_read` and
3441 :py:obj:`OpenSSL.SSL.bio_write` don't work on
3442 :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05003443 """
3444 context = Context(SSLv3_METHOD)
3445 client = socket()
3446 clientSSL = Connection(context, client)
Alex Gaynor43307782015-09-04 09:05:45 -04003447 self.assertRaises(TypeError, clientSSL.bio_read, 100)
3448 self.assertRaises(TypeError, clientSSL.bio_write, "foo")
Alex Gaynor7e8b61e2015-09-04 13:13:05 -04003449 self.assertRaises(TypeError, clientSSL.bio_shutdown)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003450
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003451 def test_outgoingOverflow(self):
3452 """
3453 If more bytes than can be written to the memory BIO are passed to
Hynek Schlawack35618382015-09-05 21:54:25 +02003454 :py:obj:`Connection.send` at once, the number of bytes which were
3455 written is returned and that many bytes from the beginning of the input
3456 can be read from the other end of the connection.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003457 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003458 server = self._server(None)
3459 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003460
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003461 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003462
3463 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003464 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003465 # Sanity check. We're trying to test what happens when the entire
3466 # input can't be sent. If the entire input was sent, this test is
3467 # meaningless.
3468 self.assertTrue(sent < size)
3469
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003470 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04003471 self.assertIdentical(receiver, server)
3472
3473 # We can rely on all of these bytes being received at once because
3474 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
3475 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003476
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003477 def test_shutdown(self):
3478 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003479 :py:obj:`Connection.bio_shutdown` signals the end of the data stream
3480 from which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003481 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04003482 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04003483 server.bio_shutdown()
3484 e = self.assertRaises(Error, server.recv, 1024)
3485 # We don't want WantReadError or ZeroReturnError or anything - it's a
3486 # handshake failure.
3487 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003488
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003489 def test_unexpectedEndOfFile(self):
3490 """
3491 If the connection is lost before an orderly SSL shutdown occurs,
3492 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
3493 "Unexpected EOF".
3494 """
3495 server_conn, client_conn = self._loopback()
3496 client_conn.sock_shutdown(SHUT_RDWR)
3497 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
3498 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
3499
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003500 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003501 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003502 Verify the return value of the :py:obj:`get_client_ca_list` method for
3503 server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003504
Jonathan Ballet78b92a22011-07-16 08:07:26 +09003505 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003506 before the client and server are connected to each other. This
3507 function should specify a list of CAs for the server to send to the
3508 client and return that same list. The list will be used to verify
Hynek Schlawack35618382015-09-05 21:54:25 +02003509 that :py:obj:`get_client_ca_list` returns the proper value at
3510 various times.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003511 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003512 server = self._server(None)
3513 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003514 self.assertEqual(client.get_client_ca_list(), [])
3515 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003516 ctx = server.get_context()
3517 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003518 self.assertEqual(client.get_client_ca_list(), [])
3519 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04003520 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003521 self.assertEqual(client.get_client_ca_list(), expected)
3522 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003523
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003524 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003525 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003526 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if
3527 called with a non-list or a list that contains objects other than
3528 X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003529 """
3530 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003531 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
3532 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
3533 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003534
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003535 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003536 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003537 If passed an empty list, :py:obj:`Context.set_client_ca_list`
3538 configures the context to send no CA names to the client and, on both
3539 the server and client sides, :py:obj:`Connection.get_client_ca_list`
3540 returns an empty list after the connection is set up.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003541 """
3542 def no_ca(ctx):
3543 ctx.set_client_ca_list([])
3544 return []
3545 self._check_client_ca_list(no_ca)
3546
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003547 def test_set_one_ca_list(self):
3548 """
3549 If passed a list containing a single X509Name,
Hynek Schlawack35618382015-09-05 21:54:25 +02003550 :py:obj:`Context.set_client_ca_list` configures the context to send
3551 that CA name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003552 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003553 X509Name after the connection is set up.
3554 """
3555 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3556 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003557
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003558 def single_ca(ctx):
3559 ctx.set_client_ca_list([cadesc])
3560 return [cadesc]
3561 self._check_client_ca_list(single_ca)
3562
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003563 def test_set_multiple_ca_list(self):
3564 """
3565 If passed a list containing multiple X509Name objects,
Hynek Schlawack35618382015-09-05 21:54:25 +02003566 :py:obj:`Context.set_client_ca_list` configures the context to send
3567 those CA names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09003568 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003569 X509Names after the connection is set up.
3570 """
3571 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3572 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3573
3574 sedesc = secert.get_subject()
3575 cldesc = clcert.get_subject()
3576
3577 def multiple_ca(ctx):
3578 L = [sedesc, cldesc]
3579 ctx.set_client_ca_list(L)
3580 return L
3581 self._check_client_ca_list(multiple_ca)
3582
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003583 def test_reset_ca_list(self):
3584 """
3585 If called multiple times, only the X509Names passed to the final call
Hynek Schlawack35618382015-09-05 21:54:25 +02003586 of :py:obj:`Context.set_client_ca_list` are used to configure the CA
3587 names sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003588 """
3589 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3590 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3591 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3592
3593 cadesc = cacert.get_subject()
3594 sedesc = secert.get_subject()
3595 cldesc = clcert.get_subject()
3596
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003597 def changed_ca(ctx):
3598 ctx.set_client_ca_list([sedesc, cldesc])
3599 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003600 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003601 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003602
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003603 def test_mutated_ca_list(self):
3604 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003605 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003606 afterwards, this does not affect the list of CA names sent to the
3607 client.
3608 """
3609 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3610 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3611
3612 cadesc = cacert.get_subject()
3613 sedesc = secert.get_subject()
3614
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003615 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003616 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003617 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003618 L.append(sedesc)
3619 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003620 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003621
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003622 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003623 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003624 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called
3625 with a non-X509 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003626 """
3627 ctx = Context(TLSv1_METHOD)
3628 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003629 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003630 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04003631 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003632
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003633 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003634 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003635 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09003636 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003637 """
3638 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3639 cadesc = cacert.get_subject()
Hynek Schlawack35618382015-09-05 21:54:25 +02003640
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003641 def single_ca(ctx):
3642 ctx.add_client_ca(cacert)
3643 return [cadesc]
3644 self._check_client_ca_list(single_ca)
3645
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003646 def test_multiple_add_client_ca(self):
3647 """
3648 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09003649 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003650 """
3651 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3652 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3653
3654 cadesc = cacert.get_subject()
3655 sedesc = secert.get_subject()
3656
3657 def multiple_ca(ctx):
3658 ctx.add_client_ca(cacert)
3659 ctx.add_client_ca(secert)
3660 return [cadesc, sedesc]
3661 self._check_client_ca_list(multiple_ca)
3662
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003663 def test_set_and_add_client_ca(self):
3664 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003665 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003666 :py:obj:`Context.add_client_ca` results in using the CA names from the
3667 first call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003668 """
3669 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3670 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3671 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3672
3673 cadesc = cacert.get_subject()
3674 sedesc = secert.get_subject()
3675 cldesc = clcert.get_subject()
3676
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003677 def mixed_set_add_ca(ctx):
3678 ctx.set_client_ca_list([cadesc, sedesc])
3679 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003680 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003681 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003682
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003683 def test_set_after_add_client_ca(self):
3684 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09003685 A call to :py:obj:`Context.set_client_ca_list` after a call to
Hynek Schlawack35618382015-09-05 21:54:25 +02003686 :py:obj:`Context.add_client_ca` replaces the CA name specified by the
3687 former call with the names specified by the latter call.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003688 """
3689 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
3690 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
3691 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
3692
3693 cadesc = cacert.get_subject()
3694 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04003695
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003696 def set_replaces_add_ca(ctx):
3697 ctx.add_client_ca(clcert)
3698 ctx.set_client_ca_list([cadesc])
3699 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003700 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003701 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003702
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003703
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003704class ConnectionBIOTests(TestCase):
3705 """
3706 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
3707 """
3708 def test_wantReadError(self):
3709 """
Hynek Schlawack35618382015-09-05 21:54:25 +02003710 :py:obj:`Connection.bio_read` raises
3711 :py:obj:`OpenSSL.SSL.WantReadError` if there are no bytes available to
3712 be read from the BIO.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003713 """
3714 ctx = Context(TLSv1_METHOD)
3715 conn = Connection(ctx, None)
3716 self.assertRaises(WantReadError, conn.bio_read, 1024)
3717
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003718 def test_buffer_size(self):
3719 """
3720 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
3721 number of bytes to read and return.
3722 """
3723 ctx = Context(TLSv1_METHOD)
3724 conn = Connection(ctx, None)
3725 conn.set_connect_state()
3726 try:
3727 conn.do_handshake()
3728 except WantReadError:
3729 pass
3730 data = conn.bio_read(2)
3731 self.assertEqual(2, len(data))
3732
Hynek Schlawack35618382015-09-05 21:54:25 +02003733 @skip_if_py3
3734 def test_buffer_size_long(self):
3735 """
3736 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
3737 :py:obj:`long` as well as :py:obj:`int`.
3738 """
3739 ctx = Context(TLSv1_METHOD)
3740 conn = Connection(ctx, None)
3741 conn.set_connect_state()
3742 try:
3743 conn.do_handshake()
3744 except WantReadError:
3745 pass
3746 data = conn.bio_read(long(2))
3747 self.assertEqual(2, len(data))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003748
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003749
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003750class InfoConstantTests(TestCase):
3751 """
3752 Tests for assorted constants exposed for use in info callbacks.
3753 """
3754 def test_integers(self):
3755 """
3756 All of the info constants are integers.
3757
3758 This is a very weak test. It would be nice to have one that actually
3759 verifies that as certain info events happen, the value passed to the
3760 info callback matches up with the constant exposed by OpenSSL.SSL.
3761 """
3762 for const in [
3763 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
3764 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
3765 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3766 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3767 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
Hynek Schlawack35618382015-09-05 21:54:25 +02003768 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE
3769 ]:
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003770 self.assertTrue(isinstance(const, int))
3771
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003772
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003773if __name__ == '__main__':
3774 main()