blob: 85d6e76905ad9859eed7607da6b62a0a36984a9d [file] [log] [blame]
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05003from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01004from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08005from weakref import WeakValueDictionary
6from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08007
Alex Gaynor10d30832017-06-29 15:31:39 -07008from cryptography.utils import deprecated
9
Cory Benfield63759dc2015-04-12 08:57:03 -040010from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -080011from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010012from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050013
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010015 UNSPECIFIED as _UNSPECIFIED,
16 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 ffi as _ffi,
18 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010019 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040021 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010022 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000023 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040024)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080025
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080026from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050027 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080028
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050029try:
30 _memoryview = memoryview
31except NameError:
32 class _memoryview(object):
33 pass
34
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020035try:
36 _buffer = buffer
37except NameError:
38 class _buffer(object):
39 pass
40
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050041OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
42SSLEAY_VERSION = _lib.SSLEAY_VERSION
43SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
44SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
45SSLEAY_DIR = _lib.SSLEAY_DIR
46SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080047
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050048SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
49RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080050
51SSLv2_METHOD = 1
52SSLv3_METHOD = 2
53SSLv23_METHOD = 3
54TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050055TLSv1_1_METHOD = 5
56TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080057
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050058OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
59OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
60OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050061
62OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
63OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080064
Alex Gaynorbf012872016-06-04 13:18:39 -070065MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090068OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050069OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
70OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
71OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040072OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
73 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
74)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
76OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040077OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050078OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
79OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
80OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
81OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
82OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
83OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
84OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
85OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
86OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040087OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
88 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
89)
Alex Gaynorbf012872016-06-04 13:18:39 -070090OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080091
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050092OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
93OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040094OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080095
Alex Gaynorc4889812015-09-04 08:43:17 -040096OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098VERIFY_PEER = _lib.SSL_VERIFY_PEER
99VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
100VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
101VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500103SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
104SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
105SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
106SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
107SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
108SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
109SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
110SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500112SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
113SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
114SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400115if _lib.Cryptography_HAS_SSL_ST:
116 SSL_ST_INIT = _lib.SSL_ST_INIT
117 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
118 SSL_ST_OK = _lib.SSL_ST_OK
119 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121SSL_CB_LOOP = _lib.SSL_CB_LOOP
122SSL_CB_EXIT = _lib.SSL_CB_EXIT
123SSL_CB_READ = _lib.SSL_CB_READ
124SSL_CB_WRITE = _lib.SSL_CB_WRITE
125SSL_CB_ALERT = _lib.SSL_CB_ALERT
126SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
127SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
128SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
129SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
130SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
131SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
132SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
133SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800134
Alex Gaynor83284952015-09-05 10:43:30 -0400135
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500136class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500137 """
138 An error occurred in an `OpenSSL.SSL` API.
139 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500140
141
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500142_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100143_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500144
145
146class WantReadError(Error):
147 pass
148
149
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500150class WantWriteError(Error):
151 pass
152
153
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500154class WantX509LookupError(Error):
155 pass
156
157
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158class ZeroReturnError(Error):
159 pass
160
161
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500162class SysCallError(Error):
163 pass
164
165
Cory Benfield0ea76e72015-03-22 09:05:28 +0000166class _CallbackExceptionHelper(object):
167 """
168 A base class for wrapper classes that allow for intelligent exception
169 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500170
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400171 :ivar list _problems: Any exceptions that occurred while executing in a
172 context where they could not be raised in the normal way. Typically
173 this is because OpenSSL has called into some Python code and requires a
174 return value. The exceptions are saved to be raised later when it is
175 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000176 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400177
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400178 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800179 self._problems = []
180
Cory Benfield0ea76e72015-03-22 09:05:28 +0000181 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400182 """
183 Raise an exception from the OpenSSL error queue or that was previously
184 captured whe running a callback.
185 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000186 if self._problems:
187 try:
188 _raise_current_error()
189 except Error:
190 pass
191 raise self._problems.pop(0)
192
193
194class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400195 """
196 Wrap a callback such that it can be used as a certificate verification
197 callback.
198 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400199
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800200 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400201 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800202
203 @wraps(callback)
204 def wrapper(ok, store_ctx):
205 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500206 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
207 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
208 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800209
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400210 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
211 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
212 connection = Connection._reverse_mapping[ssl]
213
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800214 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400215 result = callback(
216 connection, cert, error_number, error_depth, ok
217 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800218 except Exception as e:
219 self._problems.append(e)
220 return 0
221 else:
222 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500223 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800224 return 1
225 else:
226 return 0
227
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500228 self.callback = _ffi.callback(
229 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800230
231
Cory Benfield0ea76e72015-03-22 09:05:28 +0000232class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400233 """
234 Wrap a callback such that it can be used as an NPN advertisement callback.
235 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400236
Cory Benfield0ea76e72015-03-22 09:05:28 +0000237 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400238 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800239
Cory Benfield0ea76e72015-03-22 09:05:28 +0000240 @wraps(callback)
241 def wrapper(ssl, out, outlen, arg):
242 try:
243 conn = Connection._reverse_mapping[ssl]
244 protos = callback(conn)
245
246 # Join the protocols into a Python bytestring, length-prefixing
247 # each element.
248 protostr = b''.join(
249 chain.from_iterable((int2byte(len(p)), p) for p in protos)
250 )
251
252 # Save our callback arguments on the connection object. This is
253 # done to make sure that they don't get freed before OpenSSL
254 # uses them. Then, return them appropriately in the output
255 # parameters.
256 conn._npn_advertise_callback_args = [
257 _ffi.new("unsigned int *", len(protostr)),
258 _ffi.new("unsigned char[]", protostr),
259 ]
260 outlen[0] = conn._npn_advertise_callback_args[0][0]
261 out[0] = conn._npn_advertise_callback_args[1]
262 return 0
263 except Exception as e:
264 self._problems.append(e)
265 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
266
267 self.callback = _ffi.callback(
268 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
269 wrapper
270 )
271
272
273class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400274 """
275 Wrap a callback such that it can be used as an NPN selection callback.
276 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400277
Cory Benfield0ea76e72015-03-22 09:05:28 +0000278 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400279 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000280
281 @wraps(callback)
282 def wrapper(ssl, out, outlen, in_, inlen, arg):
283 try:
284 conn = Connection._reverse_mapping[ssl]
285
286 # The string passed to us is actually made up of multiple
287 # length-prefixed bytestrings. We need to split that into a
288 # list.
289 instr = _ffi.buffer(in_, inlen)[:]
290 protolist = []
291 while instr:
292 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400293 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000294 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400295 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000296
297 # Call the callback
298 outstr = callback(conn, protolist)
299
300 # Save our callback arguments on the connection object. This is
301 # done to make sure that they don't get freed before OpenSSL
302 # uses them. Then, return them appropriately in the output
303 # parameters.
304 conn._npn_select_callback_args = [
305 _ffi.new("unsigned char *", len(outstr)),
306 _ffi.new("unsigned char[]", outstr),
307 ]
308 outlen[0] = conn._npn_select_callback_args[0][0]
309 out[0] = conn._npn_select_callback_args[1]
310 return 0
311 except Exception as e:
312 self._problems.append(e)
313 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
314
315 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400316 ("int (*)(SSL *, unsigned char **, unsigned char *, "
317 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000318 wrapper
319 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800320
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800321
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400322class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400323 """
324 Wrap a callback such that it can be used as an ALPN selection callback.
325 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400326
Cory Benfieldf1177e72015-04-12 09:11:49 -0400327 def __init__(self, callback):
328 _CallbackExceptionHelper.__init__(self)
329
330 @wraps(callback)
331 def wrapper(ssl, out, outlen, in_, inlen, arg):
332 try:
333 conn = Connection._reverse_mapping[ssl]
334
335 # The string passed to us is made up of multiple
336 # length-prefixed bytestrings. We need to split that into a
337 # list.
338 instr = _ffi.buffer(in_, inlen)[:]
339 protolist = []
340 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400341 encoded_len = indexbytes(instr, 0)
342 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400343 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400344 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400345
346 # Call the callback
347 outstr = callback(conn, protolist)
348
349 if not isinstance(outstr, _binary_type):
350 raise TypeError("ALPN callback must return a bytestring.")
351
352 # Save our callback arguments on the connection object to make
353 # sure that they don't get freed before OpenSSL can use them.
354 # Then, return them in the appropriate output parameters.
355 conn._alpn_select_callback_args = [
356 _ffi.new("unsigned char *", len(outstr)),
357 _ffi.new("unsigned char[]", outstr),
358 ]
359 outlen[0] = conn._alpn_select_callback_args[0][0]
360 out[0] = conn._alpn_select_callback_args[1]
361 return 0
362 except Exception as e:
363 self._problems.append(e)
364 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
365
366 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400367 ("int (*)(SSL *, unsigned char **, unsigned char *, "
368 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400369 wrapper
370 )
371
372
Cory Benfield496652a2017-01-24 11:42:56 +0000373class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
374 """
375 Wrap a callback such that it can be used as an OCSP callback for the server
376 side.
377
378 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
379 ways. For servers, that callback is expected to retrieve some OCSP data and
380 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
381 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
382 is expected to check the OCSP data, and returns a negative value on error,
383 0 if the response is not acceptable, or positive if it is. These are
384 mutually exclusive return code behaviours, and they mean that we need two
385 helpers so that we always return an appropriate error code if the user's
386 code throws an exception.
387
388 Given that we have to have two helpers anyway, these helpers are a bit more
389 helpery than most: specifically, they hide a few more of the OpenSSL
390 functions so that the user has an easier time writing these callbacks.
391
392 This helper implements the server side.
393 """
394
395 def __init__(self, callback):
396 _CallbackExceptionHelper.__init__(self)
397
398 @wraps(callback)
399 def wrapper(ssl, cdata):
400 try:
401 conn = Connection._reverse_mapping[ssl]
402
403 # Extract the data if any was provided.
404 if cdata != _ffi.NULL:
405 data = _ffi.from_handle(cdata)
406 else:
407 data = None
408
409 # Call the callback.
410 ocsp_data = callback(conn, data)
411
412 if not isinstance(ocsp_data, _binary_type):
413 raise TypeError("OCSP callback must return a bytestring.")
414
415 # If the OCSP data was provided, we will pass it to OpenSSL.
416 # However, we have an early exit here: if no OCSP data was
417 # provided we will just exit out and tell OpenSSL that there
418 # is nothing to do.
419 if not ocsp_data:
420 return 3 # SSL_TLSEXT_ERR_NOACK
421
422 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
423 # private copy of this data, so we need to keep it alive, but
424 # it *does* want to free it itself if it gets replaced. This
425 # somewhat bonkers behaviour means we need to use
426 # OPENSSL_malloc directly, which is a pain in the butt to work
427 # with. It's ok for us to "leak" the memory here because
428 # OpenSSL now owns it and will free it.
429 ocsp_data_length = len(ocsp_data)
430 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
431 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
432
433 _lib.SSL_set_tlsext_status_ocsp_resp(
434 ssl, data_ptr, ocsp_data_length
435 )
436
437 return 0
438 except Exception as e:
439 self._problems.append(e)
440 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
441
442 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
443
444
445class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
446 """
447 Wrap a callback such that it can be used as an OCSP callback for the client
448 side.
449
450 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
451 ways. For servers, that callback is expected to retrieve some OCSP data and
452 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
453 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
454 is expected to check the OCSP data, and returns a negative value on error,
455 0 if the response is not acceptable, or positive if it is. These are
456 mutually exclusive return code behaviours, and they mean that we need two
457 helpers so that we always return an appropriate error code if the user's
458 code throws an exception.
459
460 Given that we have to have two helpers anyway, these helpers are a bit more
461 helpery than most: specifically, they hide a few more of the OpenSSL
462 functions so that the user has an easier time writing these callbacks.
463
464 This helper implements the client side.
465 """
466
467 def __init__(self, callback):
468 _CallbackExceptionHelper.__init__(self)
469
470 @wraps(callback)
471 def wrapper(ssl, cdata):
472 try:
473 conn = Connection._reverse_mapping[ssl]
474
475 # Extract the data if any was provided.
476 if cdata != _ffi.NULL:
477 data = _ffi.from_handle(cdata)
478 else:
479 data = None
480
481 # Get the OCSP data.
482 ocsp_ptr = _ffi.new("unsigned char **")
483 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
484 if ocsp_len < 0:
485 # No OCSP data.
486 ocsp_data = b''
487 else:
488 # Copy the OCSP data, then pass it to the callback.
489 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
490
491 valid = callback(conn, ocsp_data, data)
492
493 # Return 1 on success or 0 on error.
494 return int(bool(valid))
495
496 except Exception as e:
497 self._problems.append(e)
498 # Return negative value if an exception is hit.
499 return -1
500
501 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
502
503
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800504def _asFileDescriptor(obj):
505 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800506 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800507 meth = getattr(obj, "fileno", None)
508 if meth is not None:
509 obj = meth()
510
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800511 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800512 fd = obj
513
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800514 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800515 raise TypeError("argument must be an int, or have a fileno() method.")
516 elif fd < 0:
517 raise ValueError(
518 "file descriptor cannot be a negative integer (%i)" % (fd,))
519
520 return fd
521
522
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800523def SSLeay_version(type):
524 """
525 Return a string describing the version of OpenSSL in use.
526
527 :param type: One of the SSLEAY_ constants defined in this module.
528 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500529 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800530
531
Cory Benfieldef404df2016-03-29 15:32:48 +0100532def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400533 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100534 Builds a decorator that ensures that functions that rely on OpenSSL
535 functions that are not present in this build raise NotImplementedError,
536 rather than AttributeError coming out of cryptography.
537
538 :param flag: A cryptography flag that guards the functions, e.g.
539 ``Cryptography_HAS_NEXTPROTONEG``.
540 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400541 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100542 def _requires_decorator(func):
543 if not flag:
544 @wraps(func)
545 def explode(*args, **kwargs):
546 raise NotImplementedError(error)
547 return explode
548 else:
549 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400550
Cory Benfieldef404df2016-03-29 15:32:48 +0100551 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400552
553
Cory Benfieldef404df2016-03-29 15:32:48 +0100554_requires_npn = _make_requires(
555 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
556)
Cory Benfield7907e332015-04-13 17:18:25 -0400557
558
Cory Benfieldef404df2016-03-29 15:32:48 +0100559_requires_alpn = _make_requires(
560 _lib.Cryptography_HAS_ALPN, "ALPN not available"
561)
Cory Benfielde6f35882016-03-29 11:21:04 +0100562
Cory Benfielde6f35882016-03-29 11:21:04 +0100563
Cory Benfieldef404df2016-03-29 15:32:48 +0100564_requires_sni = _make_requires(
565 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
566)
Cory Benfielde6f35882016-03-29 11:21:04 +0100567
568
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800569class Session(object):
570 pass
571
572
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800573class Context(object):
574 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100575 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400576 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800577 """
578 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800579 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500580 SSLv3_METHOD: "SSLv3_method",
581 SSLv23_METHOD: "SSLv23_method",
582 TLSv1_METHOD: "TLSv1_method",
583 TLSv1_1_METHOD: "TLSv1_1_method",
584 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400585 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500586 _methods = dict(
587 (identifier, getattr(_lib, name))
588 for (identifier, name) in _methods.items()
589 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800590
591 def __init__(self, method):
592 """
593 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
594 TLSv1_METHOD.
595 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500596 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800597 raise TypeError("method must be an integer")
598
599 try:
600 method_func = self._methods[method]
601 except KeyError:
602 raise ValueError("No such protocol")
603
604 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700605 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800606
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500607 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700608 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500609 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800610
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600611 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
612 # will be auto-selected. This function was added in 1.0.2 and made a
613 # noop in 1.1.0+ (where it is set automatically).
614 try:
615 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
616 _openssl_assert(res == 1)
617 except AttributeError:
618 pass
619
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800620 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800621 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800622 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800623 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800624 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800625 self._verify_callback = None
626 self._info_callback = None
627 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800628 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000629 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100630 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000631 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100632 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400633 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100634 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000635 self._ocsp_helper = None
636 self._ocsp_callback = None
637 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800639 # SSL_CTX_set_app_data(self->ctx, self);
640 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
641 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
642 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500643 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645 def load_verify_locations(self, cafile, capath=None):
646 """
647 Let SSL know where we can find trusted certificates for the certificate
648 chain
649
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400650 :param cafile: In which file we can find the certificates (``bytes`` or
651 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800652 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400653 (``bytes`` or ``unicode``).
654
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655 :return: None
656 """
657 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500658 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400659 else:
660 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661
662 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500663 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400664 else:
665 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666
Alex Gaynor62da94d2015-09-05 14:37:34 -0400667 load_result = _lib.SSL_CTX_load_verify_locations(
668 self._context, cafile, capath
669 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500671 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673 def _wrap_callback(self, callback):
674 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800675 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800676 return callback(size, verify, self._passphrase_userdata)
677 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800678 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800679
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680 def set_passwd_cb(self, callback, userdata=None):
681 """
682 Set the passphrase callback
683
684 :param callback: The Python callback to use
685 :param userdata: (optional) A Python object which will be given as
686 argument to the callback
687 :return: None
688 """
689 if not callable(callback):
690 raise TypeError("callback must be callable")
691
692 self._passphrase_helper = self._wrap_callback(callback)
693 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500694 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695 self._context, self._passphrase_callback)
696 self._passphrase_userdata = userdata
697
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800698 def set_default_verify_paths(self):
699 """
700 Use the platform-specific CA certificate locations
701
702 :return: None
703 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500704 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400705 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800706
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707 def use_certificate_chain_file(self, certfile):
708 """
709 Load a certificate chain from a file
710
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400711 :param certfile: The name of the certificate chain file (``bytes`` or
712 ``unicode``).
713
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714 :return: None
715 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400716 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800717
Alex Gaynor62da94d2015-09-05 14:37:34 -0400718 result = _lib.SSL_CTX_use_certificate_chain_file(
719 self._context, certfile
720 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800721 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500722 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800723
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800724 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800725 """
726 Load a certificate from a file
727
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400728 :param certfile: The name of the certificate file (``bytes`` or
729 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400731
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800732 :return: None
733 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400734 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500735 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800736 raise TypeError("filetype must be an integer")
737
Alex Gaynor62da94d2015-09-05 14:37:34 -0400738 use_result = _lib.SSL_CTX_use_certificate_file(
739 self._context, certfile, filetype
740 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800741 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500742 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800743
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744 def use_certificate(self, cert):
745 """
746 Load a certificate from a X509 object
747
748 :param cert: The X509 object
749 :return: None
750 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800751 if not isinstance(cert, X509):
752 raise TypeError("cert must be an X509 instance")
753
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500754 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800755 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500756 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800757
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758 def add_extra_chain_cert(self, certobj):
759 """
760 Add certificate to chain
761
762 :param certobj: The X509 certificate object to add to the chain
763 :return: None
764 """
765 if not isinstance(certobj, X509):
766 raise TypeError("certobj must be an X509 instance")
767
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500768 copy = _lib.X509_dup(certobj._x509)
769 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800770 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500771 # TODO: This is untested.
772 _lib.X509_free(copy)
773 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800774
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800775 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500776 if self._passphrase_helper is not None:
777 self._passphrase_helper.raise_if_problem(Error)
778
779 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800780
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400781 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782 """
783 Load a private key from a file
784
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400785 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400787
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788 :return: None
789 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400790 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400792 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500794 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800795 raise TypeError("filetype must be an integer")
796
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500797 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798 self._context, keyfile, filetype)
799 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800800 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800802 def use_privatekey(self, pkey):
803 """
804 Load a private key from a PKey object
805
806 :param pkey: The PKey object
807 :return: None
808 """
809 if not isinstance(pkey, PKey):
810 raise TypeError("pkey must be a PKey instance")
811
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500812 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800813 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800814 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800816 def check_privatekey(self):
817 """
818 Check that the private key and certificate match up
819
820 :return: None (raises an exception if something's wrong)
821 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500822 if not _lib.SSL_CTX_check_private_key(self._context):
823 _raise_current_error()
824
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825 def load_client_ca(self, cafile):
826 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100827 Load the trusted certificates that will be sent to the client. Does
828 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400829 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800830
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100831 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800832 :return: None
833 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100834 ca_list = _lib.SSL_load_client_CA_file(
835 _text_to_bytes_and_warn("cafile", cafile)
836 )
837 _openssl_assert(ca_list != _ffi.NULL)
838 # SSL_CTX_set_client_CA_list doesn't return anything.
839 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800840
841 def set_session_id(self, buf):
842 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100843 Set the session id to *buf* within which a session can be reused for
844 this Context object. This is needed when doing session resumption,
845 because there is no way for a stored session to know which Context
846 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800847
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100848 :param bytes buf: The session id.
849
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800850 :returns: None
851 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100852 buf = _text_to_bytes_and_warn("buf", buf)
853 _openssl_assert(
854 _lib.SSL_CTX_set_session_id_context(
855 self._context,
856 buf,
857 len(buf),
858 ) == 1
859 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800860
861 def set_session_cache_mode(self, mode):
862 """
863 Enable/disable session caching and specify the mode used.
864
865 :param mode: One or more of the SESS_CACHE_* flags (combine using
866 bitwise or)
867 :returns: The previously set caching mode.
868 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500869 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800870 raise TypeError("mode must be an integer")
871
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800874 def get_session_cache_mode(self):
875 """
876 :returns: The currently used cache mode.
877 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500878 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800879
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800880 def set_verify(self, mode, callback):
881 """
882 Set the verify mode and verify callback
883
884 :param mode: The verify mode, this is either VERIFY_NONE or
885 VERIFY_PEER combined with possible other flags
886 :param callback: The Python callback to use
887 :return: None
888
889 See SSL_CTX_set_verify(3SSL) for further details.
890 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500891 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800892 raise TypeError("mode must be an integer")
893
894 if not callable(callback):
895 raise TypeError("callback must be callable")
896
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400897 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800898 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500899 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800901 def set_verify_depth(self, depth):
902 """
903 Set the verify depth
904
905 :param depth: An integer specifying the verify depth
906 :return: None
907 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500908 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 raise TypeError("depth must be an integer")
910
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500911 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800913 def get_verify_mode(self):
914 """
915 Get the verify mode
916
917 :return: The verify mode
918 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500919 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800921 def get_verify_depth(self):
922 """
923 Get the verify depth
924
925 :return: The verify depth
926 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500927 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800928
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929 def load_tmp_dh(self, dhfile):
930 """
931 Load parameters for Ephemeral Diffie-Hellman
932
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400933 :param dhfile: The file to load EDH parameters from (``bytes`` or
934 ``unicode``).
935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 :return: None
937 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400938 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500940 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500941 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500942 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500943 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800944
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500945 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
946 dh = _ffi.gc(dh, _lib.DH_free)
947 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800948
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400949 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600950 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700951 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600952
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400953 :param curve: A curve object to use as returned by either
954 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
955 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700956
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600957 :return: None
958 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400959 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600960
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800961 def set_cipher_list(self, cipher_list):
962 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100963 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800964
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100965 See the OpenSSL manual for more information (e.g.
966 :manpage:`ciphers(1)`).
967
968 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800969 :return: None
970 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100971 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500972
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800973 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100974 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800975
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100976 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100977 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100978 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800979
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800980 def set_client_ca_list(self, certificate_authorities):
981 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400982 Set the list of preferred client certificate signers for this server
983 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984
Alex Gaynor62da94d2015-09-05 14:37:34 -0400985 This list of certificate authorities will be sent to the client when
986 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987
988 :param certificate_authorities: a sequence of X509Names.
989 :return: None
990 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700992 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800993
994 try:
995 for ca_name in certificate_authorities:
996 if not isinstance(ca_name, X509Name):
997 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400998 "client CAs must be X509Name objects, not %s "
999 "objects" % (
1000 type(ca_name).__name__,
1001 )
1002 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001004 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001005 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001006 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001007 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001008 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001009 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001010 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001011 raise
1012
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001013 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001014
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015 def add_client_ca(self, certificate_authority):
1016 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001017 Add the CA certificate to the list of preferred signers for this
1018 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001019
1020 The list of certificate authorities will be sent to the client when the
1021 server requests a client certificate.
1022
1023 :param certificate_authority: certificate authority's X509 certificate.
1024 :return: None
1025 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001026 if not isinstance(certificate_authority, X509):
1027 raise TypeError("certificate_authority must be an X509 instance")
1028
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001029 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001030 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001031 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001032
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033 def set_timeout(self, timeout):
1034 """
1035 Set session timeout
1036
1037 :param timeout: The timeout in seconds
1038 :return: The previous session timeout
1039 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001040 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041 raise TypeError("timeout must be an integer")
1042
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001043 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001045 def get_timeout(self):
1046 """
1047 Get the session timeout
1048
1049 :return: The session timeout
1050 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001051 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001052
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001053 def set_info_callback(self, callback):
1054 """
1055 Set the info callback
1056
1057 :param callback: The Python callback to use
1058 :return: None
1059 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001060 @wraps(callback)
1061 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001062 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001063 self._info_callback = _ffi.callback(
1064 "void (*)(const SSL *, int, int)", wrapper)
1065 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001066
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067 def get_app_data(self):
1068 """
1069 Get the application data (supplied via set_app_data())
1070
1071 :return: The application data
1072 """
1073 return self._app_data
1074
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001075 def set_app_data(self, data):
1076 """
1077 Set the application data (will be returned from get_app_data())
1078
1079 :param data: Any Python object
1080 :return: None
1081 """
1082 self._app_data = data
1083
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001084 def get_cert_store(self):
1085 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001086 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001088 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001089 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 store = _lib.SSL_CTX_get_cert_store(self._context)
1091 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001092 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001093 return None
1094
1095 pystore = X509Store.__new__(X509Store)
1096 pystore._store = store
1097 return pystore
1098
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001099 def set_options(self, options):
1100 """
1101 Add options. Options set before are not cleared!
1102
1103 :param options: The options to add.
1104 :return: The new option bitmask.
1105 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001106 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001107 raise TypeError("options must be an integer")
1108
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001110
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111 def set_mode(self, mode):
1112 """
1113 Add modes via bitmask. Modes set before are not cleared!
1114
1115 :param mode: The mode to add.
1116 :return: The new mode bitmask.
1117 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001118 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001119 raise TypeError("mode must be an integer")
1120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001121 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122
Cory Benfielde6f35882016-03-29 11:21:04 +01001123 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124 def set_tlsext_servername_callback(self, callback):
1125 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001126 Specify a callback function to be called when clients specify a server
1127 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001128
1129 :param callback: The callback function. It will be invoked with one
1130 argument, the Connection instance.
1131 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001132 @wraps(callback)
1133 def wrapper(ssl, alert, arg):
1134 callback(Connection._reverse_mapping[ssl])
1135 return 0
1136
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001137 self._tlsext_servername_callback = _ffi.callback(
1138 "int (*)(const SSL *, int *, void *)", wrapper)
1139 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001140 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001141
Cory Benfield10b277f2015-04-13 17:12:42 -04001142 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001143 def set_npn_advertise_callback(self, callback):
1144 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001145 Specify a callback function that will be called when offering `Next
1146 Protocol Negotiation
1147 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001148
1149 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001150 argument, the Connection instance. It should return a list of
1151 bytestrings representing the advertised protocols, like
1152 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001153 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001154 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1155 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001156 _lib.SSL_CTX_set_next_protos_advertised_cb(
1157 self._context, self._npn_advertise_callback, _ffi.NULL)
1158
Cory Benfield10b277f2015-04-13 17:12:42 -04001159 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001160 def set_npn_select_callback(self, callback):
1161 """
1162 Specify a callback function that will be called when a server offers
1163 Next Protocol Negotiation options.
1164
1165 :param callback: The callback function. It will be invoked with two
1166 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001167 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1168 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001169 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001170 self._npn_select_helper = _NpnSelectHelper(callback)
1171 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001172 _lib.SSL_CTX_set_next_proto_select_cb(
1173 self._context, self._npn_select_callback, _ffi.NULL)
1174
Cory Benfield7907e332015-04-13 17:18:25 -04001175 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001176 def set_alpn_protos(self, protos):
1177 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001178 Specify the clients ALPN protocol list.
1179
1180 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001181
1182 :param protos: A list of the protocols to be offered to the server.
1183 This list should be a Python list of bytestrings representing the
1184 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1185 """
1186 # Take the list of protocols and join them together, prefixing them
1187 # with their lengths.
1188 protostr = b''.join(
1189 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1190 )
1191
1192 # Build a C string from the list. We don't need to save this off
1193 # because OpenSSL immediately copies the data out.
1194 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001195 input_str_len = _ffi.cast("unsigned", len(protostr))
1196 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001197
Cory Benfield7907e332015-04-13 17:18:25 -04001198 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001199 def set_alpn_select_callback(self, callback):
1200 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001201 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001202
1203 :param callback: The callback function. It will be invoked with two
1204 arguments: the Connection, and a list of offered protocols as
1205 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001206 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001207 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001208 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001209 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001210 _lib.SSL_CTX_set_alpn_select_cb(
1211 self._context, self._alpn_select_callback, _ffi.NULL)
1212
Cory Benfield496652a2017-01-24 11:42:56 +00001213 def _set_ocsp_callback(self, helper, data):
1214 """
1215 This internal helper does the common work for
1216 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1217 almost all of it.
1218 """
1219 self._ocsp_helper = helper
1220 self._ocsp_callback = helper.callback
1221 if data is None:
1222 self._ocsp_data = _ffi.NULL
1223 else:
1224 self._ocsp_data = _ffi.new_handle(data)
1225
1226 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1227 self._context, self._ocsp_callback
1228 )
1229 _openssl_assert(rc == 1)
1230 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1231 _openssl_assert(rc == 1)
1232
1233 def set_ocsp_server_callback(self, callback, data=None):
1234 """
1235 Set a callback to provide OCSP data to be stapled to the TLS handshake
1236 on the server side.
1237
1238 :param callback: The callback function. It will be invoked with two
1239 arguments: the Connection, and the optional arbitrary data you have
1240 provided. The callback must return a bytestring that contains the
1241 OCSP data to staple to the handshake. If no OCSP data is available
1242 for this connection, return the empty bytestring.
1243 :param data: Some opaque data that will be passed into the callback
1244 function when called. This can be used to avoid needing to do
1245 complex data lookups or to keep track of what context is being
1246 used. This parameter is optional.
1247 """
1248 helper = _OCSPServerCallbackHelper(callback)
1249 self._set_ocsp_callback(helper, data)
1250
1251 def set_ocsp_client_callback(self, callback, data=None):
1252 """
1253 Set a callback to validate OCSP data stapled to the TLS handshake on
1254 the client side.
1255
1256 :param callback: The callback function. It will be invoked with three
1257 arguments: the Connection, a bytestring containing the stapled OCSP
1258 assertion, and the optional arbitrary data you have provided. The
1259 callback must return a boolean that indicates the result of
1260 validating the OCSP data: ``True`` if the OCSP data is valid and
1261 the certificate can be trusted, or ``False`` if either the OCSP
1262 data is invalid or the certificate has been revoked.
1263 :param data: Some opaque data that will be passed into the callback
1264 function when called. This can be used to avoid needing to do
1265 complex data lookups or to keep track of what context is being
1266 used. This parameter is optional.
1267 """
1268 helper = _OCSPClientCallbackHelper(callback)
1269 self._set_ocsp_callback(helper, data)
1270
Alex Chanc6077062016-11-18 13:53:39 +00001271
Alex Gaynor10d30832017-06-29 15:31:39 -07001272ContextType = deprecated(
1273 Context, __name__,
1274 "ContextType has been deprecated, use Context instead", DeprecationWarning
1275)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001276
1277
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001278class Connection(object):
1279 """
1280 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281 _reverse_mapping = WeakValueDictionary()
1282
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001283 def __init__(self, context, socket=None):
1284 """
1285 Create a new Connection object, using the given OpenSSL.SSL.Context
1286 instance and socket.
1287
1288 :param context: An SSL Context to use for this connection
1289 :param socket: The socket to use for transport layer
1290 """
1291 if not isinstance(context, Context):
1292 raise TypeError("context must be a Context instance")
1293
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001294 ssl = _lib.SSL_new(context._context)
1295 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001296 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001297 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001298
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001299 # References to strings used for Next Protocol Negotiation. OpenSSL's
1300 # header files suggest that these might get copied at some point, but
1301 # doesn't specify when, so we store them here to make sure they don't
1302 # get freed before OpenSSL uses them.
1303 self._npn_advertise_callback_args = None
1304 self._npn_select_callback_args = None
1305
Cory Benfield12eae892014-06-07 15:42:56 +01001306 # References to strings used for Application Layer Protocol
1307 # Negotiation. These strings get copied at some point but it's well
1308 # after the callback returns, so we have to hang them somewhere to
1309 # avoid them getting freed.
1310 self._alpn_select_callback_args = None
1311
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001312 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001313
1314 if socket is None:
1315 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001316 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001317 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001318 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001319
Alex Gaynora829e902016-06-04 18:16:01 -07001320 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1321 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001322
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001323 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001324 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001325 self._into_ssl = None
1326 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001327 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001328 set_result = _lib.SSL_set_fd(
1329 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001330 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001331
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001332 def __getattr__(self, name):
1333 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001334 Look up attributes on the wrapped socket object if they are not found
1335 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001336 """
kjav0b66fa12015-09-02 11:51:26 +01001337 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001338 raise AttributeError("'%s' object has no attribute '%s'" % (
1339 self.__class__.__name__, name
1340 ))
kjav0b66fa12015-09-02 11:51:26 +01001341 else:
1342 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001343
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001344 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001345 if self._context._verify_helper is not None:
1346 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001347 if self._context._npn_advertise_helper is not None:
1348 self._context._npn_advertise_helper.raise_if_problem()
1349 if self._context._npn_select_helper is not None:
1350 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001351 if self._context._alpn_select_helper is not None:
1352 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001353 if self._context._ocsp_helper is not None:
1354 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001355
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001356 error = _lib.SSL_get_error(ssl, result)
1357 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001358 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001359 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001360 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001362 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001363 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001364 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001365 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001366 elif error == _lib.SSL_ERROR_SYSCALL:
1367 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001368 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001369 if platform == "win32":
1370 errno = _ffi.getwinerror()[0]
1371 else:
1372 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001373
1374 if errno != 0:
1375 raise SysCallError(errno, errorcode.get(errno))
1376 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001377 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001378 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001379 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001380 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001381 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001382 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001383 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001384
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001385 def get_context(self):
1386 """
1387 Get session context
1388 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001389 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001391 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001392 """
1393 Switch this connection to a new session context
1394
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001395 :param context: A :py:class:`Context` instance giving the new session
1396 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001397 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001398 if not isinstance(context, Context):
1399 raise TypeError("context must be a Context instance")
1400
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001402 self._context = context
1403
Cory Benfielde6f35882016-03-29 11:21:04 +01001404 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001405 def get_servername(self):
1406 """
1407 Retrieve the servername extension value if provided in the client hello
1408 message, or None if there wasn't one.
1409
1410 :return: A byte string giving the server name or :py:data:`None`.
1411 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001412 name = _lib.SSL_get_servername(
1413 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1414 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001415 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001416 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001417
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001418 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001419
Cory Benfielde6f35882016-03-29 11:21:04 +01001420 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001421 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001422 """
1423 Set the value of the servername extension to send in the client hello.
1424
1425 :param name: A byte string giving the name.
1426 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001427 if not isinstance(name, bytes):
1428 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001429 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001430 raise TypeError("name must not contain NUL byte")
1431
1432 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001433 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001434
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001435 def pending(self):
1436 """
1437 Get the number of bytes that can be safely read from the connection
1438
1439 :return: The number of bytes available in the receive buffer.
1440 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001441 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001442
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001443 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001444 """
1445 Send data on the connection. NOTE: If you get one of the WantRead,
1446 WantWrite or WantX509Lookup exceptions on this, you have to call the
1447 method again with the SAME buffer.
1448
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001449 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001450 :param flags: (optional) Included for compatibility with the socket
1451 API, the value is ignored
1452 :return: The number of bytes written
1453 """
Abraham Martine82326c2015-02-04 10:18:10 +00001454 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001455 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001456
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001457 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001458 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001459 if isinstance(buf, _buffer):
1460 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001461 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001462 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001463 if len(buf) > 2147483647:
1464 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001466 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001468 return result
1469 write = send
1470
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001471 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001472 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001473 Send "all" data on the connection. This calls send() repeatedly until
1474 all data is sent. If an error occurs, it's impossible to tell how much
1475 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001476
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001477 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001478 :param flags: (optional) Included for compatibility with the socket
1479 API, the value is ignored
1480 :return: The number of bytes written
1481 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001482 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001483
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001484 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001485 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001486 if isinstance(buf, _buffer):
1487 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001488 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001489 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490
1491 left_to_send = len(buf)
1492 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001493 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494
1495 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001496 # SSL_write's num arg is an int,
1497 # so we cannot send more than 2**31-1 bytes at once.
1498 result = _lib.SSL_write(
1499 self._ssl,
1500 data + total_sent,
1501 min(left_to_send, 2147483647)
1502 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503 self._raise_ssl_error(self._ssl, result)
1504 total_sent += result
1505 left_to_send -= result
1506
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507 def recv(self, bufsiz, flags=None):
1508 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001509 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510
1511 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001512 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1513 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514 :return: The string read from the Connection
1515 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001516 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001517 if flags is not None and flags & socket.MSG_PEEK:
1518 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1519 else:
1520 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001521 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001522 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523 read = recv
1524
Cory Benfield62d10332014-06-15 10:03:41 +01001525 def recv_into(self, buffer, nbytes=None, flags=None):
1526 """
1527 Receive data on the connection and store the data into a buffer rather
1528 than creating a new string.
1529
1530 :param buffer: The buffer to copy into.
1531 :param nbytes: (optional) The maximum number of bytes to read into the
1532 buffer. If not present, defaults to the size of the buffer. If
1533 larger than the size of the buffer, is reduced to the size of the
1534 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001535 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1536 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001537 :return: The number of bytes read into the buffer.
1538 """
1539 if nbytes is None:
1540 nbytes = len(buffer)
1541 else:
1542 nbytes = min(nbytes, len(buffer))
1543
1544 # We need to create a temporary buffer. This is annoying, it would be
1545 # better if we could pass memoryviews straight into the SSL_read call,
1546 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001547 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001548 if flags is not None and flags & socket.MSG_PEEK:
1549 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1550 else:
1551 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001552 self._raise_ssl_error(self._ssl, result)
1553
1554 # This strange line is all to avoid a memory copy. The buffer protocol
1555 # should allow us to assign a CFFI buffer to the LHS of this line, but
1556 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1557 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1558 # memoryview type.
1559 try:
1560 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1561 except NameError:
1562 buffer[:result] = _ffi.buffer(buf, result)
1563
1564 return result
1565
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001567 if _lib.BIO_should_retry(bio):
1568 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001569 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001570 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001571 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001572 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001573 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001574 # TODO: This is untested. I think io_special means the socket
1575 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001576 raise ValueError("BIO_should_io_special")
1577 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001578 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001579 raise ValueError("unknown bio failure")
1580 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001581 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001582 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001583
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 When using non-socket connections this function reads the "dirty" data
1587 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588
1589 :param bufsiz: The maximum number of bytes to read
1590 :return: The string read.
1591 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001592 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001593 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001595 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001596 raise TypeError("bufsiz must be an integer")
1597
Cory Benfielde62840e2016-11-28 12:17:08 +00001598 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001600 if result <= 0:
1601 self._handle_bio_errors(self._from_ssl, result)
1602
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001603 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001606 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 When using non-socket connections this function sends "dirty" data that
1608 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001609
1610 :param buf: The string to put into the memory BIO.
1611 :return: The number of bytes written
1612 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001613 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001614
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001615 if self._into_ssl is None:
1616 raise TypeError("Connection sock was not None")
1617
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001618 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619 if result <= 0:
1620 self._handle_bio_errors(self._into_ssl, result)
1621 return result
1622
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001623 def renegotiate(self):
1624 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001625 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001626
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001627 :return: True if the renegotiation can be started, False otherwise
1628 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001629 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001630 if not self.renegotiate_pending():
1631 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1632 return True
1633 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001634
1635 def do_handshake(self):
1636 """
1637 Perform an SSL handshake (usually called after renegotiate() or one of
1638 set_*_state()). This can raise the same exceptions as send and recv.
1639
1640 :return: None.
1641 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001642 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001643 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001644
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001645 def renegotiate_pending(self):
1646 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001647 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001648 a renegotiation is finished.
1649
1650 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001651 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001652 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001653 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001654
1655 def total_renegotiations(self):
1656 """
1657 Find out the total number of renegotiations.
1658
1659 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001660 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001662 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665 """
1666 Connect to remote host and set up client-side SSL
1667
1668 :param addr: A remote address
1669 :return: What the socket's connect method returns
1670 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001671 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001675 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001676 Connect to remote host and set up client-side SSL. Note that if the
1677 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001678
1679 :param addr: A remove address
1680 :return: What the socket's connect_ex method returns
1681 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001682 connect_ex = self._socket.connect_ex
1683 self.set_connect_state()
1684 return connect_ex(addr)
1685
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 def accept(self):
1687 """
1688 Accept incoming connection and set up SSL on it
1689
1690 :return: A (conn,addr) pair where conn is a Connection and addr is an
1691 address
1692 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693 client, addr = self._socket.accept()
1694 conn = Connection(self._context, client)
1695 conn.set_accept_state()
1696 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001698 def bio_shutdown(self):
1699 """
1700 When using non-socket connections this function signals end of
1701 data on the input for this connection.
1702
1703 :return: None
1704 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001705 if self._from_ssl is None:
1706 raise TypeError("Connection sock was not None")
1707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001708 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710 def shutdown(self):
1711 """
1712 Send closure alert
1713
1714 :return: True if the shutdown completed successfully (i.e. both sides
1715 have sent closure alerts), false otherwise (i.e. you have to
1716 wait for a ZeroReturnError on a recv() method call
1717 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001720 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001722 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001723 else:
1724 return False
1725
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 def get_cipher_list(self):
1727 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001728 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001729
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001730 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001731 """
1732 ciphers = []
1733 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001734 result = _lib.SSL_get_cipher_list(self._ssl, i)
1735 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001736 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001737 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001738 return ciphers
1739
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001740 def get_client_ca_list(self):
1741 """
1742 Get CAs whose certificates are suggested for client authentication.
1743
Alex Gaynor62da94d2015-09-05 14:37:34 -04001744 :return: If this is a server connection, a list of X509Names
1745 representing the acceptable CAs as set by
1746 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1747 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1748 connection, the list of such X509Names sent by the server, or an
1749 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001750 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001751 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1752 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001753 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001754 return []
1755
1756 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001757 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1758 name = _lib.sk_X509_NAME_value(ca_names, i)
1759 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001760 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001761
1762 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001763 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001764 result.append(pyname)
1765 return result
1766
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001767 def makefile(self):
1768 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001769 The makefile() method is not implemented, since there is no dup
1770 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001771
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001772 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001773 """
Alex Gaynor83284952015-09-05 10:43:30 -04001774 raise NotImplementedError(
1775 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001776
1777 def get_app_data(self):
1778 """
1779 Get application data
1780
1781 :return: The application data
1782 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001783 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001784
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001785 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001786 """
1787 Set application data
1788
1789 :param data - The application data
1790 :return: None
1791 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001792 self._app_data = data
1793
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 def get_shutdown(self):
1795 """
1796 Get shutdown state
1797
Alex Gaynor62da94d2015-09-05 14:37:34 -04001798 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1799 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001800 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001801 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001802
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001803 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001804 """
1805 Set shutdown state
1806
1807 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1808 :return: None
1809 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001810 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001811 raise TypeError("state must be an integer")
1812
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001813 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001814
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001815 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001817 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001818
1819 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001820 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001821 """
kjavc704a2e2015-09-07 12:12:27 +01001822 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001823
1824 def server_random(self):
1825 """
1826 Get a copy of the server hello nonce.
1827
1828 :return: A string representing the state
1829 """
Alex Gaynor93603062016-06-01 20:13:09 -07001830 session = _lib.SSL_get_session(self._ssl)
1831 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001832 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001833 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1834 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001835 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001836 _lib.SSL_get_server_random(self._ssl, outp, length)
1837 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001838
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001839 def client_random(self):
1840 """
1841 Get a copy of the client hello nonce.
1842
1843 :return: A string representing the state
1844 """
Alex Gaynor93603062016-06-01 20:13:09 -07001845 session = _lib.SSL_get_session(self._ssl)
1846 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001847 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001848
1849 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1850 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001851 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001852 _lib.SSL_get_client_random(self._ssl, outp, length)
1853 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001854
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001855 def master_key(self):
1856 """
1857 Get a copy of the master key.
1858
1859 :return: A string representing the state
1860 """
Alex Gaynor93603062016-06-01 20:13:09 -07001861 session = _lib.SSL_get_session(self._ssl)
1862 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001863 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001864
1865 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1866 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001867 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001868 _lib.SSL_SESSION_get_master_key(session, outp, length)
1869 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001870
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001871 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001872 """
1873 See shutdown(2)
1874
1875 :return: What the socket's shutdown() method returns
1876 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001877 return self._socket.shutdown(*args, **kwargs)
1878
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879 def get_peer_certificate(self):
1880 """
1881 Retrieve the other side's certificate (if any)
1882
1883 :return: The peer's certificate
1884 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001885 cert = _lib.SSL_get_peer_certificate(self._ssl)
1886 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001887 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001888 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889 return pycert
1890 return None
1891
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001892 def get_peer_cert_chain(self):
1893 """
1894 Retrieve the other side's certificate (if any)
1895
1896 :return: A list of X509 instances giving the peer's certificate chain,
1897 or None if it does not have one.
1898 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001899 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1900 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001901 return None
1902
1903 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001904 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001905 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001906 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001907 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001908 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001909 result.append(pycert)
1910 return result
1911
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912 def want_read(self):
1913 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001914 Checks if more data has to be read from the transport layer to complete
1915 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916
1917 :return: True iff more data has to be read
1918 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001919 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001920
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921 def want_write(self):
1922 """
1923 Checks if there is data to write to the transport layer to complete an
1924 operation.
1925
1926 :return: True iff there is data to write
1927 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001928 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001929
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930 def set_accept_state(self):
1931 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001932 Set the connection to work in server mode. The handshake will be
1933 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934
1935 :return: None
1936 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001937 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001938
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001939 def set_connect_state(self):
1940 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001941 Set the connection to work in client mode. The handshake will be
1942 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943
1944 :return: None
1945 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001946 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001948 def get_session(self):
1949 """
1950 Returns the Session currently used.
1951
Alex Gaynor62da94d2015-09-05 14:37:34 -04001952 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1953 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001954 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001955 session = _lib.SSL_get1_session(self._ssl)
1956 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001959 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001961 return pysession
1962
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001963 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964 """
1965 Set the session to be used when the TLS/SSL connection is established.
1966
1967 :param session: A Session instance representing the session to use.
1968 :returns: None
1969 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001970 if not isinstance(session, Session):
1971 raise TypeError("session must be a Session instance")
1972
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001973 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001974 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001975 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001976
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001977 def _get_finished_message(self, function):
1978 """
1979 Helper to implement :py:meth:`get_finished` and
1980 :py:meth:`get_peer_finished`.
1981
1982 :param function: Either :py:data:`SSL_get_finished`: or
1983 :py:data:`SSL_get_peer_finished`.
1984
1985 :return: :py:data:`None` if the desired message has not yet been
1986 received, otherwise the contents of the message.
1987 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1988 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001989 # The OpenSSL documentation says nothing about what might happen if the
1990 # count argument given is zero. Specifically, it doesn't say whether
1991 # the output buffer may be NULL in that case or not. Inspection of the
1992 # implementation reveals that it calls memcpy() unconditionally.
1993 # Section 7.1.4, paragraph 1 of the C standard suggests that
1994 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1995 # alone desirable) behavior (though it probably does on just about
1996 # every implementation...)
1997 #
1998 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1999 # one might expect) for the initial call so as to be safe against this
2000 # potentially undefined behavior.
2001 empty = _ffi.new("char[]", 0)
2002 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002003 if size == 0:
2004 # No Finished message so far.
2005 return None
2006
Cory Benfielde62840e2016-11-28 12:17:08 +00002007 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002008 function(self._ssl, buf, size)
2009 return _ffi.buffer(buf, size)[:]
2010
Fedor Brunner5747b932014-03-05 14:22:34 +01002011 def get_finished(self):
2012 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002013 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002014
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002015 :return: The contents of the message or :py:obj:`None` if the TLS
2016 handshake has not yet completed.
2017 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002018 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002019 return self._get_finished_message(_lib.SSL_get_finished)
2020
Fedor Brunner5747b932014-03-05 14:22:34 +01002021 def get_peer_finished(self):
2022 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002023 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002024
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002025 :return: The contents of the message or :py:obj:`None` if the TLS
2026 handshake has not yet completed.
2027 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002028 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002029 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002030
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002031 def get_cipher_name(self):
2032 """
2033 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002034
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002035 :returns: The name of the currently used cipher or :py:obj:`None`
2036 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002037 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002038 """
2039 cipher = _lib.SSL_get_current_cipher(self._ssl)
2040 if cipher == _ffi.NULL:
2041 return None
2042 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002043 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2044 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002045
2046 def get_cipher_bits(self):
2047 """
2048 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002049
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002050 :returns: The number of secret bits of the currently used cipher
2051 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002052 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002053 """
2054 cipher = _lib.SSL_get_current_cipher(self._ssl)
2055 if cipher == _ffi.NULL:
2056 return None
2057 else:
2058 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2059
2060 def get_cipher_version(self):
2061 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002062 Obtain the protocol version of the currently used cipher.
2063
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002064 :returns: The protocol name of the currently used cipher
2065 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002066 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002067 """
2068 cipher = _lib.SSL_get_current_cipher(self._ssl)
2069 if cipher == _ffi.NULL:
2070 return None
2071 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002072 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002073 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002074
Jim Shaverabff1882015-05-27 09:15:55 -04002075 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002076 """
2077 Obtain the protocol version of the current connection.
2078
2079 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002080 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002081 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002082 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002083 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002084 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002085 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002086
Jim Shaver208438c2015-05-28 09:52:38 -04002087 def get_protocol_version(self):
2088 """
2089 Obtain the protocol version of the current connection.
2090
2091 :returns: The TLS version of the current connection, for example
2092 the value for TLS 1 would be 0x769.
2093 :rtype: :py:class:`int`
2094 """
2095 version = _lib.SSL_version(self._ssl)
2096 return version
2097
Cory Benfield10b277f2015-04-13 17:12:42 -04002098 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002099 def get_next_proto_negotiated(self):
2100 """
2101 Get the protocol that was negotiated by NPN.
2102 """
2103 data = _ffi.new("unsigned char **")
2104 data_len = _ffi.new("unsigned int *")
2105
2106 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2107
Cory Benfieldcd010f62014-05-15 19:00:27 +01002108 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002109
Cory Benfield7907e332015-04-13 17:18:25 -04002110 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002111 def set_alpn_protos(self, protos):
2112 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002113 Specify the client's ALPN protocol list.
2114
2115 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002116
2117 :param protos: A list of the protocols to be offered to the server.
2118 This list should be a Python list of bytestrings representing the
2119 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2120 """
2121 # Take the list of protocols and join them together, prefixing them
2122 # with their lengths.
2123 protostr = b''.join(
2124 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2125 )
2126
2127 # Build a C string from the list. We don't need to save this off
2128 # because OpenSSL immediately copies the data out.
2129 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04002130 input_str_len = _ffi.cast("unsigned", len(protostr))
2131 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01002132
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002133 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002134 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002135 """
2136 Get the protocol that was negotiated by ALPN.
2137 """
Cory Benfield12eae892014-06-07 15:42:56 +01002138 data = _ffi.new("unsigned char **")
2139 data_len = _ffi.new("unsigned int *")
2140
2141 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2142
Cory Benfielde8e9c382015-04-11 17:33:48 -04002143 if not data_len:
2144 return b''
2145
Cory Benfield12eae892014-06-07 15:42:56 +01002146 return _ffi.buffer(data[0], data_len[0])[:]
2147
Cory Benfield496652a2017-01-24 11:42:56 +00002148 def request_ocsp(self):
2149 """
2150 Called to request that the server sends stapled OCSP data, if
2151 available. If this is not called on the client side then the server
2152 will not send OCSP data. Should be used in conjunction with
2153 :meth:`Context.set_ocsp_client_callback`.
2154 """
2155 rc = _lib.SSL_set_tlsext_status_type(
2156 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2157 )
2158 _openssl_assert(rc == 1)
2159
Cory Benfield12eae892014-06-07 15:42:56 +01002160
Alex Gaynor10d30832017-06-29 15:31:39 -07002161ConnectionType = deprecated(
2162 Connection, __name__,
2163 "ConnectionType has been deprecated, use Connection instead",
2164 DeprecationWarning
2165)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002166
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002167# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2168# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002169_lib.SSL_library_init()