blob: 5942200d937959c895c4d2304bae537121c29b01 [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 Calderone210c0f32015-04-12 09:20:31 -040010from sys import platform, version_info, getfilesystemencoding
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 Calderoneaac43a32015-04-12 09:51:21 -040017from six import PY3, binary_type, text_type, u
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -050018
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040019from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080020from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040021from OpenSSL.crypto import dump_privatekey, load_privatekey
22from OpenSSL.crypto import dump_certificate, load_certificate
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -040023from OpenSSL.crypto import get_elliptic_curves
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040024
Jean-Paul 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)
39
40from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070041 Error, SysCallError, WantReadError, WantWriteError, ZeroReturnError)
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -050042from OpenSSL.SSL import (
Jean-Paul Calderoned899af02013-03-19 22:10:37 -070043 Context, ContextType, Session, Connection, ConnectionType, SSLeay_version)
Jean-Paul Calderone7526d172010-09-09 17:55:31 -040044
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -040045from OpenSSL.test.util import NON_ASCII, TestCase, b
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -040046from OpenSSL.test.test_crypto import (
47 cleartextCertificatePEM, cleartextPrivateKeyPEM)
48from OpenSSL.test.test_crypto import (
49 client_cert_pem, client_key_pem, server_cert_pem, server_key_pem,
50 root_cert_pem)
51
Jean-Paul Calderone4bccf5e2008-12-28 22:50:42 -050052try:
53 from OpenSSL.SSL import OP_NO_QUERY_MTU
54except ImportError:
55 OP_NO_QUERY_MTU = None
56try:
57 from OpenSSL.SSL import OP_COOKIE_EXCHANGE
58except ImportError:
59 OP_COOKIE_EXCHANGE = None
60try:
61 from OpenSSL.SSL import OP_NO_TICKET
62except ImportError:
63 OP_NO_TICKET = None
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -040064
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040065try:
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -040066 from OpenSSL.SSL import OP_NO_COMPRESSION
67except ImportError:
68 OP_NO_COMPRESSION = None
69
70try:
Jean-Paul Calderone0222a492011-09-08 18:26:03 -040071 from OpenSSL.SSL import MODE_RELEASE_BUFFERS
72except ImportError:
73 MODE_RELEASE_BUFFERS = None
74
Jean-Paul Calderone1461c492013-10-03 16:05:00 -040075try:
76 from OpenSSL.SSL import OP_NO_TLSv1, OP_NO_TLSv1_1, OP_NO_TLSv1_2
77except ImportError:
78 OP_NO_TLSv1 = OP_NO_TLSv1_1 = OP_NO_TLSv1_2 = None
79
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -040080from OpenSSL.SSL import (
81 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT, SSL_ST_BEFORE,
82 SSL_ST_OK, SSL_ST_RENEGOTIATE,
83 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
84 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
85 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
86 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE)
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -040087
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -040088# openssl dhparam 128 -out dh-128.pem (note that 128 is a small number of bits
89# to use)
90dhparam = """\
91-----BEGIN DH PARAMETERS-----
92MBYCEQCobsg29c9WZP/54oAPcwiDAgEC
93-----END DH PARAMETERS-----
94"""
95
96
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -040097def verify_cb(conn, cert, errnum, depth, ok):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -040098 return ok
99
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400100
Rick Deanb1ccd562009-07-09 23:52:39 -0500101def socket_pair():
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400102 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400103 Establish and return a pair of network sockets connected to each other.
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400104 """
105 # Connect a pair of sockets
Rick Deanb1ccd562009-07-09 23:52:39 -0500106 port = socket()
107 port.bind(('', 0))
108 port.listen(1)
109 client = socket()
110 client.setblocking(False)
Jean-Paul Calderonef23c5d92009-07-23 17:58:15 -0400111 client.connect_ex(("127.0.0.1", port.getsockname()[1]))
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400112 client.setblocking(True)
Rick Deanb1ccd562009-07-09 23:52:39 -0500113 server = port.accept()[0]
Rick Deanb1ccd562009-07-09 23:52:39 -0500114
Jean-Paul Calderone1a9613b2009-07-16 12:13:36 -0400115 # Let's pass some unencrypted data to make sure our socket connection is
116 # fine. Just one byte, so we don't have to worry about buffers getting
117 # filled up or fragmentation.
Jean-Paul Calderone9e4eeae2010-08-22 21:32:52 -0400118 server.send(b("x"))
119 assert client.recv(1024) == b("x")
120 client.send(b("y"))
121 assert server.recv(1024) == b("y")
Rick Deanb1ccd562009-07-09 23:52:39 -0500122
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -0400123 # Most of our callers want non-blocking sockets, make it easy for them.
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400124 server.setblocking(False)
125 client.setblocking(False)
126
Rick Deanb1ccd562009-07-09 23:52:39 -0500127 return (server, client)
128
129
Jean-Paul Calderone94b24a82009-07-16 19:11:38 -0400130
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400131def handshake(client, server):
132 conns = [client, server]
133 while conns:
134 for conn in conns:
135 try:
136 conn.do_handshake()
137 except WantReadError:
138 pass
139 else:
140 conns.remove(conn)
141
142
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400143def _create_certificate_chain():
144 """
145 Construct and return a chain of certificates.
146
147 1. A new self-signed certificate authority certificate (cacert)
148 2. A new intermediate certificate signed by cacert (icert)
149 3. A new server certificate signed by icert (scert)
150 """
151 caext = X509Extension(b('basicConstraints'), False, b('CA:true'))
152
153 # Step 1
154 cakey = PKey()
155 cakey.generate_key(TYPE_RSA, 512)
156 cacert = X509()
157 cacert.get_subject().commonName = "Authority Certificate"
158 cacert.set_issuer(cacert.get_subject())
159 cacert.set_pubkey(cakey)
160 cacert.set_notBefore(b("20000101000000Z"))
161 cacert.set_notAfter(b("20200101000000Z"))
162 cacert.add_extensions([caext])
163 cacert.set_serial_number(0)
164 cacert.sign(cakey, "sha1")
165
166 # Step 2
167 ikey = PKey()
168 ikey.generate_key(TYPE_RSA, 512)
169 icert = X509()
170 icert.get_subject().commonName = "Intermediate Certificate"
171 icert.set_issuer(cacert.get_subject())
172 icert.set_pubkey(ikey)
173 icert.set_notBefore(b("20000101000000Z"))
174 icert.set_notAfter(b("20200101000000Z"))
175 icert.add_extensions([caext])
176 icert.set_serial_number(0)
177 icert.sign(cakey, "sha1")
178
179 # Step 3
180 skey = PKey()
181 skey.generate_key(TYPE_RSA, 512)
182 scert = X509()
183 scert.get_subject().commonName = "Server Certificate"
184 scert.set_issuer(icert.get_subject())
185 scert.set_pubkey(skey)
186 scert.set_notBefore(b("20000101000000Z"))
187 scert.set_notAfter(b("20200101000000Z"))
188 scert.add_extensions([
189 X509Extension(b('basicConstraints'), True, b('CA:false'))])
190 scert.set_serial_number(0)
191 scert.sign(ikey, "sha1")
192
193 return [(cakey, cacert), (ikey, icert), (skey, scert)]
194
195
196
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400197class _LoopbackMixin:
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400198 """
199 Helper mixin which defines methods for creating a connected socket pair and
200 for forcing two connected SSL sockets to talk to each other via memory BIOs.
201 """
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500202 def _loopbackClientFactory(self, socket):
203 client = Connection(Context(TLSv1_METHOD), socket)
204 client.set_connect_state()
205 return client
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400206
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500207
208 def _loopbackServerFactory(self, socket):
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400209 ctx = Context(TLSv1_METHOD)
210 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
211 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500212 server = Connection(ctx, socket)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400213 server.set_accept_state()
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -0500214 return server
215
216
217 def _loopback(self, serverFactory=None, clientFactory=None):
218 if serverFactory is None:
219 serverFactory = self._loopbackServerFactory
220 if clientFactory is None:
221 clientFactory = self._loopbackClientFactory
222
223 (server, client) = socket_pair()
224 server = serverFactory(server)
225 client = clientFactory(client)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400226
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400227 handshake(client, server)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400228
229 server.setblocking(True)
230 client.setblocking(True)
231 return server, client
232
233
234 def _interactInMemory(self, client_conn, server_conn):
235 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900236 Try to read application bytes from each of the two :py:obj:`Connection`
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400237 objects. Copy bytes back and forth between their send/receive buffers
238 for as long as there is anything to copy. When there is nothing more
Jonathan Ballet648875f2011-07-16 14:14:58 +0900239 to copy, return :py:obj:`None`. If one of them actually manages to deliver
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400240 some application bytes, return a two-tuple of the connection from which
241 the bytes were read and the bytes themselves.
242 """
243 wrote = True
244 while wrote:
245 # Loop until neither side has anything to say
246 wrote = False
247
248 # Copy stuff from each side's send buffer to the other side's
249 # receive buffer.
250 for (read, write) in [(client_conn, server_conn),
251 (server_conn, client_conn)]:
252
253 # Give the side a chance to generate some more bytes, or
254 # succeed.
255 try:
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400256 data = read.recv(2 ** 16)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400257 except WantReadError:
258 # It didn't succeed, so we'll hope it generated some
259 # output.
260 pass
261 else:
262 # It did succeed, so we'll stop now and let the caller deal
263 # with it.
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400264 return (read, data)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400265
266 while True:
267 # Keep copying as long as there's more stuff there.
268 try:
269 dirty = read.bio_read(4096)
270 except WantReadError:
271 # Okay, nothing more waiting to be sent. Stop
272 # processing this send buffer.
273 break
274 else:
275 # Keep track of the fact that someone generated some
276 # output.
277 wrote = True
278 write.bio_write(dirty)
279
280
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400281 def _handshakeInMemory(self, client_conn, server_conn):
Jean-Paul Calderoneb2b40782014-05-06 08:47:40 -0400282 """
283 Perform the TLS handshake between two :py:class:`Connection` instances
284 connected to each other via memory BIOs.
285 """
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400286 client_conn.set_connect_state()
287 server_conn.set_accept_state()
288
289 for conn in [client_conn, server_conn]:
290 try:
291 conn.do_handshake()
292 except WantReadError:
293 pass
294
295 self._interactInMemory(client_conn, server_conn)
296
297
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -0400298
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400299class VersionTests(TestCase):
300 """
301 Tests for version information exposed by
Jonathan Ballet648875f2011-07-16 14:14:58 +0900302 :py:obj:`OpenSSL.SSL.SSLeay_version` and
303 :py:obj:`OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400304 """
305 def test_OPENSSL_VERSION_NUMBER(self):
306 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900307 :py:obj:`OPENSSL_VERSION_NUMBER` is an integer with status in the low
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400308 byte and the patch, fix, minor, and major versions in the
309 nibbles above that.
310 """
311 self.assertTrue(isinstance(OPENSSL_VERSION_NUMBER, int))
312
313
314 def test_SSLeay_version(self):
315 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900316 :py:obj:`SSLeay_version` takes a version type indicator and returns
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400317 one of a number of version strings based on that indicator.
318 """
319 versions = {}
320 for t in [SSLEAY_VERSION, SSLEAY_CFLAGS, SSLEAY_BUILT_ON,
321 SSLEAY_PLATFORM, SSLEAY_DIR]:
322 version = SSLeay_version(t)
323 versions[version] = t
324 self.assertTrue(isinstance(version, bytes))
325 self.assertEqual(len(versions), 5)
326
327
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -0400328
329class ContextTests(TestCase, _LoopbackMixin):
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400330 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900331 Unit tests for :py:obj:`OpenSSL.SSL.Context`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400332 """
333 def test_method(self):
334 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900335 :py:obj:`Context` can be instantiated with one of :py:obj:`SSLv2_METHOD`,
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400336 :py:obj:`SSLv3_METHOD`, :py:obj:`SSLv23_METHOD`, :py:obj:`TLSv1_METHOD`,
337 :py:obj:`TLSv1_1_METHOD`, or :py:obj:`TLSv1_2_METHOD`.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400338 """
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400339 methods = [
340 SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD]
341 for meth in methods:
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400342 Context(meth)
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400343
Jean-Paul Calderone1461c492013-10-03 16:05:00 -0400344
345 maybe = [SSLv2_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
346 for meth in maybe:
347 try:
348 Context(meth)
349 except (Error, ValueError):
350 # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
351 # don't. Difficult to say in advance.
352 pass
Jean-Paul Calderone9f2e38e2011-04-14 09:36:55 -0400353
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400354 self.assertRaises(TypeError, Context, "")
355 self.assertRaises(ValueError, Context, 10)
356
357
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500358 if not PY3:
359 def test_method_long(self):
360 """
361 On Python 2 :py:class:`Context` accepts values of type
362 :py:obj:`long` as well as :py:obj:`int`.
363 """
364 Context(long(TLSv1_METHOD))
365
366
367
Rick Deane15b1472009-07-09 15:53:42 -0500368 def test_type(self):
369 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900370 :py:obj:`Context` and :py:obj:`ContextType` refer to the same type object and can be
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400371 used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -0500372 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -0400373 self.assertIdentical(Context, ContextType)
374 self.assertConsistentType(Context, 'Context', TLSv1_METHOD)
Rick Deane15b1472009-07-09 15:53:42 -0500375
376
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400377 def test_use_privatekey(self):
378 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900379 :py:obj:`Context.use_privatekey` takes an :py:obj:`OpenSSL.crypto.PKey` instance.
Jean-Paul Calderone30c09ea2008-03-21 17:04:05 -0400380 """
381 key = PKey()
382 key.generate_key(TYPE_RSA, 128)
383 ctx = Context(TLSv1_METHOD)
384 ctx.use_privatekey(key)
385 self.assertRaises(TypeError, ctx.use_privatekey, "")
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400386
387
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800388 def test_use_privatekey_file_missing(self):
389 """
390 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error`
391 when passed the name of a file which does not exist.
392 """
393 ctx = Context(TLSv1_METHOD)
394 self.assertRaises(Error, ctx.use_privatekey_file, self.mktemp())
395
396
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400397 def _use_privatekey_file_test(self, pemfile, filetype):
398 """
399 Verify that calling ``Context.use_privatekey_file`` with the given
400 arguments does not raise an exception.
401 """
402 key = PKey()
403 key.generate_key(TYPE_RSA, 128)
404
405 with open(pemfile, "wt") as pem:
406 pem.write(
407 dump_privatekey(FILETYPE_PEM, key).decode("ascii")
408 )
409
410 ctx = Context(TLSv1_METHOD)
411 ctx.use_privatekey_file(pemfile, filetype)
412
413
414 def test_use_privatekey_file_bytes(self):
415 """
416 A private key can be specified from a file by passing a ``bytes``
417 instance giving the file name to ``Context.use_privatekey_file``.
418 """
419 self._use_privatekey_file_test(
420 self.mktemp() + NON_ASCII.encode(getfilesystemencoding()),
421 FILETYPE_PEM,
422 )
423
424
425 def test_use_privatekey_file_unicode(self):
426 """
427 A private key can be specified from a file by passing a ``unicode``
428 instance giving the file name to ``Context.use_privatekey_file``.
429 """
430 self._use_privatekey_file_test(
431 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII,
432 FILETYPE_PEM,
433 )
434
435
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500436 if not PY3:
437 def test_use_privatekey_file_long(self):
438 """
439 On Python 2 :py:obj:`Context.use_privatekey_file` accepts a
440 filetype of type :py:obj:`long` as well as :py:obj:`int`.
441 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400442 self._use_privatekey_file_test(self.mktemp(), long(FILETYPE_PEM))
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500443
444
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800445 def test_use_certificate_wrong_args(self):
446 """
447 :py:obj:`Context.use_certificate_wrong_args` raises :py:obj:`TypeError`
448 when not passed exactly one :py:obj:`OpenSSL.crypto.X509` instance as an
449 argument.
450 """
451 ctx = Context(TLSv1_METHOD)
452 self.assertRaises(TypeError, ctx.use_certificate)
453 self.assertRaises(TypeError, ctx.use_certificate, "hello, world")
454 self.assertRaises(TypeError, ctx.use_certificate, X509(), "hello, world")
455
456
457 def test_use_certificate_uninitialized(self):
458 """
459 :py:obj:`Context.use_certificate` raises :py:obj:`OpenSSL.SSL.Error`
460 when passed a :py:obj:`OpenSSL.crypto.X509` instance which has not been
461 initialized (ie, which does not actually have any certificate data).
462 """
463 ctx = Context(TLSv1_METHOD)
464 self.assertRaises(Error, ctx.use_certificate, X509())
465
466
467 def test_use_certificate(self):
468 """
469 :py:obj:`Context.use_certificate` sets the certificate which will be
470 used to identify connections created using the context.
471 """
472 # TODO
473 # Hard to assert anything. But we could set a privatekey then ask
474 # OpenSSL if the cert and key agree using check_privatekey. Then as
475 # long as check_privatekey works right we're good...
476 ctx = Context(TLSv1_METHOD)
477 ctx.use_certificate(load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
478
479
480 def test_use_certificate_file_wrong_args(self):
481 """
482 :py:obj:`Context.use_certificate_file` raises :py:obj:`TypeError` if
483 called with zero arguments or more than two arguments, or if the first
484 argument is not a byte string or the second argumnent is not an integer.
485 """
486 ctx = Context(TLSv1_METHOD)
487 self.assertRaises(TypeError, ctx.use_certificate_file)
488 self.assertRaises(TypeError, ctx.use_certificate_file, b"somefile", object())
489 self.assertRaises(
490 TypeError, ctx.use_certificate_file, b"somefile", FILETYPE_PEM, object())
491 self.assertRaises(
492 TypeError, ctx.use_certificate_file, object(), FILETYPE_PEM)
493 self.assertRaises(
494 TypeError, ctx.use_certificate_file, b"somefile", object())
495
496
497 def test_use_certificate_file_missing(self):
498 """
499 :py:obj:`Context.use_certificate_file` raises
500 `:py:obj:`OpenSSL.SSL.Error` if passed the name of a file which does not
501 exist.
502 """
503 ctx = Context(TLSv1_METHOD)
504 self.assertRaises(Error, ctx.use_certificate_file, self.mktemp())
505
506
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400507 def _use_certificate_file_test(self, certificate_file):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800508 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400509 Verify that calling ``Context.use_certificate_file`` with the given
510 filename doesn't raise an exception.
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800511 """
512 # TODO
513 # Hard to assert anything. But we could set a privatekey then ask
514 # OpenSSL if the cert and key agree using check_privatekey. Then as
515 # long as check_privatekey works right we're good...
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400516 with open(certificate_file, "wb") as pem_file:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800517 pem_file.write(cleartextCertificatePEM)
518
519 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400520 ctx.use_certificate_file(certificate_file)
521
522
523 def test_use_certificate_file_bytes(self):
524 """
525 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
526 ``bytes`` filename) which will be used to identify connections created
527 using the context.
528 """
529 filename = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
530 self._use_certificate_file_test(filename)
531
532
533 def test_use_certificate_file_unicode(self):
534 """
535 :py:obj:`Context.use_certificate_file` sets the certificate (given as a
536 ``bytes`` filename) which will be used to identify connections created
537 using the context.
538 """
539 filename = self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
540 self._use_certificate_file_test(filename)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800541
542
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500543 if not PY3:
544 def test_use_certificate_file_long(self):
545 """
546 On Python 2 :py:obj:`Context.use_certificate_file` accepts a
547 filetype of type :py:obj:`long` as well as :py:obj:`int`.
548 """
549 pem_filename = self.mktemp()
550 with open(pem_filename, "wb") as pem_file:
551 pem_file.write(cleartextCertificatePEM)
552
553 ctx = Context(TLSv1_METHOD)
554 ctx.use_certificate_file(pem_filename, long(FILETYPE_PEM))
555
556
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400557 def test_set_app_data_wrong_args(self):
558 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900559 :py:obj:`Context.set_app_data` raises :py:obj:`TypeError` if called with other than
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400560 one argument.
561 """
562 context = Context(TLSv1_METHOD)
563 self.assertRaises(TypeError, context.set_app_data)
564 self.assertRaises(TypeError, context.set_app_data, None, None)
565
566
567 def test_get_app_data_wrong_args(self):
568 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900569 :py:obj:`Context.get_app_data` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400570 arguments.
571 """
572 context = Context(TLSv1_METHOD)
573 self.assertRaises(TypeError, context.get_app_data, None)
574
575
576 def test_app_data(self):
577 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900578 :py:obj:`Context.set_app_data` stores an object for later retrieval using
579 :py:obj:`Context.get_app_data`.
Jean-Paul Calderonebd479162010-07-30 18:03:25 -0400580 """
581 app_data = object()
582 context = Context(TLSv1_METHOD)
583 context.set_app_data(app_data)
584 self.assertIdentical(context.get_app_data(), app_data)
585
586
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400587 def test_set_options_wrong_args(self):
588 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900589 :py:obj:`Context.set_options` raises :py:obj:`TypeError` if called with the wrong
590 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone40569ca2010-07-30 18:04:58 -0400591 """
592 context = Context(TLSv1_METHOD)
593 self.assertRaises(TypeError, context.set_options)
594 self.assertRaises(TypeError, context.set_options, None)
595 self.assertRaises(TypeError, context.set_options, 1, None)
596
597
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500598 def test_set_options(self):
599 """
600 :py:obj:`Context.set_options` returns the new options value.
601 """
602 context = Context(TLSv1_METHOD)
603 options = context.set_options(OP_NO_SSLv2)
604 self.assertTrue(OP_NO_SSLv2 & options)
605
606
607 if not PY3:
608 def test_set_options_long(self):
609 """
610 On Python 2 :py:obj:`Context.set_options` accepts values of type
611 :py:obj:`long` as well as :py:obj:`int`.
612 """
613 context = Context(TLSv1_METHOD)
614 options = context.set_options(long(OP_NO_SSLv2))
615 self.assertTrue(OP_NO_SSLv2 & options)
616
617
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300618 def test_set_mode_wrong_args(self):
619 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400620 :py:obj:`Context.set`mode} raises :py:obj:`TypeError` if called with the wrong
621 number of arguments or a non-:py:obj:`int` argument.
Guillermo Gonzalez74a2c292011-08-29 16:16:58 -0300622 """
623 context = Context(TLSv1_METHOD)
624 self.assertRaises(TypeError, context.set_mode)
625 self.assertRaises(TypeError, context.set_mode, None)
626 self.assertRaises(TypeError, context.set_mode, 1, None)
627
628
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400629 if MODE_RELEASE_BUFFERS is not None:
630 def test_set_mode(self):
631 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400632 :py:obj:`Context.set_mode` accepts a mode bitvector and returns the newly
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400633 set mode.
634 """
635 context = Context(TLSv1_METHOD)
636 self.assertTrue(
637 MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS))
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500638
639 if not PY3:
640 def test_set_mode_long(self):
641 """
642 On Python 2 :py:obj:`Context.set_mode` accepts values of type
643 :py:obj:`long` as well as :py:obj:`int`.
644 """
645 context = Context(TLSv1_METHOD)
646 mode = context.set_mode(long(MODE_RELEASE_BUFFERS))
647 self.assertTrue(MODE_RELEASE_BUFFERS & mode)
Jean-Paul Calderone0222a492011-09-08 18:26:03 -0400648 else:
649 "MODE_RELEASE_BUFFERS unavailable - OpenSSL version may be too old"
650
651
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400652 def test_set_timeout_wrong_args(self):
653 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900654 :py:obj:`Context.set_timeout` raises :py:obj:`TypeError` if called with the wrong
655 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400656 """
657 context = Context(TLSv1_METHOD)
658 self.assertRaises(TypeError, context.set_timeout)
659 self.assertRaises(TypeError, context.set_timeout, None)
660 self.assertRaises(TypeError, context.set_timeout, 1, None)
661
662
663 def test_get_timeout_wrong_args(self):
664 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900665 :py:obj:`Context.get_timeout` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400666 """
667 context = Context(TLSv1_METHOD)
668 self.assertRaises(TypeError, context.get_timeout, None)
669
670
671 def test_timeout(self):
672 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900673 :py:obj:`Context.set_timeout` sets the session timeout for all connections
674 created using the context object. :py:obj:`Context.get_timeout` retrieves this
Jean-Paul Calderone5ebb44a2010-07-30 18:09:41 -0400675 value.
676 """
677 context = Context(TLSv1_METHOD)
678 context.set_timeout(1234)
679 self.assertEquals(context.get_timeout(), 1234)
680
681
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500682 if not PY3:
683 def test_timeout_long(self):
684 """
685 On Python 2 :py:obj:`Context.set_timeout` accepts values of type
686 `long` as well as int.
687 """
688 context = Context(TLSv1_METHOD)
689 context.set_timeout(long(1234))
690 self.assertEquals(context.get_timeout(), 1234)
691
692
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400693 def test_set_verify_depth_wrong_args(self):
694 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900695 :py:obj:`Context.set_verify_depth` raises :py:obj:`TypeError` if called with the wrong
696 number of arguments or a non-:py:obj:`int` argument.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400697 """
698 context = Context(TLSv1_METHOD)
699 self.assertRaises(TypeError, context.set_verify_depth)
700 self.assertRaises(TypeError, context.set_verify_depth, None)
701 self.assertRaises(TypeError, context.set_verify_depth, 1, None)
702
703
704 def test_get_verify_depth_wrong_args(self):
705 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900706 :py:obj:`Context.get_verify_depth` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400707 """
708 context = Context(TLSv1_METHOD)
709 self.assertRaises(TypeError, context.get_verify_depth, None)
710
711
712 def test_verify_depth(self):
713 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900714 :py:obj:`Context.set_verify_depth` sets the number of certificates in a chain
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400715 to follow before giving up. The value can be retrieved with
Jonathan Ballet648875f2011-07-16 14:14:58 +0900716 :py:obj:`Context.get_verify_depth`.
Jean-Paul Calderonee2b69512010-07-30 18:22:06 -0400717 """
718 context = Context(TLSv1_METHOD)
719 context.set_verify_depth(11)
720 self.assertEquals(context.get_verify_depth(), 11)
721
722
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500723 if not PY3:
724 def test_verify_depth_long(self):
725 """
726 On Python 2 :py:obj:`Context.set_verify_depth` accepts values of
727 type `long` as well as int.
728 """
729 context = Context(TLSv1_METHOD)
730 context.set_verify_depth(long(11))
731 self.assertEquals(context.get_verify_depth(), 11)
732
733
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400734 def _write_encrypted_pem(self, passphrase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400735 """
736 Write a new private key out to a new file, encrypted using the given
737 passphrase. Return the path to the new file.
738 """
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400739 key = PKey()
740 key.generate_key(TYPE_RSA, 128)
741 pemFile = self.mktemp()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400742 fObj = open(pemFile, 'w')
743 pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
744 fObj.write(pem.decode('ascii'))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400745 fObj.close()
746 return pemFile
747
748
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400749 def test_set_passwd_cb_wrong_args(self):
750 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900751 :py:obj:`Context.set_passwd_cb` raises :py:obj:`TypeError` if called with the
Jean-Paul Calderonef4480622010-08-02 18:25:03 -0400752 wrong arguments or with a non-callable first argument.
753 """
754 context = Context(TLSv1_METHOD)
755 self.assertRaises(TypeError, context.set_passwd_cb)
756 self.assertRaises(TypeError, context.set_passwd_cb, None)
757 self.assertRaises(TypeError, context.set_passwd_cb, lambda: None, None, None)
758
759
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400760 def test_set_passwd_cb(self):
761 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900762 :py:obj:`Context.set_passwd_cb` accepts a callable which will be invoked when
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400763 a private key is loaded from an encrypted PEM.
764 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400765 passphrase = b("foobar")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400766 pemFile = self._write_encrypted_pem(passphrase)
Jean-Paul Calderone828c9cb2008-04-26 18:06:54 -0400767 calledWith = []
768 def passphraseCallback(maxlen, verify, extra):
769 calledWith.append((maxlen, verify, extra))
770 return passphrase
771 context = Context(TLSv1_METHOD)
772 context.set_passwd_cb(passphraseCallback)
773 context.use_privatekey_file(pemFile)
774 self.assertTrue(len(calledWith), 1)
775 self.assertTrue(isinstance(calledWith[0][0], int))
776 self.assertTrue(isinstance(calledWith[0][1], int))
777 self.assertEqual(calledWith[0][2], None)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400778
779
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400780 def test_passwd_callback_exception(self):
781 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900782 :py:obj:`Context.use_privatekey_file` propagates any exception raised by the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400783 passphrase callback.
784 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400785 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400786 def passphraseCallback(maxlen, verify, extra):
787 raise RuntimeError("Sorry, I am a fail.")
788
789 context = Context(TLSv1_METHOD)
790 context.set_passwd_cb(passphraseCallback)
791 self.assertRaises(RuntimeError, context.use_privatekey_file, pemFile)
792
793
794 def test_passwd_callback_false(self):
795 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900796 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400797 passphrase callback returns a false value.
798 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400799 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400800 def passphraseCallback(maxlen, verify, extra):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500801 return b""
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400802
803 context = Context(TLSv1_METHOD)
804 context.set_passwd_cb(passphraseCallback)
805 self.assertRaises(Error, context.use_privatekey_file, pemFile)
806
807
808 def test_passwd_callback_non_string(self):
809 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900810 :py:obj:`Context.use_privatekey_file` raises :py:obj:`OpenSSL.SSL.Error` if the
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400811 passphrase callback returns a true non-string value.
812 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400813 pemFile = self._write_encrypted_pem(b("monkeys are nice"))
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400814 def passphraseCallback(maxlen, verify, extra):
815 return 10
816
817 context = Context(TLSv1_METHOD)
818 context.set_passwd_cb(passphraseCallback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800819 self.assertRaises(ValueError, context.use_privatekey_file, pemFile)
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400820
821
822 def test_passwd_callback_too_long(self):
823 """
824 If the passphrase returned by the passphrase callback returns a string
825 longer than the indicated maximum length, it is truncated.
826 """
827 # A priori knowledge!
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400828 passphrase = b("x") * 1024
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400829 pemFile = self._write_encrypted_pem(passphrase)
830 def passphraseCallback(maxlen, verify, extra):
831 assert maxlen == 1024
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400832 return passphrase + b("y")
Jean-Paul Calderone389d76d2010-07-30 17:57:53 -0400833
834 context = Context(TLSv1_METHOD)
835 context.set_passwd_cb(passphraseCallback)
836 # This shall succeed because the truncated result is the correct
837 # passphrase.
838 context.use_privatekey_file(pemFile)
839
840
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400841 def test_set_info_callback(self):
842 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900843 :py:obj:`Context.set_info_callback` accepts a callable which will be invoked
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400844 when certain information about an SSL connection is available.
845 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500846 (server, client) = socket_pair()
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400847
848 clientSSL = Connection(Context(TLSv1_METHOD), client)
849 clientSSL.set_connect_state()
850
851 called = []
852 def info(conn, where, ret):
853 called.append((conn, where, ret))
854 context = Context(TLSv1_METHOD)
855 context.set_info_callback(info)
856 context.use_certificate(
857 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
858 context.use_privatekey(
859 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
860
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400861 serverSSL = Connection(context, server)
862 serverSSL.set_accept_state()
863
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500864 handshake(clientSSL, serverSSL)
Jean-Paul Calderone5ef86512008-04-26 19:06:28 -0400865
Jean-Paul Calderone3835e522014-02-02 11:12:30 -0500866 # The callback must always be called with a Connection instance as the
867 # first argument. It would probably be better to split this into
868 # separate tests for client and server side info callbacks so we could
869 # assert it is called with the right Connection instance. It would
870 # also be good to assert *something* about `where` and `ret`.
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500871 notConnections = [
872 conn for (conn, where, ret) in called
873 if not isinstance(conn, Connection)]
874 self.assertEqual(
875 [], notConnections,
876 "Some info callback arguments were not Connection instaces.")
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400877
878
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400879 def _load_verify_locations_test(self, *args):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400880 """
881 Create a client context which will verify the peer certificate and call
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -0400882 its :py:obj:`load_verify_locations` method with the given arguments.
883 Then connect it to a server and ensure that the handshake succeeds.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -0400884 """
Rick Deanb1ccd562009-07-09 23:52:39 -0500885 (server, client) = socket_pair()
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400886
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400887 clientContext = Context(TLSv1_METHOD)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400888 clientContext.load_verify_locations(*args)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400889 # Require that the server certificate verify properly or the
890 # connection will fail.
891 clientContext.set_verify(
892 VERIFY_PEER,
893 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
894
895 clientSSL = Connection(clientContext, client)
896 clientSSL.set_connect_state()
897
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400898 serverContext = Context(TLSv1_METHOD)
899 serverContext.use_certificate(
900 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
901 serverContext.use_privatekey(
902 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
903
904 serverSSL = Connection(serverContext, server)
905 serverSSL.set_accept_state()
906
Jean-Paul Calderonef8742032010-09-25 00:00:32 -0400907 # Without load_verify_locations above, the handshake
908 # will fail:
909 # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
910 # 'certificate verify failed')]
911 handshake(clientSSL, serverSSL)
Jean-Paul Calderonee1bd4322008-09-07 20:17:17 -0400912
913 cert = clientSSL.get_peer_certificate()
Jean-Paul Calderone20131f52009-04-01 12:05:45 -0400914 self.assertEqual(cert.get_subject().CN, 'Testing Root CA')
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400915
Jean-Paul Calderone12608a82009-11-07 10:35:15 -0500916
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400917 def _load_verify_cafile(self, cafile):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400918 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400919 Verify that if path to a file containing a certificate is passed to
920 ``Context.load_verify_locations`` for the ``cafile`` parameter, that
921 certificate is used as a trust root for the purposes of verifying
922 connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400923 """
Jean-Paul Calderonea9868832010-08-22 21:38:34 -0400924 fObj = open(cafile, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -0400925 fObj.write(cleartextCertificatePEM.decode('ascii'))
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400926 fObj.close()
927
928 self._load_verify_locations_test(cafile)
929
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400930
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400931 def test_load_verify_bytes_cafile(self):
932 """
933 :py:obj:`Context.load_verify_locations` accepts a file name as a
934 ``bytes`` instance and uses the certificates within for verification
935 purposes.
936 """
937 cafile = self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
938 self._load_verify_cafile(cafile)
939
940
941 def test_load_verify_unicode_cafile(self):
942 """
943 :py:obj:`Context.load_verify_locations` accepts a file name as a
944 ``unicode`` instance and uses the certificates within for verification
945 purposes.
946 """
947 cafile = self.mktemp() + NON_ASCII
948 self._load_verify_cafile(cafile)
949
950
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400951 def test_load_verify_invalid_file(self):
952 """
Jonathan Ballet648875f2011-07-16 14:14:58 +0900953 :py:obj:`Context.load_verify_locations` raises :py:obj:`Error` when passed a
Jean-Paul Calderone5075fce2008-09-07 20:18:55 -0400954 non-existent cafile.
955 """
956 clientContext = Context(TLSv1_METHOD)
957 self.assertRaises(
958 Error, clientContext.load_verify_locations, self.mktemp())
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400959
960
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400961 def _load_verify_directory_locations_capath(self, capath):
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400962 """
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400963 Verify that if path to a directory containing certificate files is
964 passed to ``Context.load_verify_locations`` for the ``capath``
965 parameter, those certificates are used as trust roots for the purposes
966 of verifying connections created using that ``Context``.
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400967 """
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400968 makedirs(capath)
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400969 # Hash values computed manually with c_rehash to avoid depending on
970 # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
971 # from OpenSSL 1.0.0.
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500972 for name in [b'c7adac82.0', b'c3705638.0']:
Jean-Paul Calderone24dfb332011-05-04 18:10:26 -0400973 cafile = join(capath, name)
974 fObj = open(cafile, 'w')
975 fObj.write(cleartextCertificatePEM.decode('ascii'))
976 fObj.close()
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400977
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -0400978 self._load_verify_locations_test(None, capath)
979
980
Jean-Paul Calderone210c0f32015-04-12 09:20:31 -0400981 def test_load_verify_directory_bytes_capath(self):
982 """
983 :py:obj:`Context.load_verify_locations` accepts a directory name as a
984 ``bytes`` instance and uses the certificates within for verification
985 purposes.
986 """
987 self._load_verify_directory_locations_capath(
988 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
989 )
990
991
992 def test_load_verify_directory_unicode_capath(self):
993 """
994 :py:obj:`Context.load_verify_locations` accepts a directory name as a
995 ``unicode`` instance and uses the certificates within for verification
996 purposes.
997 """
998 self._load_verify_directory_locations_capath(self.mktemp() + NON_ASCII)
999
1000
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001001 def test_load_verify_locations_wrong_args(self):
1002 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001003 :py:obj:`Context.load_verify_locations` raises :py:obj:`TypeError` if called with
1004 the wrong number of arguments or with non-:py:obj:`str` arguments.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001005 """
1006 context = Context(TLSv1_METHOD)
1007 self.assertRaises(TypeError, context.load_verify_locations)
1008 self.assertRaises(TypeError, context.load_verify_locations, object())
1009 self.assertRaises(TypeError, context.load_verify_locations, object(), object())
1010 self.assertRaises(TypeError, context.load_verify_locations, None, None, None)
1011
1012
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04001013 if platform == "win32":
1014 "set_default_verify_paths appears not to work on Windows. "
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001015 "See LP#404343 and LP#404344."
1016 else:
1017 def test_set_default_verify_paths(self):
1018 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001019 :py:obj:`Context.set_default_verify_paths` causes the platform-specific CA
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001020 certificate locations to be used for verification purposes.
1021 """
1022 # Testing this requires a server with a certificate signed by one of
1023 # the CAs in the platform CA location. Getting one of those costs
1024 # money. Fortunately (or unfortunately, depending on your
1025 # perspective), it's easy to think of a public server on the
1026 # internet which has such a certificate. Connecting to the network
1027 # in a unit test is bad, but it's the only way I can think of to
1028 # really test this. -exarkun
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001029
Alex Gaynorb586da32014-11-15 09:22:21 -08001030 # Arg, verisign.com doesn't speak anything newer than TLS 1.0
1031 context = Context(TLSv1_METHOD)
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001032 context.set_default_verify_paths()
1033 context.set_verify(
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02001034 VERIFY_PEER,
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001035 lambda conn, cert, errno, depth, preverify_ok: preverify_ok)
Jean-Paul Calderone1cb5d022008-09-07 20:58:50 -04001036
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001037 client = socket()
1038 client.connect(('verisign.com', 443))
1039 clientSSL = Connection(context, client)
1040 clientSSL.set_connect_state()
1041 clientSSL.do_handshake()
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001042 clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
Jean-Paul Calderone28fb8f02009-07-24 18:01:31 -04001043 self.assertTrue(clientSSL.recv(1024))
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001044
1045
1046 def test_set_default_verify_paths_signature(self):
1047 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001048 :py:obj:`Context.set_default_verify_paths` takes no arguments and raises
1049 :py:obj:`TypeError` if given any.
Jean-Paul Calderone9eadb962008-09-07 21:20:44 -04001050 """
1051 context = Context(TLSv1_METHOD)
1052 self.assertRaises(TypeError, context.set_default_verify_paths, None)
1053 self.assertRaises(TypeError, context.set_default_verify_paths, 1)
1054 self.assertRaises(TypeError, context.set_default_verify_paths, "")
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05001055
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001056
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001057 def test_add_extra_chain_cert_invalid_cert(self):
1058 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001059 :py:obj:`Context.add_extra_chain_cert` raises :py:obj:`TypeError` if called with
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001060 other than one argument or if called with an object which is not an
Jonathan Ballet648875f2011-07-16 14:14:58 +09001061 instance of :py:obj:`X509`.
Jean-Paul Calderone12608a82009-11-07 10:35:15 -05001062 """
1063 context = Context(TLSv1_METHOD)
1064 self.assertRaises(TypeError, context.add_extra_chain_cert)
1065 self.assertRaises(TypeError, context.add_extra_chain_cert, object())
1066 self.assertRaises(TypeError, context.add_extra_chain_cert, object(), object())
1067
1068
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001069 def _handshake_test(self, serverContext, clientContext):
1070 """
1071 Verify that a client and server created with the given contexts can
1072 successfully handshake and communicate.
1073 """
1074 serverSocket, clientSocket = socket_pair()
1075
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001076 server = Connection(serverContext, serverSocket)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001077 server.set_accept_state()
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001078
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001079 client = Connection(clientContext, clientSocket)
1080 client.set_connect_state()
1081
1082 # Make them talk to each other.
1083 # self._interactInMemory(client, server)
1084 for i in range(3):
1085 for s in [client, server]:
1086 try:
1087 s.do_handshake()
1088 except WantReadError:
1089 pass
1090
1091
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -04001092 def test_set_verify_callback_connection_argument(self):
1093 """
1094 The first argument passed to the verify callback is the
1095 :py:class:`Connection` instance for which verification is taking place.
1096 """
1097 serverContext = Context(TLSv1_METHOD)
1098 serverContext.use_privatekey(
1099 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1100 serverContext.use_certificate(
1101 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1102 serverConnection = Connection(serverContext, None)
1103
1104 class VerifyCallback(object):
1105 def callback(self, connection, *args):
1106 self.connection = connection
1107 return 1
1108
1109 verify = VerifyCallback()
1110 clientContext = Context(TLSv1_METHOD)
1111 clientContext.set_verify(VERIFY_PEER, verify.callback)
1112 clientConnection = Connection(clientContext, None)
1113 clientConnection.set_connect_state()
1114
1115 self._handshakeInMemory(clientConnection, serverConnection)
1116
1117 self.assertIdentical(verify.connection, clientConnection)
1118
1119
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001120 def test_set_verify_callback_exception(self):
1121 """
1122 If the verify callback passed to :py:obj:`Context.set_verify` raises an
1123 exception, verification fails and the exception is propagated to the
1124 caller of :py:obj:`Connection.do_handshake`.
1125 """
1126 serverContext = Context(TLSv1_METHOD)
1127 serverContext.use_privatekey(
1128 load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM))
1129 serverContext.use_certificate(
1130 load_certificate(FILETYPE_PEM, cleartextCertificatePEM))
1131
1132 clientContext = Context(TLSv1_METHOD)
1133 def verify_callback(*args):
1134 raise Exception("silly verify failure")
1135 clientContext.set_verify(VERIFY_PEER, verify_callback)
1136
1137 exc = self.assertRaises(
1138 Exception, self._handshake_test, serverContext, clientContext)
1139 self.assertEqual("silly verify failure", str(exc))
1140
1141
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001142 def test_add_extra_chain_cert(self):
1143 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001144 :py:obj:`Context.add_extra_chain_cert` accepts an :py:obj:`X509` instance to add to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001145 the certificate chain.
1146
Jonathan Ballet648875f2011-07-16 14:14:58 +09001147 See :py:obj:`_create_certificate_chain` for the details of the certificate
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001148 chain tested.
1149
1150 The chain is tested by starting a server with scert and connecting
1151 to it with a client which trusts cacert and requires verification to
1152 succeed.
1153 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001154 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001155 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1156
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001157 # Dump the CA certificate to a file because that's the only way to load
1158 # it as a trusted CA in the client context.
1159 for cert, name in [(cacert, 'ca.pem'), (icert, 'i.pem'), (scert, 's.pem')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001160 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001161 fObj.write(dump_certificate(FILETYPE_PEM, cert).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001162 fObj.close()
1163
1164 for key, name in [(cakey, 'ca.key'), (ikey, 'i.key'), (skey, 's.key')]:
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04001165 fObj = open(name, 'w')
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04001166 fObj.write(dump_privatekey(FILETYPE_PEM, key).decode('ascii'))
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001167 fObj.close()
1168
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001169 # Create the server context
1170 serverContext = Context(TLSv1_METHOD)
1171 serverContext.use_privatekey(skey)
1172 serverContext.use_certificate(scert)
Jean-Paul Calderone16cf03d2010-09-08 18:53:39 -04001173 # The client already has cacert, we only need to give them icert.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001174 serverContext.add_extra_chain_cert(icert)
1175
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04001176 # Create the client
1177 clientContext = Context(TLSv1_METHOD)
1178 clientContext.set_verify(
1179 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001180 clientContext.load_verify_locations(b"ca.pem")
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001181
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001182 # Try it out.
1183 self._handshake_test(serverContext, clientContext)
1184
1185
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001186 def _use_certificate_chain_file_test(self, certdir):
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001187 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001188 Verify that :py:obj:`Context.use_certificate_chain_file` reads a
1189 certificate chain from a specified file.
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001190
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001191 The chain is tested by starting a server with scert and connecting to
1192 it with a client which trusts cacert and requires verification to
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001193 succeed.
1194 """
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001195 chain = _create_certificate_chain()
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001196 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1197
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001198 makedirs(certdir)
1199
1200 if isinstance(certdir, binary_type):
1201 chainFile = join(certdir, b("chain.pem"))
1202 caFile = join(certdir, b("ca.pem"))
1203 else:
1204 chainFile = join(certdir, u"chain.pem")
1205 caFile = join(certdir, u"ca.pem")
1206
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001207 # Write out the chain file.
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001208 with open(chainFile, 'wb') as fObj:
1209 # Most specific to least general.
1210 fObj.write(dump_certificate(FILETYPE_PEM, scert))
1211 fObj.write(dump_certificate(FILETYPE_PEM, icert))
1212 fObj.write(dump_certificate(FILETYPE_PEM, cacert))
1213
1214 with open(caFile, 'w') as fObj:
1215 fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode('ascii'))
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001216
1217 serverContext = Context(TLSv1_METHOD)
1218 serverContext.use_certificate_chain_file(chainFile)
1219 serverContext.use_privatekey(skey)
1220
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001221 clientContext = Context(TLSv1_METHOD)
1222 clientContext.set_verify(
1223 VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb)
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001224 clientContext.load_verify_locations(caFile)
Jean-Paul Calderonef4480622010-08-02 18:25:03 -04001225
1226 self._handshake_test(serverContext, clientContext)
1227
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001228
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -04001229 def test_use_certificate_chain_file_bytes(self):
1230 """
1231 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1232 an instance of ``bytes``) to specify additional certificates to use to
1233 construct and verify a trust chain.
1234 """
1235 self._use_certificate_chain_file_test(
1236 self.mktemp() + NON_ASCII.encode(getfilesystemencoding())
1237 )
1238
1239
1240 def test_use_certificate_chain_file_unicode(self):
1241 """
1242 ``Context.use_certificate_chain_file`` accepts the name of a file (as
1243 an instance of ``unicode``) to specify additional certificates to use
1244 to construct and verify a trust chain.
1245 """
1246 self._use_certificate_chain_file_test(
1247 self.mktemp().decode(getfilesystemencoding()) + NON_ASCII
1248 )
1249
1250
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001251 def test_use_certificate_chain_file_wrong_args(self):
1252 """
1253 :py:obj:`Context.use_certificate_chain_file` raises :py:obj:`TypeError`
1254 if passed zero or more than one argument or when passed a non-byte
1255 string single argument. It also raises :py:obj:`OpenSSL.SSL.Error` when
1256 passed a bad chain file name (for example, the name of a file which does
1257 not exist).
1258 """
1259 context = Context(TLSv1_METHOD)
1260 self.assertRaises(TypeError, context.use_certificate_chain_file)
1261 self.assertRaises(TypeError, context.use_certificate_chain_file, object())
1262 self.assertRaises(TypeError, context.use_certificate_chain_file, b"foo", object())
1263
1264 self.assertRaises(Error, context.use_certificate_chain_file, self.mktemp())
1265
Jean-Paul Calderonee0d79362010-08-03 18:46:46 -04001266 # XXX load_client_ca
1267 # XXX set_session_id
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001268
1269 def test_get_verify_mode_wrong_args(self):
1270 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001271 :py:obj:`Context.get_verify_mode` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001272 arguments.
1273 """
1274 context = Context(TLSv1_METHOD)
1275 self.assertRaises(TypeError, context.get_verify_mode, None)
1276
1277
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001278 def test_set_verify_mode(self):
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001279 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001280 :py:obj:`Context.get_verify_mode` returns the verify mode flags previously
1281 passed to :py:obj:`Context.set_verify`.
Jean-Paul Calderone0294e3d2010-09-09 18:17:48 -04001282 """
1283 context = Context(TLSv1_METHOD)
1284 self.assertEquals(context.get_verify_mode(), 0)
1285 context.set_verify(
1286 VERIFY_PEER | VERIFY_CLIENT_ONCE, lambda *args: None)
1287 self.assertEquals(
1288 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1289
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001290
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001291 if not PY3:
1292 def test_set_verify_mode_long(self):
1293 """
1294 On Python 2 :py:obj:`Context.set_verify_mode` accepts values of
1295 type :py:obj:`long` as well as :py:obj:`int`.
1296 """
1297 context = Context(TLSv1_METHOD)
1298 self.assertEquals(context.get_verify_mode(), 0)
1299 context.set_verify(
1300 long(VERIFY_PEER | VERIFY_CLIENT_ONCE), lambda *args: None)
1301 self.assertEquals(
1302 context.get_verify_mode(), VERIFY_PEER | VERIFY_CLIENT_ONCE)
1303
1304
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001305 def test_load_tmp_dh_wrong_args(self):
1306 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001307 :py:obj:`Context.load_tmp_dh` raises :py:obj:`TypeError` if called with the wrong
1308 number of arguments or with a non-:py:obj:`str` argument.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001309 """
1310 context = Context(TLSv1_METHOD)
1311 self.assertRaises(TypeError, context.load_tmp_dh)
1312 self.assertRaises(TypeError, context.load_tmp_dh, "foo", None)
1313 self.assertRaises(TypeError, context.load_tmp_dh, object())
1314
1315
1316 def test_load_tmp_dh_missing_file(self):
1317 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001318 :py:obj:`Context.load_tmp_dh` raises :py:obj:`OpenSSL.SSL.Error` if the specified file
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001319 does not exist.
1320 """
1321 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001322 self.assertRaises(Error, context.load_tmp_dh, b"hello")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001323
1324
1325 def test_load_tmp_dh(self):
1326 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001327 :py:obj:`Context.load_tmp_dh` loads Diffie-Hellman parameters from the
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001328 specified file.
1329 """
1330 context = Context(TLSv1_METHOD)
1331 dhfilename = self.mktemp()
1332 dhfile = open(dhfilename, "w")
1333 dhfile.write(dhparam)
1334 dhfile.close()
1335 context.load_tmp_dh(dhfilename)
1336 # XXX What should I assert here? -exarkun
1337
1338
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001339 def test_set_tmp_ecdh(self):
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001340 """
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001341 :py:obj:`Context.set_tmp_ecdh` sets the elliptic curve for
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001342 Diffie-Hellman to the specified curve.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001343 """
1344 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001345 for curve in get_elliptic_curves():
1346 # The only easily "assertable" thing is that it does not raise an
1347 # exception.
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001348 context.set_tmp_ecdh(curve)
Alex Gaynor12dc0842014-01-17 12:51:31 -06001349
1350
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001351 def test_set_cipher_list_bytes(self):
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001352 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001353 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`bytes` naming the
1354 ciphers which connections created with the context object will be able
1355 to choose from.
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001356 """
1357 context = Context(TLSv1_METHOD)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001358 context.set_cipher_list(b"hello world:EXP-RC4-MD5")
Jean-Paul Calderone6ace4782010-09-09 18:43:40 -04001359 conn = Connection(context, None)
1360 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001361
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001362
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001363 def test_set_cipher_list_text(self):
1364 """
1365 :py:obj:`Context.set_cipher_list` accepts a :py:obj:`unicode` naming
1366 the ciphers which connections created with the context object will be
1367 able to choose from.
1368 """
1369 context = Context(TLSv1_METHOD)
Jean-Paul Calderonec76c61c2014-01-18 13:21:52 -05001370 context.set_cipher_list(u("hello world:EXP-RC4-MD5"))
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001371 conn = Connection(context, None)
1372 self.assertEquals(conn.get_cipher_list(), ["EXP-RC4-MD5"])
1373
1374
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001375 def test_set_cipher_list_wrong_args(self):
1376 """
Jean-Paul Calderone17044832014-01-18 10:20:11 -05001377 :py:obj:`Context.set_cipher_list` raises :py:obj:`TypeError` when
1378 passed zero arguments or more than one argument or when passed a
1379 non-string single argument and raises :py:obj:`OpenSSL.SSL.Error` when
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001380 passed an incorrect cipher list string.
1381 """
1382 context = Context(TLSv1_METHOD)
1383 self.assertRaises(TypeError, context.set_cipher_list)
1384 self.assertRaises(TypeError, context.set_cipher_list, object())
1385 self.assertRaises(TypeError, context.set_cipher_list, b"EXP-RC4-MD5", object())
1386
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001387 self.assertRaises(Error, context.set_cipher_list, "imaginary-cipher")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001388
1389
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001390 def test_set_session_cache_mode_wrong_args(self):
1391 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001392 :py:obj:`Context.set_session_cache_mode` raises :py:obj:`TypeError` if
1393 called with other than one integer argument.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001394 """
1395 context = Context(TLSv1_METHOD)
1396 self.assertRaises(TypeError, context.set_session_cache_mode)
1397 self.assertRaises(TypeError, context.set_session_cache_mode, object())
1398
1399
1400 def test_get_session_cache_mode_wrong_args(self):
1401 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001402 :py:obj:`Context.get_session_cache_mode` raises :py:obj:`TypeError` if
1403 called with any arguments.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001404 """
1405 context = Context(TLSv1_METHOD)
1406 self.assertRaises(TypeError, context.get_session_cache_mode, 1)
1407
1408
1409 def test_session_cache_mode(self):
1410 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001411 :py:obj:`Context.set_session_cache_mode` specifies how sessions are
1412 cached. The setting can be retrieved via
1413 :py:obj:`Context.get_session_cache_mode`.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001414 """
1415 context = Context(TLSv1_METHOD)
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001416 context.set_session_cache_mode(SESS_CACHE_OFF)
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001417 off = context.set_session_cache_mode(SESS_CACHE_BOTH)
1418 self.assertEqual(SESS_CACHE_OFF, off)
1419 self.assertEqual(SESS_CACHE_BOTH, context.get_session_cache_mode())
1420
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001421 if not PY3:
1422 def test_session_cache_mode_long(self):
1423 """
1424 On Python 2 :py:obj:`Context.set_session_cache_mode` accepts values
1425 of type :py:obj:`long` as well as :py:obj:`int`.
1426 """
1427 context = Context(TLSv1_METHOD)
1428 context.set_session_cache_mode(long(SESS_CACHE_BOTH))
1429 self.assertEqual(
1430 SESS_CACHE_BOTH, context.get_session_cache_mode())
1431
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05001432
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433 def test_get_cert_store(self):
1434 """
1435 :py:obj:`Context.get_cert_store` returns a :py:obj:`X509Store` instance.
1436 """
1437 context = Context(TLSv1_METHOD)
1438 store = context.get_cert_store()
1439 self.assertIsInstance(store, X509Store)
1440
1441
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001442
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001443class ServerNameCallbackTests(TestCase, _LoopbackMixin):
1444 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001445 Tests for :py:obj:`Context.set_tlsext_servername_callback` and its interaction with
1446 :py:obj:`Connection`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001447 """
1448 def test_wrong_args(self):
1449 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001450 :py:obj:`Context.set_tlsext_servername_callback` raises :py:obj:`TypeError` if called
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001451 with other than one argument.
1452 """
1453 context = Context(TLSv1_METHOD)
1454 self.assertRaises(TypeError, context.set_tlsext_servername_callback)
1455 self.assertRaises(
1456 TypeError, context.set_tlsext_servername_callback, 1, 2)
1457
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001458
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001459 def test_old_callback_forgotten(self):
1460 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001461 If :py:obj:`Context.set_tlsext_servername_callback` is used to specify a new
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001462 callback, the one it replaces is dereferenced.
1463 """
1464 def callback(connection):
1465 pass
1466
1467 def replacement(connection):
1468 pass
1469
1470 context = Context(TLSv1_METHOD)
1471 context.set_tlsext_servername_callback(callback)
1472
1473 tracker = ref(callback)
1474 del callback
1475
1476 context.set_tlsext_servername_callback(replacement)
Jean-Paul Calderoned4033eb2014-01-11 08:21:46 -05001477
1478 # One run of the garbage collector happens to work on CPython. PyPy
1479 # doesn't collect the underlying object until a second run for whatever
1480 # reason. That's fine, it still demonstrates our code has properly
1481 # dropped the reference.
1482 collect()
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001483 collect()
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001484
1485 callback = tracker()
1486 if callback is not None:
1487 referrers = get_referrers(callback)
Jean-Paul Calderone7de39562014-01-11 08:17:59 -05001488 if len(referrers) > 1:
Jean-Paul Calderone4c1aacd2014-01-11 08:15:17 -05001489 self.fail("Some references remain: %r" % (referrers,))
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001490
1491
1492 def test_no_servername(self):
1493 """
1494 When a client specifies no server name, the callback passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001495 :py:obj:`Context.set_tlsext_servername_callback` is invoked and the result of
1496 :py:obj:`Connection.get_servername` is :py:obj:`None`.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001497 """
1498 args = []
1499 def servername(conn):
1500 args.append((conn, conn.get_servername()))
1501 context = Context(TLSv1_METHOD)
1502 context.set_tlsext_servername_callback(servername)
1503
1504 # Lose our reference to it. The Context is responsible for keeping it
1505 # alive now.
1506 del servername
1507 collect()
1508
1509 # Necessary to actually accept the connection
1510 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1511 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1512
1513 # Do a little connection to trigger the logic
1514 server = Connection(context, None)
1515 server.set_accept_state()
1516
1517 client = Connection(Context(TLSv1_METHOD), None)
1518 client.set_connect_state()
1519
1520 self._interactInMemory(server, client)
1521
1522 self.assertEqual([(server, None)], args)
1523
1524
1525 def test_servername(self):
1526 """
1527 When a client specifies a server name in its hello message, the callback
Jonathan Ballet648875f2011-07-16 14:14:58 +09001528 passed to :py:obj:`Contexts.set_tlsext_servername_callback` is invoked and the
1529 result of :py:obj:`Connection.get_servername` is that server name.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001530 """
1531 args = []
1532 def servername(conn):
1533 args.append((conn, conn.get_servername()))
1534 context = Context(TLSv1_METHOD)
1535 context.set_tlsext_servername_callback(servername)
1536
1537 # Necessary to actually accept the connection
1538 context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1539 context.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1540
1541 # Do a little connection to trigger the logic
1542 server = Connection(context, None)
1543 server.set_accept_state()
1544
1545 client = Connection(Context(TLSv1_METHOD), None)
1546 client.set_connect_state()
1547 client.set_tlsext_host_name(b("foo1.example.com"))
1548
1549 self._interactInMemory(server, client)
1550
1551 self.assertEqual([(server, b("foo1.example.com"))], args)
1552
1553
1554
Jean-Paul Calderonee0fcf512012-02-13 09:10:15 -05001555class SessionTests(TestCase):
1556 """
1557 Unit tests for :py:obj:`OpenSSL.SSL.Session`.
1558 """
1559 def test_construction(self):
1560 """
1561 :py:class:`Session` can be constructed with no arguments, creating a new
1562 instance of that type.
1563 """
1564 new_session = Session()
1565 self.assertTrue(isinstance(new_session, Session))
1566
1567
1568 def test_construction_wrong_args(self):
1569 """
1570 If any arguments are passed to :py:class:`Session`, :py:obj:`TypeError`
1571 is raised.
1572 """
1573 self.assertRaises(TypeError, Session, 123)
1574 self.assertRaises(TypeError, Session, "hello")
1575 self.assertRaises(TypeError, Session, object())
1576
1577
1578
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001579class ConnectionTests(TestCase, _LoopbackMixin):
Rick Deane15b1472009-07-09 15:53:42 -05001580 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001581 Unit tests for :py:obj:`OpenSSL.SSL.Connection`.
Rick Deane15b1472009-07-09 15:53:42 -05001582 """
Jean-Paul Calderone541eaf22010-09-09 18:55:08 -04001583 # XXX get_peer_certificate -> None
1584 # XXX sock_shutdown
1585 # XXX master_key -> TypeError
1586 # XXX server_random -> TypeError
1587 # XXX state_string
1588 # XXX connect -> TypeError
1589 # XXX connect_ex -> TypeError
1590 # XXX set_connect_state -> TypeError
1591 # XXX set_accept_state -> TypeError
1592 # XXX renegotiate_pending
1593 # XXX do_handshake -> TypeError
1594 # XXX bio_read -> TypeError
1595 # XXX recv -> TypeError
1596 # XXX send -> TypeError
1597 # XXX bio_write -> TypeError
1598
Rick Deane15b1472009-07-09 15:53:42 -05001599 def test_type(self):
1600 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001601 :py:obj:`Connection` and :py:obj:`ConnectionType` refer to the same type object and
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001602 can be used to create instances of that type.
Rick Deane15b1472009-07-09 15:53:42 -05001603 """
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001604 self.assertIdentical(Connection, ConnectionType)
Rick Deane15b1472009-07-09 15:53:42 -05001605 ctx = Context(TLSv1_METHOD)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001606 self.assertConsistentType(Connection, 'Connection', ctx, None)
Rick Deane15b1472009-07-09 15:53:42 -05001607
Jean-Paul Calderone68649052009-07-17 21:14:27 -04001608
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001609 def test_get_context(self):
1610 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001611 :py:obj:`Connection.get_context` returns the :py:obj:`Context` instance used to
1612 construct the :py:obj:`Connection` instance.
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001613 """
1614 context = Context(TLSv1_METHOD)
1615 connection = Connection(context, None)
1616 self.assertIdentical(connection.get_context(), context)
1617
1618
1619 def test_get_context_wrong_args(self):
1620 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001621 :py:obj:`Connection.get_context` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone4fd058a2009-11-22 11:46:42 -05001622 arguments.
1623 """
1624 connection = Connection(Context(TLSv1_METHOD), None)
1625 self.assertRaises(TypeError, connection.get_context, None)
1626
1627
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001628 def test_set_context_wrong_args(self):
1629 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001630 :py:obj:`Connection.set_context` raises :py:obj:`TypeError` if called with a
1631 non-:py:obj:`Context` instance argument or with any number of arguments other
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001632 than 1.
1633 """
1634 ctx = Context(TLSv1_METHOD)
1635 connection = Connection(ctx, None)
1636 self.assertRaises(TypeError, connection.set_context)
1637 self.assertRaises(TypeError, connection.set_context, object())
1638 self.assertRaises(TypeError, connection.set_context, "hello")
1639 self.assertRaises(TypeError, connection.set_context, 1)
1640 self.assertRaises(TypeError, connection.set_context, 1, 2)
1641 self.assertRaises(
1642 TypeError, connection.set_context, Context(TLSv1_METHOD), 2)
1643 self.assertIdentical(ctx, connection.get_context())
1644
1645
1646 def test_set_context(self):
1647 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001648 :py:obj:`Connection.set_context` specifies a new :py:obj:`Context` instance to be used
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001649 for the connection.
1650 """
1651 original = Context(SSLv23_METHOD)
1652 replacement = Context(TLSv1_METHOD)
1653 connection = Connection(original, None)
1654 connection.set_context(replacement)
1655 self.assertIdentical(replacement, connection.get_context())
1656 # Lose our references to the contexts, just in case the Connection isn't
1657 # properly managing its own contributions to their reference counts.
1658 del original, replacement
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001659 collect()
1660
1661
1662 def test_set_tlsext_host_name_wrong_args(self):
1663 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001664 If :py:obj:`Connection.set_tlsext_host_name` is called with a non-byte string
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001665 argument or a byte string with an embedded NUL or other than one
Jonathan Ballet648875f2011-07-16 14:14:58 +09001666 argument, :py:obj:`TypeError` is raised.
Jean-Paul Calderonec4cb6582011-05-26 18:47:00 -04001667 """
1668 conn = Connection(Context(TLSv1_METHOD), None)
1669 self.assertRaises(TypeError, conn.set_tlsext_host_name)
1670 self.assertRaises(TypeError, conn.set_tlsext_host_name, object())
1671 self.assertRaises(TypeError, conn.set_tlsext_host_name, 123, 456)
1672 self.assertRaises(
1673 TypeError, conn.set_tlsext_host_name, b("with\0null"))
1674
1675 if version_info >= (3,):
1676 # On Python 3.x, don't accidentally implicitly convert from text.
1677 self.assertRaises(
1678 TypeError,
1679 conn.set_tlsext_host_name, b("example.com").decode("ascii"))
Jean-Paul Calderone95613b72011-05-25 22:30:21 -04001680
1681
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001682 def test_get_servername_wrong_args(self):
1683 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001684 :py:obj:`Connection.get_servername` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone871a4d82011-05-26 19:24:02 -04001685 arguments.
1686 """
1687 connection = Connection(Context(TLSv1_METHOD), None)
1688 self.assertRaises(TypeError, connection.get_servername, object())
1689 self.assertRaises(TypeError, connection.get_servername, 1)
1690 self.assertRaises(TypeError, connection.get_servername, "hello")
1691
1692
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001693 def test_pending(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001694 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001695 :py:obj:`Connection.pending` returns the number of bytes available for
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001696 immediate read.
1697 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001698 connection = Connection(Context(TLSv1_METHOD), None)
1699 self.assertEquals(connection.pending(), 0)
1700
1701
1702 def test_pending_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001703 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001704 :py:obj:`Connection.pending` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001705 """
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04001706 connection = Connection(Context(TLSv1_METHOD), None)
1707 self.assertRaises(TypeError, connection.pending, None)
1708
1709
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001710 def test_connect_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001711 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001712 :py:obj:`Connection.connect` raises :py:obj:`TypeError` if called with a non-address
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001713 argument or with the wrong number of arguments.
1714 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001715 connection = Connection(Context(TLSv1_METHOD), socket())
1716 self.assertRaises(TypeError, connection.connect, None)
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001717 self.assertRaises(TypeError, connection.connect)
1718 self.assertRaises(TypeError, connection.connect, ("127.0.0.1", 1), None)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001719
1720
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001721 def test_connect_refused(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001722 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001723 :py:obj:`Connection.connect` raises :py:obj:`socket.error` if the underlying socket
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001724 connect method raises it.
1725 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001726 client = socket()
1727 context = Context(TLSv1_METHOD)
1728 clientSSL = Connection(context, client)
1729 exc = self.assertRaises(error, clientSSL.connect, ("127.0.0.1", 1))
Jean-Paul Calderone35adf9d2010-07-29 18:40:44 -04001730 self.assertEquals(exc.args[0], ECONNREFUSED)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001731
1732
1733 def test_connect(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001734 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001735 :py:obj:`Connection.connect` establishes a connection to the specified address.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001736 """
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001737 port = socket()
1738 port.bind(('', 0))
1739 port.listen(3)
1740
1741 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001742 clientSSL.connect(('127.0.0.1', port.getsockname()[1]))
1743 # XXX An assertion? Or something?
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001744
1745
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001746 if platform == "darwin":
1747 "connect_ex sometimes causes a kernel panic on OS X 10.6.4"
1748 else:
1749 def test_connect_ex(self):
1750 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001751 If there is a connection error, :py:obj:`Connection.connect_ex` returns the
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001752 errno instead of raising an exception.
1753 """
1754 port = socket()
1755 port.bind(('', 0))
1756 port.listen(3)
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001757
Jean-Paul Calderone7b614872010-09-24 17:43:44 -04001758 clientSSL = Connection(Context(TLSv1_METHOD), socket())
1759 clientSSL.setblocking(False)
1760 result = clientSSL.connect_ex(port.getsockname())
1761 expected = (EINPROGRESS, EWOULDBLOCK)
1762 self.assertTrue(
1763 result in expected, "%r not in %r" % (result, expected))
Jean-Paul Calderone55d91f42010-07-29 19:22:17 -04001764
1765
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001766 def test_accept_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001767 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001768 :py:obj:`Connection.accept` raises :py:obj:`TypeError` if called with any arguments.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001769 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001770 connection = Connection(Context(TLSv1_METHOD), socket())
1771 self.assertRaises(TypeError, connection.accept, None)
1772
1773
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001774 def test_accept(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001775 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001776 :py:obj:`Connection.accept` accepts a pending connection attempt and returns a
1777 tuple of a new :py:obj:`Connection` (the accepted client) and the address the
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001778 connection originated from.
1779 """
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001780 ctx = Context(TLSv1_METHOD)
1781 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1782 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001783 port = socket()
1784 portSSL = Connection(ctx, port)
1785 portSSL.bind(('', 0))
1786 portSSL.listen(3)
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001787
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001788 clientSSL = Connection(Context(TLSv1_METHOD), socket())
Jean-Paul Calderoneb6e0fd92010-09-19 09:22:13 -04001789
1790 # Calling portSSL.getsockname() here to get the server IP address sounds
1791 # great, but frequently fails on Windows.
1792 clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1]))
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001793
Jean-Paul Calderone0bcb0e02010-07-29 09:49:59 -04001794 serverSSL, address = portSSL.accept()
1795
1796 self.assertTrue(isinstance(serverSSL, Connection))
1797 self.assertIdentical(serverSSL.get_context(), ctx)
1798 self.assertEquals(address, clientSSL.getsockname())
Jean-Paul Calderone8bdeba22010-07-29 09:45:07 -04001799
1800
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001801 def test_shutdown_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001802 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001803 :py:obj:`Connection.shutdown` raises :py:obj:`TypeError` if called with the wrong
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001804 number of arguments or with arguments other than integers.
1805 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001806 connection = Connection(Context(TLSv1_METHOD), None)
1807 self.assertRaises(TypeError, connection.shutdown, None)
Jean-Paul Calderone1d3e0222010-07-29 22:52:45 -04001808 self.assertRaises(TypeError, connection.get_shutdown, None)
1809 self.assertRaises(TypeError, connection.set_shutdown)
1810 self.assertRaises(TypeError, connection.set_shutdown, None)
1811 self.assertRaises(TypeError, connection.set_shutdown, 0, 1)
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001812
1813
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001814 def test_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001815 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001816 :py:obj:`Connection.shutdown` performs an SSL-level connection shutdown.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001817 """
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001818 server, client = self._loopback()
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001819 self.assertFalse(server.shutdown())
1820 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001821 self.assertRaises(ZeroReturnError, client.recv, 1024)
Jean-Paul Calderonee4f6b472010-07-29 22:50:58 -04001822 self.assertEquals(client.get_shutdown(), RECEIVED_SHUTDOWN)
1823 client.shutdown()
1824 self.assertEquals(client.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
1825 self.assertRaises(ZeroReturnError, server.recv, 1024)
1826 self.assertEquals(server.get_shutdown(), SENT_SHUTDOWN|RECEIVED_SHUTDOWN)
Jean-Paul Calderone9485f2c2010-07-29 22:38:42 -04001827
1828
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001829 def test_set_shutdown(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001830 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001831 :py:obj:`Connection.set_shutdown` sets the state of the SSL connection shutdown
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001832 process.
1833 """
Jean-Paul Calderonec89eef22010-07-29 22:51:58 -04001834 connection = Connection(Context(TLSv1_METHOD), socket())
1835 connection.set_shutdown(RECEIVED_SHUTDOWN)
1836 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1837
1838
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001839 if not PY3:
1840 def test_set_shutdown_long(self):
1841 """
1842 On Python 2 :py:obj:`Connection.set_shutdown` accepts an argument
1843 of type :py:obj:`long` as well as :py:obj:`int`.
1844 """
1845 connection = Connection(Context(TLSv1_METHOD), socket())
1846 connection.set_shutdown(long(RECEIVED_SHUTDOWN))
1847 self.assertEquals(connection.get_shutdown(), RECEIVED_SHUTDOWN)
1848
1849
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001850 def test_app_data_wrong_args(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001851 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001852 :py:obj:`Connection.set_app_data` raises :py:obj:`TypeError` if called with other than
1853 one argument. :py:obj:`Connection.get_app_data` raises :py:obj:`TypeError` if called
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001854 with any arguments.
1855 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001856 conn = Connection(Context(TLSv1_METHOD), None)
1857 self.assertRaises(TypeError, conn.get_app_data, None)
1858 self.assertRaises(TypeError, conn.set_app_data)
1859 self.assertRaises(TypeError, conn.set_app_data, None, None)
1860
1861
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001862 def test_app_data(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001863 """
1864 Any object can be set as app data by passing it to
Jonathan Ballet648875f2011-07-16 14:14:58 +09001865 :py:obj:`Connection.set_app_data` and later retrieved with
1866 :py:obj:`Connection.get_app_data`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001867 """
Jean-Paul Calderone1bd8c792010-07-29 09:51:06 -04001868 conn = Connection(Context(TLSv1_METHOD), None)
1869 app_data = object()
1870 conn.set_app_data(app_data)
1871 self.assertIdentical(conn.get_app_data(), app_data)
1872
1873
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001874 def test_makefile(self):
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001875 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001876 :py:obj:`Connection.makefile` is not implemented and calling that method raises
1877 :py:obj:`NotImplementedError`.
Jean-Paul Calderone93dba222010-09-08 22:59:37 -04001878 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04001879 conn = Connection(Context(TLSv1_METHOD), None)
1880 self.assertRaises(NotImplementedError, conn.makefile)
1881
1882
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001883 def test_get_peer_cert_chain_wrong_args(self):
1884 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001885 :py:obj:`Connection.get_peer_cert_chain` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001886 arguments.
1887 """
1888 conn = Connection(Context(TLSv1_METHOD), None)
1889 self.assertRaises(TypeError, conn.get_peer_cert_chain, 1)
1890 self.assertRaises(TypeError, conn.get_peer_cert_chain, "foo")
1891 self.assertRaises(TypeError, conn.get_peer_cert_chain, object())
1892 self.assertRaises(TypeError, conn.get_peer_cert_chain, [])
1893
1894
1895 def test_get_peer_cert_chain(self):
1896 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001897 :py:obj:`Connection.get_peer_cert_chain` returns a list of certificates which
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001898 the connected server returned for the certification verification.
1899 """
1900 chain = _create_certificate_chain()
1901 [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
1902
1903 serverContext = Context(TLSv1_METHOD)
1904 serverContext.use_privatekey(skey)
1905 serverContext.use_certificate(scert)
1906 serverContext.add_extra_chain_cert(icert)
1907 serverContext.add_extra_chain_cert(cacert)
1908 server = Connection(serverContext, None)
1909 server.set_accept_state()
1910
1911 # Create the client
1912 clientContext = Context(TLSv1_METHOD)
1913 clientContext.set_verify(VERIFY_NONE, verify_cb)
1914 client = Connection(clientContext, None)
1915 client.set_connect_state()
1916
1917 self._interactInMemory(client, server)
1918
1919 chain = client.get_peer_cert_chain()
1920 self.assertEqual(len(chain), 3)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001921 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001922 "Server Certificate", chain[0].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001923 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001924 "Intermediate Certificate", chain[1].get_subject().CN)
Jean-Paul Calderonee33300c2011-05-19 21:44:38 -04001925 self.assertEqual(
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001926 "Authority Certificate", chain[2].get_subject().CN)
1927
1928
1929 def test_get_peer_cert_chain_none(self):
1930 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09001931 :py:obj:`Connection.get_peer_cert_chain` returns :py:obj:`None` if the peer sends no
Jean-Paul Calderone24a42432011-05-19 22:21:18 -04001932 certificate chain.
1933 """
1934 ctx = Context(TLSv1_METHOD)
1935 ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
1936 ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
1937 server = Connection(ctx, None)
1938 server.set_accept_state()
1939 client = Connection(Context(TLSv1_METHOD), None)
1940 client.set_connect_state()
1941 self._interactInMemory(client, server)
1942 self.assertIdentical(None, server.get_peer_cert_chain())
Jean-Paul Calderone20222ae2011-05-19 21:43:46 -04001943
1944
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001945 def test_get_session_wrong_args(self):
1946 """
1947 :py:obj:`Connection.get_session` raises :py:obj:`TypeError` if called
1948 with any arguments.
1949 """
1950 ctx = Context(TLSv1_METHOD)
1951 server = Connection(ctx, None)
1952 self.assertRaises(TypeError, server.get_session, 123)
1953 self.assertRaises(TypeError, server.get_session, "hello")
1954 self.assertRaises(TypeError, server.get_session, object())
1955
1956
1957 def test_get_session_unconnected(self):
1958 """
1959 :py:obj:`Connection.get_session` returns :py:obj:`None` when used with
1960 an object which has not been connected.
1961 """
1962 ctx = Context(TLSv1_METHOD)
1963 server = Connection(ctx, None)
1964 session = server.get_session()
1965 self.assertIdentical(None, session)
1966
1967
1968 def test_server_get_session(self):
1969 """
1970 On the server side of a connection, :py:obj:`Connection.get_session`
1971 returns a :py:class:`Session` instance representing the SSL session for
1972 that connection.
1973 """
1974 server, client = self._loopback()
1975 session = server.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001976 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001977
1978
1979 def test_client_get_session(self):
1980 """
1981 On the client side of a connection, :py:obj:`Connection.get_session`
1982 returns a :py:class:`Session` instance representing the SSL session for
1983 that connection.
1984 """
1985 server, client = self._loopback()
1986 session = client.get_session()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001987 self.assertIsInstance(session, Session)
Jean-Paul Calderone64eaffc2012-02-13 11:53:49 -05001988
1989
Jean-Paul Calderonefef5c4b2012-02-14 16:31:52 -05001990 def test_set_session_wrong_args(self):
1991 """
1992 If called with an object that is not an instance of :py:class:`Session`,
1993 or with other than one argument, :py:obj:`Connection.set_session` raises
1994 :py:obj:`TypeError`.
1995 """
1996 ctx = Context(TLSv1_METHOD)
1997 connection = Connection(ctx, None)
1998 self.assertRaises(TypeError, connection.set_session)
1999 self.assertRaises(TypeError, connection.set_session, 123)
2000 self.assertRaises(TypeError, connection.set_session, "hello")
2001 self.assertRaises(TypeError, connection.set_session, object())
2002 self.assertRaises(
2003 TypeError, connection.set_session, Session(), Session())
2004
2005
2006 def test_client_set_session(self):
2007 """
2008 :py:obj:`Connection.set_session`, when used prior to a connection being
2009 established, accepts a :py:class:`Session` instance and causes an
2010 attempt to re-use the session it represents when the SSL handshake is
2011 performed.
2012 """
2013 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2014 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2015 ctx = Context(TLSv1_METHOD)
2016 ctx.use_privatekey(key)
2017 ctx.use_certificate(cert)
2018 ctx.set_session_id("unity-test")
2019
2020 def makeServer(socket):
2021 server = Connection(ctx, socket)
2022 server.set_accept_state()
2023 return server
2024
2025 originalServer, originalClient = self._loopback(
2026 serverFactory=makeServer)
2027 originalSession = originalClient.get_session()
2028
2029 def makeClient(socket):
2030 client = self._loopbackClientFactory(socket)
2031 client.set_session(originalSession)
2032 return client
2033 resumedServer, resumedClient = self._loopback(
2034 serverFactory=makeServer,
2035 clientFactory=makeClient)
2036
2037 # This is a proxy: in general, we have no access to any unique
2038 # identifier for the session (new enough versions of OpenSSL expose a
2039 # hash which could be usable, but "new enough" is very, very new).
2040 # Instead, exploit the fact that the master key is re-used if the
2041 # session is re-used. As long as the master key for the two connections
2042 # is the same, the session was re-used!
2043 self.assertEqual(
2044 originalServer.master_key(), resumedServer.master_key())
2045
2046
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002047 def test_set_session_wrong_method(self):
2048 """
Jean-Paul Calderone068cb592012-02-14 16:52:43 -05002049 If :py:obj:`Connection.set_session` is passed a :py:class:`Session`
2050 instance associated with a context using a different SSL method than the
2051 :py:obj:`Connection` is using, a :py:class:`OpenSSL.SSL.Error` is
2052 raised.
Jean-Paul Calderone5ea41492012-02-14 16:51:35 -05002053 """
2054 key = load_privatekey(FILETYPE_PEM, server_key_pem)
2055 cert = load_certificate(FILETYPE_PEM, server_cert_pem)
2056 ctx = Context(TLSv1_METHOD)
2057 ctx.use_privatekey(key)
2058 ctx.use_certificate(cert)
2059 ctx.set_session_id("unity-test")
2060
2061 def makeServer(socket):
2062 server = Connection(ctx, socket)
2063 server.set_accept_state()
2064 return server
2065
2066 originalServer, originalClient = self._loopback(
2067 serverFactory=makeServer)
2068 originalSession = originalClient.get_session()
2069
2070 def makeClient(socket):
2071 # Intentionally use a different, incompatible method here.
2072 client = Connection(Context(SSLv3_METHOD), socket)
2073 client.set_connect_state()
2074 client.set_session(originalSession)
2075 return client
2076
2077 self.assertRaises(
2078 Error,
2079 self._loopback, clientFactory=makeClient, serverFactory=makeServer)
2080
2081
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002082 def test_wantWriteError(self):
2083 """
2084 :py:obj:`Connection` methods which generate output raise
2085 :py:obj:`OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
2086 fail indicating a should-write state.
2087 """
2088 client_socket, server_socket = socket_pair()
2089 # Fill up the client's send buffer so Connection won't be able to write
Jean-Paul Calderonebbff8b92014-03-22 14:20:30 -04002090 # anything. Only write a single byte at a time so we can be sure we
2091 # completely fill the buffer. Even though the socket API is allowed to
2092 # signal a short write via its return value it seems this doesn't
2093 # always happen on all platforms (FreeBSD and OS X particular) for the
2094 # very last bit of available buffer space.
2095 msg = b"x"
2096 for i in range(1024 * 1024 * 4):
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002097 try:
2098 client_socket.send(msg)
2099 except error as e:
2100 if e.errno == EWOULDBLOCK:
2101 break
2102 raise
2103 else:
2104 self.fail(
2105 "Failed to fill socket buffer, cannot test BIO want write")
2106
2107 ctx = Context(TLSv1_METHOD)
2108 conn = Connection(ctx, client_socket)
2109 # Client's speak first, so make it an SSL client
2110 conn.set_connect_state()
2111 self.assertRaises(WantWriteError, conn.do_handshake)
2112
2113 # XXX want_read
2114
Fedor Brunner416f4a12014-03-28 13:18:38 +01002115 def test_get_finished_before_connect(self):
Fedor Brunner5747b932014-03-05 14:22:34 +01002116 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002117 :py:obj:`Connection.get_finished` returns :py:obj:`None` before TLS
2118 handshake is completed.
Fedor Brunner5747b932014-03-05 14:22:34 +01002119 """
Fedor Brunner5747b932014-03-05 14:22:34 +01002120 ctx = Context(TLSv1_METHOD)
2121 connection = Connection(ctx, None)
2122 self.assertEqual(connection.get_finished(), None)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002123
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002124
Fedor Brunner416f4a12014-03-28 13:18:38 +01002125 def test_get_peer_finished_before_connect(self):
2126 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002127 :py:obj:`Connection.get_peer_finished` returns :py:obj:`None` before
2128 TLS handshake is completed.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002129 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002130 ctx = Context(TLSv1_METHOD)
2131 connection = Connection(ctx, None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002132 self.assertEqual(connection.get_peer_finished(), None)
2133
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002134
Fedor Brunner416f4a12014-03-28 13:18:38 +01002135 def test_get_finished(self):
2136 """
2137 :py:obj:`Connection.get_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002138 message send from client, or server. Finished messages are send during
2139 TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002140 """
2141
Fedor Brunner5747b932014-03-05 14:22:34 +01002142 server, client = self._loopback()
2143
2144 self.assertNotEqual(server.get_finished(), None)
2145 self.assertTrue(len(server.get_finished()) > 0)
Fedor Brunner416f4a12014-03-28 13:18:38 +01002146
Jean-Paul Calderoned979f232014-03-30 11:58:00 -04002147
Fedor Brunner416f4a12014-03-28 13:18:38 +01002148 def test_get_peer_finished(self):
2149 """
2150 :py:obj:`Connection.get_peer_finished` method returns the TLS Finished
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002151 message received from client, or server. Finished messages are send
2152 during TLS handshake.
Fedor Brunner416f4a12014-03-28 13:18:38 +01002153 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002154 server, client = self._loopback()
2155
2156 self.assertNotEqual(server.get_peer_finished(), None)
Fedor Brunner5747b932014-03-05 14:22:34 +01002157 self.assertTrue(len(server.get_peer_finished()) > 0)
2158
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002159
Fedor Brunner416f4a12014-03-28 13:18:38 +01002160 def test_tls_finished_message_symmetry(self):
2161 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002162 The TLS Finished message send by server must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002163 received by client.
2164
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002165 The TLS Finished message send by client must be the TLS Finished message
Fedor Brunner416f4a12014-03-28 13:18:38 +01002166 received by server.
2167 """
Fedor Brunner416f4a12014-03-28 13:18:38 +01002168 server, client = self._loopback()
2169
Fedor Brunner5747b932014-03-05 14:22:34 +01002170 self.assertEqual(server.get_finished(), client.get_peer_finished())
2171 self.assertEqual(client.get_finished(), server.get_peer_finished())
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002172
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002173
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002174 def test_get_cipher_name_before_connect(self):
2175 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002176 :py:obj:`Connection.get_cipher_name` returns :py:obj:`None` if no
2177 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002178 """
2179 ctx = Context(TLSv1_METHOD)
2180 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002181 self.assertIdentical(conn.get_cipher_name(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002182
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002183
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002184 def test_get_cipher_name(self):
2185 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002186 :py:obj:`Connection.get_cipher_name` returns a :py:class:`unicode`
2187 string giving the name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002188 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002189 server, client = self._loopback()
2190 server_cipher_name, client_cipher_name = \
2191 server.get_cipher_name(), client.get_cipher_name()
2192
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002193 self.assertIsInstance(server_cipher_name, text_type)
2194 self.assertIsInstance(client_cipher_name, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002195
2196 self.assertEqual(server_cipher_name, client_cipher_name)
2197
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002198
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002199 def test_get_cipher_version_before_connect(self):
2200 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002201 :py:obj:`Connection.get_cipher_version` returns :py:obj:`None` if no
2202 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002203 """
2204 ctx = Context(TLSv1_METHOD)
2205 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002206 self.assertIdentical(conn.get_cipher_version(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002207
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002208
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002209 def test_get_cipher_version(self):
2210 """
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002211 :py:obj:`Connection.get_cipher_version` returns a :py:class:`unicode`
2212 string giving the protocol name of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002213 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002214 server, client = self._loopback()
2215 server_cipher_version, client_cipher_version = \
2216 server.get_cipher_version(), client.get_cipher_version()
2217
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002218 self.assertIsInstance(server_cipher_version, text_type)
2219 self.assertIsInstance(client_cipher_version, text_type)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002220
2221 self.assertEqual(server_cipher_version, client_cipher_version)
2222
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002223
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002224 def test_get_cipher_bits_before_connect(self):
2225 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002226 :py:obj:`Connection.get_cipher_bits` returns :py:obj:`None` if no
2227 connection has been established.
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002228 """
2229 ctx = Context(TLSv1_METHOD)
2230 conn = Connection(ctx, None)
Jean-Paul Calderone069e2bf2014-03-29 18:21:58 -04002231 self.assertIdentical(conn.get_cipher_bits(), None)
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002232
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002233
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002234 def test_get_cipher_bits(self):
2235 """
Jean-Paul Calderone5b05b482014-03-30 11:28:54 -04002236 :py:obj:`Connection.get_cipher_bits` returns the number of secret bits
2237 of the currently used cipher.
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002238 """
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002239 server, client = self._loopback()
2240 server_cipher_bits, client_cipher_bits = \
2241 server.get_cipher_bits(), client.get_cipher_bits()
2242
Fedor Brunner2cffdbc2014-03-10 10:35:23 +01002243 self.assertIsInstance(server_cipher_bits, int)
2244 self.assertIsInstance(client_cipher_bits, int)
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002245
2246 self.assertEqual(server_cipher_bits, client_cipher_bits)
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002247
Jean-Paul Calderonedbd76272014-03-29 18:09:40 -04002248
2249
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002250class ConnectionGetCipherListTests(TestCase):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002251 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002252 Tests for :py:obj:`Connection.get_cipher_list`.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002253 """
Jean-Paul Calderone54a2bc02010-09-09 17:52:38 -04002254 def test_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002255 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002256 :py:obj:`Connection.get_cipher_list` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002257 arguments.
2258 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002259 connection = Connection(Context(TLSv1_METHOD), None)
2260 self.assertRaises(TypeError, connection.get_cipher_list, None)
2261
2262
2263 def test_result(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002264 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002265 :py:obj:`Connection.get_cipher_list` returns a :py:obj:`list` of
2266 :py:obj:`bytes` giving the names of the ciphers which might be used.
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002267 """
Jean-Paul Calderonef135e622010-07-28 19:14:16 -04002268 connection = Connection(Context(TLSv1_METHOD), None)
2269 ciphers = connection.get_cipher_list()
2270 self.assertTrue(isinstance(ciphers, list))
2271 for cipher in ciphers:
2272 self.assertTrue(isinstance(cipher, str))
2273
2274
2275
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002276class ConnectionSendTests(TestCase, _LoopbackMixin):
2277 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002278 Tests for :py:obj:`Connection.send`
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002279 """
2280 def test_wrong_args(self):
2281 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002282 When called with arguments other than string argument for its first
2283 parameter or more than two arguments, :py:obj:`Connection.send` raises
2284 :py:obj:`TypeError`.
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002285 """
2286 connection = Connection(Context(TLSv1_METHOD), None)
Jean-Paul Calderone77fa2602011-01-05 18:23:39 -05002287 self.assertRaises(TypeError, connection.send)
2288 self.assertRaises(TypeError, connection.send, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002289 self.assertRaises(TypeError, connection.send, "foo", object(), "bar")
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002290
2291
2292 def test_short_bytes(self):
2293 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002294 When passed a short byte string, :py:obj:`Connection.send` transmits all of it
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002295 and returns the number of bytes sent.
2296 """
2297 server, client = self._loopback()
2298 count = server.send(b('xy'))
2299 self.assertEquals(count, 2)
2300 self.assertEquals(client.recv(2), b('xy'))
2301
2302 try:
2303 memoryview
2304 except NameError:
2305 "cannot test sending memoryview without memoryview"
2306 else:
2307 def test_short_memoryview(self):
2308 """
2309 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002310 :py:obj:`Connection.send` transmits all of them and returns the number of
Jean-Paul Calderone9cbbe262011-01-05 14:53:43 -05002311 bytes sent.
2312 """
2313 server, client = self._loopback()
2314 count = server.send(memoryview(b('xy')))
2315 self.assertEquals(count, 2)
2316 self.assertEquals(client.recv(2), b('xy'))
2317
2318
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002319 try:
2320 buffer
2321 except NameError:
2322 "cannot test sending buffer without buffer"
2323 else:
2324 def test_short_buffer(self):
2325 """
2326 When passed a buffer containing a small number of bytes,
2327 :py:obj:`Connection.send` transmits all of them and returns the number of
2328 bytes sent.
2329 """
2330 server, client = self._loopback()
2331 count = server.send(buffer(b('xy')))
2332 self.assertEquals(count, 2)
2333 self.assertEquals(client.recv(2), b('xy'))
2334
2335
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002336
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002337class ConnectionSendallTests(TestCase, _LoopbackMixin):
2338 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002339 Tests for :py:obj:`Connection.sendall`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002340 """
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002341 def test_wrong_args(self):
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002342 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002343 When called with arguments other than a string argument for its first
2344 parameter or with more than two arguments, :py:obj:`Connection.sendall`
2345 raises :py:obj:`TypeError`.
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002346 """
2347 connection = Connection(Context(TLSv1_METHOD), None)
2348 self.assertRaises(TypeError, connection.sendall)
2349 self.assertRaises(TypeError, connection.sendall, object())
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002350 self.assertRaises(
2351 TypeError, connection.sendall, "foo", object(), "bar")
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002352
2353
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002354 def test_short(self):
2355 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002356 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002357 it.
2358 """
2359 server, client = self._loopback()
Jean-Paul Calderonea9868832010-08-22 21:38:34 -04002360 server.sendall(b('x'))
2361 self.assertEquals(client.recv(1), b('x'))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002362
2363
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002364 try:
2365 memoryview
2366 except NameError:
2367 "cannot test sending memoryview without memoryview"
2368 else:
2369 def test_short_memoryview(self):
2370 """
2371 When passed a memoryview onto a small number of bytes,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002372 :py:obj:`Connection.sendall` transmits all of them.
Jean-Paul Calderone691e6c92011-01-21 22:04:35 -05002373 """
2374 server, client = self._loopback()
2375 server.sendall(memoryview(b('x')))
2376 self.assertEquals(client.recv(1), b('x'))
2377
2378
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02002379 try:
2380 buffer
2381 except NameError:
2382 "cannot test sending buffers without buffers"
2383 else:
2384 def test_short_buffers(self):
2385 """
2386 When passed a buffer containing a small number of bytes,
2387 :py:obj:`Connection.sendall` transmits all of them.
2388 """
2389 server, client = self._loopback()
2390 server.sendall(buffer(b('x')))
2391 self.assertEquals(client.recv(1), b('x'))
2392
2393
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002394 def test_long(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002395 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002396 :py:obj:`Connection.sendall` transmits all of the bytes in the string passed to
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002397 it even if this requires multiple calls of an underlying write function.
2398 """
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002399 server, client = self._loopback()
Jean-Paul Calderone6241c702010-09-16 19:59:24 -04002400 # Should be enough, underlying SSL_write should only do 16k at a time.
2401 # On Windows, after 32k of bytes the write will block (forever - because
2402 # no one is yet reading).
Jean-Paul Calderone9e4c1352010-09-19 09:34:43 -04002403 message = b('x') * (1024 * 32 - 1) + b('y')
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002404 server.sendall(message)
2405 accum = []
2406 received = 0
2407 while received < len(message):
Jean-Paul Calderoneb1f7f5f2010-08-22 21:40:52 -04002408 data = client.recv(1024)
2409 accum.append(data)
2410 received += len(data)
Jean-Paul Calderonef4047852010-09-19 09:45:57 -04002411 self.assertEquals(message, b('').join(accum))
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002412
2413
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002414 def test_closed(self):
2415 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002416 If the underlying socket is closed, :py:obj:`Connection.sendall` propagates the
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002417 write error from the low level write call.
2418 """
2419 server, client = self._loopback()
Jean-Paul Calderone05d43e82010-09-24 18:01:36 -04002420 server.sock_shutdown(2)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002421 exc = self.assertRaises(SysCallError, server.sendall, b"hello, world")
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002422 if platform == "win32":
2423 self.assertEqual(exc.args[0], ESHUTDOWN)
2424 else:
2425 self.assertEqual(exc.args[0], EPIPE)
Jean-Paul Calderone974bdc02010-07-28 19:06:10 -04002426
Jean-Paul Calderone7ca48b52010-07-28 18:57:21 -04002427
Jean-Paul Calderone1d69a722010-07-29 09:05:53 -04002428
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002429class ConnectionRenegotiateTests(TestCase, _LoopbackMixin):
2430 """
2431 Tests for SSL renegotiation APIs.
2432 """
2433 def test_renegotiate_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002434 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002435 :py:obj:`Connection.renegotiate` raises :py:obj:`TypeError` if called with any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002436 arguments.
2437 """
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002438 connection = Connection(Context(TLSv1_METHOD), None)
2439 self.assertRaises(TypeError, connection.renegotiate, None)
2440
2441
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002442 def test_total_renegotiations_wrong_args(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002443 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002444 :py:obj:`Connection.total_renegotiations` raises :py:obj:`TypeError` if called with
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002445 any arguments.
2446 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002447 connection = Connection(Context(TLSv1_METHOD), None)
2448 self.assertRaises(TypeError, connection.total_renegotiations, None)
2449
2450
2451 def test_total_renegotiations(self):
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002452 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002453 :py:obj:`Connection.total_renegotiations` returns :py:obj:`0` before any
Jean-Paul Calderonea8fb0c82010-09-09 18:04:56 -04002454 renegotiations have happened.
2455 """
Jean-Paul Calderonecfecc242010-07-29 22:47:06 -04002456 connection = Connection(Context(TLSv1_METHOD), None)
2457 self.assertEquals(connection.total_renegotiations(), 0)
2458
2459
Jean-Paul Calderone8ea22522010-07-29 09:39:39 -04002460# def test_renegotiate(self):
2461# """
2462# """
2463# server, client = self._loopback()
2464
2465# server.send("hello world")
2466# self.assertEquals(client.recv(len("hello world")), "hello world")
2467
2468# self.assertEquals(server.total_renegotiations(), 0)
2469# self.assertTrue(server.renegotiate())
2470
2471# server.setblocking(False)
2472# client.setblocking(False)
2473# while server.renegotiate_pending():
2474# client.do_handshake()
2475# server.do_handshake()
2476
2477# self.assertEquals(server.total_renegotiations(), 1)
2478
2479
2480
2481
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002482class ErrorTests(TestCase):
2483 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002484 Unit tests for :py:obj:`OpenSSL.SSL.Error`.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002485 """
2486 def test_type(self):
2487 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002488 :py:obj:`Error` is an exception type.
Jean-Paul Calderone68649052009-07-17 21:14:27 -04002489 """
2490 self.assertTrue(issubclass(Error, Exception))
Rick Deane15b1472009-07-09 15:53:42 -05002491 self.assertEqual(Error.__name__, 'Error')
Rick Deane15b1472009-07-09 15:53:42 -05002492
2493
2494
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002495class ConstantsTests(TestCase):
2496 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002497 Tests for the values of constants exposed in :py:obj:`OpenSSL.SSL`.
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002498
2499 These are values defined by OpenSSL intended only to be used as flags to
2500 OpenSSL APIs. The only assertions it seems can be made about them is
2501 their values.
2502 """
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002503 # unittest.TestCase has no skip mechanism
2504 if OP_NO_QUERY_MTU is not None:
2505 def test_op_no_query_mtu(self):
2506 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002507 The value of :py:obj:`OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002508 :py:const:`SSL_OP_NO_QUERY_MTU` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002509 """
2510 self.assertEqual(OP_NO_QUERY_MTU, 0x1000)
2511 else:
2512 "OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002513
2514
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002515 if OP_COOKIE_EXCHANGE is not None:
2516 def test_op_cookie_exchange(self):
2517 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002518 The value of :py:obj:`OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the value
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002519 of :py:const:`SSL_OP_COOKIE_EXCHANGE` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002520 """
2521 self.assertEqual(OP_COOKIE_EXCHANGE, 0x2000)
2522 else:
2523 "OP_COOKIE_EXCHANGE unavailable - OpenSSL version may be too old"
Jean-Paul Calderone327d8f92008-12-28 21:55:56 -05002524
2525
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002526 if OP_NO_TICKET is not None:
2527 def test_op_no_ticket(self):
2528 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002529 The value of :py:obj:`OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002530 :py:const:`SSL_OP_NO_TICKET` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002531 """
2532 self.assertEqual(OP_NO_TICKET, 0x4000)
Jean-Paul Calderonecebd1782011-09-11 10:01:31 -04002533 else:
Jean-Paul Calderoned811b682008-12-28 22:59:15 -05002534 "OP_NO_TICKET unavailable - OpenSSL version may be too old"
Rick Dean5b7b6372009-04-01 11:34:06 -05002535
2536
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002537 if OP_NO_COMPRESSION is not None:
2538 def test_op_no_compression(self):
2539 """
Jean-Paul Calderone64efa2c2011-09-11 10:00:09 -04002540 The value of :py:obj:`OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the value
2541 of :py:const:`SSL_OP_NO_COMPRESSION` defined by :file:`openssl/ssl.h`.
Jean-Paul Calderonec62d4c12011-09-08 18:29:32 -04002542 """
2543 self.assertEqual(OP_NO_COMPRESSION, 0x20000)
2544 else:
2545 "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
2546
2547
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002548 def test_sess_cache_off(self):
2549 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002550 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
2551 :py:obj:`SSL_SESS_CACHE_OFF` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002552 """
2553 self.assertEqual(0x0, SESS_CACHE_OFF)
2554
2555
2556 def test_sess_cache_client(self):
2557 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002558 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
2559 :py:obj:`SSL_SESS_CACHE_CLIENT` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002560 """
2561 self.assertEqual(0x1, SESS_CACHE_CLIENT)
2562
2563
2564 def test_sess_cache_server(self):
2565 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002566 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
2567 :py:obj:`SSL_SESS_CACHE_SERVER` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002568 """
2569 self.assertEqual(0x2, SESS_CACHE_SERVER)
2570
2571
2572 def test_sess_cache_both(self):
2573 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002574 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
2575 :py:obj:`SSL_SESS_CACHE_BOTH` defined by ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002576 """
2577 self.assertEqual(0x3, SESS_CACHE_BOTH)
2578
2579
2580 def test_sess_cache_no_auto_clear(self):
2581 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002582 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
2583 value of :py:obj:`SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
2584 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002585 """
2586 self.assertEqual(0x80, SESS_CACHE_NO_AUTO_CLEAR)
2587
2588
2589 def test_sess_cache_no_internal_lookup(self):
2590 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002591 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
2592 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
2593 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002594 """
2595 self.assertEqual(0x100, SESS_CACHE_NO_INTERNAL_LOOKUP)
2596
2597
2598 def test_sess_cache_no_internal_store(self):
2599 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002600 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
2601 the value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
2602 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002603 """
2604 self.assertEqual(0x200, SESS_CACHE_NO_INTERNAL_STORE)
2605
2606
2607 def test_sess_cache_no_internal(self):
2608 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05002609 The value of :py:obj:`OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
2610 value of :py:obj:`SSL_SESS_CACHE_NO_INTERNAL` defined by
2611 ``openssl/ssl.h``.
Jean-Paul Calderone313bf012012-02-08 13:02:49 -05002612 """
2613 self.assertEqual(0x300, SESS_CACHE_NO_INTERNAL)
2614
2615
Jean-Paul Calderoneeeee26a2009-04-27 11:24:30 -04002616
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002617class MemoryBIOTests(TestCase, _LoopbackMixin):
Rick Deanb71c0d22009-04-01 14:09:23 -05002618 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002619 Tests for :py:obj:`OpenSSL.SSL.Connection` using a memory BIO.
Rick Deanb71c0d22009-04-01 14:09:23 -05002620 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002621 def _server(self, sock):
2622 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002623 Create a new server-side SSL :py:obj:`Connection` object wrapped around
2624 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002625 """
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002626 # Create the server side Connection. This is mostly setup boilerplate
2627 # - use TLSv1, use a particular certificate, etc.
2628 server_ctx = Context(TLSv1_METHOD)
2629 server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2630 server_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2631 server_store = server_ctx.get_cert_store()
2632 server_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
2633 server_ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
2634 server_ctx.check_privatekey()
2635 server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002636 # Here the Connection is actually created. If None is passed as the 2nd
2637 # parameter, it indicates a memory BIO should be created.
2638 server_conn = Connection(server_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002639 server_conn.set_accept_state()
2640 return server_conn
2641
2642
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002643 def _client(self, sock):
2644 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002645 Create a new client-side SSL :py:obj:`Connection` object wrapped around
2646 :py:obj:`sock`.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002647 """
2648 # Now create the client side Connection. Similar boilerplate to the
2649 # above.
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002650 client_ctx = Context(TLSv1_METHOD)
2651 client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE )
2652 client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb)
2653 client_store = client_ctx.get_cert_store()
2654 client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem))
2655 client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem))
2656 client_ctx.check_privatekey()
2657 client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
Rick Deanb1ccd562009-07-09 23:52:39 -05002658 client_conn = Connection(client_ctx, sock)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002659 client_conn.set_connect_state()
2660 return client_conn
2661
2662
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002663 def test_memoryConnect(self):
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002664 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002665 Two :py:obj:`Connection`s which use memory BIOs can be manually connected by
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002666 reading from the output of each and writing those bytes to the input of
2667 the other and in this way establish a connection and exchange
2668 application-level bytes with each other.
2669 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002670 server_conn = self._server(None)
2671 client_conn = self._client(None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002672
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002673 # There should be no key or nonces yet.
2674 self.assertIdentical(server_conn.master_key(), None)
2675 self.assertIdentical(server_conn.client_random(), None)
2676 self.assertIdentical(server_conn.server_random(), None)
Rick Deanb71c0d22009-04-01 14:09:23 -05002677
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002678 # First, the handshake needs to happen. We'll deliver bytes back and
2679 # forth between the client and server until neither of them feels like
2680 # speaking any more.
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002681 self.assertIdentical(
2682 self._interactInMemory(client_conn, server_conn), None)
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002683
2684 # Now that the handshake is done, there should be a key and nonces.
2685 self.assertNotIdentical(server_conn.master_key(), None)
2686 self.assertNotIdentical(server_conn.client_random(), None)
2687 self.assertNotIdentical(server_conn.server_random(), None)
Jean-Paul Calderone6c051e62009-07-05 13:50:34 -04002688 self.assertEquals(server_conn.client_random(), client_conn.client_random())
2689 self.assertEquals(server_conn.server_random(), client_conn.server_random())
2690 self.assertNotEquals(server_conn.client_random(), server_conn.server_random())
2691 self.assertNotEquals(client_conn.client_random(), client_conn.server_random())
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002692
2693 # Here are the bytes we'll try to send.
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002694 important_message = b('One if by land, two if by sea.')
Rick Deanb71c0d22009-04-01 14:09:23 -05002695
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002696 server_conn.write(important_message)
2697 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002698 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002699 (client_conn, important_message))
2700
2701 client_conn.write(important_message[::-1])
2702 self.assertEquals(
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002703 self._interactInMemory(client_conn, server_conn),
Jean-Paul Calderone958299e2009-04-27 12:59:12 -04002704 (server_conn, important_message[::-1]))
Rick Deanb71c0d22009-04-01 14:09:23 -05002705
2706
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002707 def test_socketConnect(self):
Rick Deanb1ccd562009-07-09 23:52:39 -05002708 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002709 Just like :py:obj:`test_memoryConnect` but with an actual socket.
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002710
2711 This is primarily to rule out the memory BIO code as the source of
Jonathan Ballet648875f2011-07-16 14:14:58 +09002712 any problems encountered while passing data over a :py:obj:`Connection` (if
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002713 this test fails, there must be a problem outside the memory BIO
2714 code, as no memory BIO is involved here). Even though this isn't a
2715 memory BIO test, it's convenient to have it here.
Rick Deanb1ccd562009-07-09 23:52:39 -05002716 """
Jean-Paul Calderone06c7cc92010-09-24 23:52:00 -04002717 server_conn, client_conn = self._loopback()
Rick Deanb1ccd562009-07-09 23:52:39 -05002718
Jean-Paul Calderonea441fdc2010-08-22 21:33:57 -04002719 important_message = b("Help me Obi Wan Kenobi, you're my only hope.")
Rick Deanb1ccd562009-07-09 23:52:39 -05002720 client_conn.send(important_message)
2721 msg = server_conn.recv(1024)
2722 self.assertEqual(msg, important_message)
2723
2724 # Again in the other direction, just for fun.
2725 important_message = important_message[::-1]
2726 server_conn.send(important_message)
2727 msg = client_conn.recv(1024)
2728 self.assertEqual(msg, important_message)
2729
2730
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04002731 def test_socketOverridesMemory(self):
Rick Deanb71c0d22009-04-01 14:09:23 -05002732 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002733 Test that :py:obj:`OpenSSL.SSL.bio_read` and :py:obj:`OpenSSL.SSL.bio_write` don't
2734 work on :py:obj:`OpenSSL.SSL.Connection`() that use sockets.
Rick Deanb71c0d22009-04-01 14:09:23 -05002735 """
2736 context = Context(SSLv3_METHOD)
2737 client = socket()
2738 clientSSL = Connection(context, client)
2739 self.assertRaises( TypeError, clientSSL.bio_read, 100)
2740 self.assertRaises( TypeError, clientSSL.bio_write, "foo")
Jean-Paul Calderone07acf3f2009-05-05 13:23:28 -04002741 self.assertRaises( TypeError, clientSSL.bio_shutdown )
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002742
2743
2744 def test_outgoingOverflow(self):
2745 """
2746 If more bytes than can be written to the memory BIO are passed to
Jonathan Ballet648875f2011-07-16 14:14:58 +09002747 :py:obj:`Connection.send` at once, the number of bytes which were written is
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002748 returned and that many bytes from the beginning of the input can be
2749 read from the other end of the connection.
2750 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002751 server = self._server(None)
2752 client = self._client(None)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002753
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002754 self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002755
2756 size = 2 ** 15
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002757 sent = client.send(b"x" * size)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002758 # Sanity check. We're trying to test what happens when the entire
2759 # input can't be sent. If the entire input was sent, this test is
2760 # meaningless.
2761 self.assertTrue(sent < size)
2762
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002763 receiver, received = self._interactInMemory(client, server)
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -04002764 self.assertIdentical(receiver, server)
2765
2766 # We can rely on all of these bytes being received at once because
2767 # _loopback passes 2 ** 16 to recv - more than 2 ** 15.
2768 self.assertEquals(len(received), sent)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002769
2770
2771 def test_shutdown(self):
2772 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002773 :py:obj:`Connection.bio_shutdown` signals the end of the data stream from
2774 which the :py:obj:`Connection` reads.
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002775 """
Jean-Paul Calderonece8324d2009-07-16 12:22:52 -04002776 server = self._server(None)
Jean-Paul Calderone3ad85d42009-04-30 20:24:35 -04002777 server.bio_shutdown()
2778 e = self.assertRaises(Error, server.recv, 1024)
2779 # We don't want WantReadError or ZeroReturnError or anything - it's a
2780 # handshake failure.
2781 self.assertEquals(e.__class__, Error)
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04002782
2783
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07002784 def test_unexpectedEndOfFile(self):
2785 """
2786 If the connection is lost before an orderly SSL shutdown occurs,
2787 :py:obj:`OpenSSL.SSL.SysCallError` is raised with a message of
2788 "Unexpected EOF".
2789 """
2790 server_conn, client_conn = self._loopback()
2791 client_conn.sock_shutdown(SHUT_RDWR)
2792 exc = self.assertRaises(SysCallError, server_conn.recv, 1024)
2793 self.assertEqual(exc.args, (-1, "Unexpected EOF"))
2794
2795
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002796 def _check_client_ca_list(self, func):
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002797 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002798 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 -04002799
Jonathan Ballet78b92a22011-07-16 08:07:26 +09002800 :param func: A function which will be called with the server context
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002801 before the client and server are connected to each other. This
2802 function should specify a list of CAs for the server to send to the
2803 client and return that same list. The list will be used to verify
Jonathan Ballet648875f2011-07-16 14:14:58 +09002804 that :py:obj:`get_client_ca_list` returns the proper value at various
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002805 times.
2806 """
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002807 server = self._server(None)
2808 client = self._client(None)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002809 self.assertEqual(client.get_client_ca_list(), [])
2810 self.assertEqual(server.get_client_ca_list(), [])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002811 ctx = server.get_context()
2812 expected = func(ctx)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002813 self.assertEqual(client.get_client_ca_list(), [])
2814 self.assertEqual(server.get_client_ca_list(), expected)
Jean-Paul Calderonebf37f0f2010-07-31 14:56:20 -04002815 self._interactInMemory(client, server)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002816 self.assertEqual(client.get_client_ca_list(), expected)
2817 self.assertEqual(server.get_client_ca_list(), expected)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002818
2819
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002820 def test_set_client_ca_list_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002821 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002822 :py:obj:`Context.set_client_ca_list` raises a :py:obj:`TypeError` if called with a
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002823 non-list or a list that contains objects other than X509Names.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002824 """
2825 ctx = Context(TLSv1_METHOD)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002826 self.assertRaises(TypeError, ctx.set_client_ca_list, "spam")
2827 self.assertRaises(TypeError, ctx.set_client_ca_list, ["spam"])
2828 self.assertIdentical(ctx.set_client_ca_list([]), None)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002829
2830
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002831 def test_set_empty_ca_list(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002832 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002833 If passed an empty list, :py:obj:`Context.set_client_ca_list` configures the
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002834 context to send no CA names to the client and, on both the server and
Jonathan Ballet648875f2011-07-16 14:14:58 +09002835 client sides, :py:obj:`Connection.get_client_ca_list` returns an empty list
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002836 after the connection is set up.
2837 """
2838 def no_ca(ctx):
2839 ctx.set_client_ca_list([])
2840 return []
2841 self._check_client_ca_list(no_ca)
2842
2843
2844 def test_set_one_ca_list(self):
2845 """
2846 If passed a list containing a single X509Name,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002847 :py:obj:`Context.set_client_ca_list` configures the context to send that CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002848 name to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002849 :py:obj:`Connection.get_client_ca_list` returns a list containing that
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002850 X509Name after the connection is set up.
2851 """
2852 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2853 cadesc = cacert.get_subject()
2854 def single_ca(ctx):
2855 ctx.set_client_ca_list([cadesc])
2856 return [cadesc]
2857 self._check_client_ca_list(single_ca)
2858
2859
2860 def test_set_multiple_ca_list(self):
2861 """
2862 If passed a list containing multiple X509Name objects,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002863 :py:obj:`Context.set_client_ca_list` configures the context to send those CA
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002864 names to the client and, on both the server and client sides,
Jonathan Ballet648875f2011-07-16 14:14:58 +09002865 :py:obj:`Connection.get_client_ca_list` returns a list containing those
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002866 X509Names after the connection is set up.
2867 """
2868 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2869 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2870
2871 sedesc = secert.get_subject()
2872 cldesc = clcert.get_subject()
2873
2874 def multiple_ca(ctx):
2875 L = [sedesc, cldesc]
2876 ctx.set_client_ca_list(L)
2877 return L
2878 self._check_client_ca_list(multiple_ca)
2879
2880
2881 def test_reset_ca_list(self):
2882 """
2883 If called multiple times, only the X509Names passed to the final call
Jonathan Ballet648875f2011-07-16 14:14:58 +09002884 of :py:obj:`Context.set_client_ca_list` are used to configure the CA names
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002885 sent to the client.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002886 """
2887 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2888 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2889 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2890
2891 cadesc = cacert.get_subject()
2892 sedesc = secert.get_subject()
2893 cldesc = clcert.get_subject()
2894
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002895 def changed_ca(ctx):
2896 ctx.set_client_ca_list([sedesc, cldesc])
2897 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002898 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002899 self._check_client_ca_list(changed_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002900
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002901
2902 def test_mutated_ca_list(self):
2903 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002904 If the list passed to :py:obj:`Context.set_client_ca_list` is mutated
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002905 afterwards, this does not affect the list of CA names sent to the
2906 client.
2907 """
2908 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2909 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2910
2911 cadesc = cacert.get_subject()
2912 sedesc = secert.get_subject()
2913
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002914 def mutated_ca(ctx):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002915 L = [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002916 ctx.set_client_ca_list([cadesc])
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002917 L.append(sedesc)
2918 return [cadesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002919 self._check_client_ca_list(mutated_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002920
2921
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002922 def test_add_client_ca_errors(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002923 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002924 :py:obj:`Context.add_client_ca` raises :py:obj:`TypeError` if called with a non-X509
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002925 object or with a number of arguments other than one.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002926 """
2927 ctx = Context(TLSv1_METHOD)
2928 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002929 self.assertRaises(TypeError, ctx.add_client_ca)
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002930 self.assertRaises(TypeError, ctx.add_client_ca, "spam")
Jean-Paul Calderone911c9112009-10-24 11:12:00 -04002931 self.assertRaises(TypeError, ctx.add_client_ca, cacert, cacert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002932
2933
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002934 def test_one_add_client_ca(self):
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002935 """
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002936 A certificate's subject can be added as a CA to be sent to the client
Jonathan Ballet648875f2011-07-16 14:14:58 +09002937 with :py:obj:`Context.add_client_ca`.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002938 """
2939 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2940 cadesc = cacert.get_subject()
2941 def single_ca(ctx):
2942 ctx.add_client_ca(cacert)
2943 return [cadesc]
2944 self._check_client_ca_list(single_ca)
2945
2946
2947 def test_multiple_add_client_ca(self):
2948 """
2949 Multiple CA names can be sent to the client by calling
Jonathan Ballet648875f2011-07-16 14:14:58 +09002950 :py:obj:`Context.add_client_ca` with multiple X509 objects.
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002951 """
2952 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2953 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2954
2955 cadesc = cacert.get_subject()
2956 sedesc = secert.get_subject()
2957
2958 def multiple_ca(ctx):
2959 ctx.add_client_ca(cacert)
2960 ctx.add_client_ca(secert)
2961 return [cadesc, sedesc]
2962 self._check_client_ca_list(multiple_ca)
2963
2964
2965 def test_set_and_add_client_ca(self):
2966 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002967 A call to :py:obj:`Context.set_client_ca_list` followed by a call to
2968 :py:obj:`Context.add_client_ca` results in using the CA names from the first
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002969 call and the CA name from the second call.
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002970 """
2971 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2972 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2973 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2974
2975 cadesc = cacert.get_subject()
2976 sedesc = secert.get_subject()
2977 cldesc = clcert.get_subject()
2978
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002979 def mixed_set_add_ca(ctx):
2980 ctx.set_client_ca_list([cadesc, sedesc])
2981 ctx.add_client_ca(clcert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002982 return [cadesc, sedesc, cldesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002983 self._check_client_ca_list(mixed_set_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02002984
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002985
2986 def test_set_after_add_client_ca(self):
2987 """
Jonathan Ballet648875f2011-07-16 14:14:58 +09002988 A call to :py:obj:`Context.set_client_ca_list` after a call to
2989 :py:obj:`Context.add_client_ca` replaces the CA name specified by the former
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002990 call with the names specified by the latter cal.
2991 """
2992 cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
2993 secert = load_certificate(FILETYPE_PEM, server_cert_pem)
2994 clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
2995
2996 cadesc = cacert.get_subject()
2997 sedesc = secert.get_subject()
Jean-Paul Calderone055a9172009-10-24 13:45:11 -04002998
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02002999 def set_replaces_add_ca(ctx):
3000 ctx.add_client_ca(clcert)
3001 ctx.set_client_ca_list([cadesc])
3002 ctx.add_client_ca(secert)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003003 return [cadesc, sedesc]
Ziga Seilnachtf93bf102009-10-23 09:51:07 +02003004 self._check_client_ca_list(set_replaces_add_ca)
Ziga Seilnacht679c4262009-09-01 01:32:29 +02003005
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003006
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003007
3008class ConnectionBIOTests(TestCase):
3009 """
3010 Tests for :py:obj:`Connection.bio_read` and :py:obj:`Connection.bio_write`.
3011 """
3012 def test_wantReadError(self):
3013 """
3014 :py:obj:`Connection.bio_read` raises :py:obj:`OpenSSL.SSL.WantReadError`
3015 if there are no bytes available to be read from the BIO.
3016 """
3017 ctx = Context(TLSv1_METHOD)
3018 conn = Connection(ctx, None)
3019 self.assertRaises(WantReadError, conn.bio_read, 1024)
3020
3021
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05003022 def test_buffer_size(self):
3023 """
3024 :py:obj:`Connection.bio_read` accepts an integer giving the maximum
3025 number of bytes to read and return.
3026 """
3027 ctx = Context(TLSv1_METHOD)
3028 conn = Connection(ctx, None)
3029 conn.set_connect_state()
3030 try:
3031 conn.do_handshake()
3032 except WantReadError:
3033 pass
3034 data = conn.bio_read(2)
3035 self.assertEqual(2, len(data))
3036
3037
3038 if not PY3:
3039 def test_buffer_size_long(self):
3040 """
3041 On Python 2 :py:obj:`Connection.bio_read` accepts values of type
3042 :py:obj:`long` as well as :py:obj:`int`.
3043 """
3044 ctx = Context(TLSv1_METHOD)
3045 conn = Connection(ctx, None)
3046 conn.set_connect_state()
3047 try:
3048 conn.do_handshake()
3049 except WantReadError:
3050 pass
3051 data = conn.bio_read(long(2))
3052 self.assertEqual(2, len(data))
3053
3054
3055
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07003056
Jean-Paul Calderone31e85a82011-03-21 19:13:35 -04003057class InfoConstantTests(TestCase):
3058 """
3059 Tests for assorted constants exposed for use in info callbacks.
3060 """
3061 def test_integers(self):
3062 """
3063 All of the info constants are integers.
3064
3065 This is a very weak test. It would be nice to have one that actually
3066 verifies that as certain info events happen, the value passed to the
3067 info callback matches up with the constant exposed by OpenSSL.SSL.
3068 """
3069 for const in [
3070 SSL_ST_CONNECT, SSL_ST_ACCEPT, SSL_ST_MASK, SSL_ST_INIT,
3071 SSL_ST_BEFORE, SSL_ST_OK, SSL_ST_RENEGOTIATE,
3072 SSL_CB_LOOP, SSL_CB_EXIT, SSL_CB_READ, SSL_CB_WRITE, SSL_CB_ALERT,
3073 SSL_CB_READ_ALERT, SSL_CB_WRITE_ALERT, SSL_CB_ACCEPT_LOOP,
3074 SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP, SSL_CB_CONNECT_EXIT,
3075 SSL_CB_HANDSHAKE_START, SSL_CB_HANDSHAKE_DONE]:
3076
3077 self.assertTrue(isinstance(const, int))
3078
Ziga Seilnacht44611bf2009-08-31 20:49:30 +02003079
Jean-Paul Calderone0b88b6a2009-07-05 12:44:41 -04003080if __name__ == '__main__':
3081 main()