blob: d4158d44c36de378abb380378de305ce015ded91 [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
Cory Benfield63759dc2015-04-12 08:57:03 -04008from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -08009from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010010from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
16 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000021 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080023
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080024from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050025 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080026
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050027try:
28 _memoryview = memoryview
29except NameError:
30 class _memoryview(object):
31 pass
32
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020033try:
34 _buffer = buffer
35except NameError:
36 class _buffer(object):
37 pass
38
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050039OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
40SSLEAY_VERSION = _lib.SSLEAY_VERSION
41SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
42SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
43SSLEAY_DIR = _lib.SSLEAY_DIR
44SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080045
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050046SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
47RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080048
49SSLv2_METHOD = 1
50SSLv3_METHOD = 2
51SSLv23_METHOD = 3
52TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050053TLSv1_1_METHOD = 5
54TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080055
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050056OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
57OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
58OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050059
60OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
61OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080062
Alex Gaynorbf012872016-06-04 13:18:39 -070063MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080064
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050065OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090066OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
68OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
69OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040070OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
71 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
72)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050073OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
74OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040075OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050076OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
77OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
78OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
79OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
80OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
81OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
82OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
83OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
84OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040085OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
86 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
87)
Alex Gaynorbf012872016-06-04 13:18:39 -070088OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050090OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
91OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040092OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080093
Alex Gaynorc4889812015-09-04 08:43:17 -040094OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080095
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050096VERIFY_PEER = _lib.SSL_VERIFY_PEER
97VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
98VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
99VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800100
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500101SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
102SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
103SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
104SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
105SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
106SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
107SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
108SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800109
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500110SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
111SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
112SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400113if _lib.Cryptography_HAS_SSL_ST:
114 SSL_ST_INIT = _lib.SSL_ST_INIT
115 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
116 SSL_ST_OK = _lib.SSL_ST_OK
117 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500119SSL_CB_LOOP = _lib.SSL_CB_LOOP
120SSL_CB_EXIT = _lib.SSL_CB_EXIT
121SSL_CB_READ = _lib.SSL_CB_READ
122SSL_CB_WRITE = _lib.SSL_CB_WRITE
123SSL_CB_ALERT = _lib.SSL_CB_ALERT
124SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
125SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
126SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
127SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
128SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
129SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
130SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
131SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800132
Alex Gaynor83284952015-09-05 10:43:30 -0400133
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500134class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500135 """
136 An error occurred in an `OpenSSL.SSL` API.
137 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500138
139
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500140_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100141_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500142
143
144class WantReadError(Error):
145 pass
146
147
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500148class WantWriteError(Error):
149 pass
150
151
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500152class WantX509LookupError(Error):
153 pass
154
155
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500156class ZeroReturnError(Error):
157 pass
158
159
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500160class SysCallError(Error):
161 pass
162
163
Cory Benfield0ea76e72015-03-22 09:05:28 +0000164class _CallbackExceptionHelper(object):
165 """
166 A base class for wrapper classes that allow for intelligent exception
167 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500168
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400169 :ivar list _problems: Any exceptions that occurred while executing in a
170 context where they could not be raised in the normal way. Typically
171 this is because OpenSSL has called into some Python code and requires a
172 return value. The exceptions are saved to be raised later when it is
173 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000174 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400175
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400176 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800177 self._problems = []
178
Cory Benfield0ea76e72015-03-22 09:05:28 +0000179 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400180 """
181 Raise an exception from the OpenSSL error queue or that was previously
182 captured whe running a callback.
183 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000184 if self._problems:
185 try:
186 _raise_current_error()
187 except Error:
188 pass
189 raise self._problems.pop(0)
190
191
192class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400193 """
194 Wrap a callback such that it can be used as a certificate verification
195 callback.
196 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400197
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800198 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400199 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800200
201 @wraps(callback)
202 def wrapper(ok, store_ctx):
203 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500204 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
205 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
206 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800207
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400208 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
209 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
210 connection = Connection._reverse_mapping[ssl]
211
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800212 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400213 result = callback(
214 connection, cert, error_number, error_depth, ok
215 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800216 except Exception as e:
217 self._problems.append(e)
218 return 0
219 else:
220 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500221 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800222 return 1
223 else:
224 return 0
225
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500226 self.callback = _ffi.callback(
227 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800228
229
Cory Benfield0ea76e72015-03-22 09:05:28 +0000230class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400231 """
232 Wrap a callback such that it can be used as an NPN advertisement callback.
233 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400234
Cory Benfield0ea76e72015-03-22 09:05:28 +0000235 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400236 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800237
Cory Benfield0ea76e72015-03-22 09:05:28 +0000238 @wraps(callback)
239 def wrapper(ssl, out, outlen, arg):
240 try:
241 conn = Connection._reverse_mapping[ssl]
242 protos = callback(conn)
243
244 # Join the protocols into a Python bytestring, length-prefixing
245 # each element.
246 protostr = b''.join(
247 chain.from_iterable((int2byte(len(p)), p) for p in protos)
248 )
249
250 # Save our callback arguments on the connection object. This is
251 # done to make sure that they don't get freed before OpenSSL
252 # uses them. Then, return them appropriately in the output
253 # parameters.
254 conn._npn_advertise_callback_args = [
255 _ffi.new("unsigned int *", len(protostr)),
256 _ffi.new("unsigned char[]", protostr),
257 ]
258 outlen[0] = conn._npn_advertise_callback_args[0][0]
259 out[0] = conn._npn_advertise_callback_args[1]
260 return 0
261 except Exception as e:
262 self._problems.append(e)
263 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
264
265 self.callback = _ffi.callback(
266 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
267 wrapper
268 )
269
270
271class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400272 """
273 Wrap a callback such that it can be used as an NPN selection callback.
274 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400275
Cory Benfield0ea76e72015-03-22 09:05:28 +0000276 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400277 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000278
279 @wraps(callback)
280 def wrapper(ssl, out, outlen, in_, inlen, arg):
281 try:
282 conn = Connection._reverse_mapping[ssl]
283
284 # The string passed to us is actually made up of multiple
285 # length-prefixed bytestrings. We need to split that into a
286 # list.
287 instr = _ffi.buffer(in_, inlen)[:]
288 protolist = []
289 while instr:
290 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400291 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400293 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000294
295 # Call the callback
296 outstr = callback(conn, protolist)
297
298 # Save our callback arguments on the connection object. This is
299 # done to make sure that they don't get freed before OpenSSL
300 # uses them. Then, return them appropriately in the output
301 # parameters.
302 conn._npn_select_callback_args = [
303 _ffi.new("unsigned char *", len(outstr)),
304 _ffi.new("unsigned char[]", outstr),
305 ]
306 outlen[0] = conn._npn_select_callback_args[0][0]
307 out[0] = conn._npn_select_callback_args[1]
308 return 0
309 except Exception as e:
310 self._problems.append(e)
311 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
312
313 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400314 ("int (*)(SSL *, unsigned char **, unsigned char *, "
315 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000316 wrapper
317 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800318
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800319
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400320class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400321 """
322 Wrap a callback such that it can be used as an ALPN selection callback.
323 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400324
Cory Benfieldf1177e72015-04-12 09:11:49 -0400325 def __init__(self, callback):
326 _CallbackExceptionHelper.__init__(self)
327
328 @wraps(callback)
329 def wrapper(ssl, out, outlen, in_, inlen, arg):
330 try:
331 conn = Connection._reverse_mapping[ssl]
332
333 # The string passed to us is made up of multiple
334 # length-prefixed bytestrings. We need to split that into a
335 # list.
336 instr = _ffi.buffer(in_, inlen)[:]
337 protolist = []
338 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400339 encoded_len = indexbytes(instr, 0)
340 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400341 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400342 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400343
344 # Call the callback
345 outstr = callback(conn, protolist)
346
347 if not isinstance(outstr, _binary_type):
348 raise TypeError("ALPN callback must return a bytestring.")
349
350 # Save our callback arguments on the connection object to make
351 # sure that they don't get freed before OpenSSL can use them.
352 # Then, return them in the appropriate output parameters.
353 conn._alpn_select_callback_args = [
354 _ffi.new("unsigned char *", len(outstr)),
355 _ffi.new("unsigned char[]", outstr),
356 ]
357 outlen[0] = conn._alpn_select_callback_args[0][0]
358 out[0] = conn._alpn_select_callback_args[1]
359 return 0
360 except Exception as e:
361 self._problems.append(e)
362 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
363
364 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400365 ("int (*)(SSL *, unsigned char **, unsigned char *, "
366 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400367 wrapper
368 )
369
370
Cory Benfield496652a2017-01-24 11:42:56 +0000371class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
372 """
373 Wrap a callback such that it can be used as an OCSP callback for the server
374 side.
375
376 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
377 ways. For servers, that callback is expected to retrieve some OCSP data and
378 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
379 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
380 is expected to check the OCSP data, and returns a negative value on error,
381 0 if the response is not acceptable, or positive if it is. These are
382 mutually exclusive return code behaviours, and they mean that we need two
383 helpers so that we always return an appropriate error code if the user's
384 code throws an exception.
385
386 Given that we have to have two helpers anyway, these helpers are a bit more
387 helpery than most: specifically, they hide a few more of the OpenSSL
388 functions so that the user has an easier time writing these callbacks.
389
390 This helper implements the server side.
391 """
392
393 def __init__(self, callback):
394 _CallbackExceptionHelper.__init__(self)
395
396 @wraps(callback)
397 def wrapper(ssl, cdata):
398 try:
399 conn = Connection._reverse_mapping[ssl]
400
401 # Extract the data if any was provided.
402 if cdata != _ffi.NULL:
403 data = _ffi.from_handle(cdata)
404 else:
405 data = None
406
407 # Call the callback.
408 ocsp_data = callback(conn, data)
409
410 if not isinstance(ocsp_data, _binary_type):
411 raise TypeError("OCSP callback must return a bytestring.")
412
413 # If the OCSP data was provided, we will pass it to OpenSSL.
414 # However, we have an early exit here: if no OCSP data was
415 # provided we will just exit out and tell OpenSSL that there
416 # is nothing to do.
417 if not ocsp_data:
418 return 3 # SSL_TLSEXT_ERR_NOACK
419
420 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
421 # private copy of this data, so we need to keep it alive, but
422 # it *does* want to free it itself if it gets replaced. This
423 # somewhat bonkers behaviour means we need to use
424 # OPENSSL_malloc directly, which is a pain in the butt to work
425 # with. It's ok for us to "leak" the memory here because
426 # OpenSSL now owns it and will free it.
427 ocsp_data_length = len(ocsp_data)
428 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
429 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
430
431 _lib.SSL_set_tlsext_status_ocsp_resp(
432 ssl, data_ptr, ocsp_data_length
433 )
434
435 return 0
436 except Exception as e:
437 self._problems.append(e)
438 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
439
440 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
441
442
443class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
444 """
445 Wrap a callback such that it can be used as an OCSP callback for the client
446 side.
447
448 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
449 ways. For servers, that callback is expected to retrieve some OCSP data and
450 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
451 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
452 is expected to check the OCSP data, and returns a negative value on error,
453 0 if the response is not acceptable, or positive if it is. These are
454 mutually exclusive return code behaviours, and they mean that we need two
455 helpers so that we always return an appropriate error code if the user's
456 code throws an exception.
457
458 Given that we have to have two helpers anyway, these helpers are a bit more
459 helpery than most: specifically, they hide a few more of the OpenSSL
460 functions so that the user has an easier time writing these callbacks.
461
462 This helper implements the client side.
463 """
464
465 def __init__(self, callback):
466 _CallbackExceptionHelper.__init__(self)
467
468 @wraps(callback)
469 def wrapper(ssl, cdata):
470 try:
471 conn = Connection._reverse_mapping[ssl]
472
473 # Extract the data if any was provided.
474 if cdata != _ffi.NULL:
475 data = _ffi.from_handle(cdata)
476 else:
477 data = None
478
479 # Get the OCSP data.
480 ocsp_ptr = _ffi.new("unsigned char **")
481 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
482 if ocsp_len < 0:
483 # No OCSP data.
484 ocsp_data = b''
485 else:
486 # Copy the OCSP data, then pass it to the callback.
487 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
488
489 valid = callback(conn, ocsp_data, data)
490
491 # Return 1 on success or 0 on error.
492 return int(bool(valid))
493
494 except Exception as e:
495 self._problems.append(e)
496 # Return negative value if an exception is hit.
497 return -1
498
499 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
500
501
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800502def _asFileDescriptor(obj):
503 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800504 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800505 meth = getattr(obj, "fileno", None)
506 if meth is not None:
507 obj = meth()
508
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800509 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800510 fd = obj
511
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800512 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800513 raise TypeError("argument must be an int, or have a fileno() method.")
514 elif fd < 0:
515 raise ValueError(
516 "file descriptor cannot be a negative integer (%i)" % (fd,))
517
518 return fd
519
520
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800521def SSLeay_version(type):
522 """
523 Return a string describing the version of OpenSSL in use.
524
525 :param type: One of the SSLEAY_ constants defined in this module.
526 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500527 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800528
529
Cory Benfieldef404df2016-03-29 15:32:48 +0100530def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400531 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100532 Builds a decorator that ensures that functions that rely on OpenSSL
533 functions that are not present in this build raise NotImplementedError,
534 rather than AttributeError coming out of cryptography.
535
536 :param flag: A cryptography flag that guards the functions, e.g.
537 ``Cryptography_HAS_NEXTPROTONEG``.
538 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400539 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100540 def _requires_decorator(func):
541 if not flag:
542 @wraps(func)
543 def explode(*args, **kwargs):
544 raise NotImplementedError(error)
545 return explode
546 else:
547 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400548
Cory Benfieldef404df2016-03-29 15:32:48 +0100549 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400550
551
Cory Benfieldef404df2016-03-29 15:32:48 +0100552_requires_npn = _make_requires(
553 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
554)
Cory Benfield7907e332015-04-13 17:18:25 -0400555
556
Cory Benfieldef404df2016-03-29 15:32:48 +0100557_requires_alpn = _make_requires(
558 _lib.Cryptography_HAS_ALPN, "ALPN not available"
559)
Cory Benfielde6f35882016-03-29 11:21:04 +0100560
Cory Benfielde6f35882016-03-29 11:21:04 +0100561
Cory Benfieldef404df2016-03-29 15:32:48 +0100562_requires_sni = _make_requires(
563 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
564)
Cory Benfielde6f35882016-03-29 11:21:04 +0100565
566
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800567class Session(object):
568 pass
569
570
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800571class Context(object):
572 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100573 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400574 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800575 """
576 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800577 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500578 SSLv3_METHOD: "SSLv3_method",
579 SSLv23_METHOD: "SSLv23_method",
580 TLSv1_METHOD: "TLSv1_method",
581 TLSv1_1_METHOD: "TLSv1_1_method",
582 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400583 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500584 _methods = dict(
585 (identifier, getattr(_lib, name))
586 for (identifier, name) in _methods.items()
587 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800588
589 def __init__(self, method):
590 """
591 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
592 TLSv1_METHOD.
593 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500594 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800595 raise TypeError("method must be an integer")
596
597 try:
598 method_func = self._methods[method]
599 except KeyError:
600 raise ValueError("No such protocol")
601
602 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700603 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800604
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500605 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700606 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500607 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600609 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
610 # will be auto-selected. This function was added in 1.0.2 and made a
611 # noop in 1.1.0+ (where it is set automatically).
612 try:
613 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
614 _openssl_assert(res == 1)
615 except AttributeError:
616 pass
617
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800618 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800619 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800620 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800621 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800622 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800623 self._verify_callback = None
624 self._info_callback = None
625 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800626 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000627 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100628 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000629 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100630 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400631 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100632 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000633 self._ocsp_helper = None
634 self._ocsp_callback = None
635 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800636
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800637 # SSL_CTX_set_app_data(self->ctx, self);
638 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
639 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
640 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500641 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800642
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800643 def load_verify_locations(self, cafile, capath=None):
644 """
645 Let SSL know where we can find trusted certificates for the certificate
646 chain
647
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400648 :param cafile: In which file we can find the certificates (``bytes`` or
649 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800650 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400651 (``bytes`` or ``unicode``).
652
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800653 :return: None
654 """
655 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500656 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400657 else:
658 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800659
660 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500661 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400662 else:
663 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664
Alex Gaynor62da94d2015-09-05 14:37:34 -0400665 load_result = _lib.SSL_CTX_load_verify_locations(
666 self._context, cafile, capath
667 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800668 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500669 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800671 def _wrap_callback(self, callback):
672 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800673 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800674 return callback(size, verify, self._passphrase_userdata)
675 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800676 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800677
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800678 def set_passwd_cb(self, callback, userdata=None):
679 """
680 Set the passphrase callback
681
682 :param callback: The Python callback to use
683 :param userdata: (optional) A Python object which will be given as
684 argument to the callback
685 :return: None
686 """
687 if not callable(callback):
688 raise TypeError("callback must be callable")
689
690 self._passphrase_helper = self._wrap_callback(callback)
691 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500692 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693 self._context, self._passphrase_callback)
694 self._passphrase_userdata = userdata
695
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696 def set_default_verify_paths(self):
697 """
698 Use the platform-specific CA certificate locations
699
700 :return: None
701 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500702 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400703 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800704
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705 def use_certificate_chain_file(self, certfile):
706 """
707 Load a certificate chain from a file
708
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400709 :param certfile: The name of the certificate chain file (``bytes`` or
710 ``unicode``).
711
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712 :return: None
713 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400714 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800715
Alex Gaynor62da94d2015-09-05 14:37:34 -0400716 result = _lib.SSL_CTX_use_certificate_chain_file(
717 self._context, certfile
718 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800719 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500720 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800721
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800722 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800723 """
724 Load a certificate from a file
725
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400726 :param certfile: The name of the certificate file (``bytes`` or
727 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400729
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 :return: None
731 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400732 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500733 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800734 raise TypeError("filetype must be an integer")
735
Alex Gaynor62da94d2015-09-05 14:37:34 -0400736 use_result = _lib.SSL_CTX_use_certificate_file(
737 self._context, certfile, filetype
738 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800739 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500740 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800741
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800742 def use_certificate(self, cert):
743 """
744 Load a certificate from a X509 object
745
746 :param cert: The X509 object
747 :return: None
748 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800749 if not isinstance(cert, X509):
750 raise TypeError("cert must be an X509 instance")
751
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500752 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800753 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500754 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800755
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756 def add_extra_chain_cert(self, certobj):
757 """
758 Add certificate to chain
759
760 :param certobj: The X509 certificate object to add to the chain
761 :return: None
762 """
763 if not isinstance(certobj, X509):
764 raise TypeError("certobj must be an X509 instance")
765
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500766 copy = _lib.X509_dup(certobj._x509)
767 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800768 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500769 # TODO: This is untested.
770 _lib.X509_free(copy)
771 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800772
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800773 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500774 if self._passphrase_helper is not None:
775 self._passphrase_helper.raise_if_problem(Error)
776
777 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800778
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400779 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780 """
781 Load a private key from a file
782
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400783 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800784 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400785
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 :return: None
787 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400788 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400790 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500792 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793 raise TypeError("filetype must be an integer")
794
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500795 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800796 self._context, keyfile, filetype)
797 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800798 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800799
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800 def use_privatekey(self, pkey):
801 """
802 Load a private key from a PKey object
803
804 :param pkey: The PKey object
805 :return: None
806 """
807 if not isinstance(pkey, PKey):
808 raise TypeError("pkey must be a PKey instance")
809
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500810 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800811 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800812 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800813
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814 def check_privatekey(self):
815 """
816 Check that the private key and certificate match up
817
818 :return: None (raises an exception if something's wrong)
819 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500820 if not _lib.SSL_CTX_check_private_key(self._context):
821 _raise_current_error()
822
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800823 def load_client_ca(self, cafile):
824 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100825 Load the trusted certificates that will be sent to the client. Does
826 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400827 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800828
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100829 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800830 :return: None
831 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100832 ca_list = _lib.SSL_load_client_CA_file(
833 _text_to_bytes_and_warn("cafile", cafile)
834 )
835 _openssl_assert(ca_list != _ffi.NULL)
836 # SSL_CTX_set_client_CA_list doesn't return anything.
837 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800838
839 def set_session_id(self, buf):
840 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100841 Set the session id to *buf* within which a session can be reused for
842 this Context object. This is needed when doing session resumption,
843 because there is no way for a stored session to know which Context
844 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100846 :param bytes buf: The session id.
847
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800848 :returns: None
849 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100850 buf = _text_to_bytes_and_warn("buf", buf)
851 _openssl_assert(
852 _lib.SSL_CTX_set_session_id_context(
853 self._context,
854 buf,
855 len(buf),
856 ) == 1
857 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800858
859 def set_session_cache_mode(self, mode):
860 """
861 Enable/disable session caching and specify the mode used.
862
863 :param mode: One or more of the SESS_CACHE_* flags (combine using
864 bitwise or)
865 :returns: The previously set caching mode.
866 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500867 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868 raise TypeError("mode must be an integer")
869
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500870 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800871
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800872 def get_session_cache_mode(self):
873 """
874 :returns: The currently used cache mode.
875 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500876 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800877
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800878 def set_verify(self, mode, callback):
879 """
880 Set the verify mode and verify callback
881
882 :param mode: The verify mode, this is either VERIFY_NONE or
883 VERIFY_PEER combined with possible other flags
884 :param callback: The Python callback to use
885 :return: None
886
887 See SSL_CTX_set_verify(3SSL) for further details.
888 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500889 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800890 raise TypeError("mode must be an integer")
891
892 if not callable(callback):
893 raise TypeError("callback must be callable")
894
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400895 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800896 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500897 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899 def set_verify_depth(self, depth):
900 """
901 Set the verify depth
902
903 :param depth: An integer specifying the verify depth
904 :return: None
905 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500906 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 raise TypeError("depth must be an integer")
908
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500909 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911 def get_verify_mode(self):
912 """
913 Get the verify mode
914
915 :return: The verify mode
916 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500917 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800918
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919 def get_verify_depth(self):
920 """
921 Get the verify depth
922
923 :return: The verify depth
924 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500925 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800926
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927 def load_tmp_dh(self, dhfile):
928 """
929 Load parameters for Ephemeral Diffie-Hellman
930
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400931 :param dhfile: The file to load EDH parameters from (``bytes`` or
932 ``unicode``).
933
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800934 :return: None
935 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400936 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800937
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500938 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500939 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500940 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500941 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500943 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
944 dh = _ffi.gc(dh, _lib.DH_free)
945 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400947 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600948 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700949 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600950
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400951 :param curve: A curve object to use as returned by either
952 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
953 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700954
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600955 :return: None
956 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400957 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600958
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959 def set_cipher_list(self, cipher_list):
960 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100961 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100963 See the OpenSSL manual for more information (e.g.
964 :manpage:`ciphers(1)`).
965
966 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967 :return: None
968 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100969 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500970
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800971 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100972 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800973
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100974 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100975 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100976 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800977
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978 def set_client_ca_list(self, certificate_authorities):
979 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400980 Set the list of preferred client certificate signers for this server
981 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800982
Alex Gaynor62da94d2015-09-05 14:37:34 -0400983 This list of certificate authorities will be sent to the client when
984 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800985
986 :param certificate_authorities: a sequence of X509Names.
987 :return: None
988 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500989 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700990 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800991
992 try:
993 for ca_name in certificate_authorities:
994 if not isinstance(ca_name, X509Name):
995 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400996 "client CAs must be X509Name objects, not %s "
997 "objects" % (
998 type(ca_name).__name__,
999 )
1000 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001001 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001002 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001004 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001005 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001006 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001007 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001008 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001009 raise
1010
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001011 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001012
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001013 def add_client_ca(self, certificate_authority):
1014 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001015 Add the CA certificate to the list of preferred signers for this
1016 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017
1018 The list of certificate authorities will be sent to the client when the
1019 server requests a client certificate.
1020
1021 :param certificate_authority: certificate authority's X509 certificate.
1022 :return: None
1023 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001024 if not isinstance(certificate_authority, X509):
1025 raise TypeError("certificate_authority must be an X509 instance")
1026
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001027 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001028 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001029 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001030
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001031 def set_timeout(self, timeout):
1032 """
1033 Set session timeout
1034
1035 :param timeout: The timeout in seconds
1036 :return: The previous session timeout
1037 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001038 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039 raise TypeError("timeout must be an integer")
1040
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001041 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043 def get_timeout(self):
1044 """
1045 Get the session timeout
1046
1047 :return: The session timeout
1048 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001049 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001050
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051 def set_info_callback(self, callback):
1052 """
1053 Set the info callback
1054
1055 :param callback: The Python callback to use
1056 :return: None
1057 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001058 @wraps(callback)
1059 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001060 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001061 self._info_callback = _ffi.callback(
1062 "void (*)(const SSL *, int, int)", wrapper)
1063 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001064
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065 def get_app_data(self):
1066 """
1067 Get the application data (supplied via set_app_data())
1068
1069 :return: The application data
1070 """
1071 return self._app_data
1072
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001073 def set_app_data(self, data):
1074 """
1075 Set the application data (will be returned from get_app_data())
1076
1077 :param data: Any Python object
1078 :return: None
1079 """
1080 self._app_data = data
1081
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001082 def get_cert_store(self):
1083 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001084 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001085
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001086 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 store = _lib.SSL_CTX_get_cert_store(self._context)
1089 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001090 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001091 return None
1092
1093 pystore = X509Store.__new__(X509Store)
1094 pystore._store = store
1095 return pystore
1096
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001097 def set_options(self, options):
1098 """
1099 Add options. Options set before are not cleared!
1100
1101 :param options: The options to add.
1102 :return: The new option bitmask.
1103 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001104 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 raise TypeError("options must be an integer")
1106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001108
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109 def set_mode(self, mode):
1110 """
1111 Add modes via bitmask. Modes set before are not cleared!
1112
1113 :param mode: The mode to add.
1114 :return: The new mode bitmask.
1115 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001116 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001117 raise TypeError("mode must be an integer")
1118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001119 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001120
Cory Benfielde6f35882016-03-29 11:21:04 +01001121 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122 def set_tlsext_servername_callback(self, callback):
1123 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001124 Specify a callback function to be called when clients specify a server
1125 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001126
1127 :param callback: The callback function. It will be invoked with one
1128 argument, the Connection instance.
1129 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001130 @wraps(callback)
1131 def wrapper(ssl, alert, arg):
1132 callback(Connection._reverse_mapping[ssl])
1133 return 0
1134
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001135 self._tlsext_servername_callback = _ffi.callback(
1136 "int (*)(const SSL *, int *, void *)", wrapper)
1137 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001138 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001139
Cory Benfield10b277f2015-04-13 17:12:42 -04001140 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001141 def set_npn_advertise_callback(self, callback):
1142 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001143 Specify a callback function that will be called when offering `Next
1144 Protocol Negotiation
1145 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001146
1147 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001148 argument, the Connection instance. It should return a list of
1149 bytestrings representing the advertised protocols, like
1150 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001151 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001152 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1153 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001154 _lib.SSL_CTX_set_next_protos_advertised_cb(
1155 self._context, self._npn_advertise_callback, _ffi.NULL)
1156
Cory Benfield10b277f2015-04-13 17:12:42 -04001157 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001158 def set_npn_select_callback(self, callback):
1159 """
1160 Specify a callback function that will be called when a server offers
1161 Next Protocol Negotiation options.
1162
1163 :param callback: The callback function. It will be invoked with two
1164 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001165 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1166 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001167 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001168 self._npn_select_helper = _NpnSelectHelper(callback)
1169 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001170 _lib.SSL_CTX_set_next_proto_select_cb(
1171 self._context, self._npn_select_callback, _ffi.NULL)
1172
Cory Benfield7907e332015-04-13 17:18:25 -04001173 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001174 def set_alpn_protos(self, protos):
1175 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001176 Specify the clients ALPN protocol list.
1177
1178 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001179
1180 :param protos: A list of the protocols to be offered to the server.
1181 This list should be a Python list of bytestrings representing the
1182 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1183 """
1184 # Take the list of protocols and join them together, prefixing them
1185 # with their lengths.
1186 protostr = b''.join(
1187 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1188 )
1189
1190 # Build a C string from the list. We don't need to save this off
1191 # because OpenSSL immediately copies the data out.
1192 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001193 input_str_len = _ffi.cast("unsigned", len(protostr))
1194 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001195
Cory Benfield7907e332015-04-13 17:18:25 -04001196 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001197 def set_alpn_select_callback(self, callback):
1198 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001199 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001200
1201 :param callback: The callback function. It will be invoked with two
1202 arguments: the Connection, and a list of offered protocols as
1203 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001204 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001205 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001206 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001207 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001208 _lib.SSL_CTX_set_alpn_select_cb(
1209 self._context, self._alpn_select_callback, _ffi.NULL)
1210
Cory Benfield496652a2017-01-24 11:42:56 +00001211 def _set_ocsp_callback(self, helper, data):
1212 """
1213 This internal helper does the common work for
1214 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1215 almost all of it.
1216 """
1217 self._ocsp_helper = helper
1218 self._ocsp_callback = helper.callback
1219 if data is None:
1220 self._ocsp_data = _ffi.NULL
1221 else:
1222 self._ocsp_data = _ffi.new_handle(data)
1223
1224 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1225 self._context, self._ocsp_callback
1226 )
1227 _openssl_assert(rc == 1)
1228 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1229 _openssl_assert(rc == 1)
1230
1231 def set_ocsp_server_callback(self, callback, data=None):
1232 """
1233 Set a callback to provide OCSP data to be stapled to the TLS handshake
1234 on the server side.
1235
1236 :param callback: The callback function. It will be invoked with two
1237 arguments: the Connection, and the optional arbitrary data you have
1238 provided. The callback must return a bytestring that contains the
1239 OCSP data to staple to the handshake. If no OCSP data is available
1240 for this connection, return the empty bytestring.
1241 :param data: Some opaque data that will be passed into the callback
1242 function when called. This can be used to avoid needing to do
1243 complex data lookups or to keep track of what context is being
1244 used. This parameter is optional.
1245 """
1246 helper = _OCSPServerCallbackHelper(callback)
1247 self._set_ocsp_callback(helper, data)
1248
1249 def set_ocsp_client_callback(self, callback, data=None):
1250 """
1251 Set a callback to validate OCSP data stapled to the TLS handshake on
1252 the client side.
1253
1254 :param callback: The callback function. It will be invoked with three
1255 arguments: the Connection, a bytestring containing the stapled OCSP
1256 assertion, and the optional arbitrary data you have provided. The
1257 callback must return a boolean that indicates the result of
1258 validating the OCSP data: ``True`` if the OCSP data is valid and
1259 the certificate can be trusted, or ``False`` if either the OCSP
1260 data is invalid or the certificate has been revoked.
1261 :param data: Some opaque data that will be passed into the callback
1262 function when called. This can be used to avoid needing to do
1263 complex data lookups or to keep track of what context is being
1264 used. This parameter is optional.
1265 """
1266 helper = _OCSPClientCallbackHelper(callback)
1267 self._set_ocsp_callback(helper, data)
1268
Alex Chanc6077062016-11-18 13:53:39 +00001269
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001270ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001271
1272
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001273class Connection(object):
1274 """
1275 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001276 _reverse_mapping = WeakValueDictionary()
1277
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001278 def __init__(self, context, socket=None):
1279 """
1280 Create a new Connection object, using the given OpenSSL.SSL.Context
1281 instance and socket.
1282
1283 :param context: An SSL Context to use for this connection
1284 :param socket: The socket to use for transport layer
1285 """
1286 if not isinstance(context, Context):
1287 raise TypeError("context must be a Context instance")
1288
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001289 ssl = _lib.SSL_new(context._context)
1290 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001291 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001292 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001293
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001294 # References to strings used for Next Protocol Negotiation. OpenSSL's
1295 # header files suggest that these might get copied at some point, but
1296 # doesn't specify when, so we store them here to make sure they don't
1297 # get freed before OpenSSL uses them.
1298 self._npn_advertise_callback_args = None
1299 self._npn_select_callback_args = None
1300
Cory Benfield12eae892014-06-07 15:42:56 +01001301 # References to strings used for Application Layer Protocol
1302 # Negotiation. These strings get copied at some point but it's well
1303 # after the callback returns, so we have to hang them somewhere to
1304 # avoid them getting freed.
1305 self._alpn_select_callback_args = None
1306
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001307 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001308
1309 if socket is None:
1310 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001311 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001312 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001313 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001314
Alex Gaynora829e902016-06-04 18:16:01 -07001315 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1316 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001317
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001319 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001320 self._into_ssl = None
1321 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001322 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001323 set_result = _lib.SSL_set_fd(
1324 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001325 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001326
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001327 def __getattr__(self, name):
1328 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001329 Look up attributes on the wrapped socket object if they are not found
1330 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001331 """
kjav0b66fa12015-09-02 11:51:26 +01001332 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001333 raise AttributeError("'%s' object has no attribute '%s'" % (
1334 self.__class__.__name__, name
1335 ))
kjav0b66fa12015-09-02 11:51:26 +01001336 else:
1337 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001338
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001339 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001340 if self._context._verify_helper is not None:
1341 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001342 if self._context._npn_advertise_helper is not None:
1343 self._context._npn_advertise_helper.raise_if_problem()
1344 if self._context._npn_select_helper is not None:
1345 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001346 if self._context._alpn_select_helper is not None:
1347 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001348 if self._context._ocsp_helper is not None:
1349 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001350
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 error = _lib.SSL_get_error(ssl, result)
1352 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001353 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001355 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001356 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001357 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001358 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001359 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001360 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 elif error == _lib.SSL_ERROR_SYSCALL:
1362 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001363 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001364 if platform == "win32":
1365 errno = _ffi.getwinerror()[0]
1366 else:
1367 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001368
1369 if errno != 0:
1370 raise SysCallError(errno, errorcode.get(errno))
1371 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001372 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001373 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001374 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001375 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001376 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001377 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001378 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001379
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001380 def get_context(self):
1381 """
1382 Get session context
1383 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001384 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001385
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001386 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001387 """
1388 Switch this connection to a new session context
1389
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 :param context: A :py:class:`Context` instance giving the new session
1391 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001392 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001393 if not isinstance(context, Context):
1394 raise TypeError("context must be a Context instance")
1395
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001396 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001397 self._context = context
1398
Cory Benfielde6f35882016-03-29 11:21:04 +01001399 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001400 def get_servername(self):
1401 """
1402 Retrieve the servername extension value if provided in the client hello
1403 message, or None if there wasn't one.
1404
1405 :return: A byte string giving the server name or :py:data:`None`.
1406 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001407 name = _lib.SSL_get_servername(
1408 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1409 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001410 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001411 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001412
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001413 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001414
Cory Benfielde6f35882016-03-29 11:21:04 +01001415 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001416 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001417 """
1418 Set the value of the servername extension to send in the client hello.
1419
1420 :param name: A byte string giving the name.
1421 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001422 if not isinstance(name, bytes):
1423 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001424 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001425 raise TypeError("name must not contain NUL byte")
1426
1427 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001428 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001429
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001430 def pending(self):
1431 """
1432 Get the number of bytes that can be safely read from the connection
1433
1434 :return: The number of bytes available in the receive buffer.
1435 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001436 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001437
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001438 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001439 """
1440 Send data on the connection. NOTE: If you get one of the WantRead,
1441 WantWrite or WantX509Lookup exceptions on this, you have to call the
1442 method again with the SAME buffer.
1443
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001444 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001445 :param flags: (optional) Included for compatibility with the socket
1446 API, the value is ignored
1447 :return: The number of bytes written
1448 """
Abraham Martine82326c2015-02-04 10:18:10 +00001449 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001450 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001451
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001452 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001453 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001454 if isinstance(buf, _buffer):
1455 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001456 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001457 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001458
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001459 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001460 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001461 return result
1462 write = send
1463
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001464 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001465 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 Send "all" data on the connection. This calls send() repeatedly until
1467 all data is sent. If an error occurs, it's impossible to tell how much
1468 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001470 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001471 :param flags: (optional) Included for compatibility with the socket
1472 API, the value is ignored
1473 :return: The number of bytes written
1474 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001475 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001476
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001477 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001478 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001479 if isinstance(buf, _buffer):
1480 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001481 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001482 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001483
1484 left_to_send = len(buf)
1485 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001486 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001487
1488 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001489 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490 self._raise_ssl_error(self._ssl, result)
1491 total_sent += result
1492 left_to_send -= result
1493
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494 def recv(self, bufsiz, flags=None):
1495 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001496 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001497
1498 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001499 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1500 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001501 :return: The string read from the Connection
1502 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001503 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001504 if flags is not None and flags & socket.MSG_PEEK:
1505 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1506 else:
1507 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001508 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001509 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510 read = recv
1511
Cory Benfield62d10332014-06-15 10:03:41 +01001512 def recv_into(self, buffer, nbytes=None, flags=None):
1513 """
1514 Receive data on the connection and store the data into a buffer rather
1515 than creating a new string.
1516
1517 :param buffer: The buffer to copy into.
1518 :param nbytes: (optional) The maximum number of bytes to read into the
1519 buffer. If not present, defaults to the size of the buffer. If
1520 larger than the size of the buffer, is reduced to the size of the
1521 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001522 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1523 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001524 :return: The number of bytes read into the buffer.
1525 """
1526 if nbytes is None:
1527 nbytes = len(buffer)
1528 else:
1529 nbytes = min(nbytes, len(buffer))
1530
1531 # We need to create a temporary buffer. This is annoying, it would be
1532 # better if we could pass memoryviews straight into the SSL_read call,
1533 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001534 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001535 if flags is not None and flags & socket.MSG_PEEK:
1536 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1537 else:
1538 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001539 self._raise_ssl_error(self._ssl, result)
1540
1541 # This strange line is all to avoid a memory copy. The buffer protocol
1542 # should allow us to assign a CFFI buffer to the LHS of this line, but
1543 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1544 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1545 # memoryview type.
1546 try:
1547 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1548 except NameError:
1549 buffer[:result] = _ffi.buffer(buf, result)
1550
1551 return result
1552
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001553 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001554 if _lib.BIO_should_retry(bio):
1555 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001556 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001557 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001558 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001559 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001560 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001561 # TODO: This is untested. I think io_special means the socket
1562 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001563 raise ValueError("BIO_should_io_special")
1564 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001565 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001566 raise ValueError("unknown bio failure")
1567 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001568 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001569 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001570
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 When using non-socket connections this function reads the "dirty" data
1574 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001575
1576 :param bufsiz: The maximum number of bytes to read
1577 :return: The string read.
1578 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001579 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001582 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001583 raise TypeError("bufsiz must be an integer")
1584
Cory Benfielde62840e2016-11-28 12:17:08 +00001585 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001586 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001587 if result <= 0:
1588 self._handle_bio_errors(self._from_ssl, result)
1589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001590 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001591
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001593 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001594 When using non-socket connections this function sends "dirty" data that
1595 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596
1597 :param buf: The string to put into the memory BIO.
1598 :return: The number of bytes written
1599 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001600 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001601
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001602 if self._into_ssl is None:
1603 raise TypeError("Connection sock was not None")
1604
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001605 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001606 if result <= 0:
1607 self._handle_bio_errors(self._into_ssl, result)
1608 return result
1609
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610 def renegotiate(self):
1611 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001612 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001613
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001614 :return: True if the renegotiation can be started, False otherwise
1615 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001616 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001617 if not self.renegotiate_pending():
1618 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1619 return True
1620 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001621
1622 def do_handshake(self):
1623 """
1624 Perform an SSL handshake (usually called after renegotiate() or one of
1625 set_*_state()). This can raise the same exceptions as send and recv.
1626
1627 :return: None.
1628 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001629 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001630 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001632 def renegotiate_pending(self):
1633 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001634 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635 a renegotiation is finished.
1636
1637 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001638 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001639 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001640 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001641
1642 def total_renegotiations(self):
1643 """
1644 Find out the total number of renegotiations.
1645
1646 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001647 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001648 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001649 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001651 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001652 """
1653 Connect to remote host and set up client-side SSL
1654
1655 :param addr: A remote address
1656 :return: What the socket's connect method returns
1657 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001658 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001659 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001660
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001661 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001663 Connect to remote host and set up client-side SSL. Note that if the
1664 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665
1666 :param addr: A remove address
1667 :return: What the socket's connect_ex method returns
1668 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001669 connect_ex = self._socket.connect_ex
1670 self.set_connect_state()
1671 return connect_ex(addr)
1672
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 def accept(self):
1674 """
1675 Accept incoming connection and set up SSL on it
1676
1677 :return: A (conn,addr) pair where conn is a Connection and addr is an
1678 address
1679 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001680 client, addr = self._socket.accept()
1681 conn = Connection(self._context, client)
1682 conn.set_accept_state()
1683 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001685 def bio_shutdown(self):
1686 """
1687 When using non-socket connections this function signals end of
1688 data on the input for this connection.
1689
1690 :return: None
1691 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001692 if self._from_ssl is None:
1693 raise TypeError("Connection sock was not None")
1694
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001695 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001696
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697 def shutdown(self):
1698 """
1699 Send closure alert
1700
1701 :return: True if the shutdown completed successfully (i.e. both sides
1702 have sent closure alerts), false otherwise (i.e. you have to
1703 wait for a ZeroReturnError on a recv() method call
1704 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001705 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001706 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001707 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001708 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001709 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710 else:
1711 return False
1712
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001713 def get_cipher_list(self):
1714 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001715 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001716
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001717 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001718 """
1719 ciphers = []
1720 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001721 result = _lib.SSL_get_cipher_list(self._ssl, i)
1722 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001723 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001724 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 return ciphers
1726
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001727 def get_client_ca_list(self):
1728 """
1729 Get CAs whose certificates are suggested for client authentication.
1730
Alex Gaynor62da94d2015-09-05 14:37:34 -04001731 :return: If this is a server connection, a list of X509Names
1732 representing the acceptable CAs as set by
1733 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1734 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1735 connection, the list of such X509Names sent by the server, or an
1736 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001737 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001738 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1739 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001740 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001741 return []
1742
1743 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001744 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1745 name = _lib.sk_X509_NAME_value(ca_names, i)
1746 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001747 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001748
1749 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001750 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 result.append(pyname)
1752 return result
1753
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001754 def makefile(self):
1755 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001756 The makefile() method is not implemented, since there is no dup
1757 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001758
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001759 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001760 """
Alex Gaynor83284952015-09-05 10:43:30 -04001761 raise NotImplementedError(
1762 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001763
1764 def get_app_data(self):
1765 """
1766 Get application data
1767
1768 :return: The application data
1769 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001770 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001771
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001772 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001773 """
1774 Set application data
1775
1776 :param data - The application data
1777 :return: None
1778 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001779 self._app_data = data
1780
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001781 def get_shutdown(self):
1782 """
1783 Get shutdown state
1784
Alex Gaynor62da94d2015-09-05 14:37:34 -04001785 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1786 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001787 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001788 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001789
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001790 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001791 """
1792 Set shutdown state
1793
1794 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1795 :return: None
1796 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001797 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001798 raise TypeError("state must be an integer")
1799
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001800 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001801
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001802 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001803 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001804 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001805
1806 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001807 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001808 """
kjavc704a2e2015-09-07 12:12:27 +01001809 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001810
1811 def server_random(self):
1812 """
1813 Get a copy of the server hello nonce.
1814
1815 :return: A string representing the state
1816 """
Alex Gaynor93603062016-06-01 20:13:09 -07001817 session = _lib.SSL_get_session(self._ssl)
1818 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001819 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001820 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1821 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001822 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001823 _lib.SSL_get_server_random(self._ssl, outp, length)
1824 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001825
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001826 def client_random(self):
1827 """
1828 Get a copy of the client hello nonce.
1829
1830 :return: A string representing the state
1831 """
Alex Gaynor93603062016-06-01 20:13:09 -07001832 session = _lib.SSL_get_session(self._ssl)
1833 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001834 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001835
1836 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1837 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001838 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001839 _lib.SSL_get_client_random(self._ssl, outp, length)
1840 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001841
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001842 def master_key(self):
1843 """
1844 Get a copy of the master key.
1845
1846 :return: A string representing the state
1847 """
Alex Gaynor93603062016-06-01 20:13:09 -07001848 session = _lib.SSL_get_session(self._ssl)
1849 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001850 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001851
1852 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1853 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001854 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001855 _lib.SSL_SESSION_get_master_key(session, outp, length)
1856 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001858 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001859 """
1860 See shutdown(2)
1861
1862 :return: What the socket's shutdown() method returns
1863 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001864 return self._socket.shutdown(*args, **kwargs)
1865
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001866 def get_peer_certificate(self):
1867 """
1868 Retrieve the other side's certificate (if any)
1869
1870 :return: The peer's certificate
1871 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001872 cert = _lib.SSL_get_peer_certificate(self._ssl)
1873 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001874 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001875 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001876 return pycert
1877 return None
1878
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879 def get_peer_cert_chain(self):
1880 """
1881 Retrieve the other side's certificate (if any)
1882
1883 :return: A list of X509 instances giving the peer's certificate chain,
1884 or None if it does not have one.
1885 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1887 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001888 return None
1889
1890 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001891 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001892 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001893 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001894 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001895 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001896 result.append(pycert)
1897 return result
1898
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001899 def want_read(self):
1900 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001901 Checks if more data has to be read from the transport layer to complete
1902 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001903
1904 :return: True iff more data has to be read
1905 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001906 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001907
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001908 def want_write(self):
1909 """
1910 Checks if there is data to write to the transport layer to complete an
1911 operation.
1912
1913 :return: True iff there is data to write
1914 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001915 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 def set_accept_state(self):
1918 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001919 Set the connection to work in server mode. The handshake will be
1920 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001921
1922 :return: None
1923 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001924 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001925
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926 def set_connect_state(self):
1927 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001928 Set the connection to work in client mode. The handshake will be
1929 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930
1931 :return: None
1932 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001933 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001935 def get_session(self):
1936 """
1937 Returns the Session currently used.
1938
Alex Gaynor62da94d2015-09-05 14:37:34 -04001939 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1940 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001942 session = _lib.SSL_get1_session(self._ssl)
1943 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001944 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001945
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001946 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001947 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948 return pysession
1949
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001950 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001951 """
1952 Set the session to be used when the TLS/SSL connection is established.
1953
1954 :param session: A Session instance representing the session to use.
1955 :returns: None
1956 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001957 if not isinstance(session, Session):
1958 raise TypeError("session must be a Session instance")
1959
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001961 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001962 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001963
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001964 def _get_finished_message(self, function):
1965 """
1966 Helper to implement :py:meth:`get_finished` and
1967 :py:meth:`get_peer_finished`.
1968
1969 :param function: Either :py:data:`SSL_get_finished`: or
1970 :py:data:`SSL_get_peer_finished`.
1971
1972 :return: :py:data:`None` if the desired message has not yet been
1973 received, otherwise the contents of the message.
1974 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1975 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001976 # The OpenSSL documentation says nothing about what might happen if the
1977 # count argument given is zero. Specifically, it doesn't say whether
1978 # the output buffer may be NULL in that case or not. Inspection of the
1979 # implementation reveals that it calls memcpy() unconditionally.
1980 # Section 7.1.4, paragraph 1 of the C standard suggests that
1981 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1982 # alone desirable) behavior (though it probably does on just about
1983 # every implementation...)
1984 #
1985 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1986 # one might expect) for the initial call so as to be safe against this
1987 # potentially undefined behavior.
1988 empty = _ffi.new("char[]", 0)
1989 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001990 if size == 0:
1991 # No Finished message so far.
1992 return None
1993
Cory Benfielde62840e2016-11-28 12:17:08 +00001994 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001995 function(self._ssl, buf, size)
1996 return _ffi.buffer(buf, size)[:]
1997
Fedor Brunner5747b932014-03-05 14:22:34 +01001998 def get_finished(self):
1999 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002000 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002001
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002002 :return: The contents of the message or :py:obj:`None` if the TLS
2003 handshake has not yet completed.
2004 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002005 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002006 return self._get_finished_message(_lib.SSL_get_finished)
2007
Fedor Brunner5747b932014-03-05 14:22:34 +01002008 def get_peer_finished(self):
2009 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002010 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002011
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002012 :return: The contents of the message or :py:obj:`None` if the TLS
2013 handshake has not yet completed.
2014 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002015 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002016 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002017
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002018 def get_cipher_name(self):
2019 """
2020 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002021
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002022 :returns: The name of the currently used cipher or :py:obj:`None`
2023 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002024 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002025 """
2026 cipher = _lib.SSL_get_current_cipher(self._ssl)
2027 if cipher == _ffi.NULL:
2028 return None
2029 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002030 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2031 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002032
2033 def get_cipher_bits(self):
2034 """
2035 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002036
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002037 :returns: The number of secret bits of the currently used cipher
2038 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002039 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002040 """
2041 cipher = _lib.SSL_get_current_cipher(self._ssl)
2042 if cipher == _ffi.NULL:
2043 return None
2044 else:
2045 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2046
2047 def get_cipher_version(self):
2048 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002049 Obtain the protocol version of the currently used cipher.
2050
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002051 :returns: The protocol name of the currently used cipher
2052 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002053 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002054 """
2055 cipher = _lib.SSL_get_current_cipher(self._ssl)
2056 if cipher == _ffi.NULL:
2057 return None
2058 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002059 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002060 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002061
Jim Shaverabff1882015-05-27 09:15:55 -04002062 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002063 """
2064 Obtain the protocol version of the current connection.
2065
2066 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002067 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002068 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002069 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002070 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002071 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002072 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002073
Jim Shaver208438c2015-05-28 09:52:38 -04002074 def get_protocol_version(self):
2075 """
2076 Obtain the protocol version of the current connection.
2077
2078 :returns: The TLS version of the current connection, for example
2079 the value for TLS 1 would be 0x769.
2080 :rtype: :py:class:`int`
2081 """
2082 version = _lib.SSL_version(self._ssl)
2083 return version
2084
Cory Benfield10b277f2015-04-13 17:12:42 -04002085 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002086 def get_next_proto_negotiated(self):
2087 """
2088 Get the protocol that was negotiated by NPN.
2089 """
2090 data = _ffi.new("unsigned char **")
2091 data_len = _ffi.new("unsigned int *")
2092
2093 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2094
Cory Benfieldcd010f62014-05-15 19:00:27 +01002095 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002096
Cory Benfield7907e332015-04-13 17:18:25 -04002097 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002098 def set_alpn_protos(self, protos):
2099 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002100 Specify the client's ALPN protocol list.
2101
2102 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002103
2104 :param protos: A list of the protocols to be offered to the server.
2105 This list should be a Python list of bytestrings representing the
2106 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2107 """
2108 # Take the list of protocols and join them together, prefixing them
2109 # with their lengths.
2110 protostr = b''.join(
2111 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2112 )
2113
2114 # Build a C string from the list. We don't need to save this off
2115 # because OpenSSL immediately copies the data out.
2116 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04002117 input_str_len = _ffi.cast("unsigned", len(protostr))
2118 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01002119
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002120 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002121 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002122 """
2123 Get the protocol that was negotiated by ALPN.
2124 """
Cory Benfield12eae892014-06-07 15:42:56 +01002125 data = _ffi.new("unsigned char **")
2126 data_len = _ffi.new("unsigned int *")
2127
2128 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2129
Cory Benfielde8e9c382015-04-11 17:33:48 -04002130 if not data_len:
2131 return b''
2132
Cory Benfield12eae892014-06-07 15:42:56 +01002133 return _ffi.buffer(data[0], data_len[0])[:]
2134
Cory Benfield496652a2017-01-24 11:42:56 +00002135 def request_ocsp(self):
2136 """
2137 Called to request that the server sends stapled OCSP data, if
2138 available. If this is not called on the client side then the server
2139 will not send OCSP data. Should be used in conjunction with
2140 :meth:`Context.set_ocsp_client_callback`.
2141 """
2142 rc = _lib.SSL_set_tlsext_status_type(
2143 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2144 )
2145 _openssl_assert(rc == 1)
2146
Cory Benfield12eae892014-06-07 15:42:56 +01002147
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002148ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002149
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002150# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2151# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002152_lib.SSL_library_init()