blob: bbd97e6b5675b39d99f56f313f480d0fdd4c6e9a [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
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -040010from sys import platform, version_info
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070011from socket import 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
Jean-Paul Calderone460cc1f2009-03-07 11:31:12 -050016
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -040017from six import PY3, text_type, u
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050018
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040019from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080020from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040021from OpenSSL.crypto import dump_privatekey, load_privatekey
22from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040023from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040024
Jean-Paul Calderoneb41d1f42014-04-17 16:02:04 -040025from OpenSSL.SSL import _lib
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040026from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
27from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040028from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040029from OpenSSL.SSL import (
30 SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
31 TLSv1_1_METHOD, TLSv1_2_METHOD)
32from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040033from OpenSSL.SSL import (
34 VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040035
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040036from OpenSSL.SSL import (
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050037 SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
38 SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
39 SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
40
41from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070042 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050043from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070044 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040045
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050046from OpenSSL.test.util import TestCase, b
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040047from OpenSSL.test.test_crypto import (
48 cleartextCertificatePEM, cleartextPrivateKeyPEM)
49from OpenSSL.test.test_crypto import (
50 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
51 root_cert_pem)
52
Jean-Paul Calderone4bccf5e2008-12-28 22:50:42 -050053try:
54 from OpenSSL.SSL import OP_NO_QUERY_MTU
55except ImportError:
56 OP_NO_QUERY_MTU = None
57try:
58 from OpenSSL.SSL import OP_COOKIE_EXCHANGE
59except ImportError:
60 OP_COOKIE_EXCHANGE = None
61try:
62 from OpenSSL.SSL import OP_NO_TICKET
63except ImportError:
64 OP_NO_TICKET = None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -040065
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040066try:
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -040067 from OpenSSL.SSL import OP_NO_COMPRESSION
68except ImportError:
69 OP_NO_COMPRESSION = None
70
71try:
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040072 from OpenSSL.SSL import MODE_RELEASE_BUFFERS
73except ImportError:
74 MODE_RELEASE_BUFFERS = None
75
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040076try:
77 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
78except ImportError:
79 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
80
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040081from OpenSSL.SSL import (
82 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
83 SSL_ST_OK, SSL_ST_RENEGOTIATE,
84 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
85 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
86 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
87 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040088
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040089# openssl dhparam 128 -out dh-128.pem (note that 128 is a small number of bits
90# to use)
91dhparam = """\
92-----BEGIN DH PARAMETERS-----
93MBYCEQCobsg29c9WZP/54oAPcwiDAgEC
94-----END DH PARAMETERS-----
95"""
96
97
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -040098def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -040099 return ok
100
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400101
Rick Deanb1ccd562009-07-09 23:52:39 -0500102def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400103 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400104 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400105 """
106 # Connect a pair of sockets
Rick Deanb1ccd562009-07-09 23:52:39 -0500107 port = socket()
108 port.bind(('', 0))
109 port.listen(1)
110 client = socket()
111 client.setblocking(False)
Jean-Paul Calderonef23c5d92009-07-23 17:58:15 -0400112 client.connect_ex(("127.0.0.1", port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400113 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500114 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500115
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400116 # Let's pass some unencrypted data to make sure our socket connection is
117 # fine. Just one byte, so we don't have to worry about buffers getting
118 # filled up or fragmentation.
Jean-Paul Calderone9e4eeae2010-08-22 21:32:52 -0400119 server.send(b("x"))
120 assert client.recv(1024) == b("x")
121 client.send(b("y"))
122 assert server.recv(1024) == b("y")
Rick Deanb1ccd562009-07-09 23:52:39 -0500123
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400124 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400125 server.setblocking(False)
126 client.setblocking(False)
127
Rick Deanb1ccd562009-07-09 23:52:39 -0500128 return (server, client)
129
130
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400131
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400132def handshake(client, server):
133 conns = [client, server]
134 while conns:
135 for conn in conns:
136 try:
137 conn.do_handshake()
138 except WantReadError:
139 pass
140 else:
141 conns.remove(conn)
142
143
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400144def _create_certificate_chain():
145 """
146 Construct and return a chain of certificates.
147
148 1. A new self-signed certificate authority certificate (cacert)
149 2. A new intermediate certificate signed by cacert (icert)
150 3. A new server certificate signed by icert (scert)
151 """
152 caext = X509Extension(b('basicConstraints'), False, b('CA:true'))
153
154 # Step 1
155 cakey = PKey()
156 cakey.generate_key(TYPE_RSA, 512)
157 cacert = X509()
158 cacert.get_subject().commonName = "Authority Certificate"
159 cacert.set_issuer(cacert.get_subject())
160 cacert.set_pubkey(cakey)
161 cacert.set_notBefore(b("20000101000000Z"))
162 cacert.set_notAfter(b("20200101000000Z"))
163 cacert.add_extensions([caext])
164 cacert.set_serial_number(0)
165 cacert.sign(cakey, "sha1")
166
167 # Step 2
168 ikey = PKey()
169 ikey.generate_key(TYPE_RSA, 512)
170 icert = X509()
171 icert.get_subject().commonName = "Intermediate Certificate"
172 icert.set_issuer(cacert.get_subject())
173 icert.set_pubkey(ikey)
174 icert.set_notBefore(b("20000101000000Z"))
175 icert.set_notAfter(b("20200101000000Z"))
176 icert.add_extensions([caext])
177 icert.set_serial_number(0)
178 icert.sign(cakey, "sha1")
179
180 # Step 3
181 skey = PKey()
182 skey.generate_key(TYPE_RSA, 512)
183 scert = X509()
184 scert.get_subject().commonName = "Server Certificate"
185 scert.set_issuer(icert.get_subject())
186 scert.set_pubkey(skey)
187 scert.set_notBefore(b("20000101000000Z"))
188 scert.set_notAfter(b("20200101000000Z"))
189 scert.add_extensions([
190 X509Extension(b('basicConstraints'), True, b('CA:false'))])
191 scert.set_serial_number(0)
192 scert.sign(ikey, "sha1")
193
194 return [(cakey, cacert), (ikey, icert), (skey, scert)]
195
196
197
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400198class _LoopbackMixin:
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400199 """
200 Helper mixin which defines methods for creating a connected socket pair and
201 for forcing two connected SSL sockets to talk to each other via memory BIOs.
202 """
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500203 def _loopbackClientFactory(self, socket):
204 client = Connection(Context(TLSv1_METHOD), socket)
205 client.set_connect_state()
206 return client
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400207
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500208
209 def _loopbackServerFactory(self, socket):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400210 ctx = Context(TLSv1_METHOD)
211 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
212 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500213 server = Connection(ctx, socket)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400214 server.set_accept_state()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500215 return server
216
217
218 def _loopback(self, serverFactory=None, clientFactory=None):
219 if serverFactory is None:
220 serverFactory = self._loopbackServerFactory
221 if clientFactory is None:
222 clientFactory = self._loopbackClientFactory
223
224 (server, client) = socket_pair()
225 server = serverFactory(server)
226 client = clientFactory(client)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400227
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400228 handshake(client, server)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400229
230 server.setblocking(True)
231 client.setblocking(True)
232 return server, client
233
234
235 def _interactInMemory(self, client_conn, server_conn):
236 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900237 Try to read application bytes from each of the two :py:obj:`Connection`
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400238 objects. Copy bytes back and forth between their send/receive buffers
239 for as long as there is anything to copy. When there is nothing more
Jonathan Ballet648875f2011-07-16 14:14:58 +0900240 to copy, return :py:obj:`None`. If one of them actually manages to deliver
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400241 some application bytes, return a two-tuple of the connection from which
242 the bytes were read and the bytes themselves.
243 """
244 wrote = True
245 while wrote:
246 # Loop until neither side has anything to say
247 wrote = False
248
249 # Copy stuff from each side's send buffer to the other side's
250 # receive buffer.
251 for (read, write) in [(client_conn, server_conn),
252 (server_conn, client_conn)]:
253
254 # Give the side a chance to generate some more bytes, or
255 # succeed.
256 try:
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400257 data = read.recv(2 ** 16)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400258 except WantReadError:
259 # It didn't succeed, so we'll hope it generated some
260 # output.
261 pass
262 else:
263 # It did succeed, so we'll stop now and let the caller deal
264 # with it.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400265 return (read, data)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400266
267 while True:
268 # Keep copying as long as there's more stuff there.
269 try:
270 dirty = read.bio_read(4096)
271 except WantReadError:
272 # Okay, nothing more waiting to be sent. Stop
273 # processing this send buffer.
274 break
275 else:
276 # Keep track of the fact that someone generated some
277 # output.
278 wrote = True
279 write.bio_write(dirty)
280
281
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400282 def _handshakeInMemory(self, client_conn, server_conn):
Jean-Paul Calderoneb2b40782014-05-06 08:47:40 -0400283 """
284 Perform the TLS handshake between two :py:class:`Connection` instances
285 connected to each other via memory BIOs.
286 """
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400287 client_conn.set_connect_state()
288 server_conn.set_accept_state()
289
290 for conn in [client_conn, server_conn]:
291 try:
292 conn.do_handshake()
293 except WantReadError:
294 pass
295
296 self._interactInMemory(client_conn, server_conn)
297
298
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400299
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400300class VersionTests(TestCase):
301 """
302 Tests for version information exposed by
Jonathan Ballet648875f2011-07-16 14:14:58 +0900303 :py:obj:`OpenSSL.SSL.SSLeay_version` and
304 :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400305 """
306 def test_OPENSSL_VERSION_NUMBER(self):
307 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900308 :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400309 byte and the patch, fix, minor, and major versions in the
310 nibbles above that.
311 """
312 self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
313
314
315 def test_SSLeay_version(self):
316 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900317 :py:obj:`SSLeay_version` takes a version type indicator and returns
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400318 one of a number of version strings based on that indicator.
319 """
320 versions = {}
321 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
322 SSLEAY_PLATFORM, SSLEAY_DIR]:
323 version = SSLeay_version(t)
324 versions[version] = t
325 self.assertTrue(isinstance(version, bytes))
326 self.assertEqual(len(versions), 5)
327
328
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400329
330class ContextTests(TestCase, _LoopbackMixin):
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400331 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900332 Unit tests for :py:obj:`OpenSSL.SSL.Context`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400333 """
334 def test_method(self):
335 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900336 :py:obj:`Context` can be instantiated with one of :py:obj:`SSLv2_METHOD`,
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400337 :py:obj:`SSLv3_METHOD`, :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
338 :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400339 """
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400340 methods = [
341 SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]
342 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400343 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400344
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400345
346 maybe = [SSLv2_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
347 for meth in maybe:
348 try:
349 Context(meth)
350 except (Error, ValueError):
351 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
352 # don't. Difficult to say in advance.
353 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400354
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400355 self.assertRaises(TypeError, Context, "")
356 self.assertRaises(ValueError, Context, 10)
357
358
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500359 if not PY3:
360 def test_method_long(self):
361 """
362 On Python 2 :py:class:`Context` accepts values of type
363 :py:obj:`long` as well as :py:obj:`int`.
364 """
365 Context(long(TLSv1_METHOD))
366
367
368
Rick Deane15b1472009-07-09 15:53:42 -0500369 def test_type(self):
370 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900371 :py:obj:`Context` and :py:obj:`ContextType` refer to the same type object and can be
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400372 used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500373 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400374 self.assertIdentical(Context, ContextType)
375 self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500376
377
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400378 def test_use_privatekey(self):
379 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900380 :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey` instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400381 """
382 key = PKey()
383 key.generate_key(TYPE_RSA, 128)
384 ctx = Context(TLSv1_METHOD)
385 ctx.use_privatekey(key)
386 self.assertRaises(TypeError, ctx.use_privatekey, "")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400387
388
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800389 def test_use_privatekey_file_missing(self):
390 """
391 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error`
392 when passed the name of a file which does not exist.
393 """
394 ctx = Context(TLSv1_METHOD)
395 self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
396
397
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500398 if not PY3:
399 def test_use_privatekey_file_long(self):
400 """
401 On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
402 filetype of type :py:obj:`long` as well as :py:obj:`int`.
403 """
404 pemfile = self.mktemp()
405
406 key = PKey()
407 key.generate_key(TYPE_RSA, 128)
408
409 with open(pemfile, "wt") as pem:
410 pem.write(
411 dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
412
413 ctx = Context(TLSv1_METHOD)
414 ctx.use_privatekey_file(pemfile, long(FILETYPE_PEM))
415
416
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800417 def test_use_certificate_wrong_args(self):
418 """
419 :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
420 when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as an
421 argument.
422 """
423 ctx = Context(TLSv1_METHOD)
424 self.assertRaises(TypeError, ctx.use_certificate)
425 self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
426 self.assertRaises(TypeError, ctx.use_certificate, X509(), "hello, world")
427
428
429 def test_use_certificate_uninitialized(self):
430 """
431 :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
432 when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
433 initialized (ie, which does not actually have any certificate data).
434 """
435 ctx = Context(TLSv1_METHOD)
436 self.assertRaises(Error, ctx.use_certificate, X509())
437
438
439 def test_use_certificate(self):
440 """
441 :py:obj:`Context.use_certificate` sets the certificate which will be
442 used to identify connections created using the context.
443 """
444 # TODO
445 # Hard to assert anything. But we could set a privatekey then ask
446 # OpenSSL if the cert and key agree using check_privatekey. Then as
447 # long as check_privatekey works right we're good...
448 ctx = Context(TLSv1_METHOD)
449 ctx.use_certificate(load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
450
451
452 def test_use_certificate_file_wrong_args(self):
453 """
454 :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
455 called with zero arguments or more than two arguments, or if the first
456 argument is not a byte string or the second argumnent is not an integer.
457 """
458 ctx = Context(TLSv1_METHOD)
459 self.assertRaises(TypeError, ctx.use_certificate_file)
460 self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile", object())
461 self.assertRaises(
462 TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM, object())
463 self.assertRaises(
464 TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
465 self.assertRaises(
466 TypeError, ctx.use_certificate_file, b"somefile", object())
467
468
469 def test_use_certificate_file_missing(self):
470 """
471 :py:obj:`Context.use_certificate_file` raises
472 `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does not
473 exist.
474 """
475 ctx = Context(TLSv1_METHOD)
476 self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
477
478
479 def test_use_certificate_file(self):
480 """
481 :py:obj:`Context.use_certificate` sets the certificate which will be
482 used to identify connections created using the context.
483 """
484 # TODO
485 # Hard to assert anything. But we could set a privatekey then ask
486 # OpenSSL if the cert and key agree using check_privatekey. Then as
487 # long as check_privatekey works right we're good...
488 pem_filename = self.mktemp()
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500489 with open(pem_filename, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800490 pem_file.write(cleartextCertificatePEM)
491
492 ctx = Context(TLSv1_METHOD)
493 ctx.use_certificate_file(pem_filename)
494
495
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500496 if not PY3:
497 def test_use_certificate_file_long(self):
498 """
499 On Python 2 :py:obj:`Context.use_certificate_file` accepts a
500 filetype of type :py:obj:`long` as well as :py:obj:`int`.
501 """
502 pem_filename = self.mktemp()
503 with open(pem_filename, "wb") as pem_file:
504 pem_file.write(cleartextCertificatePEM)
505
506 ctx = Context(TLSv1_METHOD)
507 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
508
509
Jean-Paul Calderone932f5cc2014-12-11 13:58:00 -0500510 def test_check_privatekey_valid(self):
511 """
512 :py:obj:`Context.check_privatekey` returns :py:obj:`None` if the
513 :py:obj:`Context` instance has been configured to use a matched key and
514 certificate pair.
515 """
516 key = load_privatekey(FILETYPE_PEM, client_key_pem)
517 cert = load_certificate(FILETYPE_PEM, client_cert_pem)
518 context = Context(TLSv1_METHOD)
519 context.use_privatekey(key)
520 context.use_certificate(cert)
521 self.assertIs(None, context.check_privatekey())
522
523
524 def test_check_privatekey_invalid(self):
525 """
526 :py:obj:`Context.check_privatekey` raises :py:obj:`Error` if the
527 :py:obj:`Context` instance has been configured to use a key and
528 certificate pair which don't relate to each other.
529 """
530 key = load_privatekey(FILETYPE_PEM, client_key_pem)
531 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
532 context = Context(TLSv1_METHOD)
533 context.use_privatekey(key)
534 context.use_certificate(cert)
535 self.assertRaises(Error, context.check_privatekey)
536
537
538 def test_check_privatekey_wrong_args(self):
539 """
540 :py:obj:`Context.check_privatekey` raises :py:obj:`TypeError` if called
541 with other than no arguments.
542 """
543 context = Context(TLSv1_METHOD)
544 self.assertRaises(TypeError, context.check_privatekey, object())
545
546
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400547 def test_set_app_data_wrong_args(self):
548 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900549 :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called with other than
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400550 one argument.
551 """
552 context = Context(TLSv1_METHOD)
553 self.assertRaises(TypeError, context.set_app_data)
554 self.assertRaises(TypeError, context.set_app_data, None, None)
555
556
557 def test_get_app_data_wrong_args(self):
558 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900559 :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400560 arguments.
561 """
562 context = Context(TLSv1_METHOD)
563 self.assertRaises(TypeError, context.get_app_data, None)
564
565
566 def test_app_data(self):
567 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900568 :py:obj:`Context.set_app_data` stores an object for later retrieval using
569 :py:obj:`Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400570 """
571 app_data = object()
572 context = Context(TLSv1_METHOD)
573 context.set_app_data(app_data)
574 self.assertIdentical(context.get_app_data(), app_data)
575
576
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400577 def test_set_options_wrong_args(self):
578 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900579 :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with the wrong
580 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400581 """
582 context = Context(TLSv1_METHOD)
583 self.assertRaises(TypeError, context.set_options)
584 self.assertRaises(TypeError, context.set_options, None)
585 self.assertRaises(TypeError, context.set_options, 1, None)
586
587
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500588 def test_set_options(self):
589 """
590 :py:obj:`Context.set_options` returns the new options value.
591 """
592 context = Context(TLSv1_METHOD)
593 options = context.set_options(OP_NO_SSLv2)
594 self.assertTrue(OP_NO_SSLv2 & options)
595
596
597 if not PY3:
598 def test_set_options_long(self):
599 """
600 On Python 2 :py:obj:`Context.set_options` accepts values of type
601 :py:obj:`long` as well as :py:obj:`int`.
602 """
603 context = Context(TLSv1_METHOD)
604 options = context.set_options(long(OP_NO_SSLv2))
605 self.assertTrue(OP_NO_SSLv2 & options)
606
607
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300608 def test_set_mode_wrong_args(self):
609 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400610 :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with the wrong
611 number of arguments or a non-:py:obj:`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300612 """
613 context = Context(TLSv1_METHOD)
614 self.assertRaises(TypeError, context.set_mode)
615 self.assertRaises(TypeError, context.set_mode, None)
616 self.assertRaises(TypeError, context.set_mode, 1, None)
617
618
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400619 if MODE_RELEASE_BUFFERS is not None:
620 def test_set_mode(self):
621 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400622 :py:obj:`Context.set_mode` accepts a mode bitvector and returns the newly
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400623 set mode.
624 """
625 context = Context(TLSv1_METHOD)
626 self.assertTrue(
627 MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500628
629 if not PY3:
630 def test_set_mode_long(self):
631 """
632 On Python 2 :py:obj:`Context.set_mode` accepts values of type
633 :py:obj:`long` as well as :py:obj:`int`.
634 """
635 context = Context(TLSv1_METHOD)
636 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
637 self.assertTrue(MODE_RELEASE_BUFFERS & mode)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400638 else:
639 "MODE_RELEASE_BUFFERS unavailable - OpenSSL version may be too old"
640
641
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400642 def test_set_timeout_wrong_args(self):
643 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900644 :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with the wrong
645 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400646 """
647 context = Context(TLSv1_METHOD)
648 self.assertRaises(TypeError, context.set_timeout)
649 self.assertRaises(TypeError, context.set_timeout, None)
650 self.assertRaises(TypeError, context.set_timeout, 1, None)
651
652
653 def test_get_timeout_wrong_args(self):
654 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900655 :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400656 """
657 context = Context(TLSv1_METHOD)
658 self.assertRaises(TypeError, context.get_timeout, None)
659
660
661 def test_timeout(self):
662 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900663 :py:obj:`Context.set_timeout` sets the session timeout for all connections
664 created using the context object. :py:obj:`Context.get_timeout` retrieves this
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400665 value.
666 """
667 context = Context(TLSv1_METHOD)
668 context.set_timeout(1234)
669 self.assertEquals(context.get_timeout(), 1234)
670
671
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500672 if not PY3:
673 def test_timeout_long(self):
674 """
675 On Python 2 :py:obj:`Context.set_timeout` accepts values of type
676 `long` as well as int.
677 """
678 context = Context(TLSv1_METHOD)
679 context.set_timeout(long(1234))
680 self.assertEquals(context.get_timeout(), 1234)
681
682
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400683 def test_set_verify_depth_wrong_args(self):
684 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900685 :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called with the wrong
686 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400687 """
688 context = Context(TLSv1_METHOD)
689 self.assertRaises(TypeError, context.set_verify_depth)
690 self.assertRaises(TypeError, context.set_verify_depth, None)
691 self.assertRaises(TypeError, context.set_verify_depth, 1, None)
692
693
694 def test_get_verify_depth_wrong_args(self):
695 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900696 :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400697 """
698 context = Context(TLSv1_METHOD)
699 self.assertRaises(TypeError, context.get_verify_depth, None)
700
701
702 def test_verify_depth(self):
703 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900704 :py:obj:`Context.set_verify_depth` sets the number of certificates in a chain
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400705 to follow before giving up. The value can be retrieved with
Jonathan Ballet648875f2011-07-16 14:14:58 +0900706 :py:obj:`Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400707 """
708 context = Context(TLSv1_METHOD)
709 context.set_verify_depth(11)
710 self.assertEquals(context.get_verify_depth(), 11)
711
712
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500713 if not PY3:
714 def test_verify_depth_long(self):
715 """
716 On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
717 type `long` as well as int.
718 """
719 context = Context(TLSv1_METHOD)
720 context.set_verify_depth(long(11))
721 self.assertEquals(context.get_verify_depth(), 11)
722
723
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400724 def _write_encrypted_pem(self, passphrase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400725 """
726 Write a new private key out to a new file, encrypted using the given
727 passphrase. Return the path to the new file.
728 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400729 key = PKey()
730 key.generate_key(TYPE_RSA, 128)
731 pemFile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400732 fObj = open(pemFile, 'w')
733 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
734 fObj.write(pem.decode('ascii'))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400735 fObj.close()
736 return pemFile
737
738
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400739 def test_set_passwd_cb_wrong_args(self):
740 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900741 :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called with the
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400742 wrong arguments or with a non-callable first argument.
743 """
744 context = Context(TLSv1_METHOD)
745 self.assertRaises(TypeError, context.set_passwd_cb)
746 self.assertRaises(TypeError, context.set_passwd_cb, None)
747 self.assertRaises(TypeError, context.set_passwd_cb, lambda: None, None, None)
748
749
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400750 def test_set_passwd_cb(self):
751 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900752 :py:obj:`Context.set_passwd_cb` accepts a callable which will be invoked when
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400753 a private key is loaded from an encrypted PEM.
754 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400755 passphrase = b("foobar")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400756 pemFile = self._write_encrypted_pem(passphrase)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400757 calledWith = []
758 def passphraseCallback(maxlen, verify, extra):
759 calledWith.append((maxlen, verify, extra))
760 return passphrase
761 context = Context(TLSv1_METHOD)
762 context.set_passwd_cb(passphraseCallback)
763 context.use_privatekey_file(pemFile)
764 self.assertTrue(len(calledWith), 1)
765 self.assertTrue(isinstance(calledWith[0][0], int))
766 self.assertTrue(isinstance(calledWith[0][1], int))
767 self.assertEqual(calledWith[0][2], None)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400768
769
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400770 def test_passwd_callback_exception(self):
771 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900772 :py:obj:`Context.use_privatekey_file` propagates any exception raised by the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400773 passphrase callback.
774 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400775 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400776 def passphraseCallback(maxlen, verify, extra):
777 raise RuntimeError("Sorry, I am a fail.")
778
779 context = Context(TLSv1_METHOD)
780 context.set_passwd_cb(passphraseCallback)
781 self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
782
783
784 def test_passwd_callback_false(self):
785 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900786 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400787 passphrase callback returns a false value.
788 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400789 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400790 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500791 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400792
793 context = Context(TLSv1_METHOD)
794 context.set_passwd_cb(passphraseCallback)
795 self.assertRaises(Error, context.use_privatekey_file, pemFile)
796
797
798 def test_passwd_callback_non_string(self):
799 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900800 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400801 passphrase callback returns a true non-string value.
802 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400803 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400804 def passphraseCallback(maxlen, verify, extra):
805 return 10
806
807 context = Context(TLSv1_METHOD)
808 context.set_passwd_cb(passphraseCallback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809 self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400810
811
812 def test_passwd_callback_too_long(self):
813 """
814 If the passphrase returned by the passphrase callback returns a string
815 longer than the indicated maximum length, it is truncated.
816 """
817 # A priori knowledge!
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400818 passphrase = b("x") * 1024
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400819 pemFile = self._write_encrypted_pem(passphrase)
820 def passphraseCallback(maxlen, verify, extra):
821 assert maxlen == 1024
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400822 return passphrase + b("y")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400823
824 context = Context(TLSv1_METHOD)
825 context.set_passwd_cb(passphraseCallback)
826 # This shall succeed because the truncated result is the correct
827 # passphrase.
828 context.use_privatekey_file(pemFile)
829
830
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400831 def test_set_info_callback(self):
832 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900833 :py:obj:`Context.set_info_callback` accepts a callable which will be invoked
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400834 when certain information about an SSL connection is available.
835 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500836 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400837
838 clientSSL = Connection(Context(TLSv1_METHOD), client)
839 clientSSL.set_connect_state()
840
841 called = []
842 def info(conn, where, ret):
843 called.append((conn, where, ret))
844 context = Context(TLSv1_METHOD)
845 context.set_info_callback(info)
846 context.use_certificate(
847 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
848 context.use_privatekey(
849 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
850
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400851 serverSSL = Connection(context, server)
852 serverSSL.set_accept_state()
853
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500854 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400855
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500856 # The callback must always be called with a Connection instance as the
857 # first argument. It would probably be better to split this into
858 # separate tests for client and server side info callbacks so we could
859 # assert it is called with the right Connection instance. It would
860 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500861 notConnections = [
862 conn for (conn, where, ret) in called
863 if not isinstance(conn, Connection)]
864 self.assertEqual(
865 [], notConnections,
866 "Some info callback arguments were not Connection instaces.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400867
868
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400869 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400870 """
871 Create a client context which will verify the peer certificate and call
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400872 its :py:obj:`load_verify_locations` method with the given arguments.
873 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400874 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500875 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400876
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400877 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400878 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400879 # Require that the server certificate verify properly or the
880 # connection will fail.
881 clientContext.set_verify(
882 VERIFY_PEER,
883 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
884
885 clientSSL = Connection(clientContext, client)
886 clientSSL.set_connect_state()
887
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400888 serverContext = Context(TLSv1_METHOD)
889 serverContext.use_certificate(
890 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
891 serverContext.use_privatekey(
892 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
893
894 serverSSL = Connection(serverContext, server)
895 serverSSL.set_accept_state()
896
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400897 # Without load_verify_locations above, the handshake
898 # will fail:
899 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
900 # 'certificate verify failed')]
901 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400902
903 cert = clientSSL.get_peer_certificate()
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400904 self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400905
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500906
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400907 def test_load_verify_file(self):
908 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900909 :py:obj:`Context.load_verify_locations` accepts a file name and uses the
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400910 certificates within for verification purposes.
911 """
912 cafile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400913 fObj = open(cafile, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400914 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400915 fObj.close()
916
917 self._load_verify_locations_test(cafile)
918
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400919
920 def test_load_verify_invalid_file(self):
921 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900922 :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when passed a
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400923 non-existent cafile.
924 """
925 clientContext = Context(TLSv1_METHOD)
926 self.assertRaises(
927 Error, clientContext.load_verify_locations, self.mktemp())
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400928
929
930 def test_load_verify_directory(self):
931 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900932 :py:obj:`Context.load_verify_locations` accepts a directory name and uses
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400933 the certificates within for verification purposes.
934 """
935 capath = self.mktemp()
936 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400937 # Hash values computed manually with c_rehash to avoid depending on
938 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
939 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500940 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400941 cafile = join(capath, name)
942 fObj = open(cafile, 'w')
943 fObj.write(cleartextCertificatePEM.decode('ascii'))
944 fObj.close()
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400945
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400946 self._load_verify_locations_test(None, capath)
947
948
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400949 def test_load_verify_locations_wrong_args(self):
950 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900951 :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if called with
952 the wrong number of arguments or with non-:py:obj:`str` arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400953 """
954 context = Context(TLSv1_METHOD)
955 self.assertRaises(TypeError, context.load_verify_locations)
956 self.assertRaises(TypeError, context.load_verify_locations, object())
957 self.assertRaises(TypeError, context.load_verify_locations, object(), object())
958 self.assertRaises(TypeError, context.load_verify_locations, None, None, None)
959
960
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400961 if platform == "win32":
962 "set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400963 "See LP#404343 and LP#404344."
964 else:
965 def test_set_default_verify_paths(self):
966 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900967 :py:obj:`Context.set_default_verify_paths` causes the platform-specific CA
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400968 certificate locations to be used for verification purposes.
969 """
970 # Testing this requires a server with a certificate signed by one of
971 # the CAs in the platform CA location. Getting one of those costs
972 # money. Fortunately (or unfortunately, depending on your
973 # perspective), it's easy to think of a public server on the
974 # internet which has such a certificate. Connecting to the network
975 # in a unit test is bad, but it's the only way I can think of to
976 # really test this. -exarkun
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400977
Alex Gaynorb586da32014-11-15 09:22:21 -0800978 # Arg, verisign.com doesn't speak anything newer than TLS 1.0
979 context = Context(TLSv1_METHOD)
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400980 context.set_default_verify_paths()
981 context.set_verify(
Ziga Seilnacht44611bf2009-08-31 20:49:30 +0200982 VERIFY_PEER,
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400983 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400984
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400985 client = socket()
986 client.connect(('verisign.com', 443))
987 clientSSL = Connection(context, client)
988 clientSSL.set_connect_state()
989 clientSSL.do_handshake()
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500990 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400991 self.assertTrue(clientSSL.recv(1024))
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -0400992
993
994 def test_set_default_verify_paths_signature(self):
995 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900996 :py:obj:`Context.set_default_verify_paths` takes no arguments and raises
997 :py:obj:`TypeError` if given any.
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -0400998 """
999 context = Context(TLSv1_METHOD)
1000 self.assertRaises(TypeError, context.set_default_verify_paths, None)
1001 self.assertRaises(TypeError, context.set_default_verify_paths, 1)
1002 self.assertRaises(TypeError, context.set_default_verify_paths, "")
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001003
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001004
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001005 def test_add_extra_chain_cert_invalid_cert(self):
1006 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001007 :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if called with
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001008 other than one argument or if called with an object which is not an
Jonathan Ballet648875f2011-07-16 14:14:58 +09001009 instance of :py:obj:`X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001010 """
1011 context = Context(TLSv1_METHOD)
1012 self.assertRaises(TypeError, context.add_extra_chain_cert)
1013 self.assertRaises(TypeError, context.add_extra_chain_cert, object())
1014 self.assertRaises(TypeError, context.add_extra_chain_cert, object(), object())
1015
1016
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001017 def _handshake_test(self, serverContext, clientContext):
1018 """
1019 Verify that a client and server created with the given contexts can
1020 successfully handshake and communicate.
1021 """
1022 serverSocket, clientSocket = socket_pair()
1023
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001024 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001025 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001026
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001027 client = Connection(clientContext, clientSocket)
1028 client.set_connect_state()
1029
1030 # Make them talk to each other.
1031 # self._interactInMemory(client, server)
1032 for i in range(3):
1033 for s in [client, server]:
1034 try:
1035 s.do_handshake()
1036 except WantReadError:
1037 pass
1038
1039
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001040 def test_set_verify_callback_connection_argument(self):
1041 """
1042 The first argument passed to the verify callback is the
1043 :py:class:`Connection` instance for which verification is taking place.
1044 """
1045 serverContext = Context(TLSv1_METHOD)
1046 serverContext.use_privatekey(
1047 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1048 serverContext.use_certificate(
1049 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1050 serverConnection = Connection(serverContext, None)
1051
1052 class VerifyCallback(object):
1053 def callback(self, connection, *args):
1054 self.connection = connection
1055 return 1
1056
1057 verify = VerifyCallback()
1058 clientContext = Context(TLSv1_METHOD)
1059 clientContext.set_verify(VERIFY_PEER, verify.callback)
1060 clientConnection = Connection(clientContext, None)
1061 clientConnection.set_connect_state()
1062
1063 self._handshakeInMemory(clientConnection, serverConnection)
1064
1065 self.assertIdentical(verify.connection, clientConnection)
1066
1067
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001068 def test_set_verify_callback_exception(self):
1069 """
1070 If the verify callback passed to :py:obj:`Context.set_verify` raises an
1071 exception, verification fails and the exception is propagated to the
1072 caller of :py:obj:`Connection.do_handshake`.
1073 """
1074 serverContext = Context(TLSv1_METHOD)
1075 serverContext.use_privatekey(
1076 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1077 serverContext.use_certificate(
1078 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1079
1080 clientContext = Context(TLSv1_METHOD)
1081 def verify_callback(*args):
1082 raise Exception("silly verify failure")
1083 clientContext.set_verify(VERIFY_PEER, verify_callback)
1084
1085 exc = self.assertRaises(
1086 Exception, self._handshake_test, serverContext, clientContext)
1087 self.assertEqual("silly verify failure", str(exc))
1088
1089
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001090 def test_add_extra_chain_cert(self):
1091 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001092 :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509` instance to add to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001093 the certificate chain.
1094
Jonathan Ballet648875f2011-07-16 14:14:58 +09001095 See :py:obj:`_create_certificate_chain` for the details of the certificate
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001096 chain tested.
1097
1098 The chain is tested by starting a server with scert and connecting
1099 to it with a client which trusts cacert and requires verification to
1100 succeed.
1101 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001102 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001103 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1104
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001105 # Dump the CA certificate to a file because that's the only way to load
1106 # it as a trusted CA in the client context.
1107 for cert, name in [(cacert, 'ca.pem'), (icert, 'i.pem'), (scert, 's.pem')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001108 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001109 fObj.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001110 fObj.close()
1111
1112 for key, name in [(cakey, 'ca.key'), (ikey, 'i.key'), (skey, 's.key')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001113 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001114 fObj.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001115 fObj.close()
1116
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001117 # Create the server context
1118 serverContext = Context(TLSv1_METHOD)
1119 serverContext.use_privatekey(skey)
1120 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001121 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001122 serverContext.add_extra_chain_cert(icert)
1123
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001124 # Create the client
1125 clientContext = Context(TLSv1_METHOD)
1126 clientContext.set_verify(
1127 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001128 clientContext.load_verify_locations(b"ca.pem")
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001129
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001130 # Try it out.
1131 self._handshake_test(serverContext, clientContext)
1132
1133
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001134 def test_use_certificate_chain_file(self):
1135 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001136 :py:obj:`Context.use_certificate_chain_file` reads a certificate chain from
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001137 the specified file.
1138
1139 The chain is tested by starting a server with scert and connecting
1140 to it with a client which trusts cacert and requires verification to
1141 succeed.
1142 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001143 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001144 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1145
1146 # Write out the chain file.
1147 chainFile = self.mktemp()
Jean-Paul Calderoned8607982014-01-18 10:30:55 -05001148 fObj = open(chainFile, 'wb')
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001149 # Most specific to least general.
Jean-Paul Calderoned8607982014-01-18 10:30:55 -05001150 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1151 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1152 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001153 fObj.close()
1154
1155 serverContext = Context(TLSv1_METHOD)
1156 serverContext.use_certificate_chain_file(chainFile)
1157 serverContext.use_privatekey(skey)
1158
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001159 fObj = open('ca.pem', 'w')
1160 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001161 fObj.close()
1162
1163 clientContext = Context(TLSv1_METHOD)
1164 clientContext.set_verify(
1165 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001166 clientContext.load_verify_locations(b"ca.pem")
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001167
1168 self._handshake_test(serverContext, clientContext)
1169
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001170
1171 def test_use_certificate_chain_file_wrong_args(self):
1172 """
1173 :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
1174 if passed zero or more than one argument or when passed a non-byte
1175 string single argument. It also raises :py:obj:`OpenSSL.SSL.Error` when
1176 passed a bad chain file name (for example, the name of a file which does
1177 not exist).
1178 """
1179 context = Context(TLSv1_METHOD)
1180 self.assertRaises(TypeError, context.use_certificate_chain_file)
1181 self.assertRaises(TypeError, context.use_certificate_chain_file, object())
1182 self.assertRaises(TypeError, context.use_certificate_chain_file, b"foo", object())
1183
1184 self.assertRaises(Error, context.use_certificate_chain_file, self.mktemp())
1185
Jean-Paul Calderonee0d79362010-08-03 18:46:46 -04001186 # XXX load_client_ca
1187 # XXX set_session_id
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001188
1189 def test_get_verify_mode_wrong_args(self):
1190 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001191 :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001192 arguments.
1193 """
1194 context = Context(TLSv1_METHOD)
1195 self.assertRaises(TypeError, context.get_verify_mode, None)
1196
1197
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001198 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001199 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001200 :py:obj:`Context.get_verify_mode` returns the verify mode flags previously
1201 passed to :py:obj:`Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001202 """
1203 context = Context(TLSv1_METHOD)
1204 self.assertEquals(context.get_verify_mode(), 0)
1205 context.set_verify(
1206 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
1207 self.assertEquals(
1208 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1209
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001210
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001211 if not PY3:
1212 def test_set_verify_mode_long(self):
1213 """
1214 On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
1215 type :py:obj:`long` as well as :py:obj:`int`.
1216 """
1217 context = Context(TLSv1_METHOD)
1218 self.assertEquals(context.get_verify_mode(), 0)
1219 context.set_verify(
1220 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None)
1221 self.assertEquals(
1222 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1223
1224
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001225 def test_load_tmp_dh_wrong_args(self):
1226 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001227 :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with the wrong
1228 number of arguments or with a non-:py:obj:`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001229 """
1230 context = Context(TLSv1_METHOD)
1231 self.assertRaises(TypeError, context.load_tmp_dh)
1232 self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
1233 self.assertRaises(TypeError, context.load_tmp_dh, object())
1234
1235
1236 def test_load_tmp_dh_missing_file(self):
1237 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001238 :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the specified file
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001239 does not exist.
1240 """
1241 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001242 self.assertRaises(Error, context.load_tmp_dh, b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001243
1244
1245 def test_load_tmp_dh(self):
1246 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001247 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001248 specified file.
1249 """
1250 context = Context(TLSv1_METHOD)
1251 dhfilename = self.mktemp()
1252 dhfile = open(dhfilename, "w")
1253 dhfile.write(dhparam)
1254 dhfile.close()
1255 context.load_tmp_dh(dhfilename)
1256 # XXX What should I assert here? -exarkun
1257
1258
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001259 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001260 """
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001261 :py:obj:`Context.set_tmp_ecdh` sets the elliptic curve for
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001262 Diffie-Hellman to the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001263 """
1264 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001265 for curve in get_elliptic_curves():
1266 # The only easily "assertable" thing is that it does not raise an
1267 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001268 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001269
1270
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001271 def test_set_cipher_list_bytes(self):
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001272 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001273 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
1274 ciphers which connections created with the context object will be able
1275 to choose from.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001276 """
1277 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001278 context.set_cipher_list(b"hello world:EXP-RC4-MD5")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001279 conn = Connection(context, None)
1280 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001281
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001282
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001283 def test_set_cipher_list_text(self):
1284 """
1285 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
1286 the ciphers which connections created with the context object will be
1287 able to choose from.
1288 """
1289 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -05001290 context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001291 conn = Connection(context, None)
1292 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
1293
1294
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295 def test_set_cipher_list_wrong_args(self):
1296 """
Jean-Paul Calderone17044832014-01-18 10:20:11 -05001297 :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
1298 passed zero arguments or more than one argument or when passed a
1299 non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001300 passed an incorrect cipher list string.
1301 """
1302 context = Context(TLSv1_METHOD)
1303 self.assertRaises(TypeError, context.set_cipher_list)
1304 self.assertRaises(TypeError, context.set_cipher_list, object())
1305 self.assertRaises(TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object())
1306
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001307 self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001308
1309
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001310 def test_set_session_cache_mode_wrong_args(self):
1311 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001312 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1313 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001314 """
1315 context = Context(TLSv1_METHOD)
1316 self.assertRaises(TypeError, context.set_session_cache_mode)
1317 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1318
1319
1320 def test_get_session_cache_mode_wrong_args(self):
1321 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001322 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1323 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001324 """
1325 context = Context(TLSv1_METHOD)
1326 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1327
1328
1329 def test_session_cache_mode(self):
1330 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001331 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1332 cached. The setting can be retrieved via
1333 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001334 """
1335 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001336 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001337 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1338 self.assertEqual(SESS_CACHE_OFF, off)
1339 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1340
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001341 if not PY3:
1342 def test_session_cache_mode_long(self):
1343 """
1344 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1345 of type :py:obj:`long` as well as :py:obj:`int`.
1346 """
1347 context = Context(TLSv1_METHOD)
1348 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1349 self.assertEqual(
1350 SESS_CACHE_BOTH, context.get_session_cache_mode())
1351
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001352
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001353 def test_get_cert_store(self):
1354 """
1355 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store` instance.
1356 """
1357 context = Context(TLSv1_METHOD)
1358 store = context.get_cert_store()
1359 self.assertIsInstance(store, X509Store)
1360
1361
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001362
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001363class ServerNameCallbackTests(TestCase, _LoopbackMixin):
1364 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001365 Tests for :py:obj:`Context.set_tlsext_servername_callback` and its interaction with
1366 :py:obj:`Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001367 """
1368 def test_wrong_args(self):
1369 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001370 :py:obj:`Context.set_tlsext_servername_callback` raises :py:obj:`TypeError` if called
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001371 with other than one argument.
1372 """
1373 context = Context(TLSv1_METHOD)
1374 self.assertRaises(TypeError, context.set_tlsext_servername_callback)
1375 self.assertRaises(
1376 TypeError, context.set_tlsext_servername_callback, 1, 2)
1377
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001378
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001379 def test_old_callback_forgotten(self):
1380 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001381 If :py:obj:`Context.set_tlsext_servername_callback` is used to specify a new
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001382 callback, the one it replaces is dereferenced.
1383 """
1384 def callback(connection):
1385 pass
1386
1387 def replacement(connection):
1388 pass
1389
1390 context = Context(TLSv1_METHOD)
1391 context.set_tlsext_servername_callback(callback)
1392
1393 tracker = ref(callback)
1394 del callback
1395
1396 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001397
1398 # One run of the garbage collector happens to work on CPython. PyPy
1399 # doesn't collect the underlying object until a second run for whatever
1400 # reason. That's fine, it still demonstrates our code has properly
1401 # dropped the reference.
1402 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001403 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001404
1405 callback = tracker()
1406 if callback is not None:
1407 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001408 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001409 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001410
1411
1412 def test_no_servername(self):
1413 """
1414 When a client specifies no server name, the callback passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001415 :py:obj:`Context.set_tlsext_servername_callback` is invoked and the result of
1416 :py:obj:`Connection.get_servername` is :py:obj:`None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001417 """
1418 args = []
1419 def servername(conn):
1420 args.append((conn, conn.get_servername()))
1421 context = Context(TLSv1_METHOD)
1422 context.set_tlsext_servername_callback(servername)
1423
1424 # Lose our reference to it. The Context is responsible for keeping it
1425 # alive now.
1426 del servername
1427 collect()
1428
1429 # Necessary to actually accept the connection
1430 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1431 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1432
1433 # Do a little connection to trigger the logic
1434 server = Connection(context, None)
1435 server.set_accept_state()
1436
1437 client = Connection(Context(TLSv1_METHOD), None)
1438 client.set_connect_state()
1439
1440 self._interactInMemory(server, client)
1441
1442 self.assertEqual([(server, None)], args)
1443
1444
1445 def test_servername(self):
1446 """
1447 When a client specifies a server name in its hello message, the callback
Jonathan Ballet648875f2011-07-16 14:14:58 +09001448 passed to :py:obj:`Contexts.set_tlsext_servername_callback` is invoked and the
1449 result of :py:obj:`Connection.get_servername` is that server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001450 """
1451 args = []
1452 def servername(conn):
1453 args.append((conn, conn.get_servername()))
1454 context = Context(TLSv1_METHOD)
1455 context.set_tlsext_servername_callback(servername)
1456
1457 # Necessary to actually accept the connection
1458 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1459 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1460
1461 # Do a little connection to trigger the logic
1462 server = Connection(context, None)
1463 server.set_accept_state()
1464
1465 client = Connection(Context(TLSv1_METHOD), None)
1466 client.set_connect_state()
1467 client.set_tlsext_host_name(b("foo1.example.com"))
1468
1469 self._interactInMemory(server, client)
1470
1471 self.assertEqual([(server, b("foo1.example.com"))], args)
1472
1473
1474
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05001475class SessionTests(TestCase):
1476 """
1477 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
1478 """
1479 def test_construction(self):
1480 """
1481 :py:class:`Session` can be constructed with no arguments, creating a new
1482 instance of that type.
1483 """
1484 new_session = Session()
1485 self.assertTrue(isinstance(new_session, Session))
1486
1487
1488 def test_construction_wrong_args(self):
1489 """
1490 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
1491 is raised.
1492 """
1493 self.assertRaises(TypeError, Session, 123)
1494 self.assertRaises(TypeError, Session, "hello")
1495 self.assertRaises(TypeError, Session, object())
1496
1497
1498
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001499class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05001500 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001501 Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05001502 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04001503 # XXX get_peer_certificate -> None
1504 # XXX sock_shutdown
1505 # XXX master_key -> TypeError
1506 # XXX server_random -> TypeError
1507 # XXX state_string
1508 # XXX connect -> TypeError
1509 # XXX connect_ex -> TypeError
1510 # XXX set_connect_state -> TypeError
1511 # XXX set_accept_state -> TypeError
1512 # XXX renegotiate_pending
1513 # XXX do_handshake -> TypeError
1514 # XXX bio_read -> TypeError
1515 # XXX recv -> TypeError
1516 # XXX send -> TypeError
1517 # XXX bio_write -> TypeError
1518
Rick Deane15b1472009-07-09 15:53:42 -05001519 def test_type(self):
1520 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001521 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same type object and
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001522 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05001523 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001524 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05001525 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001526 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05001527
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001528
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001529 def test_get_context(self):
1530 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001531 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance used to
1532 construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001533 """
1534 context = Context(TLSv1_METHOD)
1535 connection = Connection(context, None)
1536 self.assertIdentical(connection.get_context(), context)
1537
1538
1539 def test_get_context_wrong_args(self):
1540 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001541 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001542 arguments.
1543 """
1544 connection = Connection(Context(TLSv1_METHOD), None)
1545 self.assertRaises(TypeError, connection.get_context, None)
1546
1547
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001548 def test_set_context_wrong_args(self):
1549 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001550 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called with a
1551 non-:py:obj:`Context` instance argument or with any number of arguments other
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001552 than 1.
1553 """
1554 ctx = Context(TLSv1_METHOD)
1555 connection = Connection(ctx, None)
1556 self.assertRaises(TypeError, connection.set_context)
1557 self.assertRaises(TypeError, connection.set_context, object())
1558 self.assertRaises(TypeError, connection.set_context, "hello")
1559 self.assertRaises(TypeError, connection.set_context, 1)
1560 self.assertRaises(TypeError, connection.set_context, 1, 2)
1561 self.assertRaises(
1562 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
1563 self.assertIdentical(ctx, connection.get_context())
1564
1565
1566 def test_set_context(self):
1567 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001568 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context` instance to be used
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001569 for the connection.
1570 """
1571 original = Context(SSLv23_METHOD)
1572 replacement = Context(TLSv1_METHOD)
1573 connection = Connection(original, None)
1574 connection.set_context(replacement)
1575 self.assertIdentical(replacement, connection.get_context())
1576 # Lose our references to the contexts, just in case the Connection isn't
1577 # properly managing its own contributions to their reference counts.
1578 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001579 collect()
1580
1581
1582 def test_set_tlsext_host_name_wrong_args(self):
1583 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001584 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte string
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001585 argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09001586 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001587 """
1588 conn = Connection(Context(TLSv1_METHOD), None)
1589 self.assertRaises(TypeError, conn.set_tlsext_host_name)
1590 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
1591 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
1592 self.assertRaises(
1593 TypeError, conn.set_tlsext_host_name, b("with\0null"))
1594
1595 if version_info >= (3,):
1596 # On Python 3.x, don't accidentally implicitly convert from text.
1597 self.assertRaises(
1598 TypeError,
1599 conn.set_tlsext_host_name, b("example.com").decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001600
1601
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001602 def test_get_servername_wrong_args(self):
1603 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001604 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001605 arguments.
1606 """
1607 connection = Connection(Context(TLSv1_METHOD), None)
1608 self.assertRaises(TypeError, connection.get_servername, object())
1609 self.assertRaises(TypeError, connection.get_servername, 1)
1610 self.assertRaises(TypeError, connection.get_servername, "hello")
1611
1612
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001613 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001614 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001615 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001616 immediate read.
1617 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001618 connection = Connection(Context(TLSv1_METHOD), None)
1619 self.assertEquals(connection.pending(), 0)
1620
1621
1622 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001623 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001624 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001625 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001626 connection = Connection(Context(TLSv1_METHOD), None)
1627 self.assertRaises(TypeError, connection.pending, None)
1628
1629
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001630 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001631 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001632 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with a non-address
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001633 argument or with the wrong number of arguments.
1634 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001635 connection = Connection(Context(TLSv1_METHOD), socket())
1636 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001637 self.assertRaises(TypeError, connection.connect)
1638 self.assertRaises(TypeError, connection.connect, ("127.0.0.1", 1), None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001639
1640
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001641 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001642 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001643 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the underlying socket
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001644 connect method raises it.
1645 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001646 client = socket()
1647 context = Context(TLSv1_METHOD)
1648 clientSSL = Connection(context, client)
1649 exc = self.assertRaises(error, clientSSL.connect, ("127.0.0.1", 1))
Jean-Paul Calderone35adf9d2010-07-29 18:40:44 -04001650 self.assertEquals(exc.args[0], ECONNREFUSED)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001651
1652
1653 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001654 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001655 :py:obj:`Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001656 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001657 port = socket()
1658 port.bind(('', 0))
1659 port.listen(3)
1660
1661 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001662 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
1663 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001664
1665
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001666 if platform == "darwin":
1667 "connect_ex sometimes causes a kernel panic on OS X 10.6.4"
1668 else:
1669 def test_connect_ex(self):
1670 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001671 If there is a connection error, :py:obj:`Connection.connect_ex` returns the
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001672 errno instead of raising an exception.
1673 """
1674 port = socket()
1675 port.bind(('', 0))
1676 port.listen(3)
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001677
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001678 clientSSL = Connection(Context(TLSv1_METHOD), socket())
1679 clientSSL.setblocking(False)
1680 result = clientSSL.connect_ex(port.getsockname())
1681 expected = (EINPROGRESS, EWOULDBLOCK)
1682 self.assertTrue(
1683 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001684
1685
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001686 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001687 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001688 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001689 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001690 connection = Connection(Context(TLSv1_METHOD), socket())
1691 self.assertRaises(TypeError, connection.accept, None)
1692
1693
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001694 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001695 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001696 :py:obj:`Connection.accept` accepts a pending connection attempt and returns a
1697 tuple of a new :py:obj:`Connection` (the accepted client) and the address the
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001698 connection originated from.
1699 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001700 ctx = Context(TLSv1_METHOD)
1701 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1702 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001703 port = socket()
1704 portSSL = Connection(ctx, port)
1705 portSSL.bind(('', 0))
1706 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001707
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001708 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001709
1710 # Calling portSSL.getsockname() here to get the server IP address sounds
1711 # great, but frequently fails on Windows.
1712 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001713
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001714 serverSSL, address = portSSL.accept()
1715
1716 self.assertTrue(isinstance(serverSSL, Connection))
1717 self.assertIdentical(serverSSL.get_context(), ctx)
1718 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001719
1720
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001721 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001722 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001723 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with the wrong
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001724 number of arguments or with arguments other than integers.
1725 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001726 connection = Connection(Context(TLSv1_METHOD), None)
1727 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04001728 self.assertRaises(TypeError, connection.get_shutdown, None)
1729 self.assertRaises(TypeError, connection.set_shutdown)
1730 self.assertRaises(TypeError, connection.set_shutdown, None)
1731 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001732
1733
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001734 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001735 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001736 :py:obj:`Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001737 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001738 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001739 self.assertFalse(server.shutdown())
1740 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001741 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001742 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
1743 client.shutdown()
1744 self.assertEquals(client.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
1745 self.assertRaises(ZeroReturnError, server.recv, 1024)
1746 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001747
1748
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001749 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001750 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001751 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection shutdown
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001752 process.
1753 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001754 connection = Connection(Context(TLSv1_METHOD), socket())
1755 connection.set_shutdown(RECEIVED_SHUTDOWN)
1756 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1757
1758
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001759 if not PY3:
1760 def test_set_shutdown_long(self):
1761 """
1762 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
1763 of type :py:obj:`long` as well as :py:obj:`int`.
1764 """
1765 connection = Connection(Context(TLSv1_METHOD), socket())
1766 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
1767 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1768
1769
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001770 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001771 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001772 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called with other than
1773 one argument. :py:obj:`Connection.get_app_data` raises :py:obj:`TypeError` if called
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001774 with any arguments.
1775 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001776 conn = Connection(Context(TLSv1_METHOD), None)
1777 self.assertRaises(TypeError, conn.get_app_data, None)
1778 self.assertRaises(TypeError, conn.set_app_data)
1779 self.assertRaises(TypeError, conn.set_app_data, None, None)
1780
1781
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001782 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001783 """
1784 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001785 :py:obj:`Connection.set_app_data` and later retrieved with
1786 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001787 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001788 conn = Connection(Context(TLSv1_METHOD), None)
1789 app_data = object()
1790 conn.set_app_data(app_data)
1791 self.assertIdentical(conn.get_app_data(), app_data)
1792
1793
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001794 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001795 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001796 :py:obj:`Connection.makefile` is not implemented and calling that method raises
1797 :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001798 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001799 conn = Connection(Context(TLSv1_METHOD), None)
1800 self.assertRaises(NotImplementedError, conn.makefile)
1801
1802
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001803 def test_get_peer_cert_chain_wrong_args(self):
1804 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001805 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001806 arguments.
1807 """
1808 conn = Connection(Context(TLSv1_METHOD), None)
1809 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
1810 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
1811 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
1812 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
1813
1814
1815 def test_get_peer_cert_chain(self):
1816 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001817 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates which
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001818 the connected server returned for the certification verification.
1819 """
1820 chain = _create_certificate_chain()
1821 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1822
1823 serverContext = Context(TLSv1_METHOD)
1824 serverContext.use_privatekey(skey)
1825 serverContext.use_certificate(scert)
1826 serverContext.add_extra_chain_cert(icert)
1827 serverContext.add_extra_chain_cert(cacert)
1828 server = Connection(serverContext, None)
1829 server.set_accept_state()
1830
1831 # Create the client
1832 clientContext = Context(TLSv1_METHOD)
1833 clientContext.set_verify(VERIFY_NONE, verify_cb)
1834 client = Connection(clientContext, None)
1835 client.set_connect_state()
1836
1837 self._interactInMemory(client, server)
1838
1839 chain = client.get_peer_cert_chain()
1840 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001841 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001842 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001843 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001844 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001845 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001846 "Authority Certificate", chain[2].get_subject().CN)
1847
1848
1849 def test_get_peer_cert_chain_none(self):
1850 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001851 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the peer sends no
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001852 certificate chain.
1853 """
1854 ctx = Context(TLSv1_METHOD)
1855 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1856 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1857 server = Connection(ctx, None)
1858 server.set_accept_state()
1859 client = Connection(Context(TLSv1_METHOD), None)
1860 client.set_connect_state()
1861 self._interactInMemory(client, server)
1862 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001863
1864
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001865 def test_get_session_wrong_args(self):
1866 """
1867 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
1868 with any arguments.
1869 """
1870 ctx = Context(TLSv1_METHOD)
1871 server = Connection(ctx, None)
1872 self.assertRaises(TypeError, server.get_session, 123)
1873 self.assertRaises(TypeError, server.get_session, "hello")
1874 self.assertRaises(TypeError, server.get_session, object())
1875
1876
1877 def test_get_session_unconnected(self):
1878 """
1879 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
1880 an object which has not been connected.
1881 """
1882 ctx = Context(TLSv1_METHOD)
1883 server = Connection(ctx, None)
1884 session = server.get_session()
1885 self.assertIdentical(None, session)
1886
1887
1888 def test_server_get_session(self):
1889 """
1890 On the server side of a connection, :py:obj:`Connection.get_session`
1891 returns a :py:class:`Session` instance representing the SSL session for
1892 that connection.
1893 """
1894 server, client = self._loopback()
1895 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001896 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001897
1898
1899 def test_client_get_session(self):
1900 """
1901 On the client side of a connection, :py:obj:`Connection.get_session`
1902 returns a :py:class:`Session` instance representing the SSL session for
1903 that connection.
1904 """
1905 server, client = self._loopback()
1906 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001907 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001908
1909
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001910 def test_set_session_wrong_args(self):
1911 """
1912 If called with an object that is not an instance of :py:class:`Session`,
1913 or with other than one argument, :py:obj:`Connection.set_session` raises
1914 :py:obj:`TypeError`.
1915 """
1916 ctx = Context(TLSv1_METHOD)
1917 connection = Connection(ctx, None)
1918 self.assertRaises(TypeError, connection.set_session)
1919 self.assertRaises(TypeError, connection.set_session, 123)
1920 self.assertRaises(TypeError, connection.set_session, "hello")
1921 self.assertRaises(TypeError, connection.set_session, object())
1922 self.assertRaises(
1923 TypeError, connection.set_session, Session(), Session())
1924
1925
1926 def test_client_set_session(self):
1927 """
1928 :py:obj:`Connection.set_session`, when used prior to a connection being
1929 established, accepts a :py:class:`Session` instance and causes an
1930 attempt to re-use the session it represents when the SSL handshake is
1931 performed.
1932 """
1933 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1934 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1935 ctx = Context(TLSv1_METHOD)
1936 ctx.use_privatekey(key)
1937 ctx.use_certificate(cert)
1938 ctx.set_session_id("unity-test")
1939
1940 def makeServer(socket):
1941 server = Connection(ctx, socket)
1942 server.set_accept_state()
1943 return server
1944
1945 originalServer, originalClient = self._loopback(
1946 serverFactory=makeServer)
1947 originalSession = originalClient.get_session()
1948
1949 def makeClient(socket):
1950 client = self._loopbackClientFactory(socket)
1951 client.set_session(originalSession)
1952 return client
1953 resumedServer, resumedClient = self._loopback(
1954 serverFactory=makeServer,
1955 clientFactory=makeClient)
1956
1957 # This is a proxy: in general, we have no access to any unique
1958 # identifier for the session (new enough versions of OpenSSL expose a
1959 # hash which could be usable, but "new enough" is very, very new).
1960 # Instead, exploit the fact that the master key is re-used if the
1961 # session is re-used. As long as the master key for the two connections
1962 # is the same, the session was re-used!
1963 self.assertEqual(
1964 originalServer.master_key(), resumedServer.master_key())
1965
1966
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001967 def test_set_session_wrong_method(self):
1968 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05001969 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
1970 instance associated with a context using a different SSL method than the
1971 :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
1972 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001973 """
1974 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1975 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1976 ctx = Context(TLSv1_METHOD)
1977 ctx.use_privatekey(key)
1978 ctx.use_certificate(cert)
1979 ctx.set_session_id("unity-test")
1980
1981 def makeServer(socket):
1982 server = Connection(ctx, socket)
1983 server.set_accept_state()
1984 return server
1985
1986 originalServer, originalClient = self._loopback(
1987 serverFactory=makeServer)
1988 originalSession = originalClient.get_session()
1989
1990 def makeClient(socket):
1991 # Intentionally use a different, incompatible method here.
1992 client = Connection(Context(SSLv3_METHOD), socket)
1993 client.set_connect_state()
1994 client.set_session(originalSession)
1995 return client
1996
1997 self.assertRaises(
1998 Error,
1999 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2000
2001
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002002 def test_wantWriteError(self):
2003 """
2004 :py:obj:`Connection` methods which generate output raise
2005 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2006 fail indicating a should-write state.
2007 """
2008 client_socket, server_socket = socket_pair()
2009 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002010 # anything. Only write a single byte at a time so we can be sure we
2011 # completely fill the buffer. Even though the socket API is allowed to
2012 # signal a short write via its return value it seems this doesn't
2013 # always happen on all platforms (FreeBSD and OS X particular) for the
2014 # very last bit of available buffer space.
2015 msg = b"x"
2016 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002017 try:
2018 client_socket.send(msg)
2019 except error as e:
2020 if e.errno == EWOULDBLOCK:
2021 break
2022 raise
2023 else:
2024 self.fail(
2025 "Failed to fill socket buffer, cannot test BIO want write")
2026
2027 ctx = Context(TLSv1_METHOD)
2028 conn = Connection(ctx, client_socket)
2029 # Client's speak first, so make it an SSL client
2030 conn.set_connect_state()
2031 self.assertRaises(WantWriteError, conn.do_handshake)
2032
2033 # XXX want_read
2034
Fedor Brunner416f4a12014-03-28 13:18:38 +01002035 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002036 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002037 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2038 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002039 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002040 ctx = Context(TLSv1_METHOD)
2041 connection = Connection(ctx, None)
2042 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002043
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002044
Fedor Brunner416f4a12014-03-28 13:18:38 +01002045 def test_get_peer_finished_before_connect(self):
2046 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002047 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2048 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002049 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002050 ctx = Context(TLSv1_METHOD)
2051 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002052 self.assertEqual(connection.get_peer_finished(), None)
2053
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002054
Fedor Brunner416f4a12014-03-28 13:18:38 +01002055 def test_get_finished(self):
2056 """
2057 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002058 message send from client, or server. Finished messages are send during
2059 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002060 """
2061
Fedor Brunner5747b932014-03-05 14:22:34 +01002062 server, client = self._loopback()
2063
2064 self.assertNotEqual(server.get_finished(), None)
2065 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002066
Jean-Paul Calderoned979f232014-03-30 11:58:00 -04002067
Fedor Brunner416f4a12014-03-28 13:18:38 +01002068 def test_get_peer_finished(self):
2069 """
2070 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002071 message received from client, or server. Finished messages are send
2072 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002073 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002074 server, client = self._loopback()
2075
2076 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002077 self.assertTrue(len(server.get_peer_finished()) > 0)
2078
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002079
Fedor Brunner416f4a12014-03-28 13:18:38 +01002080 def test_tls_finished_message_symmetry(self):
2081 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002082 The TLS Finished message send by server must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002083 received by client.
2084
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002085 The TLS Finished message send by client must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002086 received by server.
2087 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002088 server, client = self._loopback()
2089
Fedor Brunner5747b932014-03-05 14:22:34 +01002090 self.assertEqual(server.get_finished(), client.get_peer_finished())
2091 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002092
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002093
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002094 def test_get_cipher_name_before_connect(self):
2095 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002096 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2097 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002098 """
2099 ctx = Context(TLSv1_METHOD)
2100 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002101 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002102
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002103
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002104 def test_get_cipher_name(self):
2105 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002106 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2107 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002108 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002109 server, client = self._loopback()
2110 server_cipher_name, client_cipher_name = \
2111 server.get_cipher_name(), client.get_cipher_name()
2112
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002113 self.assertIsInstance(server_cipher_name, text_type)
2114 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002115
2116 self.assertEqual(server_cipher_name, client_cipher_name)
2117
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002118
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002119 def test_get_cipher_version_before_connect(self):
2120 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002121 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2122 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002123 """
2124 ctx = Context(TLSv1_METHOD)
2125 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002126 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002127
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002128
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002129 def test_get_cipher_version(self):
2130 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002131 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2132 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002133 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002134 server, client = self._loopback()
2135 server_cipher_version, client_cipher_version = \
2136 server.get_cipher_version(), client.get_cipher_version()
2137
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002138 self.assertIsInstance(server_cipher_version, text_type)
2139 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002140
2141 self.assertEqual(server_cipher_version, client_cipher_version)
2142
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002143
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002144 def test_get_cipher_bits_before_connect(self):
2145 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002146 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2147 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002148 """
2149 ctx = Context(TLSv1_METHOD)
2150 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002151 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002152
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002153
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002154 def test_get_cipher_bits(self):
2155 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002156 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2157 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002158 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002159 server, client = self._loopback()
2160 server_cipher_bits, client_cipher_bits = \
2161 server.get_cipher_bits(), client.get_cipher_bits()
2162
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002163 self.assertIsInstance(server_cipher_bits, int)
2164 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002165
2166 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002167
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002168
2169
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002170class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002171 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002172 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002173 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002174 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002175 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002176 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002177 arguments.
2178 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002179 connection = Connection(Context(TLSv1_METHOD), None)
2180 self.assertRaises(TypeError, connection.get_cipher_list, None)
2181
2182
2183 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002184 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002185 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2186 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002187 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002188 connection = Connection(Context(TLSv1_METHOD), None)
2189 ciphers = connection.get_cipher_list()
2190 self.assertTrue(isinstance(ciphers, list))
2191 for cipher in ciphers:
2192 self.assertTrue(isinstance(cipher, str))
2193
2194
2195
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002196class ConnectionSendTests(TestCase, _LoopbackMixin):
2197 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002198 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002199 """
2200 def test_wrong_args(self):
2201 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002202 When called with arguments other than string argument for its first
2203 parameter or more than two arguments, :py:obj:`Connection.send` raises
2204 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002205 """
2206 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002207 self.assertRaises(TypeError, connection.send)
2208 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002209 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002210
2211
2212 def test_short_bytes(self):
2213 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002214 When passed a short byte string, :py:obj:`Connection.send` transmits all of it
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002215 and returns the number of bytes sent.
2216 """
2217 server, client = self._loopback()
2218 count = server.send(b('xy'))
2219 self.assertEquals(count, 2)
2220 self.assertEquals(client.recv(2), b('xy'))
2221
2222 try:
2223 memoryview
2224 except NameError:
2225 "cannot test sending memoryview without memoryview"
2226 else:
2227 def test_short_memoryview(self):
2228 """
2229 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002230 :py:obj:`Connection.send` transmits all of them and returns the number of
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002231 bytes sent.
2232 """
2233 server, client = self._loopback()
2234 count = server.send(memoryview(b('xy')))
2235 self.assertEquals(count, 2)
2236 self.assertEquals(client.recv(2), b('xy'))
2237
2238
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002239 try:
2240 buffer
2241 except NameError:
2242 "cannot test sending buffer without buffer"
2243 else:
2244 def test_short_buffer(self):
2245 """
2246 When passed a buffer containing a small number of bytes,
2247 :py:obj:`Connection.send` transmits all of them and returns the number of
2248 bytes sent.
2249 """
2250 server, client = self._loopback()
2251 count = server.send(buffer(b('xy')))
2252 self.assertEquals(count, 2)
2253 self.assertEquals(client.recv(2), b('xy'))
2254
2255
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002256
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002257class ConnectionSendallTests(TestCase, _LoopbackMixin):
2258 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002259 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002260 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002261 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002262 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002263 When called with arguments other than a string argument for its first
2264 parameter or with more than two arguments, :py:obj:`Connection.sendall`
2265 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002266 """
2267 connection = Connection(Context(TLSv1_METHOD), None)
2268 self.assertRaises(TypeError, connection.sendall)
2269 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002270 self.assertRaises(
2271 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002272
2273
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002274 def test_short(self):
2275 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002276 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002277 it.
2278 """
2279 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04002280 server.sendall(b('x'))
2281 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002282
2283
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002284 try:
2285 memoryview
2286 except NameError:
2287 "cannot test sending memoryview without memoryview"
2288 else:
2289 def test_short_memoryview(self):
2290 """
2291 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002292 :py:obj:`Connection.sendall` transmits all of them.
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002293 """
2294 server, client = self._loopback()
2295 server.sendall(memoryview(b('x')))
2296 self.assertEquals(client.recv(1), b('x'))
2297
2298
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002299 try:
2300 buffer
2301 except NameError:
2302 "cannot test sending buffers without buffers"
2303 else:
2304 def test_short_buffers(self):
2305 """
2306 When passed a buffer containing a small number of bytes,
2307 :py:obj:`Connection.sendall` transmits all of them.
2308 """
2309 server, client = self._loopback()
2310 server.sendall(buffer(b('x')))
2311 self.assertEquals(client.recv(1), b('x'))
2312
2313
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002314 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002315 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002316 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002317 it even if this requires multiple calls of an underlying write function.
2318 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002319 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04002320 # Should be enough, underlying SSL_write should only do 16k at a time.
2321 # On Windows, after 32k of bytes the write will block (forever - because
2322 # no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04002323 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002324 server.sendall(message)
2325 accum = []
2326 received = 0
2327 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04002328 data = client.recv(1024)
2329 accum.append(data)
2330 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04002331 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002332
2333
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002334 def test_closed(self):
2335 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002336 If the underlying socket is closed, :py:obj:`Connection.sendall` propagates the
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002337 write error from the low level write call.
2338 """
2339 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04002340 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002341 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002342 if platform == "win32":
2343 self.assertEqual(exc.args[0], ESHUTDOWN)
2344 else:
2345 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002346
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002347
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002348
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002349class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
2350 """
2351 Tests for SSL renegotiation APIs.
2352 """
2353 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002354 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002355 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002356 arguments.
2357 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002358 connection = Connection(Context(TLSv1_METHOD), None)
2359 self.assertRaises(TypeError, connection.renegotiate, None)
2360
2361
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002362 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002363 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002364 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if called with
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002365 any arguments.
2366 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002367 connection = Connection(Context(TLSv1_METHOD), None)
2368 self.assertRaises(TypeError, connection.total_renegotiations, None)
2369
2370
2371 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002372 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002373 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002374 renegotiations have happened.
2375 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002376 connection = Connection(Context(TLSv1_METHOD), None)
2377 self.assertEquals(connection.total_renegotiations(), 0)
2378
2379
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002380# def test_renegotiate(self):
2381# """
2382# """
2383# server, client = self._loopback()
2384
2385# server.send("hello world")
2386# self.assertEquals(client.recv(len("hello world")), "hello world")
2387
2388# self.assertEquals(server.total_renegotiations(), 0)
2389# self.assertTrue(server.renegotiate())
2390
2391# server.setblocking(False)
2392# client.setblocking(False)
2393# while server.renegotiate_pending():
2394# client.do_handshake()
2395# server.do_handshake()
2396
2397# self.assertEquals(server.total_renegotiations(), 1)
2398
2399
2400
2401
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002402class ErrorTests(TestCase):
2403 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002404 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002405 """
2406 def test_type(self):
2407 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002408 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002409 """
2410 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05002411 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05002412
2413
2414
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002415class ConstantsTests(TestCase):
2416 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002417 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002418
2419 These are values defined by OpenSSL intended only to be used as flags to
2420 OpenSSL APIs. The only assertions it seems can be made about them is
2421 their values.
2422 """
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002423 # unittest.TestCase has no skip mechanism
2424 if OP_NO_QUERY_MTU is not None:
2425 def test_op_no_query_mtu(self):
2426 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002427 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002428 :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002429 """
2430 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
2431 else:
2432 "OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002433
2434
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002435 if OP_COOKIE_EXCHANGE is not None:
2436 def test_op_cookie_exchange(self):
2437 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002438 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the value
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002439 of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002440 """
2441 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
2442 else:
2443 "OP_COOKIE_EXCHANGE unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002444
2445
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002446 if OP_NO_TICKET is not None:
2447 def test_op_no_ticket(self):
2448 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002449 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002450 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002451 """
2452 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderonecebd1782011-09-11 10:01:31 -04002453 else:
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002454 "OP_NO_TICKET unavailable - OpenSSL version may be too old"
Rick Dean5b7b6372009-04-01 11:34:06 -05002455
2456
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002457 if OP_NO_COMPRESSION is not None:
2458 def test_op_no_compression(self):
2459 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002460 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the value
2461 of :py:const:`SSL_OP_NO_COMPRESSION` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002462 """
2463 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
2464 else:
2465 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
2466
2467
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002468 def test_sess_cache_off(self):
2469 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002470 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
2471 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002472 """
2473 self.assertEqual(0x0, SESS_CACHE_OFF)
2474
2475
2476 def test_sess_cache_client(self):
2477 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002478 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
2479 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002480 """
2481 self.assertEqual(0x1, SESS_CACHE_CLIENT)
2482
2483
2484 def test_sess_cache_server(self):
2485 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002486 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
2487 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002488 """
2489 self.assertEqual(0x2, SESS_CACHE_SERVER)
2490
2491
2492 def test_sess_cache_both(self):
2493 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002494 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
2495 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002496 """
2497 self.assertEqual(0x3, SESS_CACHE_BOTH)
2498
2499
2500 def test_sess_cache_no_auto_clear(self):
2501 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002502 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
2503 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
2504 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002505 """
2506 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
2507
2508
2509 def test_sess_cache_no_internal_lookup(self):
2510 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002511 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
2512 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
2513 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002514 """
2515 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
2516
2517
2518 def test_sess_cache_no_internal_store(self):
2519 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002520 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
2521 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
2522 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002523 """
2524 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
2525
2526
2527 def test_sess_cache_no_internal(self):
2528 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002529 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
2530 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
2531 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002532 """
2533 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
2534
2535
Jean-Paul Calderoneeeee26a2009-04-27 11:24:30 -04002536
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002537class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05002538 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002539 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05002540 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002541 def _server(self, sock):
2542 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002543 Create a new server-side SSL :py:obj:`Connection` object wrapped around
2544 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002545 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002546 # Create the server side Connection. This is mostly setup boilerplate
2547 # - use TLSv1, use a particular certificate, etc.
2548 server_ctx = Context(TLSv1_METHOD)
2549 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2550 server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2551 server_store = server_ctx.get_cert_store()
2552 server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2553 server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2554 server_ctx.check_privatekey()
2555 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002556 # Here the Connection is actually created. If None is passed as the 2nd
2557 # parameter, it indicates a memory BIO should be created.
2558 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002559 server_conn.set_accept_state()
2560 return server_conn
2561
2562
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002563 def _client(self, sock):
2564 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002565 Create a new client-side SSL :py:obj:`Connection` object wrapped around
2566 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002567 """
2568 # Now create the client side Connection. Similar boilerplate to the
2569 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002570 client_ctx = Context(TLSv1_METHOD)
2571 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2572 client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2573 client_store = client_ctx.get_cert_store()
2574 client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
2575 client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
2576 client_ctx.check_privatekey()
2577 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002578 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002579 client_conn.set_connect_state()
2580 return client_conn
2581
2582
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002583 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002584 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002585 Two :py:obj:`Connection`s which use memory BIOs can be manually connected by
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002586 reading from the output of each and writing those bytes to the input of
2587 the other and in this way establish a connection and exchange
2588 application-level bytes with each other.
2589 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002590 server_conn = self._server(None)
2591 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002592
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002593 # There should be no key or nonces yet.
2594 self.assertIdentical(server_conn.master_key(), None)
2595 self.assertIdentical(server_conn.client_random(), None)
2596 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002597
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002598 # First, the handshake needs to happen. We'll deliver bytes back and
2599 # forth between the client and server until neither of them feels like
2600 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002601 self.assertIdentical(
2602 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002603
2604 # Now that the handshake is done, there should be a key and nonces.
2605 self.assertNotIdentical(server_conn.master_key(), None)
2606 self.assertNotIdentical(server_conn.client_random(), None)
2607 self.assertNotIdentical(server_conn.server_random(), None)
Jean-Paul Calderone6c051e62009-07-05 13:50:34 -04002608 self.assertEquals(server_conn.client_random(), client_conn.client_random())
2609 self.assertEquals(server_conn.server_random(), client_conn.server_random())
2610 self.assertNotEquals(server_conn.client_random(), server_conn.server_random())
2611 self.assertNotEquals(client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002612
2613 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002614 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05002615
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002616 server_conn.write(important_message)
2617 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002618 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002619 (client_conn, important_message))
2620
2621 client_conn.write(important_message[::-1])
2622 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002623 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002624 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05002625
2626
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002627 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05002628 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002629 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002630
2631 This is primarily to rule out the memory BIO code as the source of
Jonathan Ballet648875f2011-07-16 14:14:58 +09002632 any problems encountered while passing data over a :py:obj:`Connection` (if
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002633 this test fails, there must be a problem outside the memory BIO
2634 code, as no memory BIO is involved here). Even though this isn't a
2635 memory BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05002636 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04002637 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05002638
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002639 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05002640 client_conn.send(important_message)
2641 msg = server_conn.recv(1024)
2642 self.assertEqual(msg, important_message)
2643
2644 # Again in the other direction, just for fun.
2645 important_message = important_message[::-1]
2646 server_conn.send(important_message)
2647 msg = client_conn.recv(1024)
2648 self.assertEqual(msg, important_message)
2649
2650
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04002651 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05002652 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002653 Test that :py:obj:`OpenSSL.SSL.bio_read` and :py:obj:`OpenSSL.SSL.bio_write` don't
2654 work on :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05002655 """
2656 context = Context(SSLv3_METHOD)
2657 client = socket()
2658 clientSSL = Connection(context, client)
2659 self.assertRaises( TypeError, clientSSL.bio_read, 100)
2660 self.assertRaises( TypeError, clientSSL.bio_write, "foo")
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04002661 self.assertRaises( TypeError, clientSSL.bio_shutdown )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002662
2663
2664 def test_outgoingOverflow(self):
2665 """
2666 If more bytes than can be written to the memory BIO are passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002667 :py:obj:`Connection.send` at once, the number of bytes which were written is
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002668 returned and that many bytes from the beginning of the input can be
2669 read from the other end of the connection.
2670 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002671 server = self._server(None)
2672 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002673
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002674 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002675
2676 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002677 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002678 # Sanity check. We're trying to test what happens when the entire
2679 # input can't be sent. If the entire input was sent, this test is
2680 # meaningless.
2681 self.assertTrue(sent < size)
2682
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002683 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002684 self.assertIdentical(receiver, server)
2685
2686 # We can rely on all of these bytes being received at once because
2687 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
2688 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002689
2690
2691 def test_shutdown(self):
2692 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002693 :py:obj:`Connection.bio_shutdown` signals the end of the data stream from
2694 which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002695 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002696 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002697 server.bio_shutdown()
2698 e = self.assertRaises(Error, server.recv, 1024)
2699 # We don't want WantReadError or ZeroReturnError or anything - it's a
2700 # handshake failure.
2701 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002702
2703
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002704 def test_unexpectedEndOfFile(self):
2705 """
2706 If the connection is lost before an orderly SSL shutdown occurs,
2707 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
2708 "Unexpected EOF".
2709 """
2710 server_conn, client_conn = self._loopback()
2711 client_conn.sock_shutdown(SHUT_RDWR)
2712 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
2713 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
2714
2715
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002716 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002717 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002718 Verify the return value of the :py:obj:`get_client_ca_list` method for server and client connections.
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002719
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002720 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002721 before the client and server are connected to each other. This
2722 function should specify a list of CAs for the server to send to the
2723 client and return that same list. The list will be used to verify
Jonathan Ballet648875f2011-07-16 14:14:58 +09002724 that :py:obj:`get_client_ca_list` returns the proper value at various
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002725 times.
2726 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002727 server = self._server(None)
2728 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002729 self.assertEqual(client.get_client_ca_list(), [])
2730 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002731 ctx = server.get_context()
2732 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002733 self.assertEqual(client.get_client_ca_list(), [])
2734 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002735 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002736 self.assertEqual(client.get_client_ca_list(), expected)
2737 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002738
2739
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002740 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002741 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002742 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if called with a
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002743 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002744 """
2745 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002746 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
2747 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
2748 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002749
2750
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002751 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002752 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002753 If passed an empty list, :py:obj:`Context.set_client_ca_list` configures the
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002754 context to send no CA names to the client and, on both the server and
Jonathan Ballet648875f2011-07-16 14:14:58 +09002755 client sides, :py:obj:`Connection.get_client_ca_list` returns an empty list
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002756 after the connection is set up.
2757 """
2758 def no_ca(ctx):
2759 ctx.set_client_ca_list([])
2760 return []
2761 self._check_client_ca_list(no_ca)
2762
2763
2764 def test_set_one_ca_list(self):
2765 """
2766 If passed a list containing a single X509Name,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002767 :py:obj:`Context.set_client_ca_list` configures the context to send that CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002768 name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002769 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002770 X509Name after the connection is set up.
2771 """
2772 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2773 cadesc = cacert.get_subject()
2774 def single_ca(ctx):
2775 ctx.set_client_ca_list([cadesc])
2776 return [cadesc]
2777 self._check_client_ca_list(single_ca)
2778
2779
2780 def test_set_multiple_ca_list(self):
2781 """
2782 If passed a list containing multiple X509Name objects,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002783 :py:obj:`Context.set_client_ca_list` configures the context to send those CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002784 names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002785 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002786 X509Names after the connection is set up.
2787 """
2788 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2789 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2790
2791 sedesc = secert.get_subject()
2792 cldesc = clcert.get_subject()
2793
2794 def multiple_ca(ctx):
2795 L = [sedesc, cldesc]
2796 ctx.set_client_ca_list(L)
2797 return L
2798 self._check_client_ca_list(multiple_ca)
2799
2800
2801 def test_reset_ca_list(self):
2802 """
2803 If called multiple times, only the X509Names passed to the final call
Jonathan Ballet648875f2011-07-16 14:14:58 +09002804 of :py:obj:`Context.set_client_ca_list` are used to configure the CA names
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002805 sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002806 """
2807 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2808 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2809 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2810
2811 cadesc = cacert.get_subject()
2812 sedesc = secert.get_subject()
2813 cldesc = clcert.get_subject()
2814
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002815 def changed_ca(ctx):
2816 ctx.set_client_ca_list([sedesc, cldesc])
2817 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002818 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002819 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002820
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002821
2822 def test_mutated_ca_list(self):
2823 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002824 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002825 afterwards, this does not affect the list of CA names sent to the
2826 client.
2827 """
2828 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2829 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2830
2831 cadesc = cacert.get_subject()
2832 sedesc = secert.get_subject()
2833
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002834 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002835 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002836 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002837 L.append(sedesc)
2838 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002839 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002840
2841
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002842 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002843 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002844 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called with a non-X509
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002845 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002846 """
2847 ctx = Context(TLSv1_METHOD)
2848 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002849 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002850 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002851 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002852
2853
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002854 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002855 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002856 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09002857 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002858 """
2859 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2860 cadesc = cacert.get_subject()
2861 def single_ca(ctx):
2862 ctx.add_client_ca(cacert)
2863 return [cadesc]
2864 self._check_client_ca_list(single_ca)
2865
2866
2867 def test_multiple_add_client_ca(self):
2868 """
2869 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09002870 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002871 """
2872 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2873 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2874
2875 cadesc = cacert.get_subject()
2876 sedesc = secert.get_subject()
2877
2878 def multiple_ca(ctx):
2879 ctx.add_client_ca(cacert)
2880 ctx.add_client_ca(secert)
2881 return [cadesc, sedesc]
2882 self._check_client_ca_list(multiple_ca)
2883
2884
2885 def test_set_and_add_client_ca(self):
2886 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002887 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
2888 :py:obj:`Context.add_client_ca` results in using the CA names from the first
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002889 call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002890 """
2891 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2892 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2893 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2894
2895 cadesc = cacert.get_subject()
2896 sedesc = secert.get_subject()
2897 cldesc = clcert.get_subject()
2898
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002899 def mixed_set_add_ca(ctx):
2900 ctx.set_client_ca_list([cadesc, sedesc])
2901 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002902 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002903 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002904
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002905
2906 def test_set_after_add_client_ca(self):
2907 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002908 A call to :py:obj:`Context.set_client_ca_list` after a call to
2909 :py:obj:`Context.add_client_ca` replaces the CA name specified by the former
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002910 call with the names specified by the latter cal.
2911 """
2912 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2913 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2914 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2915
2916 cadesc = cacert.get_subject()
2917 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002918
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002919 def set_replaces_add_ca(ctx):
2920 ctx.add_client_ca(clcert)
2921 ctx.set_client_ca_list([cadesc])
2922 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002923 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002924 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002925
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002926
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002927
2928class ConnectionBIOTests(TestCase):
2929 """
2930 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
2931 """
2932 def test_wantReadError(self):
2933 """
2934 :py:obj:`Connection.bio_read` raises :py:obj:`OpenSSL.SSL.WantReadError`
2935 if there are no bytes available to be read from the BIO.
2936 """
2937 ctx = Context(TLSv1_METHOD)
2938 conn = Connection(ctx, None)
2939 self.assertRaises(WantReadError, conn.bio_read, 1024)
2940
2941
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002942 def test_buffer_size(self):
2943 """
2944 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
2945 number of bytes to read and return.
2946 """
2947 ctx = Context(TLSv1_METHOD)
2948 conn = Connection(ctx, None)
2949 conn.set_connect_state()
2950 try:
2951 conn.do_handshake()
2952 except WantReadError:
2953 pass
2954 data = conn.bio_read(2)
2955 self.assertEqual(2, len(data))
2956
2957
2958 if not PY3:
2959 def test_buffer_size_long(self):
2960 """
2961 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
2962 :py:obj:`long` as well as :py:obj:`int`.
2963 """
2964 ctx = Context(TLSv1_METHOD)
2965 conn = Connection(ctx, None)
2966 conn.set_connect_state()
2967 try:
2968 conn.do_handshake()
2969 except WantReadError:
2970 pass
2971 data = conn.bio_read(long(2))
2972 self.assertEqual(2, len(data))
2973
2974
2975
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002976
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04002977class InfoConstantTests(TestCase):
2978 """
2979 Tests for assorted constants exposed for use in info callbacks.
2980 """
2981 def test_integers(self):
2982 """
2983 All of the info constants are integers.
2984
2985 This is a very weak test. It would be nice to have one that actually
2986 verifies that as certain info events happen, the value passed to the
2987 info callback matches up with the constant exposed by OpenSSL.SSL.
2988 """
2989 for const in [
2990 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
2991 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
2992 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
2993 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
2994 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
2995 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE]:
2996
2997 self.assertTrue(isinstance(const, int))
2998
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02002999
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003000if __name__ == '__main__':
3001 main()