blob: b4f81b4fe03c2f50c4c07a32b1f288a1663fb2c4 [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 """
Andy Lutomirski61d7d392014-04-04 12:16:56 -07001181 :py:obj:`Context.set_tmp_ecdh_curve` sets the elliptic
1182 curve for 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 """
1208 :py:obj:`Context.set_tmp_ecdh_curve` raises
1209 :py:obj:`UnknownObject` if passed a curve_name that OpenSSL
1210 does not recognize and EC is available. It raises
1211 :py:obj:`ECNotAvailable` if EC is not available at all.
1212 """
1213 context = Context(TLSv1_METHOD)
1214 try:
1215 context.set_tmp_ecdh_curve('not_an_elliptic_curve')
1216 except ECNotAvailable:
1217 self.assertFalse(_Cryptography_HAS_EC)
1218 except UnknownObject:
1219 self.assertTrue(_Cryptography_HAS_EC)
1220 else:
1221 self.assertFalse(True)
1222
1223
1224 def test_set_tmp_ecdh_curve_not_a_curve(self):
1225 """
1226 :py:obj:`Context.set_tmp_ecdh_curve` raises
1227 :py:obj:`UnsupportedEllipticCurve` if passed a curve_name that
1228 OpenSSL cannot instantiate as an elliptic curve. It raises
1229 :py:obj:`ECNotAvailable` if EC is not available at all.
1230 """
1231 context = Context(TLSv1_METHOD)
1232 try:
1233 context.set_tmp_ecdh_curve('sha256')
1234 except ECNotAvailable:
1235 self.assertFalse(_Cryptography_HAS_EC)
1236 except UnknownObject:
1237 self.assertTrue(_Cryptography_HAS_EC)
1238 else:
1239 self.assertFalse(True)
1240
1241
Laurens Van Houtvenf5df2432014-04-03 12:17:28 +02001242 def test_has_curve_descriptions(self):
1243 """
1244 If the underlying cryptography bindings claim to have elliptic
1245 curve support, there should be at least one curve.
1246
1247 (In theory there could be an OpenSSL that violates this
1248 assumption. If so, this test will fail and we'll find out.)
1249
1250 """
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001251 if _Cryptography_HAS_EC:
Laurens Van Houtvenf5df2432014-04-03 12:17:28 +02001252 self.assertNotEqual(len(ELLIPTIC_CURVE_DESCRIPTIONS), 0)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001253
1254
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001255 def test_set_cipher_list_bytes(self):
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001256 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001257 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
1258 ciphers which connections created with the context object will be able
1259 to choose from.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001260 """
1261 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001262 context.set_cipher_list(b"hello world:EXP-RC4-MD5")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001263 conn = Connection(context, None)
1264 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001265
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001266
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001267 def test_set_cipher_list_text(self):
1268 """
1269 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
1270 the ciphers which connections created with the context object will be
1271 able to choose from.
1272 """
1273 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -05001274 context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001275 conn = Connection(context, None)
1276 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
1277
1278
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001279 def test_set_cipher_list_wrong_args(self):
1280 """
Jean-Paul Calderone17044832014-01-18 10:20:11 -05001281 :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
1282 passed zero arguments or more than one argument or when passed a
1283 non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001284 passed an incorrect cipher list string.
1285 """
1286 context = Context(TLSv1_METHOD)
1287 self.assertRaises(TypeError, context.set_cipher_list)
1288 self.assertRaises(TypeError, context.set_cipher_list, object())
1289 self.assertRaises(TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object())
1290
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001291 self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001292
1293
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001294 def test_set_session_cache_mode_wrong_args(self):
1295 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001296 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1297 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001298 """
1299 context = Context(TLSv1_METHOD)
1300 self.assertRaises(TypeError, context.set_session_cache_mode)
1301 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1302
1303
1304 def test_get_session_cache_mode_wrong_args(self):
1305 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001306 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1307 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001308 """
1309 context = Context(TLSv1_METHOD)
1310 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1311
1312
1313 def test_session_cache_mode(self):
1314 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001315 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1316 cached. The setting can be retrieved via
1317 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001318 """
1319 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001320 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001321 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1322 self.assertEqual(SESS_CACHE_OFF, off)
1323 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1324
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001325 if not PY3:
1326 def test_session_cache_mode_long(self):
1327 """
1328 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1329 of type :py:obj:`long` as well as :py:obj:`int`.
1330 """
1331 context = Context(TLSv1_METHOD)
1332 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1333 self.assertEqual(
1334 SESS_CACHE_BOTH, context.get_session_cache_mode())
1335
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001336
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001337 def test_get_cert_store(self):
1338 """
1339 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store` instance.
1340 """
1341 context = Context(TLSv1_METHOD)
1342 store = context.get_cert_store()
1343 self.assertIsInstance(store, X509Store)
1344
1345
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001346
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001347class ServerNameCallbackTests(TestCase, _LoopbackMixin):
1348 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001349 Tests for :py:obj:`Context.set_tlsext_servername_callback` and its interaction with
1350 :py:obj:`Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001351 """
1352 def test_wrong_args(self):
1353 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001354 :py:obj:`Context.set_tlsext_servername_callback` raises :py:obj:`TypeError` if called
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001355 with other than one argument.
1356 """
1357 context = Context(TLSv1_METHOD)
1358 self.assertRaises(TypeError, context.set_tlsext_servername_callback)
1359 self.assertRaises(
1360 TypeError, context.set_tlsext_servername_callback, 1, 2)
1361
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001362
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001363 def test_old_callback_forgotten(self):
1364 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001365 If :py:obj:`Context.set_tlsext_servername_callback` is used to specify a new
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001366 callback, the one it replaces is dereferenced.
1367 """
1368 def callback(connection):
1369 pass
1370
1371 def replacement(connection):
1372 pass
1373
1374 context = Context(TLSv1_METHOD)
1375 context.set_tlsext_servername_callback(callback)
1376
1377 tracker = ref(callback)
1378 del callback
1379
1380 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001381
1382 # One run of the garbage collector happens to work on CPython. PyPy
1383 # doesn't collect the underlying object until a second run for whatever
1384 # reason. That's fine, it still demonstrates our code has properly
1385 # dropped the reference.
1386 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001387 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001388
1389 callback = tracker()
1390 if callback is not None:
1391 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001392 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001393 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001394
1395
1396 def test_no_servername(self):
1397 """
1398 When a client specifies no server name, the callback passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001399 :py:obj:`Context.set_tlsext_servername_callback` is invoked and the result of
1400 :py:obj:`Connection.get_servername` is :py:obj:`None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001401 """
1402 args = []
1403 def servername(conn):
1404 args.append((conn, conn.get_servername()))
1405 context = Context(TLSv1_METHOD)
1406 context.set_tlsext_servername_callback(servername)
1407
1408 # Lose our reference to it. The Context is responsible for keeping it
1409 # alive now.
1410 del servername
1411 collect()
1412
1413 # Necessary to actually accept the connection
1414 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1415 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1416
1417 # Do a little connection to trigger the logic
1418 server = Connection(context, None)
1419 server.set_accept_state()
1420
1421 client = Connection(Context(TLSv1_METHOD), None)
1422 client.set_connect_state()
1423
1424 self._interactInMemory(server, client)
1425
1426 self.assertEqual([(server, None)], args)
1427
1428
1429 def test_servername(self):
1430 """
1431 When a client specifies a server name in its hello message, the callback
Jonathan Ballet648875f2011-07-16 14:14:58 +09001432 passed to :py:obj:`Contexts.set_tlsext_servername_callback` is invoked and the
1433 result of :py:obj:`Connection.get_servername` is that server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001434 """
1435 args = []
1436 def servername(conn):
1437 args.append((conn, conn.get_servername()))
1438 context = Context(TLSv1_METHOD)
1439 context.set_tlsext_servername_callback(servername)
1440
1441 # Necessary to actually accept the connection
1442 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1443 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1444
1445 # Do a little connection to trigger the logic
1446 server = Connection(context, None)
1447 server.set_accept_state()
1448
1449 client = Connection(Context(TLSv1_METHOD), None)
1450 client.set_connect_state()
1451 client.set_tlsext_host_name(b("foo1.example.com"))
1452
1453 self._interactInMemory(server, client)
1454
1455 self.assertEqual([(server, b("foo1.example.com"))], args)
1456
1457
1458
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05001459class SessionTests(TestCase):
1460 """
1461 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
1462 """
1463 def test_construction(self):
1464 """
1465 :py:class:`Session` can be constructed with no arguments, creating a new
1466 instance of that type.
1467 """
1468 new_session = Session()
1469 self.assertTrue(isinstance(new_session, Session))
1470
1471
1472 def test_construction_wrong_args(self):
1473 """
1474 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
1475 is raised.
1476 """
1477 self.assertRaises(TypeError, Session, 123)
1478 self.assertRaises(TypeError, Session, "hello")
1479 self.assertRaises(TypeError, Session, object())
1480
1481
1482
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001483class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05001484 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001485 Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05001486 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04001487 # XXX get_peer_certificate -> None
1488 # XXX sock_shutdown
1489 # XXX master_key -> TypeError
1490 # XXX server_random -> TypeError
1491 # XXX state_string
1492 # XXX connect -> TypeError
1493 # XXX connect_ex -> TypeError
1494 # XXX set_connect_state -> TypeError
1495 # XXX set_accept_state -> TypeError
1496 # XXX renegotiate_pending
1497 # XXX do_handshake -> TypeError
1498 # XXX bio_read -> TypeError
1499 # XXX recv -> TypeError
1500 # XXX send -> TypeError
1501 # XXX bio_write -> TypeError
1502
Rick Deane15b1472009-07-09 15:53:42 -05001503 def test_type(self):
1504 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001505 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same type object and
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001506 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05001507 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001508 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05001509 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001510 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05001511
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001512
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001513 def test_get_context(self):
1514 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001515 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance used to
1516 construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001517 """
1518 context = Context(TLSv1_METHOD)
1519 connection = Connection(context, None)
1520 self.assertIdentical(connection.get_context(), context)
1521
1522
1523 def test_get_context_wrong_args(self):
1524 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001525 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001526 arguments.
1527 """
1528 connection = Connection(Context(TLSv1_METHOD), None)
1529 self.assertRaises(TypeError, connection.get_context, None)
1530
1531
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001532 def test_set_context_wrong_args(self):
1533 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001534 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called with a
1535 non-:py:obj:`Context` instance argument or with any number of arguments other
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001536 than 1.
1537 """
1538 ctx = Context(TLSv1_METHOD)
1539 connection = Connection(ctx, None)
1540 self.assertRaises(TypeError, connection.set_context)
1541 self.assertRaises(TypeError, connection.set_context, object())
1542 self.assertRaises(TypeError, connection.set_context, "hello")
1543 self.assertRaises(TypeError, connection.set_context, 1)
1544 self.assertRaises(TypeError, connection.set_context, 1, 2)
1545 self.assertRaises(
1546 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
1547 self.assertIdentical(ctx, connection.get_context())
1548
1549
1550 def test_set_context(self):
1551 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001552 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context` instance to be used
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001553 for the connection.
1554 """
1555 original = Context(SSLv23_METHOD)
1556 replacement = Context(TLSv1_METHOD)
1557 connection = Connection(original, None)
1558 connection.set_context(replacement)
1559 self.assertIdentical(replacement, connection.get_context())
1560 # Lose our references to the contexts, just in case the Connection isn't
1561 # properly managing its own contributions to their reference counts.
1562 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001563 collect()
1564
1565
1566 def test_set_tlsext_host_name_wrong_args(self):
1567 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001568 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte string
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001569 argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09001570 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001571 """
1572 conn = Connection(Context(TLSv1_METHOD), None)
1573 self.assertRaises(TypeError, conn.set_tlsext_host_name)
1574 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
1575 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
1576 self.assertRaises(
1577 TypeError, conn.set_tlsext_host_name, b("with\0null"))
1578
1579 if version_info >= (3,):
1580 # On Python 3.x, don't accidentally implicitly convert from text.
1581 self.assertRaises(
1582 TypeError,
1583 conn.set_tlsext_host_name, b("example.com").decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001584
1585
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001586 def test_get_servername_wrong_args(self):
1587 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001588 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001589 arguments.
1590 """
1591 connection = Connection(Context(TLSv1_METHOD), None)
1592 self.assertRaises(TypeError, connection.get_servername, object())
1593 self.assertRaises(TypeError, connection.get_servername, 1)
1594 self.assertRaises(TypeError, connection.get_servername, "hello")
1595
1596
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001597 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001598 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001599 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001600 immediate read.
1601 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001602 connection = Connection(Context(TLSv1_METHOD), None)
1603 self.assertEquals(connection.pending(), 0)
1604
1605
1606 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001607 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001608 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001609 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001610 connection = Connection(Context(TLSv1_METHOD), None)
1611 self.assertRaises(TypeError, connection.pending, None)
1612
1613
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001614 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001615 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001616 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with a non-address
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001617 argument or with the wrong number of arguments.
1618 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001619 connection = Connection(Context(TLSv1_METHOD), socket())
1620 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001621 self.assertRaises(TypeError, connection.connect)
1622 self.assertRaises(TypeError, connection.connect, ("127.0.0.1", 1), None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001623
1624
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001625 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001626 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001627 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the underlying socket
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001628 connect method raises it.
1629 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001630 client = socket()
1631 context = Context(TLSv1_METHOD)
1632 clientSSL = Connection(context, client)
1633 exc = self.assertRaises(error, clientSSL.connect, ("127.0.0.1", 1))
Jean-Paul Calderone35adf9d2010-07-29 18:40:44 -04001634 self.assertEquals(exc.args[0], ECONNREFUSED)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001635
1636
1637 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001638 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001639 :py:obj:`Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001640 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001641 port = socket()
1642 port.bind(('', 0))
1643 port.listen(3)
1644
1645 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001646 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
1647 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001648
1649
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001650 if platform == "darwin":
1651 "connect_ex sometimes causes a kernel panic on OS X 10.6.4"
1652 else:
1653 def test_connect_ex(self):
1654 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001655 If there is a connection error, :py:obj:`Connection.connect_ex` returns the
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001656 errno instead of raising an exception.
1657 """
1658 port = socket()
1659 port.bind(('', 0))
1660 port.listen(3)
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001661
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001662 clientSSL = Connection(Context(TLSv1_METHOD), socket())
1663 clientSSL.setblocking(False)
1664 result = clientSSL.connect_ex(port.getsockname())
1665 expected = (EINPROGRESS, EWOULDBLOCK)
1666 self.assertTrue(
1667 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001668
1669
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001670 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001671 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001672 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001673 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001674 connection = Connection(Context(TLSv1_METHOD), socket())
1675 self.assertRaises(TypeError, connection.accept, None)
1676
1677
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001678 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001679 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001680 :py:obj:`Connection.accept` accepts a pending connection attempt and returns a
1681 tuple of a new :py:obj:`Connection` (the accepted client) and the address the
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001682 connection originated from.
1683 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001684 ctx = Context(TLSv1_METHOD)
1685 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1686 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001687 port = socket()
1688 portSSL = Connection(ctx, port)
1689 portSSL.bind(('', 0))
1690 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001691
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001692 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001693
1694 # Calling portSSL.getsockname() here to get the server IP address sounds
1695 # great, but frequently fails on Windows.
1696 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001697
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001698 serverSSL, address = portSSL.accept()
1699
1700 self.assertTrue(isinstance(serverSSL, Connection))
1701 self.assertIdentical(serverSSL.get_context(), ctx)
1702 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001703
1704
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001705 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001706 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001707 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with the wrong
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001708 number of arguments or with arguments other than integers.
1709 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001710 connection = Connection(Context(TLSv1_METHOD), None)
1711 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04001712 self.assertRaises(TypeError, connection.get_shutdown, None)
1713 self.assertRaises(TypeError, connection.set_shutdown)
1714 self.assertRaises(TypeError, connection.set_shutdown, None)
1715 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001716
1717
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001718 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001719 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001720 :py:obj:`Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001721 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001722 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001723 self.assertFalse(server.shutdown())
1724 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001725 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001726 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
1727 client.shutdown()
1728 self.assertEquals(client.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
1729 self.assertRaises(ZeroReturnError, server.recv, 1024)
1730 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001731
1732
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001733 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001734 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001735 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection shutdown
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001736 process.
1737 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001738 connection = Connection(Context(TLSv1_METHOD), socket())
1739 connection.set_shutdown(RECEIVED_SHUTDOWN)
1740 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1741
1742
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001743 if not PY3:
1744 def test_set_shutdown_long(self):
1745 """
1746 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
1747 of type :py:obj:`long` as well as :py:obj:`int`.
1748 """
1749 connection = Connection(Context(TLSv1_METHOD), socket())
1750 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
1751 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1752
1753
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001754 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001755 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001756 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called with other than
1757 one argument. :py:obj:`Connection.get_app_data` raises :py:obj:`TypeError` if called
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001758 with any arguments.
1759 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001760 conn = Connection(Context(TLSv1_METHOD), None)
1761 self.assertRaises(TypeError, conn.get_app_data, None)
1762 self.assertRaises(TypeError, conn.set_app_data)
1763 self.assertRaises(TypeError, conn.set_app_data, None, None)
1764
1765
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001766 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001767 """
1768 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001769 :py:obj:`Connection.set_app_data` and later retrieved with
1770 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001771 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001772 conn = Connection(Context(TLSv1_METHOD), None)
1773 app_data = object()
1774 conn.set_app_data(app_data)
1775 self.assertIdentical(conn.get_app_data(), app_data)
1776
1777
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001778 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001779 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001780 :py:obj:`Connection.makefile` is not implemented and calling that method raises
1781 :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001782 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001783 conn = Connection(Context(TLSv1_METHOD), None)
1784 self.assertRaises(NotImplementedError, conn.makefile)
1785
1786
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001787 def test_get_peer_cert_chain_wrong_args(self):
1788 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001789 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001790 arguments.
1791 """
1792 conn = Connection(Context(TLSv1_METHOD), None)
1793 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
1794 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
1795 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
1796 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
1797
1798
1799 def test_get_peer_cert_chain(self):
1800 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001801 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates which
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001802 the connected server returned for the certification verification.
1803 """
1804 chain = _create_certificate_chain()
1805 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1806
1807 serverContext = Context(TLSv1_METHOD)
1808 serverContext.use_privatekey(skey)
1809 serverContext.use_certificate(scert)
1810 serverContext.add_extra_chain_cert(icert)
1811 serverContext.add_extra_chain_cert(cacert)
1812 server = Connection(serverContext, None)
1813 server.set_accept_state()
1814
1815 # Create the client
1816 clientContext = Context(TLSv1_METHOD)
1817 clientContext.set_verify(VERIFY_NONE, verify_cb)
1818 client = Connection(clientContext, None)
1819 client.set_connect_state()
1820
1821 self._interactInMemory(client, server)
1822
1823 chain = client.get_peer_cert_chain()
1824 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001825 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001826 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001827 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001828 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001829 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001830 "Authority Certificate", chain[2].get_subject().CN)
1831
1832
1833 def test_get_peer_cert_chain_none(self):
1834 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001835 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the peer sends no
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001836 certificate chain.
1837 """
1838 ctx = Context(TLSv1_METHOD)
1839 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1840 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1841 server = Connection(ctx, None)
1842 server.set_accept_state()
1843 client = Connection(Context(TLSv1_METHOD), None)
1844 client.set_connect_state()
1845 self._interactInMemory(client, server)
1846 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001847
1848
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001849 def test_get_session_wrong_args(self):
1850 """
1851 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
1852 with any arguments.
1853 """
1854 ctx = Context(TLSv1_METHOD)
1855 server = Connection(ctx, None)
1856 self.assertRaises(TypeError, server.get_session, 123)
1857 self.assertRaises(TypeError, server.get_session, "hello")
1858 self.assertRaises(TypeError, server.get_session, object())
1859
1860
1861 def test_get_session_unconnected(self):
1862 """
1863 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
1864 an object which has not been connected.
1865 """
1866 ctx = Context(TLSv1_METHOD)
1867 server = Connection(ctx, None)
1868 session = server.get_session()
1869 self.assertIdentical(None, session)
1870
1871
1872 def test_server_get_session(self):
1873 """
1874 On the server side of a connection, :py:obj:`Connection.get_session`
1875 returns a :py:class:`Session` instance representing the SSL session for
1876 that connection.
1877 """
1878 server, client = self._loopback()
1879 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001880 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001881
1882
1883 def test_client_get_session(self):
1884 """
1885 On the client side of a connection, :py:obj:`Connection.get_session`
1886 returns a :py:class:`Session` instance representing the SSL session for
1887 that connection.
1888 """
1889 server, client = self._loopback()
1890 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001892
1893
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001894 def test_set_session_wrong_args(self):
1895 """
1896 If called with an object that is not an instance of :py:class:`Session`,
1897 or with other than one argument, :py:obj:`Connection.set_session` raises
1898 :py:obj:`TypeError`.
1899 """
1900 ctx = Context(TLSv1_METHOD)
1901 connection = Connection(ctx, None)
1902 self.assertRaises(TypeError, connection.set_session)
1903 self.assertRaises(TypeError, connection.set_session, 123)
1904 self.assertRaises(TypeError, connection.set_session, "hello")
1905 self.assertRaises(TypeError, connection.set_session, object())
1906 self.assertRaises(
1907 TypeError, connection.set_session, Session(), Session())
1908
1909
1910 def test_client_set_session(self):
1911 """
1912 :py:obj:`Connection.set_session`, when used prior to a connection being
1913 established, accepts a :py:class:`Session` instance and causes an
1914 attempt to re-use the session it represents when the SSL handshake is
1915 performed.
1916 """
1917 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1918 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1919 ctx = Context(TLSv1_METHOD)
1920 ctx.use_privatekey(key)
1921 ctx.use_certificate(cert)
1922 ctx.set_session_id("unity-test")
1923
1924 def makeServer(socket):
1925 server = Connection(ctx, socket)
1926 server.set_accept_state()
1927 return server
1928
1929 originalServer, originalClient = self._loopback(
1930 serverFactory=makeServer)
1931 originalSession = originalClient.get_session()
1932
1933 def makeClient(socket):
1934 client = self._loopbackClientFactory(socket)
1935 client.set_session(originalSession)
1936 return client
1937 resumedServer, resumedClient = self._loopback(
1938 serverFactory=makeServer,
1939 clientFactory=makeClient)
1940
1941 # This is a proxy: in general, we have no access to any unique
1942 # identifier for the session (new enough versions of OpenSSL expose a
1943 # hash which could be usable, but "new enough" is very, very new).
1944 # Instead, exploit the fact that the master key is re-used if the
1945 # session is re-used. As long as the master key for the two connections
1946 # is the same, the session was re-used!
1947 self.assertEqual(
1948 originalServer.master_key(), resumedServer.master_key())
1949
1950
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001951 def test_set_session_wrong_method(self):
1952 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05001953 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
1954 instance associated with a context using a different SSL method than the
1955 :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
1956 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05001957 """
1958 key = load_privatekey(FILETYPE_PEM, server_key_pem)
1959 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
1960 ctx = Context(TLSv1_METHOD)
1961 ctx.use_privatekey(key)
1962 ctx.use_certificate(cert)
1963 ctx.set_session_id("unity-test")
1964
1965 def makeServer(socket):
1966 server = Connection(ctx, socket)
1967 server.set_accept_state()
1968 return server
1969
1970 originalServer, originalClient = self._loopback(
1971 serverFactory=makeServer)
1972 originalSession = originalClient.get_session()
1973
1974 def makeClient(socket):
1975 # Intentionally use a different, incompatible method here.
1976 client = Connection(Context(SSLv3_METHOD), socket)
1977 client.set_connect_state()
1978 client.set_session(originalSession)
1979 return client
1980
1981 self.assertRaises(
1982 Error,
1983 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
1984
1985
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001986 def test_wantWriteError(self):
1987 """
1988 :py:obj:`Connection` methods which generate output raise
1989 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
1990 fail indicating a should-write state.
1991 """
1992 client_socket, server_socket = socket_pair()
1993 # Fill up the client's send buffer so Connection won't be able to write
1994 # anything.
Jean-Paul Calderone7d7c9c22014-02-18 16:38:26 -05001995 msg = b"x" * 512
Jean-Paul Calderone22c28b42014-02-18 16:40:34 -05001996 for i in range(2048):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001997 try:
1998 client_socket.send(msg)
1999 except error as e:
2000 if e.errno == EWOULDBLOCK:
2001 break
2002 raise
2003 else:
2004 self.fail(
2005 "Failed to fill socket buffer, cannot test BIO want write")
2006
2007 ctx = Context(TLSv1_METHOD)
2008 conn = Connection(ctx, client_socket)
2009 # Client's speak first, so make it an SSL client
2010 conn.set_connect_state()
2011 self.assertRaises(WantWriteError, conn.do_handshake)
2012
2013 # XXX want_read
2014
Fedor Brunner416f4a12014-03-28 13:18:38 +01002015 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002016 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002017 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2018 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002019 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002020 ctx = Context(TLSv1_METHOD)
2021 connection = Connection(ctx, None)
2022 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002023
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002024
Fedor Brunner416f4a12014-03-28 13:18:38 +01002025 def test_get_peer_finished_before_connect(self):
2026 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002027 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2028 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002029 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002030 ctx = Context(TLSv1_METHOD)
2031 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002032 self.assertEqual(connection.get_peer_finished(), None)
2033
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002034
Fedor Brunner416f4a12014-03-28 13:18:38 +01002035 def test_get_finished(self):
2036 """
2037 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002038 message send from client, or server. Finished messages are send during
2039 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002040 """
2041
Fedor Brunner5747b932014-03-05 14:22:34 +01002042 server, client = self._loopback()
2043
2044 self.assertNotEqual(server.get_finished(), None)
2045 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002046
Jean-Paul Calderoned979f232014-03-30 11:58:00 -04002047
Fedor Brunner416f4a12014-03-28 13:18:38 +01002048 def test_get_peer_finished(self):
2049 """
2050 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002051 message received from client, or server. Finished messages are send
2052 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002053 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002054 server, client = self._loopback()
2055
2056 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002057 self.assertTrue(len(server.get_peer_finished()) > 0)
2058
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002059
Fedor Brunner416f4a12014-03-28 13:18:38 +01002060 def test_tls_finished_message_symmetry(self):
2061 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002062 The TLS Finished message send by server must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002063 received by client.
2064
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002065 The TLS Finished message send by client must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002066 received by server.
2067 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002068 server, client = self._loopback()
2069
Fedor Brunner5747b932014-03-05 14:22:34 +01002070 self.assertEqual(server.get_finished(), client.get_peer_finished())
2071 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002072
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002073
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002074 def test_get_cipher_name_before_connect(self):
2075 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002076 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2077 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002078 """
2079 ctx = Context(TLSv1_METHOD)
2080 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002081 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002082
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002083
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002084 def test_get_cipher_name(self):
2085 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002086 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2087 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002088 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002089 server, client = self._loopback()
2090 server_cipher_name, client_cipher_name = \
2091 server.get_cipher_name(), client.get_cipher_name()
2092
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002093 self.assertIsInstance(server_cipher_name, text_type)
2094 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002095
2096 self.assertEqual(server_cipher_name, client_cipher_name)
2097
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002098
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002099 def test_get_cipher_version_before_connect(self):
2100 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002101 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2102 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002103 """
2104 ctx = Context(TLSv1_METHOD)
2105 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002106 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002107
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002108
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002109 def test_get_cipher_version(self):
2110 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002111 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2112 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002113 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002114 server, client = self._loopback()
2115 server_cipher_version, client_cipher_version = \
2116 server.get_cipher_version(), client.get_cipher_version()
2117
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002118 self.assertIsInstance(server_cipher_version, text_type)
2119 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002120
2121 self.assertEqual(server_cipher_version, client_cipher_version)
2122
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002123
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002124 def test_get_cipher_bits_before_connect(self):
2125 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002126 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2127 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002128 """
2129 ctx = Context(TLSv1_METHOD)
2130 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002131 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002132
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002133
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002134 def test_get_cipher_bits(self):
2135 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002136 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2137 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002138 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002139 server, client = self._loopback()
2140 server_cipher_bits, client_cipher_bits = \
2141 server.get_cipher_bits(), client.get_cipher_bits()
2142
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002143 self.assertIsInstance(server_cipher_bits, int)
2144 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002145
2146 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002147
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002148
2149
2150class ConnectionGetCipherListTests(TestCase):
2151 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002152 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002153 """
2154 def test_wrong_args(self):
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002155 """
2156 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if called with any
2157 arguments.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002158 """
2159 connection = Connection(Context(TLSv1_METHOD), None)
2160 self.assertRaises(TypeError, connection.get_cipher_list, None)
2161
Jonathan Ballet648875f2011-07-16 14:14:58 +09002162
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002163 def test_result(self):
2164 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002165 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2166 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002167 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002168 connection = Connection(Context(TLSv1_METHOD), None)
2169 ciphers = connection.get_cipher_list()
2170 self.assertTrue(isinstance(ciphers, list))
2171 for cipher in ciphers:
2172 self.assertTrue(isinstance(cipher, str))
2173
2174
2175
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002176class ConnectionSendTests(TestCase, _LoopbackMixin):
2177 """
2178 Tests for :py:obj:`Connection.send`
2179 """
2180 def test_wrong_args(self):
2181 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002182 When called with arguments other than string argument for its first
2183 parameter or more than two arguments, :py:obj:`Connection.send` raises
2184 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002185 """
2186 connection = Connection(Context(TLSv1_METHOD), None)
2187 self.assertRaises(TypeError, connection.send)
2188 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002189 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002190
2191
2192 def test_short_bytes(self):
2193 """
2194 When passed a short byte string, :py:obj:`Connection.send` transmits all of it
2195 and returns the number of bytes sent.
2196 """
2197 server, client = self._loopback()
2198 count = server.send(b('xy'))
2199 self.assertEquals(count, 2)
2200 self.assertEquals(client.recv(2), b('xy'))
2201
2202 try:
2203 memoryview
2204 except NameError:
2205 "cannot test sending memoryview without memoryview"
2206 else:
2207 def test_short_memoryview(self):
2208 """
2209 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002210 :py:obj:`Connection.send` transmits all of them and returns the number of
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002211 bytes sent.
2212 """
2213 server, client = self._loopback()
2214 count = server.send(memoryview(b('xy')))
2215 self.assertEquals(count, 2)
2216 self.assertEquals(client.recv(2), b('xy'))
2217
2218
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002219
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002220class ConnectionSendallTests(TestCase, _LoopbackMixin):
2221 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002222 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002223 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002224 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002225 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002226 When called with arguments other than a string argument for its first
2227 parameter or with more than two arguments, :py:obj:`Connection.sendall`
2228 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002229 """
2230 connection = Connection(Context(TLSv1_METHOD), None)
2231 self.assertRaises(TypeError, connection.sendall)
2232 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002233 self.assertRaises(
2234 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002235
2236
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002237 def test_short(self):
2238 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002239 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002240 it.
2241 """
2242 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04002243 server.sendall(b('x'))
2244 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002245
2246
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002247 try:
2248 memoryview
2249 except NameError:
2250 "cannot test sending memoryview without memoryview"
2251 else:
2252 def test_short_memoryview(self):
2253 """
2254 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002255 :py:obj:`Connection.sendall` transmits all of them.
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002256 """
2257 server, client = self._loopback()
2258 server.sendall(memoryview(b('x')))
2259 self.assertEquals(client.recv(1), b('x'))
2260
2261
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002262 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002263 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002264 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002265 it even if this requires multiple calls of an underlying write function.
2266 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002267 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04002268 # Should be enough, underlying SSL_write should only do 16k at a time.
2269 # On Windows, after 32k of bytes the write will block (forever - because
2270 # no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04002271 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002272 server.sendall(message)
2273 accum = []
2274 received = 0
2275 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04002276 data = client.recv(1024)
2277 accum.append(data)
2278 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04002279 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002280
2281
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002282 def test_closed(self):
2283 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002284 If the underlying socket is closed, :py:obj:`Connection.sendall` propagates the
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002285 write error from the low level write call.
2286 """
2287 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04002288 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002289 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002290 if platform == "win32":
2291 self.assertEqual(exc.args[0], ESHUTDOWN)
2292 else:
2293 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002294
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002295
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002296
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002297class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
2298 """
2299 Tests for SSL renegotiation APIs.
2300 """
2301 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002302 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002303 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002304 arguments.
2305 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002306 connection = Connection(Context(TLSv1_METHOD), None)
2307 self.assertRaises(TypeError, connection.renegotiate, None)
2308
2309
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002310 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002311 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002312 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if called with
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002313 any arguments.
2314 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002315 connection = Connection(Context(TLSv1_METHOD), None)
2316 self.assertRaises(TypeError, connection.total_renegotiations, None)
2317
2318
2319 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002320 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002321 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002322 renegotiations have happened.
2323 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002324 connection = Connection(Context(TLSv1_METHOD), None)
2325 self.assertEquals(connection.total_renegotiations(), 0)
2326
2327
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002328# def test_renegotiate(self):
2329# """
2330# """
2331# server, client = self._loopback()
2332
2333# server.send("hello world")
2334# self.assertEquals(client.recv(len("hello world")), "hello world")
2335
2336# self.assertEquals(server.total_renegotiations(), 0)
2337# self.assertTrue(server.renegotiate())
2338
2339# server.setblocking(False)
2340# client.setblocking(False)
2341# while server.renegotiate_pending():
2342# client.do_handshake()
2343# server.do_handshake()
2344
2345# self.assertEquals(server.total_renegotiations(), 1)
2346
2347
2348
2349
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002350class ErrorTests(TestCase):
2351 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002352 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002353 """
2354 def test_type(self):
2355 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002356 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002357 """
2358 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05002359 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05002360
2361
2362
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002363class ConstantsTests(TestCase):
2364 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002365 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002366
2367 These are values defined by OpenSSL intended only to be used as flags to
2368 OpenSSL APIs. The only assertions it seems can be made about them is
2369 their values.
2370 """
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002371 # unittest.TestCase has no skip mechanism
2372 if OP_NO_QUERY_MTU is not None:
2373 def test_op_no_query_mtu(self):
2374 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002375 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002376 :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002377 """
2378 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
2379 else:
2380 "OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002381
2382
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002383 if OP_COOKIE_EXCHANGE is not None:
2384 def test_op_cookie_exchange(self):
2385 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002386 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the value
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002387 of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002388 """
2389 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
2390 else:
2391 "OP_COOKIE_EXCHANGE unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002392
2393
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002394 if OP_NO_TICKET is not None:
2395 def test_op_no_ticket(self):
2396 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002397 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002398 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002399 """
2400 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderonecebd1782011-09-11 10:01:31 -04002401 else:
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002402 "OP_NO_TICKET unavailable - OpenSSL version may be too old"
Rick Dean5b7b6372009-04-01 11:34:06 -05002403
2404
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002405 if OP_NO_COMPRESSION is not None:
2406 def test_op_no_compression(self):
2407 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002408 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the value
2409 of :py:const:`SSL_OP_NO_COMPRESSION` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002410 """
2411 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
2412 else:
2413 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
2414
2415
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002416 def test_sess_cache_off(self):
2417 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002418 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
2419 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002420 """
2421 self.assertEqual(0x0, SESS_CACHE_OFF)
2422
2423
2424 def test_sess_cache_client(self):
2425 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002426 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
2427 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002428 """
2429 self.assertEqual(0x1, SESS_CACHE_CLIENT)
2430
2431
2432 def test_sess_cache_server(self):
2433 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002434 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
2435 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002436 """
2437 self.assertEqual(0x2, SESS_CACHE_SERVER)
2438
2439
2440 def test_sess_cache_both(self):
2441 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002442 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
2443 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002444 """
2445 self.assertEqual(0x3, SESS_CACHE_BOTH)
2446
2447
2448 def test_sess_cache_no_auto_clear(self):
2449 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002450 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
2451 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
2452 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002453 """
2454 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
2455
2456
2457 def test_sess_cache_no_internal_lookup(self):
2458 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002459 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
2460 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
2461 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002462 """
2463 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
2464
2465
2466 def test_sess_cache_no_internal_store(self):
2467 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002468 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
2469 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
2470 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002471 """
2472 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
2473
2474
2475 def test_sess_cache_no_internal(self):
2476 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002477 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
2478 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
2479 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002480 """
2481 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
2482
2483
Jean-Paul Calderoneeeee26a2009-04-27 11:24:30 -04002484
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002485class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05002486 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002487 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05002488 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002489 def _server(self, sock):
2490 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002491 Create a new server-side SSL :py:obj:`Connection` object wrapped around
2492 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002493 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002494 # Create the server side Connection. This is mostly setup boilerplate
2495 # - use TLSv1, use a particular certificate, etc.
2496 server_ctx = Context(TLSv1_METHOD)
2497 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2498 server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2499 server_store = server_ctx.get_cert_store()
2500 server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2501 server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2502 server_ctx.check_privatekey()
2503 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002504 # Here the Connection is actually created. If None is passed as the 2nd
2505 # parameter, it indicates a memory BIO should be created.
2506 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002507 server_conn.set_accept_state()
2508 return server_conn
2509
2510
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002511 def _client(self, sock):
2512 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002513 Create a new client-side SSL :py:obj:`Connection` object wrapped around
2514 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002515 """
2516 # Now create the client side Connection. Similar boilerplate to the
2517 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002518 client_ctx = Context(TLSv1_METHOD)
2519 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2520 client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2521 client_store = client_ctx.get_cert_store()
2522 client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
2523 client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
2524 client_ctx.check_privatekey()
2525 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002526 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002527 client_conn.set_connect_state()
2528 return client_conn
2529
2530
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002531 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002532 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002533 Two :py:obj:`Connection`s which use memory BIOs can be manually connected by
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002534 reading from the output of each and writing those bytes to the input of
2535 the other and in this way establish a connection and exchange
2536 application-level bytes with each other.
2537 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002538 server_conn = self._server(None)
2539 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002540
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002541 # There should be no key or nonces yet.
2542 self.assertIdentical(server_conn.master_key(), None)
2543 self.assertIdentical(server_conn.client_random(), None)
2544 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002545
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002546 # First, the handshake needs to happen. We'll deliver bytes back and
2547 # forth between the client and server until neither of them feels like
2548 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002549 self.assertIdentical(
2550 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002551
2552 # Now that the handshake is done, there should be a key and nonces.
2553 self.assertNotIdentical(server_conn.master_key(), None)
2554 self.assertNotIdentical(server_conn.client_random(), None)
2555 self.assertNotIdentical(server_conn.server_random(), None)
Jean-Paul Calderone6c051e62009-07-05 13:50:34 -04002556 self.assertEquals(server_conn.client_random(), client_conn.client_random())
2557 self.assertEquals(server_conn.server_random(), client_conn.server_random())
2558 self.assertNotEquals(server_conn.client_random(), server_conn.server_random())
2559 self.assertNotEquals(client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002560
2561 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002562 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05002563
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002564 server_conn.write(important_message)
2565 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002566 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002567 (client_conn, important_message))
2568
2569 client_conn.write(important_message[::-1])
2570 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002571 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002572 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05002573
2574
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002575 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05002576 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002577 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002578
2579 This is primarily to rule out the memory BIO code as the source of
Jonathan Ballet648875f2011-07-16 14:14:58 +09002580 any problems encountered while passing data over a :py:obj:`Connection` (if
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002581 this test fails, there must be a problem outside the memory BIO
2582 code, as no memory BIO is involved here). Even though this isn't a
2583 memory BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05002584 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04002585 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05002586
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002587 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05002588 client_conn.send(important_message)
2589 msg = server_conn.recv(1024)
2590 self.assertEqual(msg, important_message)
2591
2592 # Again in the other direction, just for fun.
2593 important_message = important_message[::-1]
2594 server_conn.send(important_message)
2595 msg = client_conn.recv(1024)
2596 self.assertEqual(msg, important_message)
2597
2598
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04002599 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05002600 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002601 Test that :py:obj:`OpenSSL.SSL.bio_read` and :py:obj:`OpenSSL.SSL.bio_write` don't
2602 work on :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05002603 """
2604 context = Context(SSLv3_METHOD)
2605 client = socket()
2606 clientSSL = Connection(context, client)
2607 self.assertRaises( TypeError, clientSSL.bio_read, 100)
2608 self.assertRaises( TypeError, clientSSL.bio_write, "foo")
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04002609 self.assertRaises( TypeError, clientSSL.bio_shutdown )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002610
2611
2612 def test_outgoingOverflow(self):
2613 """
2614 If more bytes than can be written to the memory BIO are passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002615 :py:obj:`Connection.send` at once, the number of bytes which were written is
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002616 returned and that many bytes from the beginning of the input can be
2617 read from the other end of the connection.
2618 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002619 server = self._server(None)
2620 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002621
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002622 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002623
2624 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002625 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002626 # Sanity check. We're trying to test what happens when the entire
2627 # input can't be sent. If the entire input was sent, this test is
2628 # meaningless.
2629 self.assertTrue(sent < size)
2630
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002631 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002632 self.assertIdentical(receiver, server)
2633
2634 # We can rely on all of these bytes being received at once because
2635 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
2636 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002637
2638
2639 def test_shutdown(self):
2640 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002641 :py:obj:`Connection.bio_shutdown` signals the end of the data stream from
2642 which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002643 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002644 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002645 server.bio_shutdown()
2646 e = self.assertRaises(Error, server.recv, 1024)
2647 # We don't want WantReadError or ZeroReturnError or anything - it's a
2648 # handshake failure.
2649 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002650
2651
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002652 def test_unexpectedEndOfFile(self):
2653 """
2654 If the connection is lost before an orderly SSL shutdown occurs,
2655 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
2656 "Unexpected EOF".
2657 """
2658 server_conn, client_conn = self._loopback()
2659 client_conn.sock_shutdown(SHUT_RDWR)
2660 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
2661 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
2662
2663
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002664 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002665 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002666 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 -04002667
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002668 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002669 before the client and server are connected to each other. This
2670 function should specify a list of CAs for the server to send to the
2671 client and return that same list. The list will be used to verify
Jonathan Ballet648875f2011-07-16 14:14:58 +09002672 that :py:obj:`get_client_ca_list` returns the proper value at various
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002673 times.
2674 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002675 server = self._server(None)
2676 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002677 self.assertEqual(client.get_client_ca_list(), [])
2678 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002679 ctx = server.get_context()
2680 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002681 self.assertEqual(client.get_client_ca_list(), [])
2682 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002683 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002684 self.assertEqual(client.get_client_ca_list(), expected)
2685 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002686
2687
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002688 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002689 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002690 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if called with a
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002691 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002692 """
2693 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002694 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
2695 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
2696 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002697
2698
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002699 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002700 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002701 If passed an empty list, :py:obj:`Context.set_client_ca_list` configures the
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002702 context to send no CA names to the client and, on both the server and
Jonathan Ballet648875f2011-07-16 14:14:58 +09002703 client sides, :py:obj:`Connection.get_client_ca_list` returns an empty list
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002704 after the connection is set up.
2705 """
2706 def no_ca(ctx):
2707 ctx.set_client_ca_list([])
2708 return []
2709 self._check_client_ca_list(no_ca)
2710
2711
2712 def test_set_one_ca_list(self):
2713 """
2714 If passed a list containing a single X509Name,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002715 :py:obj:`Context.set_client_ca_list` configures the context to send that CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002716 name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002717 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002718 X509Name after the connection is set up.
2719 """
2720 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2721 cadesc = cacert.get_subject()
2722 def single_ca(ctx):
2723 ctx.set_client_ca_list([cadesc])
2724 return [cadesc]
2725 self._check_client_ca_list(single_ca)
2726
2727
2728 def test_set_multiple_ca_list(self):
2729 """
2730 If passed a list containing multiple X509Name objects,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002731 :py:obj:`Context.set_client_ca_list` configures the context to send those CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002732 names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002733 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002734 X509Names after the connection is set up.
2735 """
2736 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2737 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2738
2739 sedesc = secert.get_subject()
2740 cldesc = clcert.get_subject()
2741
2742 def multiple_ca(ctx):
2743 L = [sedesc, cldesc]
2744 ctx.set_client_ca_list(L)
2745 return L
2746 self._check_client_ca_list(multiple_ca)
2747
2748
2749 def test_reset_ca_list(self):
2750 """
2751 If called multiple times, only the X509Names passed to the final call
Jonathan Ballet648875f2011-07-16 14:14:58 +09002752 of :py:obj:`Context.set_client_ca_list` are used to configure the CA names
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002753 sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002754 """
2755 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2756 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2757 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2758
2759 cadesc = cacert.get_subject()
2760 sedesc = secert.get_subject()
2761 cldesc = clcert.get_subject()
2762
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002763 def changed_ca(ctx):
2764 ctx.set_client_ca_list([sedesc, cldesc])
2765 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002766 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002767 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002768
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002769
2770 def test_mutated_ca_list(self):
2771 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002772 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002773 afterwards, this does not affect the list of CA names sent to the
2774 client.
2775 """
2776 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2777 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2778
2779 cadesc = cacert.get_subject()
2780 sedesc = secert.get_subject()
2781
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002782 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002783 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002784 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002785 L.append(sedesc)
2786 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002787 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002788
2789
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002790 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002791 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002792 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called with a non-X509
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002793 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002794 """
2795 ctx = Context(TLSv1_METHOD)
2796 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002797 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002798 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002799 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002800
2801
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002802 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002803 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002804 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09002805 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002806 """
2807 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2808 cadesc = cacert.get_subject()
2809 def single_ca(ctx):
2810 ctx.add_client_ca(cacert)
2811 return [cadesc]
2812 self._check_client_ca_list(single_ca)
2813
2814
2815 def test_multiple_add_client_ca(self):
2816 """
2817 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09002818 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002819 """
2820 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2821 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2822
2823 cadesc = cacert.get_subject()
2824 sedesc = secert.get_subject()
2825
2826 def multiple_ca(ctx):
2827 ctx.add_client_ca(cacert)
2828 ctx.add_client_ca(secert)
2829 return [cadesc, sedesc]
2830 self._check_client_ca_list(multiple_ca)
2831
2832
2833 def test_set_and_add_client_ca(self):
2834 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002835 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
2836 :py:obj:`Context.add_client_ca` results in using the CA names from the first
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002837 call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002838 """
2839 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2840 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2841 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2842
2843 cadesc = cacert.get_subject()
2844 sedesc = secert.get_subject()
2845 cldesc = clcert.get_subject()
2846
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002847 def mixed_set_add_ca(ctx):
2848 ctx.set_client_ca_list([cadesc, sedesc])
2849 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002850 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002851 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002852
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002853
2854 def test_set_after_add_client_ca(self):
2855 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002856 A call to :py:obj:`Context.set_client_ca_list` after a call to
2857 :py:obj:`Context.add_client_ca` replaces the CA name specified by the former
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002858 call with the names specified by the latter cal.
2859 """
2860 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2861 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2862 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2863
2864 cadesc = cacert.get_subject()
2865 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002866
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002867 def set_replaces_add_ca(ctx):
2868 ctx.add_client_ca(clcert)
2869 ctx.set_client_ca_list([cadesc])
2870 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002871 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002872 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002873
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002874
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002875
2876class ConnectionBIOTests(TestCase):
2877 """
2878 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
2879 """
2880 def test_wantReadError(self):
2881 """
2882 :py:obj:`Connection.bio_read` raises :py:obj:`OpenSSL.SSL.WantReadError`
2883 if there are no bytes available to be read from the BIO.
2884 """
2885 ctx = Context(TLSv1_METHOD)
2886 conn = Connection(ctx, None)
2887 self.assertRaises(WantReadError, conn.bio_read, 1024)
2888
2889
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002890 def test_buffer_size(self):
2891 """
2892 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
2893 number of bytes to read and return.
2894 """
2895 ctx = Context(TLSv1_METHOD)
2896 conn = Connection(ctx, None)
2897 conn.set_connect_state()
2898 try:
2899 conn.do_handshake()
2900 except WantReadError:
2901 pass
2902 data = conn.bio_read(2)
2903 self.assertEqual(2, len(data))
2904
2905
2906 if not PY3:
2907 def test_buffer_size_long(self):
2908 """
2909 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
2910 :py:obj:`long` as well as :py:obj:`int`.
2911 """
2912 ctx = Context(TLSv1_METHOD)
2913 conn = Connection(ctx, None)
2914 conn.set_connect_state()
2915 try:
2916 conn.do_handshake()
2917 except WantReadError:
2918 pass
2919 data = conn.bio_read(long(2))
2920 self.assertEqual(2, len(data))
2921
2922
2923
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002924
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04002925class InfoConstantTests(TestCase):
2926 """
2927 Tests for assorted constants exposed for use in info callbacks.
2928 """
2929 def test_integers(self):
2930 """
2931 All of the info constants are integers.
2932
2933 This is a very weak test. It would be nice to have one that actually
2934 verifies that as certain info events happen, the value passed to the
2935 info callback matches up with the constant exposed by OpenSSL.SSL.
2936 """
2937 for const in [
2938 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
2939 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
2940 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
2941 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
2942 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
2943 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE]:
2944
2945 self.assertTrue(isinstance(const, int))
2946
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02002947
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002948if __name__ == '__main__':
2949 main()