blob: db33afb3db2ef0b9f3741360b0169a74f5697fba [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
23
Jean-Paul Calderoneb41d1f42014-04-17 16:02:04 -040024from OpenSSL.SSL import _lib
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -040025from OpenSSL.SSL import OPENSSL_VERSION_NUMBER, SSLEAY_VERSION, SSLEAY_CFLAGS
26from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -040027from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040028from OpenSSL.SSL import (
29 SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD,
30 TLSv1_1_METHOD, TLSv1_2_METHOD)
31from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040032from OpenSSL.SSL import (
33 VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_CLIENT_ONCE, VERIFY_NONE)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040034
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040035from OpenSSL.SSL import (
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050036 SESS_CACHE_OFF, SESS_CACHE_CLIENT, SESS_CACHE_SERVER, SESS_CACHE_BOTH,
37 SESS_CACHE_NO_AUTO_CLEAR, SESS_CACHE_NO_INTERNAL_LOOKUP,
38 SESS_CACHE_NO_INTERNAL_STORE, SESS_CACHE_NO_INTERNAL)
Andy Lutomirskif05a2732014-03-13 17:22:25 -070039from OpenSSL.SSL import (
Andy Lutomirski61d7d392014-04-04 12:16:56 -070040 _Cryptography_HAS_EC, ELLIPTIC_CURVE_DESCRIPTIONS,
41 ECNotAvailable, UnknownObject)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -050042
43from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070044 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050045from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070046 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040047
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050048from OpenSSL.test.util import TestCase, b
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040049from OpenSSL.test.test_crypto import (
50 cleartextCertificatePEM, cleartextPrivateKeyPEM)
51from OpenSSL.test.test_crypto import (
52 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
53 root_cert_pem)
54
Jean-Paul Calderone4bccf5e2008-12-28 22:50:42 -050055try:
56 from OpenSSL.SSL import OP_NO_QUERY_MTU
57except ImportError:
58 OP_NO_QUERY_MTU = None
59try:
60 from OpenSSL.SSL import OP_COOKIE_EXCHANGE
61except ImportError:
62 OP_COOKIE_EXCHANGE = None
63try:
64 from OpenSSL.SSL import OP_NO_TICKET
65except ImportError:
66 OP_NO_TICKET = None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -040067
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040068try:
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -040069 from OpenSSL.SSL import OP_NO_COMPRESSION
70except ImportError:
71 OP_NO_COMPRESSION = None
72
73try:
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040074 from OpenSSL.SSL import MODE_RELEASE_BUFFERS
75except ImportError:
76 MODE_RELEASE_BUFFERS = None
77
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040078try:
79 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
80except ImportError:
81 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
82
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040083from OpenSSL.SSL import (
84 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
85 SSL_ST_OK, SSL_ST_RENEGOTIATE,
86 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
87 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
88 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
89 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040090
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040091# openssl dhparam 128 -out dh-128.pem (note that 128 is a small number of bits
92# to use)
93dhparam = """\
94-----BEGIN DH PARAMETERS-----
95MBYCEQCobsg29c9WZP/54oAPcwiDAgEC
96-----END DH PARAMETERS-----
97"""
98
99
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400100def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400101 return ok
102
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400103
Rick Deanb1ccd562009-07-09 23:52:39 -0500104def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400105 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400106 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400107 """
108 # Connect a pair of sockets
Rick Deanb1ccd562009-07-09 23:52:39 -0500109 port = socket()
110 port.bind(('', 0))
111 port.listen(1)
112 client = socket()
113 client.setblocking(False)
Jean-Paul Calderonef23c5d92009-07-23 17:58:15 -0400114 client.connect_ex(("127.0.0.1", port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400115 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500116 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500117
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400118 # Let's pass some unencrypted data to make sure our socket connection is
119 # fine. Just one byte, so we don't have to worry about buffers getting
120 # filled up or fragmentation.
Jean-Paul Calderone9e4eeae2010-08-22 21:32:52 -0400121 server.send(b("x"))
122 assert client.recv(1024) == b("x")
123 client.send(b("y"))
124 assert server.recv(1024) == b("y")
Rick Deanb1ccd562009-07-09 23:52:39 -0500125
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400126 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400127 server.setblocking(False)
128 client.setblocking(False)
129
Rick Deanb1ccd562009-07-09 23:52:39 -0500130 return (server, client)
131
132
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400133
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400134def handshake(client, server):
135 conns = [client, server]
136 while conns:
137 for conn in conns:
138 try:
139 conn.do_handshake()
140 except WantReadError:
141 pass
142 else:
143 conns.remove(conn)
144
145
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400146def _create_certificate_chain():
147 """
148 Construct and return a chain of certificates.
149
150 1. A new self-signed certificate authority certificate (cacert)
151 2. A new intermediate certificate signed by cacert (icert)
152 3. A new server certificate signed by icert (scert)
153 """
154 caext = X509Extension(b('basicConstraints'), False, b('CA:true'))
155
156 # Step 1
157 cakey = PKey()
158 cakey.generate_key(TYPE_RSA, 512)
159 cacert = X509()
160 cacert.get_subject().commonName = "Authority Certificate"
161 cacert.set_issuer(cacert.get_subject())
162 cacert.set_pubkey(cakey)
163 cacert.set_notBefore(b("20000101000000Z"))
164 cacert.set_notAfter(b("20200101000000Z"))
165 cacert.add_extensions([caext])
166 cacert.set_serial_number(0)
167 cacert.sign(cakey, "sha1")
168
169 # Step 2
170 ikey = PKey()
171 ikey.generate_key(TYPE_RSA, 512)
172 icert = X509()
173 icert.get_subject().commonName = "Intermediate Certificate"
174 icert.set_issuer(cacert.get_subject())
175 icert.set_pubkey(ikey)
176 icert.set_notBefore(b("20000101000000Z"))
177 icert.set_notAfter(b("20200101000000Z"))
178 icert.add_extensions([caext])
179 icert.set_serial_number(0)
180 icert.sign(cakey, "sha1")
181
182 # Step 3
183 skey = PKey()
184 skey.generate_key(TYPE_RSA, 512)
185 scert = X509()
186 scert.get_subject().commonName = "Server Certificate"
187 scert.set_issuer(icert.get_subject())
188 scert.set_pubkey(skey)
189 scert.set_notBefore(b("20000101000000Z"))
190 scert.set_notAfter(b("20200101000000Z"))
191 scert.add_extensions([
192 X509Extension(b('basicConstraints'), True, b('CA:false'))])
193 scert.set_serial_number(0)
194 scert.sign(ikey, "sha1")
195
196 return [(cakey, cacert), (ikey, icert), (skey, scert)]
197
198
199
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400200class _LoopbackMixin:
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400201 """
202 Helper mixin which defines methods for creating a connected socket pair and
203 for forcing two connected SSL sockets to talk to each other via memory BIOs.
204 """
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500205 def _loopbackClientFactory(self, socket):
206 client = Connection(Context(TLSv1_METHOD), socket)
207 client.set_connect_state()
208 return client
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400209
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500210
211 def _loopbackServerFactory(self, socket):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400212 ctx = Context(TLSv1_METHOD)
213 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
214 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500215 server = Connection(ctx, socket)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400216 server.set_accept_state()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500217 return server
218
219
220 def _loopback(self, serverFactory=None, clientFactory=None):
221 if serverFactory is None:
222 serverFactory = self._loopbackServerFactory
223 if clientFactory is None:
224 clientFactory = self._loopbackClientFactory
225
226 (server, client) = socket_pair()
227 server = serverFactory(server)
228 client = clientFactory(client)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400229
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400230 handshake(client, server)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400231
232 server.setblocking(True)
233 client.setblocking(True)
234 return server, client
235
236
237 def _interactInMemory(self, client_conn, server_conn):
238 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900239 Try to read application bytes from each of the two :py:obj:`Connection`
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400240 objects. Copy bytes back and forth between their send/receive buffers
241 for as long as there is anything to copy. When there is nothing more
Jonathan Ballet648875f2011-07-16 14:14:58 +0900242 to copy, return :py:obj:`None`. If one of them actually manages to deliver
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400243 some application bytes, return a two-tuple of the connection from which
244 the bytes were read and the bytes themselves.
245 """
246 wrote = True
247 while wrote:
248 # Loop until neither side has anything to say
249 wrote = False
250
251 # Copy stuff from each side's send buffer to the other side's
252 # receive buffer.
253 for (read, write) in [(client_conn, server_conn),
254 (server_conn, client_conn)]:
255
256 # Give the side a chance to generate some more bytes, or
257 # succeed.
258 try:
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400259 data = read.recv(2 ** 16)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400260 except WantReadError:
261 # It didn't succeed, so we'll hope it generated some
262 # output.
263 pass
264 else:
265 # It did succeed, so we'll stop now and let the caller deal
266 # with it.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400267 return (read, data)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400268
269 while True:
270 # Keep copying as long as there's more stuff there.
271 try:
272 dirty = read.bio_read(4096)
273 except WantReadError:
274 # Okay, nothing more waiting to be sent. Stop
275 # processing this send buffer.
276 break
277 else:
278 # Keep track of the fact that someone generated some
279 # output.
280 wrote = True
281 write.bio_write(dirty)
282
283
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400284
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400285class VersionTests(TestCase):
286 """
287 Tests for version information exposed by
Jonathan Ballet648875f2011-07-16 14:14:58 +0900288 :py:obj:`OpenSSL.SSL.SSLeay_version` and
289 :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400290 """
291 def test_OPENSSL_VERSION_NUMBER(self):
292 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900293 :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400294 byte and the patch, fix, minor, and major versions in the
295 nibbles above that.
296 """
297 self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
298
299
300 def test_SSLeay_version(self):
301 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900302 :py:obj:`SSLeay_version` takes a version type indicator and returns
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400303 one of a number of version strings based on that indicator.
304 """
305 versions = {}
306 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
307 SSLEAY_PLATFORM, SSLEAY_DIR]:
308 version = SSLeay_version(t)
309 versions[version] = t
310 self.assertTrue(isinstance(version, bytes))
311 self.assertEqual(len(versions), 5)
312
313
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400314
315class ContextTests(TestCase, _LoopbackMixin):
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400316 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900317 Unit tests for :py:obj:`OpenSSL.SSL.Context`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400318 """
319 def test_method(self):
320 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900321 :py:obj:`Context` can be instantiated with one of :py:obj:`SSLv2_METHOD`,
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400322 :py:obj:`SSLv3_METHOD`, :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
323 :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400324 """
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400325 methods = [
326 SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]
327 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400328 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400329
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400330
331 maybe = [SSLv2_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
332 for meth in maybe:
333 try:
334 Context(meth)
335 except (Error, ValueError):
336 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
337 # don't. Difficult to say in advance.
338 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400339
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400340 self.assertRaises(TypeError, Context, "")
341 self.assertRaises(ValueError, Context, 10)
342
343
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500344 if not PY3:
345 def test_method_long(self):
346 """
347 On Python 2 :py:class:`Context` accepts values of type
348 :py:obj:`long` as well as :py:obj:`int`.
349 """
350 Context(long(TLSv1_METHOD))
351
352
353
Rick Deane15b1472009-07-09 15:53:42 -0500354 def test_type(self):
355 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900356 :py:obj:`Context` and :py:obj:`ContextType` refer to the same type object and can be
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400357 used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500358 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400359 self.assertIdentical(Context, ContextType)
360 self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500361
362
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400363 def test_use_privatekey(self):
364 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900365 :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey` instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400366 """
367 key = PKey()
368 key.generate_key(TYPE_RSA, 128)
369 ctx = Context(TLSv1_METHOD)
370 ctx.use_privatekey(key)
371 self.assertRaises(TypeError, ctx.use_privatekey, "")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400372
373
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800374 def test_use_privatekey_file_missing(self):
375 """
376 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error`
377 when passed the name of a file which does not exist.
378 """
379 ctx = Context(TLSv1_METHOD)
380 self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
381
382
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500383 if not PY3:
384 def test_use_privatekey_file_long(self):
385 """
386 On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
387 filetype of type :py:obj:`long` as well as :py:obj:`int`.
388 """
389 pemfile = self.mktemp()
390
391 key = PKey()
392 key.generate_key(TYPE_RSA, 128)
393
394 with open(pemfile, "wt") as pem:
395 pem.write(
396 dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
397
398 ctx = Context(TLSv1_METHOD)
399 ctx.use_privatekey_file(pemfile, long(FILETYPE_PEM))
400
401
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800402 def test_use_certificate_wrong_args(self):
403 """
404 :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
405 when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as an
406 argument.
407 """
408 ctx = Context(TLSv1_METHOD)
409 self.assertRaises(TypeError, ctx.use_certificate)
410 self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
411 self.assertRaises(TypeError, ctx.use_certificate, X509(), "hello, world")
412
413
414 def test_use_certificate_uninitialized(self):
415 """
416 :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
417 when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
418 initialized (ie, which does not actually have any certificate data).
419 """
420 ctx = Context(TLSv1_METHOD)
421 self.assertRaises(Error, ctx.use_certificate, X509())
422
423
424 def test_use_certificate(self):
425 """
426 :py:obj:`Context.use_certificate` sets the certificate which will be
427 used to identify connections created using the context.
428 """
429 # TODO
430 # Hard to assert anything. But we could set a privatekey then ask
431 # OpenSSL if the cert and key agree using check_privatekey. Then as
432 # long as check_privatekey works right we're good...
433 ctx = Context(TLSv1_METHOD)
434 ctx.use_certificate(load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
435
436
437 def test_use_certificate_file_wrong_args(self):
438 """
439 :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
440 called with zero arguments or more than two arguments, or if the first
441 argument is not a byte string or the second argumnent is not an integer.
442 """
443 ctx = Context(TLSv1_METHOD)
444 self.assertRaises(TypeError, ctx.use_certificate_file)
445 self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile", object())
446 self.assertRaises(
447 TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM, object())
448 self.assertRaises(
449 TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
450 self.assertRaises(
451 TypeError, ctx.use_certificate_file, b"somefile", object())
452
453
454 def test_use_certificate_file_missing(self):
455 """
456 :py:obj:`Context.use_certificate_file` raises
457 `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does not
458 exist.
459 """
460 ctx = Context(TLSv1_METHOD)
461 self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
462
463
464 def test_use_certificate_file(self):
465 """
466 :py:obj:`Context.use_certificate` sets the certificate which will be
467 used to identify connections created using the context.
468 """
469 # TODO
470 # Hard to assert anything. But we could set a privatekey then ask
471 # OpenSSL if the cert and key agree using check_privatekey. Then as
472 # long as check_privatekey works right we're good...
473 pem_filename = self.mktemp()
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500474 with open(pem_filename, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800475 pem_file.write(cleartextCertificatePEM)
476
477 ctx = Context(TLSv1_METHOD)
478 ctx.use_certificate_file(pem_filename)
479
480
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500481 if not PY3:
482 def test_use_certificate_file_long(self):
483 """
484 On Python 2 :py:obj:`Context.use_certificate_file` accepts a
485 filetype of type :py:obj:`long` as well as :py:obj:`int`.
486 """
487 pem_filename = self.mktemp()
488 with open(pem_filename, "wb") as pem_file:
489 pem_file.write(cleartextCertificatePEM)
490
491 ctx = Context(TLSv1_METHOD)
492 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
493
494
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400495 def test_set_app_data_wrong_args(self):
496 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900497 :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called with other than
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400498 one argument.
499 """
500 context = Context(TLSv1_METHOD)
501 self.assertRaises(TypeError, context.set_app_data)
502 self.assertRaises(TypeError, context.set_app_data, None, None)
503
504
505 def test_get_app_data_wrong_args(self):
506 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900507 :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400508 arguments.
509 """
510 context = Context(TLSv1_METHOD)
511 self.assertRaises(TypeError, context.get_app_data, None)
512
513
514 def test_app_data(self):
515 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900516 :py:obj:`Context.set_app_data` stores an object for later retrieval using
517 :py:obj:`Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400518 """
519 app_data = object()
520 context = Context(TLSv1_METHOD)
521 context.set_app_data(app_data)
522 self.assertIdentical(context.get_app_data(), app_data)
523
524
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400525 def test_set_options_wrong_args(self):
526 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900527 :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with the wrong
528 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400529 """
530 context = Context(TLSv1_METHOD)
531 self.assertRaises(TypeError, context.set_options)
532 self.assertRaises(TypeError, context.set_options, None)
533 self.assertRaises(TypeError, context.set_options, 1, None)
534
535
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500536 def test_set_options(self):
537 """
538 :py:obj:`Context.set_options` returns the new options value.
539 """
540 context = Context(TLSv1_METHOD)
541 options = context.set_options(OP_NO_SSLv2)
542 self.assertTrue(OP_NO_SSLv2 & options)
543
544
545 if not PY3:
546 def test_set_options_long(self):
547 """
548 On Python 2 :py:obj:`Context.set_options` accepts values of type
549 :py:obj:`long` as well as :py:obj:`int`.
550 """
551 context = Context(TLSv1_METHOD)
552 options = context.set_options(long(OP_NO_SSLv2))
553 self.assertTrue(OP_NO_SSLv2 & options)
554
555
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300556 def test_set_mode_wrong_args(self):
557 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400558 :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with the wrong
559 number of arguments or a non-:py:obj:`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300560 """
561 context = Context(TLSv1_METHOD)
562 self.assertRaises(TypeError, context.set_mode)
563 self.assertRaises(TypeError, context.set_mode, None)
564 self.assertRaises(TypeError, context.set_mode, 1, None)
565
566
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400567 if MODE_RELEASE_BUFFERS is not None:
568 def test_set_mode(self):
569 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400570 :py:obj:`Context.set_mode` accepts a mode bitvector and returns the newly
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400571 set mode.
572 """
573 context = Context(TLSv1_METHOD)
574 self.assertTrue(
575 MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500576
577 if not PY3:
578 def test_set_mode_long(self):
579 """
580 On Python 2 :py:obj:`Context.set_mode` accepts values of type
581 :py:obj:`long` as well as :py:obj:`int`.
582 """
583 context = Context(TLSv1_METHOD)
584 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
585 self.assertTrue(MODE_RELEASE_BUFFERS & mode)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400586 else:
587 "MODE_RELEASE_BUFFERS unavailable - OpenSSL version may be too old"
588
589
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400590 def test_set_timeout_wrong_args(self):
591 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900592 :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with the wrong
593 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400594 """
595 context = Context(TLSv1_METHOD)
596 self.assertRaises(TypeError, context.set_timeout)
597 self.assertRaises(TypeError, context.set_timeout, None)
598 self.assertRaises(TypeError, context.set_timeout, 1, None)
599
600
601 def test_get_timeout_wrong_args(self):
602 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900603 :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400604 """
605 context = Context(TLSv1_METHOD)
606 self.assertRaises(TypeError, context.get_timeout, None)
607
608
609 def test_timeout(self):
610 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900611 :py:obj:`Context.set_timeout` sets the session timeout for all connections
612 created using the context object. :py:obj:`Context.get_timeout` retrieves this
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400613 value.
614 """
615 context = Context(TLSv1_METHOD)
616 context.set_timeout(1234)
617 self.assertEquals(context.get_timeout(), 1234)
618
619
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500620 if not PY3:
621 def test_timeout_long(self):
622 """
623 On Python 2 :py:obj:`Context.set_timeout` accepts values of type
624 `long` as well as int.
625 """
626 context = Context(TLSv1_METHOD)
627 context.set_timeout(long(1234))
628 self.assertEquals(context.get_timeout(), 1234)
629
630
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400631 def test_set_verify_depth_wrong_args(self):
632 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900633 :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called with the wrong
634 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400635 """
636 context = Context(TLSv1_METHOD)
637 self.assertRaises(TypeError, context.set_verify_depth)
638 self.assertRaises(TypeError, context.set_verify_depth, None)
639 self.assertRaises(TypeError, context.set_verify_depth, 1, None)
640
641
642 def test_get_verify_depth_wrong_args(self):
643 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900644 :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400645 """
646 context = Context(TLSv1_METHOD)
647 self.assertRaises(TypeError, context.get_verify_depth, None)
648
649
650 def test_verify_depth(self):
651 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900652 :py:obj:`Context.set_verify_depth` sets the number of certificates in a chain
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400653 to follow before giving up. The value can be retrieved with
Jonathan Ballet648875f2011-07-16 14:14:58 +0900654 :py:obj:`Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400655 """
656 context = Context(TLSv1_METHOD)
657 context.set_verify_depth(11)
658 self.assertEquals(context.get_verify_depth(), 11)
659
660
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500661 if not PY3:
662 def test_verify_depth_long(self):
663 """
664 On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
665 type `long` as well as int.
666 """
667 context = Context(TLSv1_METHOD)
668 context.set_verify_depth(long(11))
669 self.assertEquals(context.get_verify_depth(), 11)
670
671
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400672 def _write_encrypted_pem(self, passphrase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400673 """
674 Write a new private key out to a new file, encrypted using the given
675 passphrase. Return the path to the new file.
676 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400677 key = PKey()
678 key.generate_key(TYPE_RSA, 128)
679 pemFile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400680 fObj = open(pemFile, 'w')
681 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
682 fObj.write(pem.decode('ascii'))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400683 fObj.close()
684 return pemFile
685
686
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400687 def test_set_passwd_cb_wrong_args(self):
688 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900689 :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called with the
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400690 wrong arguments or with a non-callable first argument.
691 """
692 context = Context(TLSv1_METHOD)
693 self.assertRaises(TypeError, context.set_passwd_cb)
694 self.assertRaises(TypeError, context.set_passwd_cb, None)
695 self.assertRaises(TypeError, context.set_passwd_cb, lambda: None, None, None)
696
697
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400698 def test_set_passwd_cb(self):
699 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900700 :py:obj:`Context.set_passwd_cb` accepts a callable which will be invoked when
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400701 a private key is loaded from an encrypted PEM.
702 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400703 passphrase = b("foobar")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400704 pemFile = self._write_encrypted_pem(passphrase)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400705 calledWith = []
706 def passphraseCallback(maxlen, verify, extra):
707 calledWith.append((maxlen, verify, extra))
708 return passphrase
709 context = Context(TLSv1_METHOD)
710 context.set_passwd_cb(passphraseCallback)
711 context.use_privatekey_file(pemFile)
712 self.assertTrue(len(calledWith), 1)
713 self.assertTrue(isinstance(calledWith[0][0], int))
714 self.assertTrue(isinstance(calledWith[0][1], int))
715 self.assertEqual(calledWith[0][2], None)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400716
717
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400718 def test_passwd_callback_exception(self):
719 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900720 :py:obj:`Context.use_privatekey_file` propagates any exception raised by the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400721 passphrase callback.
722 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400723 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400724 def passphraseCallback(maxlen, verify, extra):
725 raise RuntimeError("Sorry, I am a fail.")
726
727 context = Context(TLSv1_METHOD)
728 context.set_passwd_cb(passphraseCallback)
729 self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
730
731
732 def test_passwd_callback_false(self):
733 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900734 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400735 passphrase callback returns a false value.
736 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400737 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400738 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500739 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400740
741 context = Context(TLSv1_METHOD)
742 context.set_passwd_cb(passphraseCallback)
743 self.assertRaises(Error, context.use_privatekey_file, pemFile)
744
745
746 def test_passwd_callback_non_string(self):
747 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900748 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400749 passphrase callback returns a true non-string value.
750 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400751 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400752 def passphraseCallback(maxlen, verify, extra):
753 return 10
754
755 context = Context(TLSv1_METHOD)
756 context.set_passwd_cb(passphraseCallback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757 self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400758
759
760 def test_passwd_callback_too_long(self):
761 """
762 If the passphrase returned by the passphrase callback returns a string
763 longer than the indicated maximum length, it is truncated.
764 """
765 # A priori knowledge!
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400766 passphrase = b("x") * 1024
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400767 pemFile = self._write_encrypted_pem(passphrase)
768 def passphraseCallback(maxlen, verify, extra):
769 assert maxlen == 1024
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400770 return passphrase + b("y")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400771
772 context = Context(TLSv1_METHOD)
773 context.set_passwd_cb(passphraseCallback)
774 # This shall succeed because the truncated result is the correct
775 # passphrase.
776 context.use_privatekey_file(pemFile)
777
778
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400779 def test_set_info_callback(self):
780 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900781 :py:obj:`Context.set_info_callback` accepts a callable which will be invoked
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400782 when certain information about an SSL connection is available.
783 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500784 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400785
786 clientSSL = Connection(Context(TLSv1_METHOD), client)
787 clientSSL.set_connect_state()
788
789 called = []
790 def info(conn, where, ret):
791 called.append((conn, where, ret))
792 context = Context(TLSv1_METHOD)
793 context.set_info_callback(info)
794 context.use_certificate(
795 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
796 context.use_privatekey(
797 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
798
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400799 serverSSL = Connection(context, server)
800 serverSSL.set_accept_state()
801
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500802 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400803
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500804 # The callback must always be called with a Connection instance as the
805 # first argument. It would probably be better to split this into
806 # separate tests for client and server side info callbacks so we could
807 # assert it is called with the right Connection instance. It would
808 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500809 notConnections = [
810 conn for (conn, where, ret) in called
811 if not isinstance(conn, Connection)]
812 self.assertEqual(
813 [], notConnections,
814 "Some info callback arguments were not Connection instaces.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400815
816
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400817 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400818 """
819 Create a client context which will verify the peer certificate and call
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400820 its :py:obj:`load_verify_locations` method with the given arguments.
821 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400822 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500823 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400824
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400825 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400826 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400827 # Require that the server certificate verify properly or the
828 # connection will fail.
829 clientContext.set_verify(
830 VERIFY_PEER,
831 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
832
833 clientSSL = Connection(clientContext, client)
834 clientSSL.set_connect_state()
835
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400836 serverContext = Context(TLSv1_METHOD)
837 serverContext.use_certificate(
838 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
839 serverContext.use_privatekey(
840 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
841
842 serverSSL = Connection(serverContext, server)
843 serverSSL.set_accept_state()
844
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400845 # Without load_verify_locations above, the handshake
846 # will fail:
847 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
848 # 'certificate verify failed')]
849 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400850
851 cert = clientSSL.get_peer_certificate()
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400852 self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400853
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500854
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400855 def test_load_verify_file(self):
856 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900857 :py:obj:`Context.load_verify_locations` accepts a file name and uses the
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400858 certificates within for verification purposes.
859 """
860 cafile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400861 fObj = open(cafile, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400862 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400863 fObj.close()
864
865 self._load_verify_locations_test(cafile)
866
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400867
868 def test_load_verify_invalid_file(self):
869 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900870 :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when passed a
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400871 non-existent cafile.
872 """
873 clientContext = Context(TLSv1_METHOD)
874 self.assertRaises(
875 Error, clientContext.load_verify_locations, self.mktemp())
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400876
877
878 def test_load_verify_directory(self):
879 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900880 :py:obj:`Context.load_verify_locations` accepts a directory name and uses
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400881 the certificates within for verification purposes.
882 """
883 capath = self.mktemp()
884 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400885 # Hash values computed manually with c_rehash to avoid depending on
886 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
887 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500888 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400889 cafile = join(capath, name)
890 fObj = open(cafile, 'w')
891 fObj.write(cleartextCertificatePEM.decode('ascii'))
892 fObj.close()
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400893
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400894 self._load_verify_locations_test(None, capath)
895
896
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400897 def test_load_verify_locations_wrong_args(self):
898 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900899 :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if called with
900 the wrong number of arguments or with non-:py:obj:`str` arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400901 """
902 context = Context(TLSv1_METHOD)
903 self.assertRaises(TypeError, context.load_verify_locations)
904 self.assertRaises(TypeError, context.load_verify_locations, object())
905 self.assertRaises(TypeError, context.load_verify_locations, object(), object())
906 self.assertRaises(TypeError, context.load_verify_locations, None, None, None)
907
908
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400909 if platform == "win32":
910 "set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400911 "See LP#404343 and LP#404344."
912 else:
913 def test_set_default_verify_paths(self):
914 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900915 :py:obj:`Context.set_default_verify_paths` causes the platform-specific CA
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400916 certificate locations to be used for verification purposes.
917 """
918 # Testing this requires a server with a certificate signed by one of
919 # the CAs in the platform CA location. Getting one of those costs
920 # money. Fortunately (or unfortunately, depending on your
921 # perspective), it's easy to think of a public server on the
922 # internet which has such a certificate. Connecting to the network
923 # in a unit test is bad, but it's the only way I can think of to
924 # really test this. -exarkun
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400925
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400926 # Arg, verisign.com doesn't speak TLSv1
927 context = Context(SSLv3_METHOD)
928 context.set_default_verify_paths()
929 context.set_verify(
Ziga Seilnacht44611bf2009-08-31 20:49:30 +0200930 VERIFY_PEER,
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400931 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400932
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400933 client = socket()
934 client.connect(('verisign.com', 443))
935 clientSSL = Connection(context, client)
936 clientSSL.set_connect_state()
937 clientSSL.do_handshake()
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500938 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -0400939 self.assertTrue(clientSSL.recv(1024))
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -0400940
941
942 def test_set_default_verify_paths_signature(self):
943 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900944 :py:obj:`Context.set_default_verify_paths` takes no arguments and raises
945 :py:obj:`TypeError` if given any.
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -0400946 """
947 context = Context(TLSv1_METHOD)
948 self.assertRaises(TypeError, context.set_default_verify_paths, None)
949 self.assertRaises(TypeError, context.set_default_verify_paths, 1)
950 self.assertRaises(TypeError, context.set_default_verify_paths, "")
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -0500951
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400952
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500953 def test_add_extra_chain_cert_invalid_cert(self):
954 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900955 :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if called with
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500956 other than one argument or if called with an object which is not an
Jonathan Ballet648875f2011-07-16 14:14:58 +0900957 instance of :py:obj:`X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500958 """
959 context = Context(TLSv1_METHOD)
960 self.assertRaises(TypeError, context.add_extra_chain_cert)
961 self.assertRaises(TypeError, context.add_extra_chain_cert, object())
962 self.assertRaises(TypeError, context.add_extra_chain_cert, object(), object())
963
964
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400965 def _handshake_test(self, serverContext, clientContext):
966 """
967 Verify that a client and server created with the given contexts can
968 successfully handshake and communicate.
969 """
970 serverSocket, clientSocket = socket_pair()
971
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400972 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -0400973 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400974
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400975 client = Connection(clientContext, clientSocket)
976 client.set_connect_state()
977
978 # Make them talk to each other.
979 # self._interactInMemory(client, server)
980 for i in range(3):
981 for s in [client, server]:
982 try:
983 s.do_handshake()
984 except WantReadError:
985 pass
986
987
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800988 def test_set_verify_callback_exception(self):
989 """
990 If the verify callback passed to :py:obj:`Context.set_verify` raises an
991 exception, verification fails and the exception is propagated to the
992 caller of :py:obj:`Connection.do_handshake`.
993 """
994 serverContext = Context(TLSv1_METHOD)
995 serverContext.use_privatekey(
996 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
997 serverContext.use_certificate(
998 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
999
1000 clientContext = Context(TLSv1_METHOD)
1001 def verify_callback(*args):
1002 raise Exception("silly verify failure")
1003 clientContext.set_verify(VERIFY_PEER, verify_callback)
1004
1005 exc = self.assertRaises(
1006 Exception, self._handshake_test, serverContext, clientContext)
1007 self.assertEqual("silly verify failure", str(exc))
1008
1009
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001010 def test_add_extra_chain_cert(self):
1011 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001012 :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509` instance to add to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001013 the certificate chain.
1014
Jonathan Ballet648875f2011-07-16 14:14:58 +09001015 See :py:obj:`_create_certificate_chain` for the details of the certificate
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001016 chain tested.
1017
1018 The chain is tested by starting a server with scert and connecting
1019 to it with a client which trusts cacert and requires verification to
1020 succeed.
1021 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001022 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001023 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1024
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001025 # Dump the CA certificate to a file because that's the only way to load
1026 # it as a trusted CA in the client context.
1027 for cert, name in [(cacert, 'ca.pem'), (icert, 'i.pem'), (scert, 's.pem')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001028 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001029 fObj.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001030 fObj.close()
1031
1032 for key, name in [(cakey, 'ca.key'), (ikey, 'i.key'), (skey, 's.key')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001033 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001034 fObj.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001035 fObj.close()
1036
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001037 # Create the server context
1038 serverContext = Context(TLSv1_METHOD)
1039 serverContext.use_privatekey(skey)
1040 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001041 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001042 serverContext.add_extra_chain_cert(icert)
1043
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001044 # Create the client
1045 clientContext = Context(TLSv1_METHOD)
1046 clientContext.set_verify(
1047 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001048 clientContext.load_verify_locations(b"ca.pem")
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001049
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001050 # Try it out.
1051 self._handshake_test(serverContext, clientContext)
1052
1053
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001054 def test_use_certificate_chain_file(self):
1055 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001056 :py:obj:`Context.use_certificate_chain_file` reads a certificate chain from
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001057 the specified file.
1058
1059 The chain is tested by starting a server with scert and connecting
1060 to it with a client which trusts cacert and requires verification to
1061 succeed.
1062 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001063 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001064 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1065
1066 # Write out the chain file.
1067 chainFile = self.mktemp()
Jean-Paul Calderoned8607982014-01-18 10:30:55 -05001068 fObj = open(chainFile, 'wb')
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001069 # Most specific to least general.
Jean-Paul Calderoned8607982014-01-18 10:30:55 -05001070 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1071 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1072 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001073 fObj.close()
1074
1075 serverContext = Context(TLSv1_METHOD)
1076 serverContext.use_certificate_chain_file(chainFile)
1077 serverContext.use_privatekey(skey)
1078
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001079 fObj = open('ca.pem', 'w')
1080 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001081 fObj.close()
1082
1083 clientContext = Context(TLSv1_METHOD)
1084 clientContext.set_verify(
1085 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001086 clientContext.load_verify_locations(b"ca.pem")
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001087
1088 self._handshake_test(serverContext, clientContext)
1089
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001090
1091 def test_use_certificate_chain_file_wrong_args(self):
1092 """
1093 :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
1094 if passed zero or more than one argument or when passed a non-byte
1095 string single argument. It also raises :py:obj:`OpenSSL.SSL.Error` when
1096 passed a bad chain file name (for example, the name of a file which does
1097 not exist).
1098 """
1099 context = Context(TLSv1_METHOD)
1100 self.assertRaises(TypeError, context.use_certificate_chain_file)
1101 self.assertRaises(TypeError, context.use_certificate_chain_file, object())
1102 self.assertRaises(TypeError, context.use_certificate_chain_file, b"foo", object())
1103
1104 self.assertRaises(Error, context.use_certificate_chain_file, self.mktemp())
1105
Jean-Paul Calderonee0d79362010-08-03 18:46:46 -04001106 # XXX load_client_ca
1107 # XXX set_session_id
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001108
1109 def test_get_verify_mode_wrong_args(self):
1110 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001111 :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001112 arguments.
1113 """
1114 context = Context(TLSv1_METHOD)
1115 self.assertRaises(TypeError, context.get_verify_mode, None)
1116
1117
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001118 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001119 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001120 :py:obj:`Context.get_verify_mode` returns the verify mode flags previously
1121 passed to :py:obj:`Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001122 """
1123 context = Context(TLSv1_METHOD)
1124 self.assertEquals(context.get_verify_mode(), 0)
1125 context.set_verify(
1126 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
1127 self.assertEquals(
1128 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1129
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001130
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001131 if not PY3:
1132 def test_set_verify_mode_long(self):
1133 """
1134 On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
1135 type :py:obj:`long` as well as :py:obj:`int`.
1136 """
1137 context = Context(TLSv1_METHOD)
1138 self.assertEquals(context.get_verify_mode(), 0)
1139 context.set_verify(
1140 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None)
1141 self.assertEquals(
1142 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1143
1144
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001145 def test_load_tmp_dh_wrong_args(self):
1146 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001147 :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with the wrong
1148 number of arguments or with a non-:py:obj:`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001149 """
1150 context = Context(TLSv1_METHOD)
1151 self.assertRaises(TypeError, context.load_tmp_dh)
1152 self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
1153 self.assertRaises(TypeError, context.load_tmp_dh, object())
1154
1155
1156 def test_load_tmp_dh_missing_file(self):
1157 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001158 :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the specified file
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001159 does not exist.
1160 """
1161 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001162 self.assertRaises(Error, context.load_tmp_dh, b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001163
1164
1165 def test_load_tmp_dh(self):
1166 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001167 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001168 specified file.
1169 """
1170 context = Context(TLSv1_METHOD)
1171 dhfilename = self.mktemp()
1172 dhfile = open(dhfilename, "w")
1173 dhfile.write(dhparam)
1174 dhfile.close()
1175 context.load_tmp_dh(dhfilename)
1176 # XXX What should I assert here? -exarkun
1177
1178
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001179 def test_set_tmp_ecdh_curve(self):
1180 """
Jean-Paul Calderone3dfd4512014-04-17 16:02:19 -04001181 :py:obj:`Context.set_tmp_ecdh_curve` sets the elliptic curve for
1182 Diffie-Hellman to the specified named curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001183 """
1184 context = Context(TLSv1_METHOD)
1185 for curve in ELLIPTIC_CURVE_DESCRIPTIONS.keys():
1186 context.set_tmp_ecdh_curve(curve) # Must not throw.
1187
Laurens Van Houtvenf5df2432014-04-03 12:17:28 +02001188
Jean-Paul Calderoneb41d1f42014-04-17 16:02:04 -04001189 def test_set_tmp_ecdh_curve_not_available(self):
1190 """
1191 :py:obj:`Context.set_tmp_ecdh_curve` raises :py:obj:`ECNotAvailable` if
1192 elliptic curve support is not available from the underlying OpenSSL
1193 version at all.
1194 """
1195 self.addCleanup(
1196 setattr,
1197 _lib, "Cryptography_HAS_EC", _lib.Cryptography_HAS_EC)
1198 _lib.Cryptography_HAS_EC = False
1199
1200 context = Context(TLSv1_METHOD)
1201 self.assertRaises(
1202 ECNotAvailable,
1203 context.set_tmp_ecdh_curve, next(iter(ELLIPTIC_CURVE_DESCRIPTIONS)))
1204
1205
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001206 def test_set_tmp_ecdh_curve_bad_sn(self):
1207 """
Jean-Paul Calderone3dfd4512014-04-17 16:02:19 -04001208 :py:obj:`Context.set_tmp_ecdh_curve` raises :py:obj:`UnknownObject` if
1209 passed a curve_name that OpenSSL does not recognize and EC is
1210 available.
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001211 """
1212 context = Context(TLSv1_METHOD)
1213 try:
1214 context.set_tmp_ecdh_curve('not_an_elliptic_curve')
1215 except ECNotAvailable:
1216 self.assertFalse(_Cryptography_HAS_EC)
1217 except UnknownObject:
1218 self.assertTrue(_Cryptography_HAS_EC)
1219 else:
Jean-Paul Calderone5c7b52f2014-04-17 16:02:51 -04001220 self.fail(
1221 "set_tmp_ecdh_curve did not fail when called with "
1222 "non-existent curve name")
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001223
1224
1225 def test_set_tmp_ecdh_curve_not_a_curve(self):
1226 """
1227 :py:obj:`Context.set_tmp_ecdh_curve` raises
Jean-Paul Calderone3dfd4512014-04-17 16:02:19 -04001228 :py:obj:`UnsupportedEllipticCurve` if passed a curve_name that OpenSSL
1229 cannot instantiate as an elliptic curve. It raises
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001230 :py:obj:`ECNotAvailable` if EC is not available at all.
1231 """
1232 context = Context(TLSv1_METHOD)
1233 try:
1234 context.set_tmp_ecdh_curve('sha256')
1235 except ECNotAvailable:
1236 self.assertFalse(_Cryptography_HAS_EC)
1237 except UnknownObject:
1238 self.assertTrue(_Cryptography_HAS_EC)
1239 else:
Jean-Paul Calderone5c7b52f2014-04-17 16:02:51 -04001240 self.fail(
1241 "set_tmp_ecdh_curve did not fail when called with "
1242 "a name that is not an elliptic curve")
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001243
1244
Laurens Van Houtvenf5df2432014-04-03 12:17:28 +02001245 def test_has_curve_descriptions(self):
1246 """
1247 If the underlying cryptography bindings claim to have elliptic
1248 curve support, there should be at least one curve.
1249
1250 (In theory there could be an OpenSSL that violates this
1251 assumption. If so, this test will fail and we'll find out.)
1252
1253 """
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001254 if _Cryptography_HAS_EC:
Laurens Van Houtvenf5df2432014-04-03 12:17:28 +02001255 self.assertNotEqual(len(ELLIPTIC_CURVE_DESCRIPTIONS), 0)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001256
1257
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001258 def test_set_cipher_list_bytes(self):
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001259 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001260 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
1261 ciphers which connections created with the context object will be able
1262 to choose from.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001263 """
1264 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001265 context.set_cipher_list(b"hello world:EXP-RC4-MD5")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001266 conn = Connection(context, None)
1267 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001268
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001269
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001270 def test_set_cipher_list_text(self):
1271 """
1272 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
1273 the ciphers which connections created with the context object will be
1274 able to choose from.
1275 """
1276 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -05001277 context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001278 conn = Connection(context, None)
1279 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
1280
1281
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001282 def test_set_cipher_list_wrong_args(self):
1283 """
Jean-Paul Calderone17044832014-01-18 10:20:11 -05001284 :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
1285 passed zero arguments or more than one argument or when passed a
1286 non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001287 passed an incorrect cipher list string.
1288 """
1289 context = Context(TLSv1_METHOD)
1290 self.assertRaises(TypeError, context.set_cipher_list)
1291 self.assertRaises(TypeError, context.set_cipher_list, object())
1292 self.assertRaises(TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object())
1293
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001294 self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295
1296
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001297 def test_set_session_cache_mode_wrong_args(self):
1298 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001299 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1300 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001301 """
1302 context = Context(TLSv1_METHOD)
1303 self.assertRaises(TypeError, context.set_session_cache_mode)
1304 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1305
1306
1307 def test_get_session_cache_mode_wrong_args(self):
1308 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001309 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1310 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001311 """
1312 context = Context(TLSv1_METHOD)
1313 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1314
1315
1316 def test_session_cache_mode(self):
1317 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001318 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1319 cached. The setting can be retrieved via
1320 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001321 """
1322 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001323 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001324 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1325 self.assertEqual(SESS_CACHE_OFF, off)
1326 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1327
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001328 if not PY3:
1329 def test_session_cache_mode_long(self):
1330 """
1331 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1332 of type :py:obj:`long` as well as :py:obj:`int`.
1333 """
1334 context = Context(TLSv1_METHOD)
1335 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1336 self.assertEqual(
1337 SESS_CACHE_BOTH, context.get_session_cache_mode())
1338
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001339
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001340 def test_get_cert_store(self):
1341 """
1342 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store` instance.
1343 """
1344 context = Context(TLSv1_METHOD)
1345 store = context.get_cert_store()
1346 self.assertIsInstance(store, X509Store)
1347
1348
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001349
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001350class ServerNameCallbackTests(TestCase, _LoopbackMixin):
1351 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001352 Tests for :py:obj:`Context.set_tlsext_servername_callback` and its interaction with
1353 :py:obj:`Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001354 """
1355 def test_wrong_args(self):
1356 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001357 :py:obj:`Context.set_tlsext_servername_callback` raises :py:obj:`TypeError` if called
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001358 with other than one argument.
1359 """
1360 context = Context(TLSv1_METHOD)
1361 self.assertRaises(TypeError, context.set_tlsext_servername_callback)
1362 self.assertRaises(
1363 TypeError, context.set_tlsext_servername_callback, 1, 2)
1364
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001365
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001366 def test_old_callback_forgotten(self):
1367 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001368 If :py:obj:`Context.set_tlsext_servername_callback` is used to specify a new
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001369 callback, the one it replaces is dereferenced.
1370 """
1371 def callback(connection):
1372 pass
1373
1374 def replacement(connection):
1375 pass
1376
1377 context = Context(TLSv1_METHOD)
1378 context.set_tlsext_servername_callback(callback)
1379
1380 tracker = ref(callback)
1381 del callback
1382
1383 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001384
1385 # One run of the garbage collector happens to work on CPython. PyPy
1386 # doesn't collect the underlying object until a second run for whatever
1387 # reason. That's fine, it still demonstrates our code has properly
1388 # dropped the reference.
1389 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001390 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001391
1392 callback = tracker()
1393 if callback is not None:
1394 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001395 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001396 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001397
1398
1399 def test_no_servername(self):
1400 """
1401 When a client specifies no server name, the callback passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001402 :py:obj:`Context.set_tlsext_servername_callback` is invoked and the result of
1403 :py:obj:`Connection.get_servername` is :py:obj:`None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001404 """
1405 args = []
1406 def servername(conn):
1407 args.append((conn, conn.get_servername()))
1408 context = Context(TLSv1_METHOD)
1409 context.set_tlsext_servername_callback(servername)
1410
1411 # Lose our reference to it. The Context is responsible for keeping it
1412 # alive now.
1413 del servername
1414 collect()
1415
1416 # Necessary to actually accept the connection
1417 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1418 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1419
1420 # Do a little connection to trigger the logic
1421 server = Connection(context, None)
1422 server.set_accept_state()
1423
1424 client = Connection(Context(TLSv1_METHOD), None)
1425 client.set_connect_state()
1426
1427 self._interactInMemory(server, client)
1428
1429 self.assertEqual([(server, None)], args)
1430
1431
1432 def test_servername(self):
1433 """
1434 When a client specifies a server name in its hello message, the callback
Jonathan Ballet648875f2011-07-16 14:14:58 +09001435 passed to :py:obj:`Contexts.set_tlsext_servername_callback` is invoked and the
1436 result of :py:obj:`Connection.get_servername` is that server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001437 """
1438 args = []
1439 def servername(conn):
1440 args.append((conn, conn.get_servername()))
1441 context = Context(TLSv1_METHOD)
1442 context.set_tlsext_servername_callback(servername)
1443
1444 # Necessary to actually accept the connection
1445 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1446 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1447
1448 # Do a little connection to trigger the logic
1449 server = Connection(context, None)
1450 server.set_accept_state()
1451
1452 client = Connection(Context(TLSv1_METHOD), None)
1453 client.set_connect_state()
1454 client.set_tlsext_host_name(b("foo1.example.com"))
1455
1456 self._interactInMemory(server, client)
1457
1458 self.assertEqual([(server, b("foo1.example.com"))], args)
1459
1460
1461
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05001462class SessionTests(TestCase):
1463 """
1464 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
1465 """
1466 def test_construction(self):
1467 """
1468 :py:class:`Session` can be constructed with no arguments, creating a new
1469 instance of that type.
1470 """
1471 new_session = Session()
1472 self.assertTrue(isinstance(new_session, Session))
1473
1474
1475 def test_construction_wrong_args(self):
1476 """
1477 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
1478 is raised.
1479 """
1480 self.assertRaises(TypeError, Session, 123)
1481 self.assertRaises(TypeError, Session, "hello")
1482 self.assertRaises(TypeError, Session, object())
1483
1484
1485
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001486class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05001487 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001488 Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05001489 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04001490 # XXX get_peer_certificate -> None
1491 # XXX sock_shutdown
1492 # XXX master_key -> TypeError
1493 # XXX server_random -> TypeError
1494 # XXX state_string
1495 # XXX connect -> TypeError
1496 # XXX connect_ex -> TypeError
1497 # XXX set_connect_state -> TypeError
1498 # XXX set_accept_state -> TypeError
1499 # XXX renegotiate_pending
1500 # XXX do_handshake -> TypeError
1501 # XXX bio_read -> TypeError
1502 # XXX recv -> TypeError
1503 # XXX send -> TypeError
1504 # XXX bio_write -> TypeError
1505
Rick Deane15b1472009-07-09 15:53:42 -05001506 def test_type(self):
1507 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001508 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same type object and
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001509 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05001510 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001511 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05001512 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001513 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05001514
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001515
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001516 def test_get_context(self):
1517 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001518 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance used to
1519 construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001520 """
1521 context = Context(TLSv1_METHOD)
1522 connection = Connection(context, None)
1523 self.assertIdentical(connection.get_context(), context)
1524
1525
1526 def test_get_context_wrong_args(self):
1527 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001528 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001529 arguments.
1530 """
1531 connection = Connection(Context(TLSv1_METHOD), None)
1532 self.assertRaises(TypeError, connection.get_context, None)
1533
1534
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001535 def test_set_context_wrong_args(self):
1536 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001537 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called with a
1538 non-:py:obj:`Context` instance argument or with any number of arguments other
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001539 than 1.
1540 """
1541 ctx = Context(TLSv1_METHOD)
1542 connection = Connection(ctx, None)
1543 self.assertRaises(TypeError, connection.set_context)
1544 self.assertRaises(TypeError, connection.set_context, object())
1545 self.assertRaises(TypeError, connection.set_context, "hello")
1546 self.assertRaises(TypeError, connection.set_context, 1)
1547 self.assertRaises(TypeError, connection.set_context, 1, 2)
1548 self.assertRaises(
1549 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
1550 self.assertIdentical(ctx, connection.get_context())
1551
1552
1553 def test_set_context(self):
1554 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001555 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context` instance to be used
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001556 for the connection.
1557 """
1558 original = Context(SSLv23_METHOD)
1559 replacement = Context(TLSv1_METHOD)
1560 connection = Connection(original, None)
1561 connection.set_context(replacement)
1562 self.assertIdentical(replacement, connection.get_context())
1563 # Lose our references to the contexts, just in case the Connection isn't
1564 # properly managing its own contributions to their reference counts.
1565 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001566 collect()
1567
1568
1569 def test_set_tlsext_host_name_wrong_args(self):
1570 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001571 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte string
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001572 argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09001573 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001574 """
1575 conn = Connection(Context(TLSv1_METHOD), None)
1576 self.assertRaises(TypeError, conn.set_tlsext_host_name)
1577 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
1578 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
1579 self.assertRaises(
1580 TypeError, conn.set_tlsext_host_name, b("with\0null"))
1581
1582 if version_info >= (3,):
1583 # On Python 3.x, don't accidentally implicitly convert from text.
1584 self.assertRaises(
1585 TypeError,
1586 conn.set_tlsext_host_name, b("example.com").decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001587
1588
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001589 def test_get_servername_wrong_args(self):
1590 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001591 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001592 arguments.
1593 """
1594 connection = Connection(Context(TLSv1_METHOD), None)
1595 self.assertRaises(TypeError, connection.get_servername, object())
1596 self.assertRaises(TypeError, connection.get_servername, 1)
1597 self.assertRaises(TypeError, connection.get_servername, "hello")
1598
1599
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001600 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001601 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001602 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001603 immediate read.
1604 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001605 connection = Connection(Context(TLSv1_METHOD), None)
1606 self.assertEquals(connection.pending(), 0)
1607
1608
1609 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001610 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001611 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001612 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001613 connection = Connection(Context(TLSv1_METHOD), None)
1614 self.assertRaises(TypeError, connection.pending, None)
1615
1616
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001617 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001618 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001619 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with a non-address
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001620 argument or with the wrong number of arguments.
1621 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001622 connection = Connection(Context(TLSv1_METHOD), socket())
1623 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001624 self.assertRaises(TypeError, connection.connect)
1625 self.assertRaises(TypeError, connection.connect, ("127.0.0.1", 1), None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001626
1627
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001628 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001629 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001630 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the underlying socket
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001631 connect method raises it.
1632 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001633 client = socket()
1634 context = Context(TLSv1_METHOD)
1635 clientSSL = Connection(context, client)
1636 exc = self.assertRaises(error, clientSSL.connect, ("127.0.0.1", 1))
Jean-Paul Calderone35adf9d2010-07-29 18:40:44 -04001637 self.assertEquals(exc.args[0], ECONNREFUSED)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001638
1639
1640 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001641 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001642 :py:obj:`Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001643 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001644 port = socket()
1645 port.bind(('', 0))
1646 port.listen(3)
1647
1648 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001649 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
1650 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001651
1652
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001653 if platform == "darwin":
1654 "connect_ex sometimes causes a kernel panic on OS X 10.6.4"
1655 else:
1656 def test_connect_ex(self):
1657 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001658 If there is a connection error, :py:obj:`Connection.connect_ex` returns the
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001659 errno instead of raising an exception.
1660 """
1661 port = socket()
1662 port.bind(('', 0))
1663 port.listen(3)
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001664
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001665 clientSSL = Connection(Context(TLSv1_METHOD), socket())
1666 clientSSL.setblocking(False)
1667 result = clientSSL.connect_ex(port.getsockname())
1668 expected = (EINPROGRESS, EWOULDBLOCK)
1669 self.assertTrue(
1670 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001671
1672
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001673 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001674 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001675 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001676 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001677 connection = Connection(Context(TLSv1_METHOD), socket())
1678 self.assertRaises(TypeError, connection.accept, None)
1679
1680
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001681 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001682 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001683 :py:obj:`Connection.accept` accepts a pending connection attempt and returns a
1684 tuple of a new :py:obj:`Connection` (the accepted client) and the address the
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001685 connection originated from.
1686 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001687 ctx = Context(TLSv1_METHOD)
1688 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1689 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001690 port = socket()
1691 portSSL = Connection(ctx, port)
1692 portSSL.bind(('', 0))
1693 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001694
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001695 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001696
1697 # Calling portSSL.getsockname() here to get the server IP address sounds
1698 # great, but frequently fails on Windows.
1699 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001700
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001701 serverSSL, address = portSSL.accept()
1702
1703 self.assertTrue(isinstance(serverSSL, Connection))
1704 self.assertIdentical(serverSSL.get_context(), ctx)
1705 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001706
1707
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001708 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001709 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001710 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with the wrong
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001711 number of arguments or with arguments other than integers.
1712 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001713 connection = Connection(Context(TLSv1_METHOD), None)
1714 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04001715 self.assertRaises(TypeError, connection.get_shutdown, None)
1716 self.assertRaises(TypeError, connection.set_shutdown)
1717 self.assertRaises(TypeError, connection.set_shutdown, None)
1718 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001719
1720
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001721 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001722 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001723 :py:obj:`Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001724 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001725 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001726 self.assertFalse(server.shutdown())
1727 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001728 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001729 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
1730 client.shutdown()
1731 self.assertEquals(client.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
1732 self.assertRaises(ZeroReturnError, server.recv, 1024)
1733 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001734
1735
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001736 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001737 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001738 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection shutdown
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001739 process.
1740 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001741 connection = Connection(Context(TLSv1_METHOD), socket())
1742 connection.set_shutdown(RECEIVED_SHUTDOWN)
1743 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1744
1745
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001746 if not PY3:
1747 def test_set_shutdown_long(self):
1748 """
1749 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
1750 of type :py:obj:`long` as well as :py:obj:`int`.
1751 """
1752 connection = Connection(Context(TLSv1_METHOD), socket())
1753 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
1754 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1755
1756
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001757 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001758 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001759 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called with other than
1760 one argument. :py:obj:`Connection.get_app_data` raises :py:obj:`TypeError` if called
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001761 with any arguments.
1762 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001763 conn = Connection(Context(TLSv1_METHOD), None)
1764 self.assertRaises(TypeError, conn.get_app_data, None)
1765 self.assertRaises(TypeError, conn.set_app_data)
1766 self.assertRaises(TypeError, conn.set_app_data, None, None)
1767
1768
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001769 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001770 """
1771 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001772 :py:obj:`Connection.set_app_data` and later retrieved with
1773 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001774 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001775 conn = Connection(Context(TLSv1_METHOD), None)
1776 app_data = object()
1777 conn.set_app_data(app_data)
1778 self.assertIdentical(conn.get_app_data(), app_data)
1779
1780
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001781 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001782 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001783 :py:obj:`Connection.makefile` is not implemented and calling that method raises
1784 :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001785 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001786 conn = Connection(Context(TLSv1_METHOD), None)
1787 self.assertRaises(NotImplementedError, conn.makefile)
1788
1789
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001790 def test_get_peer_cert_chain_wrong_args(self):
1791 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001792 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001793 arguments.
1794 """
1795 conn = Connection(Context(TLSv1_METHOD), None)
1796 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
1797 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
1798 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
1799 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
1800
1801
1802 def test_get_peer_cert_chain(self):
1803 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001804 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates which
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001805 the connected server returned for the certification verification.
1806 """
1807 chain = _create_certificate_chain()
1808 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1809
1810 serverContext = Context(TLSv1_METHOD)
1811 serverContext.use_privatekey(skey)
1812 serverContext.use_certificate(scert)
1813 serverContext.add_extra_chain_cert(icert)
1814 serverContext.add_extra_chain_cert(cacert)
1815 server = Connection(serverContext, None)
1816 server.set_accept_state()
1817
1818 # Create the client
1819 clientContext = Context(TLSv1_METHOD)
1820 clientContext.set_verify(VERIFY_NONE, verify_cb)
1821 client = Connection(clientContext, None)
1822 client.set_connect_state()
1823
1824 self._interactInMemory(client, server)
1825
1826 chain = client.get_peer_cert_chain()
1827 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001828 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001829 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001830 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001831 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001832 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001833 "Authority Certificate", chain[2].get_subject().CN)
1834
1835
1836 def test_get_peer_cert_chain_none(self):
1837 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001838 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the peer sends no
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001839 certificate chain.
1840 """
1841 ctx = Context(TLSv1_METHOD)
1842 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1843 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1844 server = Connection(ctx, None)
1845 server.set_accept_state()
1846 client = Connection(Context(TLSv1_METHOD), None)
1847 client.set_connect_state()
1848 self._interactInMemory(client, server)
1849 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001850
1851
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001852 def test_get_session_wrong_args(self):
1853 """
1854 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
1855 with any arguments.
1856 """
1857 ctx = Context(TLSv1_METHOD)
1858 server = Connection(ctx, None)
1859 self.assertRaises(TypeError, server.get_session, 123)
1860 self.assertRaises(TypeError, server.get_session, "hello")
1861 self.assertRaises(TypeError, server.get_session, object())
1862
1863
1864 def test_get_session_unconnected(self):
1865 """
1866 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
1867 an object which has not been connected.
1868 """
1869 ctx = Context(TLSv1_METHOD)
1870 server = Connection(ctx, None)
1871 session = server.get_session()
1872 self.assertIdentical(None, session)
1873
1874
1875 def test_server_get_session(self):
1876 """
1877 On the server side of a connection, :py:obj:`Connection.get_session`
1878 returns a :py:class:`Session` instance representing the SSL session for
1879 that connection.
1880 """
1881 server, client = self._loopback()
1882 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001883 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001884
1885
1886 def test_client_get_session(self):
1887 """
1888 On the client side of a connection, :py:obj:`Connection.get_session`
1889 returns a :py:class:`Session` instance representing the SSL session for
1890 that connection.
1891 """
1892 server, client = self._loopback()
1893 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001894 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001895
1896
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001897 def test_set_session_wrong_args(self):
1898 """
1899 If called with an object that is not an instance of :py:class:`Session`,
1900 or with other than one argument, :py:obj:`Connection.set_session` raises
1901 :py:obj:`TypeError`.
1902 """
1903 ctx = Context(TLSv1_METHOD)
1904 connection = Connection(ctx, None)
1905 self.assertRaises(TypeError, connection.set_session)
1906 self.assertRaises(TypeError, connection.set_session, 123)
1907 self.assertRaises(TypeError, connection.set_session, "hello")
1908 self.assertRaises(TypeError, connection.set_session, object())
1909 self.assertRaises(
1910 TypeError, connection.set_session, Session(), Session())
1911
1912
1913 def test_client_set_session(self):
1914 """
1915 :py:obj:`Connection.set_session`, when used prior to a connection being
1916 established, accepts a :py:class:`Session` instance and causes an
1917 attempt to re-use the session it represents when the SSL handshake is
1918 performed.
1919 """
1920 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1921 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1922 ctx = Context(TLSv1_METHOD)
1923 ctx.use_privatekey(key)
1924 ctx.use_certificate(cert)
1925 ctx.set_session_id("unity-test")
1926
1927 def makeServer(socket):
1928 server = Connection(ctx, socket)
1929 server.set_accept_state()
1930 return server
1931
1932 originalServer, originalClient = self._loopback(
1933 serverFactory=makeServer)
1934 originalSession = originalClient.get_session()
1935
1936 def makeClient(socket):
1937 client = self._loopbackClientFactory(socket)
1938 client.set_session(originalSession)
1939 return client
1940 resumedServer, resumedClient = self._loopback(
1941 serverFactory=makeServer,
1942 clientFactory=makeClient)
1943
1944 # This is a proxy: in general, we have no access to any unique
1945 # identifier for the session (new enough versions of OpenSSL expose a
1946 # hash which could be usable, but "new enough" is very, very new).
1947 # Instead, exploit the fact that the master key is re-used if the
1948 # session is re-used. As long as the master key for the two connections
1949 # is the same, the session was re-used!
1950 self.assertEqual(
1951 originalServer.master_key(), resumedServer.master_key())
1952
1953
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001954 def test_set_session_wrong_method(self):
1955 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05001956 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
1957 instance associated with a context using a different SSL method than the
1958 :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
1959 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001960 """
1961 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1962 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1963 ctx = Context(TLSv1_METHOD)
1964 ctx.use_privatekey(key)
1965 ctx.use_certificate(cert)
1966 ctx.set_session_id("unity-test")
1967
1968 def makeServer(socket):
1969 server = Connection(ctx, socket)
1970 server.set_accept_state()
1971 return server
1972
1973 originalServer, originalClient = self._loopback(
1974 serverFactory=makeServer)
1975 originalSession = originalClient.get_session()
1976
1977 def makeClient(socket):
1978 # Intentionally use a different, incompatible method here.
1979 client = Connection(Context(SSLv3_METHOD), socket)
1980 client.set_connect_state()
1981 client.set_session(originalSession)
1982 return client
1983
1984 self.assertRaises(
1985 Error,
1986 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
1987
1988
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001989 def test_wantWriteError(self):
1990 """
1991 :py:obj:`Connection` methods which generate output raise
1992 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
1993 fail indicating a should-write state.
1994 """
1995 client_socket, server_socket = socket_pair()
1996 # Fill up the client's send buffer so Connection won't be able to write
1997 # anything.
Jean-Paul Calderone7d7c9c22014-02-18 16:38:26 -05001998 msg = b"x" * 512
Jean-Paul Calderone22c28b42014-02-18 16:40:34 -05001999 for i in range(2048):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002000 try:
2001 client_socket.send(msg)
2002 except error as e:
2003 if e.errno == EWOULDBLOCK:
2004 break
2005 raise
2006 else:
2007 self.fail(
2008 "Failed to fill socket buffer, cannot test BIO want write")
2009
2010 ctx = Context(TLSv1_METHOD)
2011 conn = Connection(ctx, client_socket)
2012 # Client's speak first, so make it an SSL client
2013 conn.set_connect_state()
2014 self.assertRaises(WantWriteError, conn.do_handshake)
2015
2016 # XXX want_read
2017
Fedor Brunner416f4a12014-03-28 13:18:38 +01002018 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002019 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002020 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2021 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002022 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002023 ctx = Context(TLSv1_METHOD)
2024 connection = Connection(ctx, None)
2025 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002026
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002027
Fedor Brunner416f4a12014-03-28 13:18:38 +01002028 def test_get_peer_finished_before_connect(self):
2029 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002030 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2031 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002032 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002033 ctx = Context(TLSv1_METHOD)
2034 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002035 self.assertEqual(connection.get_peer_finished(), None)
2036
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002037
Fedor Brunner416f4a12014-03-28 13:18:38 +01002038 def test_get_finished(self):
2039 """
2040 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002041 message send from client, or server. Finished messages are send during
2042 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002043 """
2044
Fedor Brunner5747b932014-03-05 14:22:34 +01002045 server, client = self._loopback()
2046
2047 self.assertNotEqual(server.get_finished(), None)
2048 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002049
Jean-Paul Calderoned979f232014-03-30 11:58:00 -04002050
Fedor Brunner416f4a12014-03-28 13:18:38 +01002051 def test_get_peer_finished(self):
2052 """
2053 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002054 message received from client, or server. Finished messages are send
2055 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002056 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002057 server, client = self._loopback()
2058
2059 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002060 self.assertTrue(len(server.get_peer_finished()) > 0)
2061
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002062
Fedor Brunner416f4a12014-03-28 13:18:38 +01002063 def test_tls_finished_message_symmetry(self):
2064 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002065 The TLS Finished message send by server must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002066 received by client.
2067
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002068 The TLS Finished message send by client must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002069 received by server.
2070 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002071 server, client = self._loopback()
2072
Fedor Brunner5747b932014-03-05 14:22:34 +01002073 self.assertEqual(server.get_finished(), client.get_peer_finished())
2074 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002075
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002076
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002077 def test_get_cipher_name_before_connect(self):
2078 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002079 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2080 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002081 """
2082 ctx = Context(TLSv1_METHOD)
2083 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002084 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002085
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002086
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002087 def test_get_cipher_name(self):
2088 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002089 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2090 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002091 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002092 server, client = self._loopback()
2093 server_cipher_name, client_cipher_name = \
2094 server.get_cipher_name(), client.get_cipher_name()
2095
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002096 self.assertIsInstance(server_cipher_name, text_type)
2097 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002098
2099 self.assertEqual(server_cipher_name, client_cipher_name)
2100
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002101
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002102 def test_get_cipher_version_before_connect(self):
2103 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002104 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2105 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002106 """
2107 ctx = Context(TLSv1_METHOD)
2108 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002109 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002110
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002111
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002112 def test_get_cipher_version(self):
2113 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002114 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2115 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002116 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002117 server, client = self._loopback()
2118 server_cipher_version, client_cipher_version = \
2119 server.get_cipher_version(), client.get_cipher_version()
2120
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002121 self.assertIsInstance(server_cipher_version, text_type)
2122 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002123
2124 self.assertEqual(server_cipher_version, client_cipher_version)
2125
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002126
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002127 def test_get_cipher_bits_before_connect(self):
2128 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002129 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2130 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002131 """
2132 ctx = Context(TLSv1_METHOD)
2133 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002134 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002135
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002136
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002137 def test_get_cipher_bits(self):
2138 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002139 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2140 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002141 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002142 server, client = self._loopback()
2143 server_cipher_bits, client_cipher_bits = \
2144 server.get_cipher_bits(), client.get_cipher_bits()
2145
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002146 self.assertIsInstance(server_cipher_bits, int)
2147 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002148
2149 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002150
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002151
2152
2153class ConnectionGetCipherListTests(TestCase):
2154 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002155 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002156 """
2157 def test_wrong_args(self):
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002158 """
2159 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if called with any
2160 arguments.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002161 """
2162 connection = Connection(Context(TLSv1_METHOD), None)
2163 self.assertRaises(TypeError, connection.get_cipher_list, None)
2164
Jonathan Ballet648875f2011-07-16 14:14:58 +09002165
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002166 def test_result(self):
2167 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002168 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2169 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002170 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002171 connection = Connection(Context(TLSv1_METHOD), None)
2172 ciphers = connection.get_cipher_list()
2173 self.assertTrue(isinstance(ciphers, list))
2174 for cipher in ciphers:
2175 self.assertTrue(isinstance(cipher, str))
2176
2177
2178
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002179class ConnectionSendTests(TestCase, _LoopbackMixin):
2180 """
2181 Tests for :py:obj:`Connection.send`
2182 """
2183 def test_wrong_args(self):
2184 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002185 When called with arguments other than string argument for its first
2186 parameter or more than two arguments, :py:obj:`Connection.send` raises
2187 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002188 """
2189 connection = Connection(Context(TLSv1_METHOD), None)
2190 self.assertRaises(TypeError, connection.send)
2191 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002192 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002193
2194
2195 def test_short_bytes(self):
2196 """
2197 When passed a short byte string, :py:obj:`Connection.send` transmits all of it
2198 and returns the number of bytes sent.
2199 """
2200 server, client = self._loopback()
2201 count = server.send(b('xy'))
2202 self.assertEquals(count, 2)
2203 self.assertEquals(client.recv(2), b('xy'))
2204
2205 try:
2206 memoryview
2207 except NameError:
2208 "cannot test sending memoryview without memoryview"
2209 else:
2210 def test_short_memoryview(self):
2211 """
2212 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002213 :py:obj:`Connection.send` transmits all of them and returns the number of
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002214 bytes sent.
2215 """
2216 server, client = self._loopback()
2217 count = server.send(memoryview(b('xy')))
2218 self.assertEquals(count, 2)
2219 self.assertEquals(client.recv(2), b('xy'))
2220
2221
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002222
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002223class ConnectionSendallTests(TestCase, _LoopbackMixin):
2224 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002225 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002226 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002227 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002228 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002229 When called with arguments other than a string argument for its first
2230 parameter or with more than two arguments, :py:obj:`Connection.sendall`
2231 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002232 """
2233 connection = Connection(Context(TLSv1_METHOD), None)
2234 self.assertRaises(TypeError, connection.sendall)
2235 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002236 self.assertRaises(
2237 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002238
2239
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002240 def test_short(self):
2241 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002242 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002243 it.
2244 """
2245 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04002246 server.sendall(b('x'))
2247 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002248
2249
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002250 try:
2251 memoryview
2252 except NameError:
2253 "cannot test sending memoryview without memoryview"
2254 else:
2255 def test_short_memoryview(self):
2256 """
2257 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002258 :py:obj:`Connection.sendall` transmits all of them.
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002259 """
2260 server, client = self._loopback()
2261 server.sendall(memoryview(b('x')))
2262 self.assertEquals(client.recv(1), b('x'))
2263
2264
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002265 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002266 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002267 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002268 it even if this requires multiple calls of an underlying write function.
2269 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002270 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04002271 # Should be enough, underlying SSL_write should only do 16k at a time.
2272 # On Windows, after 32k of bytes the write will block (forever - because
2273 # no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04002274 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002275 server.sendall(message)
2276 accum = []
2277 received = 0
2278 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04002279 data = client.recv(1024)
2280 accum.append(data)
2281 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04002282 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002283
2284
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002285 def test_closed(self):
2286 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002287 If the underlying socket is closed, :py:obj:`Connection.sendall` propagates the
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002288 write error from the low level write call.
2289 """
2290 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04002291 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002292 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002293 if platform == "win32":
2294 self.assertEqual(exc.args[0], ESHUTDOWN)
2295 else:
2296 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002297
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002298
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002299
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002300class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
2301 """
2302 Tests for SSL renegotiation APIs.
2303 """
2304 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002305 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002306 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002307 arguments.
2308 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002309 connection = Connection(Context(TLSv1_METHOD), None)
2310 self.assertRaises(TypeError, connection.renegotiate, None)
2311
2312
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002313 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002314 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002315 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if called with
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002316 any arguments.
2317 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002318 connection = Connection(Context(TLSv1_METHOD), None)
2319 self.assertRaises(TypeError, connection.total_renegotiations, None)
2320
2321
2322 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002323 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002324 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002325 renegotiations have happened.
2326 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002327 connection = Connection(Context(TLSv1_METHOD), None)
2328 self.assertEquals(connection.total_renegotiations(), 0)
2329
2330
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002331# def test_renegotiate(self):
2332# """
2333# """
2334# server, client = self._loopback()
2335
2336# server.send("hello world")
2337# self.assertEquals(client.recv(len("hello world")), "hello world")
2338
2339# self.assertEquals(server.total_renegotiations(), 0)
2340# self.assertTrue(server.renegotiate())
2341
2342# server.setblocking(False)
2343# client.setblocking(False)
2344# while server.renegotiate_pending():
2345# client.do_handshake()
2346# server.do_handshake()
2347
2348# self.assertEquals(server.total_renegotiations(), 1)
2349
2350
2351
2352
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002353class ErrorTests(TestCase):
2354 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002355 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002356 """
2357 def test_type(self):
2358 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002359 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002360 """
2361 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05002362 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05002363
2364
2365
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002366class ConstantsTests(TestCase):
2367 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002368 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002369
2370 These are values defined by OpenSSL intended only to be used as flags to
2371 OpenSSL APIs. The only assertions it seems can be made about them is
2372 their values.
2373 """
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002374 # unittest.TestCase has no skip mechanism
2375 if OP_NO_QUERY_MTU is not None:
2376 def test_op_no_query_mtu(self):
2377 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002378 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002379 :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002380 """
2381 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
2382 else:
2383 "OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002384
2385
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002386 if OP_COOKIE_EXCHANGE is not None:
2387 def test_op_cookie_exchange(self):
2388 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002389 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the value
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002390 of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002391 """
2392 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
2393 else:
2394 "OP_COOKIE_EXCHANGE unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002395
2396
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002397 if OP_NO_TICKET is not None:
2398 def test_op_no_ticket(self):
2399 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002400 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002401 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002402 """
2403 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderonecebd1782011-09-11 10:01:31 -04002404 else:
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002405 "OP_NO_TICKET unavailable - OpenSSL version may be too old"
Rick Dean5b7b6372009-04-01 11:34:06 -05002406
2407
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002408 if OP_NO_COMPRESSION is not None:
2409 def test_op_no_compression(self):
2410 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002411 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the value
2412 of :py:const:`SSL_OP_NO_COMPRESSION` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002413 """
2414 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
2415 else:
2416 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
2417
2418
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002419 def test_sess_cache_off(self):
2420 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002421 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
2422 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002423 """
2424 self.assertEqual(0x0, SESS_CACHE_OFF)
2425
2426
2427 def test_sess_cache_client(self):
2428 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002429 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
2430 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002431 """
2432 self.assertEqual(0x1, SESS_CACHE_CLIENT)
2433
2434
2435 def test_sess_cache_server(self):
2436 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002437 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
2438 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002439 """
2440 self.assertEqual(0x2, SESS_CACHE_SERVER)
2441
2442
2443 def test_sess_cache_both(self):
2444 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002445 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
2446 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002447 """
2448 self.assertEqual(0x3, SESS_CACHE_BOTH)
2449
2450
2451 def test_sess_cache_no_auto_clear(self):
2452 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002453 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
2454 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
2455 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002456 """
2457 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
2458
2459
2460 def test_sess_cache_no_internal_lookup(self):
2461 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002462 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
2463 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
2464 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002465 """
2466 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
2467
2468
2469 def test_sess_cache_no_internal_store(self):
2470 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002471 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
2472 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
2473 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002474 """
2475 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
2476
2477
2478 def test_sess_cache_no_internal(self):
2479 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002480 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
2481 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
2482 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002483 """
2484 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
2485
2486
Jean-Paul Calderoneeeee26a2009-04-27 11:24:30 -04002487
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002488class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05002489 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002490 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05002491 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002492 def _server(self, sock):
2493 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002494 Create a new server-side SSL :py:obj:`Connection` object wrapped around
2495 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002496 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002497 # Create the server side Connection. This is mostly setup boilerplate
2498 # - use TLSv1, use a particular certificate, etc.
2499 server_ctx = Context(TLSv1_METHOD)
2500 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2501 server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2502 server_store = server_ctx.get_cert_store()
2503 server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2504 server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2505 server_ctx.check_privatekey()
2506 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002507 # Here the Connection is actually created. If None is passed as the 2nd
2508 # parameter, it indicates a memory BIO should be created.
2509 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002510 server_conn.set_accept_state()
2511 return server_conn
2512
2513
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002514 def _client(self, sock):
2515 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002516 Create a new client-side SSL :py:obj:`Connection` object wrapped around
2517 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002518 """
2519 # Now create the client side Connection. Similar boilerplate to the
2520 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002521 client_ctx = Context(TLSv1_METHOD)
2522 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2523 client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2524 client_store = client_ctx.get_cert_store()
2525 client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
2526 client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
2527 client_ctx.check_privatekey()
2528 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002529 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002530 client_conn.set_connect_state()
2531 return client_conn
2532
2533
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002534 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002535 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002536 Two :py:obj:`Connection`s which use memory BIOs can be manually connected by
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002537 reading from the output of each and writing those bytes to the input of
2538 the other and in this way establish a connection and exchange
2539 application-level bytes with each other.
2540 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002541 server_conn = self._server(None)
2542 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002543
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002544 # There should be no key or nonces yet.
2545 self.assertIdentical(server_conn.master_key(), None)
2546 self.assertIdentical(server_conn.client_random(), None)
2547 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002548
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002549 # First, the handshake needs to happen. We'll deliver bytes back and
2550 # forth between the client and server until neither of them feels like
2551 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002552 self.assertIdentical(
2553 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002554
2555 # Now that the handshake is done, there should be a key and nonces.
2556 self.assertNotIdentical(server_conn.master_key(), None)
2557 self.assertNotIdentical(server_conn.client_random(), None)
2558 self.assertNotIdentical(server_conn.server_random(), None)
Jean-Paul Calderone6c051e62009-07-05 13:50:34 -04002559 self.assertEquals(server_conn.client_random(), client_conn.client_random())
2560 self.assertEquals(server_conn.server_random(), client_conn.server_random())
2561 self.assertNotEquals(server_conn.client_random(), server_conn.server_random())
2562 self.assertNotEquals(client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002563
2564 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002565 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05002566
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002567 server_conn.write(important_message)
2568 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002569 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002570 (client_conn, important_message))
2571
2572 client_conn.write(important_message[::-1])
2573 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002574 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002575 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05002576
2577
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002578 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05002579 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002580 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002581
2582 This is primarily to rule out the memory BIO code as the source of
Jonathan Ballet648875f2011-07-16 14:14:58 +09002583 any problems encountered while passing data over a :py:obj:`Connection` (if
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002584 this test fails, there must be a problem outside the memory BIO
2585 code, as no memory BIO is involved here). Even though this isn't a
2586 memory BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05002587 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04002588 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05002589
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002590 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05002591 client_conn.send(important_message)
2592 msg = server_conn.recv(1024)
2593 self.assertEqual(msg, important_message)
2594
2595 # Again in the other direction, just for fun.
2596 important_message = important_message[::-1]
2597 server_conn.send(important_message)
2598 msg = client_conn.recv(1024)
2599 self.assertEqual(msg, important_message)
2600
2601
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04002602 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05002603 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002604 Test that :py:obj:`OpenSSL.SSL.bio_read` and :py:obj:`OpenSSL.SSL.bio_write` don't
2605 work on :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05002606 """
2607 context = Context(SSLv3_METHOD)
2608 client = socket()
2609 clientSSL = Connection(context, client)
2610 self.assertRaises( TypeError, clientSSL.bio_read, 100)
2611 self.assertRaises( TypeError, clientSSL.bio_write, "foo")
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04002612 self.assertRaises( TypeError, clientSSL.bio_shutdown )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002613
2614
2615 def test_outgoingOverflow(self):
2616 """
2617 If more bytes than can be written to the memory BIO are passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002618 :py:obj:`Connection.send` at once, the number of bytes which were written is
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002619 returned and that many bytes from the beginning of the input can be
2620 read from the other end of the connection.
2621 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002622 server = self._server(None)
2623 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002624
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002625 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002626
2627 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002628 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002629 # Sanity check. We're trying to test what happens when the entire
2630 # input can't be sent. If the entire input was sent, this test is
2631 # meaningless.
2632 self.assertTrue(sent < size)
2633
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002634 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002635 self.assertIdentical(receiver, server)
2636
2637 # We can rely on all of these bytes being received at once because
2638 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
2639 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002640
2641
2642 def test_shutdown(self):
2643 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002644 :py:obj:`Connection.bio_shutdown` signals the end of the data stream from
2645 which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002646 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002647 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002648 server.bio_shutdown()
2649 e = self.assertRaises(Error, server.recv, 1024)
2650 # We don't want WantReadError or ZeroReturnError or anything - it's a
2651 # handshake failure.
2652 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002653
2654
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002655 def test_unexpectedEndOfFile(self):
2656 """
2657 If the connection is lost before an orderly SSL shutdown occurs,
2658 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
2659 "Unexpected EOF".
2660 """
2661 server_conn, client_conn = self._loopback()
2662 client_conn.sock_shutdown(SHUT_RDWR)
2663 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
2664 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
2665
2666
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002667 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002668 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002669 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 -04002670
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002671 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002672 before the client and server are connected to each other. This
2673 function should specify a list of CAs for the server to send to the
2674 client and return that same list. The list will be used to verify
Jonathan Ballet648875f2011-07-16 14:14:58 +09002675 that :py:obj:`get_client_ca_list` returns the proper value at various
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002676 times.
2677 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002678 server = self._server(None)
2679 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002680 self.assertEqual(client.get_client_ca_list(), [])
2681 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002682 ctx = server.get_context()
2683 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002684 self.assertEqual(client.get_client_ca_list(), [])
2685 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002686 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002687 self.assertEqual(client.get_client_ca_list(), expected)
2688 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002689
2690
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002691 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002692 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002693 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if called with a
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002694 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002695 """
2696 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002697 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
2698 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
2699 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002700
2701
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002702 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002703 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002704 If passed an empty list, :py:obj:`Context.set_client_ca_list` configures the
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002705 context to send no CA names to the client and, on both the server and
Jonathan Ballet648875f2011-07-16 14:14:58 +09002706 client sides, :py:obj:`Connection.get_client_ca_list` returns an empty list
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002707 after the connection is set up.
2708 """
2709 def no_ca(ctx):
2710 ctx.set_client_ca_list([])
2711 return []
2712 self._check_client_ca_list(no_ca)
2713
2714
2715 def test_set_one_ca_list(self):
2716 """
2717 If passed a list containing a single X509Name,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002718 :py:obj:`Context.set_client_ca_list` configures the context to send that CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002719 name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002720 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002721 X509Name after the connection is set up.
2722 """
2723 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2724 cadesc = cacert.get_subject()
2725 def single_ca(ctx):
2726 ctx.set_client_ca_list([cadesc])
2727 return [cadesc]
2728 self._check_client_ca_list(single_ca)
2729
2730
2731 def test_set_multiple_ca_list(self):
2732 """
2733 If passed a list containing multiple X509Name objects,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002734 :py:obj:`Context.set_client_ca_list` configures the context to send those CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002735 names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002736 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002737 X509Names after the connection is set up.
2738 """
2739 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2740 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2741
2742 sedesc = secert.get_subject()
2743 cldesc = clcert.get_subject()
2744
2745 def multiple_ca(ctx):
2746 L = [sedesc, cldesc]
2747 ctx.set_client_ca_list(L)
2748 return L
2749 self._check_client_ca_list(multiple_ca)
2750
2751
2752 def test_reset_ca_list(self):
2753 """
2754 If called multiple times, only the X509Names passed to the final call
Jonathan Ballet648875f2011-07-16 14:14:58 +09002755 of :py:obj:`Context.set_client_ca_list` are used to configure the CA names
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002756 sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002757 """
2758 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2759 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2760 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2761
2762 cadesc = cacert.get_subject()
2763 sedesc = secert.get_subject()
2764 cldesc = clcert.get_subject()
2765
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002766 def changed_ca(ctx):
2767 ctx.set_client_ca_list([sedesc, cldesc])
2768 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002769 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002770 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002771
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002772
2773 def test_mutated_ca_list(self):
2774 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002775 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002776 afterwards, this does not affect the list of CA names sent to the
2777 client.
2778 """
2779 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2780 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2781
2782 cadesc = cacert.get_subject()
2783 sedesc = secert.get_subject()
2784
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002785 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002786 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002787 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002788 L.append(sedesc)
2789 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002790 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002791
2792
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002793 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002794 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002795 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called with a non-X509
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002796 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002797 """
2798 ctx = Context(TLSv1_METHOD)
2799 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002800 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002801 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002802 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002803
2804
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002805 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002806 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002807 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09002808 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002809 """
2810 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2811 cadesc = cacert.get_subject()
2812 def single_ca(ctx):
2813 ctx.add_client_ca(cacert)
2814 return [cadesc]
2815 self._check_client_ca_list(single_ca)
2816
2817
2818 def test_multiple_add_client_ca(self):
2819 """
2820 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09002821 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002822 """
2823 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2824 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2825
2826 cadesc = cacert.get_subject()
2827 sedesc = secert.get_subject()
2828
2829 def multiple_ca(ctx):
2830 ctx.add_client_ca(cacert)
2831 ctx.add_client_ca(secert)
2832 return [cadesc, sedesc]
2833 self._check_client_ca_list(multiple_ca)
2834
2835
2836 def test_set_and_add_client_ca(self):
2837 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002838 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
2839 :py:obj:`Context.add_client_ca` results in using the CA names from the first
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002840 call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002841 """
2842 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2843 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2844 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2845
2846 cadesc = cacert.get_subject()
2847 sedesc = secert.get_subject()
2848 cldesc = clcert.get_subject()
2849
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002850 def mixed_set_add_ca(ctx):
2851 ctx.set_client_ca_list([cadesc, sedesc])
2852 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002853 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002854 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002855
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002856
2857 def test_set_after_add_client_ca(self):
2858 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002859 A call to :py:obj:`Context.set_client_ca_list` after a call to
2860 :py:obj:`Context.add_client_ca` replaces the CA name specified by the former
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002861 call with the names specified by the latter cal.
2862 """
2863 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2864 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2865 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2866
2867 cadesc = cacert.get_subject()
2868 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002869
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002870 def set_replaces_add_ca(ctx):
2871 ctx.add_client_ca(clcert)
2872 ctx.set_client_ca_list([cadesc])
2873 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002874 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002875 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002876
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002877
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002878
2879class ConnectionBIOTests(TestCase):
2880 """
2881 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
2882 """
2883 def test_wantReadError(self):
2884 """
2885 :py:obj:`Connection.bio_read` raises :py:obj:`OpenSSL.SSL.WantReadError`
2886 if there are no bytes available to be read from the BIO.
2887 """
2888 ctx = Context(TLSv1_METHOD)
2889 conn = Connection(ctx, None)
2890 self.assertRaises(WantReadError, conn.bio_read, 1024)
2891
2892
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002893 def test_buffer_size(self):
2894 """
2895 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
2896 number of bytes to read and return.
2897 """
2898 ctx = Context(TLSv1_METHOD)
2899 conn = Connection(ctx, None)
2900 conn.set_connect_state()
2901 try:
2902 conn.do_handshake()
2903 except WantReadError:
2904 pass
2905 data = conn.bio_read(2)
2906 self.assertEqual(2, len(data))
2907
2908
2909 if not PY3:
2910 def test_buffer_size_long(self):
2911 """
2912 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
2913 :py:obj:`long` as well as :py:obj:`int`.
2914 """
2915 ctx = Context(TLSv1_METHOD)
2916 conn = Connection(ctx, None)
2917 conn.set_connect_state()
2918 try:
2919 conn.do_handshake()
2920 except WantReadError:
2921 pass
2922 data = conn.bio_read(long(2))
2923 self.assertEqual(2, len(data))
2924
2925
2926
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002927
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04002928class InfoConstantTests(TestCase):
2929 """
2930 Tests for assorted constants exposed for use in info callbacks.
2931 """
2932 def test_integers(self):
2933 """
2934 All of the info constants are integers.
2935
2936 This is a very weak test. It would be nice to have one that actually
2937 verifies that as certain info events happen, the value passed to the
2938 info callback matches up with the constant exposed by OpenSSL.SSL.
2939 """
2940 for const in [
2941 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
2942 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
2943 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
2944 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
2945 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
2946 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE]:
2947
2948 self.assertTrue(isinstance(const, int))
2949
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02002950
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002951if __name__ == '__main__':
2952 main()