blob: 003ed43ce68888ed477b46ebc13ab47ff56effb2 [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):
774 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500775 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800776 exception = self._passphrase_helper.raise_if_problem(Error)
777 if exception is not None:
778 raise exception
779
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400780 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800781 """
782 Load a private key from a file
783
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400784 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400786
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787 :return: None
788 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400789 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400791 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500793 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 raise TypeError("filetype must be an integer")
795
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500796 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800797 self._context, keyfile, filetype)
798 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800799 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801 def use_privatekey(self, pkey):
802 """
803 Load a private key from a PKey object
804
805 :param pkey: The PKey object
806 :return: None
807 """
808 if not isinstance(pkey, PKey):
809 raise TypeError("pkey must be a PKey instance")
810
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800812 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800813 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800814
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815 def check_privatekey(self):
816 """
817 Check that the private key and certificate match up
818
819 :return: None (raises an exception if something's wrong)
820 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500821 if not _lib.SSL_CTX_check_private_key(self._context):
822 _raise_current_error()
823
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800824 def load_client_ca(self, cafile):
825 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100826 Load the trusted certificates that will be sent to the client. Does
827 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400828 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100830 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800831 :return: None
832 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100833 ca_list = _lib.SSL_load_client_CA_file(
834 _text_to_bytes_and_warn("cafile", cafile)
835 )
836 _openssl_assert(ca_list != _ffi.NULL)
837 # SSL_CTX_set_client_CA_list doesn't return anything.
838 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800839
840 def set_session_id(self, buf):
841 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100842 Set the session id to *buf* within which a session can be reused for
843 this Context object. This is needed when doing session resumption,
844 because there is no way for a stored session to know which Context
845 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800846
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100847 :param bytes buf: The session id.
848
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800849 :returns: None
850 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100851 buf = _text_to_bytes_and_warn("buf", buf)
852 _openssl_assert(
853 _lib.SSL_CTX_set_session_id_context(
854 self._context,
855 buf,
856 len(buf),
857 ) == 1
858 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800859
860 def set_session_cache_mode(self, mode):
861 """
862 Enable/disable session caching and specify the mode used.
863
864 :param mode: One or more of the SESS_CACHE_* flags (combine using
865 bitwise or)
866 :returns: The previously set caching mode.
867 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500868 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800869 raise TypeError("mode must be an integer")
870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500871 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800872
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873 def get_session_cache_mode(self):
874 """
875 :returns: The currently used cache mode.
876 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500877 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800878
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800879 def set_verify(self, mode, callback):
880 """
881 Set the verify mode and verify callback
882
883 :param mode: The verify mode, this is either VERIFY_NONE or
884 VERIFY_PEER combined with possible other flags
885 :param callback: The Python callback to use
886 :return: None
887
888 See SSL_CTX_set_verify(3SSL) for further details.
889 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500890 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891 raise TypeError("mode must be an integer")
892
893 if not callable(callback):
894 raise TypeError("callback must be callable")
895
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400896 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800897 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500898 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900 def set_verify_depth(self, depth):
901 """
902 Set the verify depth
903
904 :param depth: An integer specifying the verify depth
905 :return: None
906 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500907 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908 raise TypeError("depth must be an integer")
909
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500910 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800911
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912 def get_verify_mode(self):
913 """
914 Get the verify mode
915
916 :return: The verify mode
917 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500918 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920 def get_verify_depth(self):
921 """
922 Get the verify depth
923
924 :return: The verify depth
925 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500926 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800928 def load_tmp_dh(self, dhfile):
929 """
930 Load parameters for Ephemeral Diffie-Hellman
931
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400932 :param dhfile: The file to load EDH parameters from (``bytes`` or
933 ``unicode``).
934
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800935 :return: None
936 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400937 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800938
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500939 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500940 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500941 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500942 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500944 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
945 dh = _ffi.gc(dh, _lib.DH_free)
946 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800947
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400948 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600949 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700950 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600951
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400952 :param curve: A curve object to use as returned by either
953 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
954 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700955
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600956 :return: None
957 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400958 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600959
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960 def set_cipher_list(self, cipher_list):
961 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100962 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800963
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100964 See the OpenSSL manual for more information (e.g.
965 :manpage:`ciphers(1)`).
966
967 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800968 :return: None
969 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100970 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500971
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800972 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100973 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800974
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100975 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100976 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100977 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800978
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979 def set_client_ca_list(self, certificate_authorities):
980 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400981 Set the list of preferred client certificate signers for this server
982 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800983
Alex Gaynor62da94d2015-09-05 14:37:34 -0400984 This list of certificate authorities will be sent to the client when
985 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986
987 :param certificate_authorities: a sequence of X509Names.
988 :return: None
989 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500990 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700991 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800992
993 try:
994 for ca_name in certificate_authorities:
995 if not isinstance(ca_name, X509Name):
996 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400997 "client CAs must be X509Name objects, not %s "
998 "objects" % (
999 type(ca_name).__name__,
1000 )
1001 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001002 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001003 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001005 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001006 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001007 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001008 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001009 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001010 raise
1011
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001012 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001013
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014 def add_client_ca(self, certificate_authority):
1015 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001016 Add the CA certificate to the list of preferred signers for this
1017 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001018
1019 The list of certificate authorities will be sent to the client when the
1020 server requests a client certificate.
1021
1022 :param certificate_authority: certificate authority's X509 certificate.
1023 :return: None
1024 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001025 if not isinstance(certificate_authority, X509):
1026 raise TypeError("certificate_authority must be an X509 instance")
1027
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001028 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001029 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001030 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001031
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001032 def set_timeout(self, timeout):
1033 """
1034 Set session timeout
1035
1036 :param timeout: The timeout in seconds
1037 :return: The previous session timeout
1038 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001039 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001040 raise TypeError("timeout must be an integer")
1041
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001042 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001043
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001044 def get_timeout(self):
1045 """
1046 Get the session timeout
1047
1048 :return: The session timeout
1049 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001050 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001051
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001052 def set_info_callback(self, callback):
1053 """
1054 Set the info callback
1055
1056 :param callback: The Python callback to use
1057 :return: None
1058 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001059 @wraps(callback)
1060 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001061 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001062 self._info_callback = _ffi.callback(
1063 "void (*)(const SSL *, int, int)", wrapper)
1064 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001065
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001066 def get_app_data(self):
1067 """
1068 Get the application data (supplied via set_app_data())
1069
1070 :return: The application data
1071 """
1072 return self._app_data
1073
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001074 def set_app_data(self, data):
1075 """
1076 Set the application data (will be returned from get_app_data())
1077
1078 :param data: Any Python object
1079 :return: None
1080 """
1081 self._app_data = data
1082
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001083 def get_cert_store(self):
1084 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001085 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001086
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001087 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001088 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001089 store = _lib.SSL_CTX_get_cert_store(self._context)
1090 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001091 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001092 return None
1093
1094 pystore = X509Store.__new__(X509Store)
1095 pystore._store = store
1096 return pystore
1097
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001098 def set_options(self, options):
1099 """
1100 Add options. Options set before are not cleared!
1101
1102 :param options: The options to add.
1103 :return: The new option bitmask.
1104 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001105 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001106 raise TypeError("options must be an integer")
1107
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001108 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001109
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001110 def set_mode(self, mode):
1111 """
1112 Add modes via bitmask. Modes set before are not cleared!
1113
1114 :param mode: The mode to add.
1115 :return: The new mode bitmask.
1116 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001117 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001118 raise TypeError("mode must be an integer")
1119
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001120 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001121
Cory Benfielde6f35882016-03-29 11:21:04 +01001122 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001123 def set_tlsext_servername_callback(self, callback):
1124 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001125 Specify a callback function to be called when clients specify a server
1126 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001127
1128 :param callback: The callback function. It will be invoked with one
1129 argument, the Connection instance.
1130 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001131 @wraps(callback)
1132 def wrapper(ssl, alert, arg):
1133 callback(Connection._reverse_mapping[ssl])
1134 return 0
1135
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001136 self._tlsext_servername_callback = _ffi.callback(
1137 "int (*)(const SSL *, int *, void *)", wrapper)
1138 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001139 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001140
Cory Benfield10b277f2015-04-13 17:12:42 -04001141 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001142 def set_npn_advertise_callback(self, callback):
1143 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001144 Specify a callback function that will be called when offering `Next
1145 Protocol Negotiation
1146 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001147
1148 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001149 argument, the Connection instance. It should return a list of
1150 bytestrings representing the advertised protocols, like
1151 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001152 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001153 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1154 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001155 _lib.SSL_CTX_set_next_protos_advertised_cb(
1156 self._context, self._npn_advertise_callback, _ffi.NULL)
1157
Cory Benfield10b277f2015-04-13 17:12:42 -04001158 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001159 def set_npn_select_callback(self, callback):
1160 """
1161 Specify a callback function that will be called when a server offers
1162 Next Protocol Negotiation options.
1163
1164 :param callback: The callback function. It will be invoked with two
1165 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001166 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1167 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001168 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001169 self._npn_select_helper = _NpnSelectHelper(callback)
1170 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001171 _lib.SSL_CTX_set_next_proto_select_cb(
1172 self._context, self._npn_select_callback, _ffi.NULL)
1173
Cory Benfield7907e332015-04-13 17:18:25 -04001174 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001175 def set_alpn_protos(self, protos):
1176 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001177 Specify the clients ALPN protocol list.
1178
1179 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001180
1181 :param protos: A list of the protocols to be offered to the server.
1182 This list should be a Python list of bytestrings representing the
1183 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1184 """
1185 # Take the list of protocols and join them together, prefixing them
1186 # with their lengths.
1187 protostr = b''.join(
1188 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1189 )
1190
1191 # Build a C string from the list. We don't need to save this off
1192 # because OpenSSL immediately copies the data out.
1193 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001194 input_str_len = _ffi.cast("unsigned", len(protostr))
1195 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001196
Cory Benfield7907e332015-04-13 17:18:25 -04001197 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001198 def set_alpn_select_callback(self, callback):
1199 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001200 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001201
1202 :param callback: The callback function. It will be invoked with two
1203 arguments: the Connection, and a list of offered protocols as
1204 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001205 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001206 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001207 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001208 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001209 _lib.SSL_CTX_set_alpn_select_cb(
1210 self._context, self._alpn_select_callback, _ffi.NULL)
1211
Cory Benfield496652a2017-01-24 11:42:56 +00001212 def _set_ocsp_callback(self, helper, data):
1213 """
1214 This internal helper does the common work for
1215 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1216 almost all of it.
1217 """
1218 self._ocsp_helper = helper
1219 self._ocsp_callback = helper.callback
1220 if data is None:
1221 self._ocsp_data = _ffi.NULL
1222 else:
1223 self._ocsp_data = _ffi.new_handle(data)
1224
1225 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1226 self._context, self._ocsp_callback
1227 )
1228 _openssl_assert(rc == 1)
1229 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1230 _openssl_assert(rc == 1)
1231
1232 def set_ocsp_server_callback(self, callback, data=None):
1233 """
1234 Set a callback to provide OCSP data to be stapled to the TLS handshake
1235 on the server side.
1236
1237 :param callback: The callback function. It will be invoked with two
1238 arguments: the Connection, and the optional arbitrary data you have
1239 provided. The callback must return a bytestring that contains the
1240 OCSP data to staple to the handshake. If no OCSP data is available
1241 for this connection, return the empty bytestring.
1242 :param data: Some opaque data that will be passed into the callback
1243 function when called. This can be used to avoid needing to do
1244 complex data lookups or to keep track of what context is being
1245 used. This parameter is optional.
1246 """
1247 helper = _OCSPServerCallbackHelper(callback)
1248 self._set_ocsp_callback(helper, data)
1249
1250 def set_ocsp_client_callback(self, callback, data=None):
1251 """
1252 Set a callback to validate OCSP data stapled to the TLS handshake on
1253 the client side.
1254
1255 :param callback: The callback function. It will be invoked with three
1256 arguments: the Connection, a bytestring containing the stapled OCSP
1257 assertion, and the optional arbitrary data you have provided. The
1258 callback must return a boolean that indicates the result of
1259 validating the OCSP data: ``True`` if the OCSP data is valid and
1260 the certificate can be trusted, or ``False`` if either the OCSP
1261 data is invalid or the certificate has been revoked.
1262 :param data: Some opaque data that will be passed into the callback
1263 function when called. This can be used to avoid needing to do
1264 complex data lookups or to keep track of what context is being
1265 used. This parameter is optional.
1266 """
1267 helper = _OCSPClientCallbackHelper(callback)
1268 self._set_ocsp_callback(helper, data)
1269
Alex Chanc6077062016-11-18 13:53:39 +00001270
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001271ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001272
1273
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001274class Connection(object):
1275 """
1276 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001277 _reverse_mapping = WeakValueDictionary()
1278
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001279 def __init__(self, context, socket=None):
1280 """
1281 Create a new Connection object, using the given OpenSSL.SSL.Context
1282 instance and socket.
1283
1284 :param context: An SSL Context to use for this connection
1285 :param socket: The socket to use for transport layer
1286 """
1287 if not isinstance(context, Context):
1288 raise TypeError("context must be a Context instance")
1289
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001290 ssl = _lib.SSL_new(context._context)
1291 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001292 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001293 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001294
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001295 # References to strings used for Next Protocol Negotiation. OpenSSL's
1296 # header files suggest that these might get copied at some point, but
1297 # doesn't specify when, so we store them here to make sure they don't
1298 # get freed before OpenSSL uses them.
1299 self._npn_advertise_callback_args = None
1300 self._npn_select_callback_args = None
1301
Cory Benfield12eae892014-06-07 15:42:56 +01001302 # References to strings used for Application Layer Protocol
1303 # Negotiation. These strings get copied at some point but it's well
1304 # after the callback returns, so we have to hang them somewhere to
1305 # avoid them getting freed.
1306 self._alpn_select_callback_args = None
1307
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001308 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001309
1310 if socket is None:
1311 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001312 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001313 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001314 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001315
Alex Gaynora829e902016-06-04 18:16:01 -07001316 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1317 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001318
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001319 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001320 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001321 self._into_ssl = None
1322 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001323 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001324 set_result = _lib.SSL_set_fd(
1325 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001326 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001327
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001328 def __getattr__(self, name):
1329 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001330 Look up attributes on the wrapped socket object if they are not found
1331 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001332 """
kjav0b66fa12015-09-02 11:51:26 +01001333 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001334 raise AttributeError("'%s' object has no attribute '%s'" % (
1335 self.__class__.__name__, name
1336 ))
kjav0b66fa12015-09-02 11:51:26 +01001337 else:
1338 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001339
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001340 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001341 if self._context._verify_helper is not None:
1342 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001343 if self._context._npn_advertise_helper is not None:
1344 self._context._npn_advertise_helper.raise_if_problem()
1345 if self._context._npn_select_helper is not None:
1346 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001347 if self._context._alpn_select_helper is not None:
1348 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001349 if self._context._ocsp_helper is not None:
1350 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001351
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001352 error = _lib.SSL_get_error(ssl, result)
1353 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001354 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001355 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001356 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001357 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001358 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001359 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001360 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001361 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001362 elif error == _lib.SSL_ERROR_SYSCALL:
1363 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001364 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001365 if platform == "win32":
1366 errno = _ffi.getwinerror()[0]
1367 else:
1368 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001369
1370 if errno != 0:
1371 raise SysCallError(errno, errorcode.get(errno))
1372 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001373 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001374 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001375 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001376 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001377 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001378 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001379 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001380
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001381 def get_context(self):
1382 """
1383 Get session context
1384 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001386
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001387 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001388 """
1389 Switch this connection to a new session context
1390
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001391 :param context: A :py:class:`Context` instance giving the new session
1392 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001393 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001394 if not isinstance(context, Context):
1395 raise TypeError("context must be a Context instance")
1396
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001397 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001398 self._context = context
1399
Cory Benfielde6f35882016-03-29 11:21:04 +01001400 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001401 def get_servername(self):
1402 """
1403 Retrieve the servername extension value if provided in the client hello
1404 message, or None if there wasn't one.
1405
1406 :return: A byte string giving the server name or :py:data:`None`.
1407 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001408 name = _lib.SSL_get_servername(
1409 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1410 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001411 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001412 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001413
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001414 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001415
Cory Benfielde6f35882016-03-29 11:21:04 +01001416 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001417 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001418 """
1419 Set the value of the servername extension to send in the client hello.
1420
1421 :param name: A byte string giving the name.
1422 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001423 if not isinstance(name, bytes):
1424 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001425 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001426 raise TypeError("name must not contain NUL byte")
1427
1428 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001429 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001430
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001431 def pending(self):
1432 """
1433 Get the number of bytes that can be safely read from the connection
1434
1435 :return: The number of bytes available in the receive buffer.
1436 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001437 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001438
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001439 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001440 """
1441 Send data on the connection. NOTE: If you get one of the WantRead,
1442 WantWrite or WantX509Lookup exceptions on this, you have to call the
1443 method again with the SAME buffer.
1444
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001445 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001446 :param flags: (optional) Included for compatibility with the socket
1447 API, the value is ignored
1448 :return: The number of bytes written
1449 """
Abraham Martine82326c2015-02-04 10:18:10 +00001450 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001451 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001452
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001453 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001454 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001455 if isinstance(buf, _buffer):
1456 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001457 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001458 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001459
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001460 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001461 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001462 return result
1463 write = send
1464
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001466 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 Send "all" data on the connection. This calls send() repeatedly until
1468 all data is sent. If an error occurs, it's impossible to tell how much
1469 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001471 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001472 :param flags: (optional) Included for compatibility with the socket
1473 API, the value is ignored
1474 :return: The number of bytes written
1475 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001476 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001477
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001478 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001479 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001480 if isinstance(buf, _buffer):
1481 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001482 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001483 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001484
1485 left_to_send = len(buf)
1486 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001487 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001488
1489 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001490 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001491 self._raise_ssl_error(self._ssl, result)
1492 total_sent += result
1493 left_to_send -= result
1494
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495 def recv(self, bufsiz, flags=None):
1496 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001497 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498
1499 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001500 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1501 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001502 :return: The string read from the Connection
1503 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001504 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001505 if flags is not None and flags & socket.MSG_PEEK:
1506 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1507 else:
1508 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001509 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001510 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001511 read = recv
1512
Cory Benfield62d10332014-06-15 10:03:41 +01001513 def recv_into(self, buffer, nbytes=None, flags=None):
1514 """
1515 Receive data on the connection and store the data into a buffer rather
1516 than creating a new string.
1517
1518 :param buffer: The buffer to copy into.
1519 :param nbytes: (optional) The maximum number of bytes to read into the
1520 buffer. If not present, defaults to the size of the buffer. If
1521 larger than the size of the buffer, is reduced to the size of the
1522 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001523 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1524 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001525 :return: The number of bytes read into the buffer.
1526 """
1527 if nbytes is None:
1528 nbytes = len(buffer)
1529 else:
1530 nbytes = min(nbytes, len(buffer))
1531
1532 # We need to create a temporary buffer. This is annoying, it would be
1533 # better if we could pass memoryviews straight into the SSL_read call,
1534 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001535 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001536 if flags is not None and flags & socket.MSG_PEEK:
1537 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1538 else:
1539 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001540 self._raise_ssl_error(self._ssl, result)
1541
1542 # This strange line is all to avoid a memory copy. The buffer protocol
1543 # should allow us to assign a CFFI buffer to the LHS of this line, but
1544 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1545 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1546 # memoryview type.
1547 try:
1548 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1549 except NameError:
1550 buffer[:result] = _ffi.buffer(buf, result)
1551
1552 return result
1553
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001554 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001555 if _lib.BIO_should_retry(bio):
1556 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001557 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001558 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001559 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001560 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001561 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001562 # TODO: This is untested. I think io_special means the socket
1563 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001564 raise ValueError("BIO_should_io_special")
1565 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001566 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001567 raise ValueError("unknown bio failure")
1568 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001569 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001570 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001572 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001573 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001574 When using non-socket connections this function reads the "dirty" data
1575 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576
1577 :param bufsiz: The maximum number of bytes to read
1578 :return: The string read.
1579 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001580 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001582
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001583 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 raise TypeError("bufsiz must be an integer")
1585
Cory Benfielde62840e2016-11-28 12:17:08 +00001586 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001587 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001588 if result <= 0:
1589 self._handle_bio_errors(self._from_ssl, result)
1590
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001591 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001593 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001595 When using non-socket connections this function sends "dirty" data that
1596 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597
1598 :param buf: The string to put into the memory BIO.
1599 :return: The number of bytes written
1600 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001601 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001602
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001603 if self._into_ssl is None:
1604 raise TypeError("Connection sock was not None")
1605
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001606 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 if result <= 0:
1608 self._handle_bio_errors(self._into_ssl, result)
1609 return result
1610
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001611 def renegotiate(self):
1612 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001613 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001614
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001615 :return: True if the renegotiation can be started, False otherwise
1616 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001617 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001618 if not self.renegotiate_pending():
1619 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1620 return True
1621 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001622
1623 def do_handshake(self):
1624 """
1625 Perform an SSL handshake (usually called after renegotiate() or one of
1626 set_*_state()). This can raise the same exceptions as send and recv.
1627
1628 :return: None.
1629 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001630 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001631 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001632
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633 def renegotiate_pending(self):
1634 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001635 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001636 a renegotiation is finished.
1637
1638 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001639 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001640 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001641 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001642
1643 def total_renegotiations(self):
1644 """
1645 Find out the total number of renegotiations.
1646
1647 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001648 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001649 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001650 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001651
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001652 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001653 """
1654 Connect to remote host and set up client-side SSL
1655
1656 :param addr: A remote address
1657 :return: What the socket's connect method returns
1658 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001659 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001660 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001661
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001664 Connect to remote host and set up client-side SSL. Note that if the
1665 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001666
1667 :param addr: A remove address
1668 :return: What the socket's connect_ex method returns
1669 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670 connect_ex = self._socket.connect_ex
1671 self.set_connect_state()
1672 return connect_ex(addr)
1673
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001674 def accept(self):
1675 """
1676 Accept incoming connection and set up SSL on it
1677
1678 :return: A (conn,addr) pair where conn is a Connection and addr is an
1679 address
1680 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681 client, addr = self._socket.accept()
1682 conn = Connection(self._context, client)
1683 conn.set_accept_state()
1684 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001685
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 def bio_shutdown(self):
1687 """
1688 When using non-socket connections this function signals end of
1689 data on the input for this connection.
1690
1691 :return: None
1692 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693 if self._from_ssl is None:
1694 raise TypeError("Connection sock was not None")
1695
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001696 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001697
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001698 def shutdown(self):
1699 """
1700 Send closure alert
1701
1702 :return: True if the shutdown completed successfully (i.e. both sides
1703 have sent closure alerts), false otherwise (i.e. you have to
1704 wait for a ZeroReturnError on a recv() method call
1705 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001706 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001707 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001708 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001709 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001710 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 else:
1712 return False
1713
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001714 def get_cipher_list(self):
1715 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001716 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001717
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001718 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719 """
1720 ciphers = []
1721 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001722 result = _lib.SSL_get_cipher_list(self._ssl, i)
1723 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001725 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 return ciphers
1727
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001728 def get_client_ca_list(self):
1729 """
1730 Get CAs whose certificates are suggested for client authentication.
1731
Alex Gaynor62da94d2015-09-05 14:37:34 -04001732 :return: If this is a server connection, a list of X509Names
1733 representing the acceptable CAs as set by
1734 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1735 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1736 connection, the list of such X509Names sent by the server, or an
1737 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001738 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1740 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001741 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 return []
1743
1744 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1746 name = _lib.sk_X509_NAME_value(ca_names, i)
1747 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001748 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001749
1750 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001751 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001752 result.append(pyname)
1753 return result
1754
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001755 def makefile(self):
1756 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001757 The makefile() method is not implemented, since there is no dup
1758 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001759
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001760 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001761 """
Alex Gaynor83284952015-09-05 10:43:30 -04001762 raise NotImplementedError(
1763 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001764
1765 def get_app_data(self):
1766 """
1767 Get application data
1768
1769 :return: The application data
1770 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001771 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001772
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001773 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001774 """
1775 Set application data
1776
1777 :param data - The application data
1778 :return: None
1779 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780 self._app_data = data
1781
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001782 def get_shutdown(self):
1783 """
1784 Get shutdown state
1785
Alex Gaynor62da94d2015-09-05 14:37:34 -04001786 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1787 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001788 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001789 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001790
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001791 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792 """
1793 Set shutdown state
1794
1795 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1796 :return: None
1797 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001798 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001799 raise TypeError("state must be an integer")
1800
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001801 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001802
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001803 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001804 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001805 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001806
1807 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001808 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809 """
kjavc704a2e2015-09-07 12:12:27 +01001810 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001811
1812 def server_random(self):
1813 """
1814 Get a copy of the server hello nonce.
1815
1816 :return: A string representing the state
1817 """
Alex Gaynor93603062016-06-01 20:13:09 -07001818 session = _lib.SSL_get_session(self._ssl)
1819 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001820 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001821 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1822 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001823 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001824 _lib.SSL_get_server_random(self._ssl, outp, length)
1825 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001826
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001827 def client_random(self):
1828 """
1829 Get a copy of the client hello nonce.
1830
1831 :return: A string representing the state
1832 """
Alex Gaynor93603062016-06-01 20:13:09 -07001833 session = _lib.SSL_get_session(self._ssl)
1834 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001835 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001836
1837 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1838 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001839 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001840 _lib.SSL_get_client_random(self._ssl, outp, length)
1841 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001842
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001843 def master_key(self):
1844 """
1845 Get a copy of the master key.
1846
1847 :return: A string representing the state
1848 """
Alex Gaynor93603062016-06-01 20:13:09 -07001849 session = _lib.SSL_get_session(self._ssl)
1850 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001851 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001852
1853 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1854 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001855 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001856 _lib.SSL_SESSION_get_master_key(session, outp, length)
1857 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001858
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001859 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001860 """
1861 See shutdown(2)
1862
1863 :return: What the socket's shutdown() method returns
1864 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001865 return self._socket.shutdown(*args, **kwargs)
1866
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001867 def get_peer_certificate(self):
1868 """
1869 Retrieve the other side's certificate (if any)
1870
1871 :return: The peer's certificate
1872 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001873 cert = _lib.SSL_get_peer_certificate(self._ssl)
1874 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001876 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001877 return pycert
1878 return None
1879
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880 def get_peer_cert_chain(self):
1881 """
1882 Retrieve the other side's certificate (if any)
1883
1884 :return: A list of X509 instances giving the peer's certificate chain,
1885 or None if it does not have one.
1886 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001887 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1888 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001889 return None
1890
1891 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001892 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001893 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001894 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001895 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001896 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001897 result.append(pycert)
1898 return result
1899
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001900 def want_read(self):
1901 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001902 Checks if more data has to be read from the transport layer to complete
1903 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001904
1905 :return: True iff more data has to be read
1906 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001907 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001908
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001909 def want_write(self):
1910 """
1911 Checks if there is data to write to the transport layer to complete an
1912 operation.
1913
1914 :return: True iff there is data to write
1915 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001916 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001917
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001918 def set_accept_state(self):
1919 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001920 Set the connection to work in server mode. The handshake will be
1921 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001922
1923 :return: None
1924 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001925 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001927 def set_connect_state(self):
1928 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001929 Set the connection to work in client mode. The handshake will be
1930 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001931
1932 :return: None
1933 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001934 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001935
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001936 def get_session(self):
1937 """
1938 Returns the Session currently used.
1939
Alex Gaynor62da94d2015-09-05 14:37:34 -04001940 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1941 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001942 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001943 session = _lib.SSL_get1_session(self._ssl)
1944 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001945 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001946
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001947 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001948 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001949 return pysession
1950
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001951 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001952 """
1953 Set the session to be used when the TLS/SSL connection is established.
1954
1955 :param session: A Session instance representing the session to use.
1956 :returns: None
1957 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001958 if not isinstance(session, Session):
1959 raise TypeError("session must be a Session instance")
1960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001961 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001962 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001963 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001965 def _get_finished_message(self, function):
1966 """
1967 Helper to implement :py:meth:`get_finished` and
1968 :py:meth:`get_peer_finished`.
1969
1970 :param function: Either :py:data:`SSL_get_finished`: or
1971 :py:data:`SSL_get_peer_finished`.
1972
1973 :return: :py:data:`None` if the desired message has not yet been
1974 received, otherwise the contents of the message.
1975 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1976 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001977 # The OpenSSL documentation says nothing about what might happen if the
1978 # count argument given is zero. Specifically, it doesn't say whether
1979 # the output buffer may be NULL in that case or not. Inspection of the
1980 # implementation reveals that it calls memcpy() unconditionally.
1981 # Section 7.1.4, paragraph 1 of the C standard suggests that
1982 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1983 # alone desirable) behavior (though it probably does on just about
1984 # every implementation...)
1985 #
1986 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1987 # one might expect) for the initial call so as to be safe against this
1988 # potentially undefined behavior.
1989 empty = _ffi.new("char[]", 0)
1990 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001991 if size == 0:
1992 # No Finished message so far.
1993 return None
1994
Cory Benfielde62840e2016-11-28 12:17:08 +00001995 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001996 function(self._ssl, buf, size)
1997 return _ffi.buffer(buf, size)[:]
1998
Fedor Brunner5747b932014-03-05 14:22:34 +01001999 def get_finished(self):
2000 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002001 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002002
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002003 :return: The contents of the message or :py:obj:`None` if the TLS
2004 handshake has not yet completed.
2005 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002006 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002007 return self._get_finished_message(_lib.SSL_get_finished)
2008
Fedor Brunner5747b932014-03-05 14:22:34 +01002009 def get_peer_finished(self):
2010 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002011 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002012
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002013 :return: The contents of the message or :py:obj:`None` if the TLS
2014 handshake has not yet completed.
2015 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002016 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002017 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002018
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002019 def get_cipher_name(self):
2020 """
2021 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002022
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002023 :returns: The name of the currently used cipher or :py:obj:`None`
2024 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002025 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002026 """
2027 cipher = _lib.SSL_get_current_cipher(self._ssl)
2028 if cipher == _ffi.NULL:
2029 return None
2030 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002031 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2032 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002033
2034 def get_cipher_bits(self):
2035 """
2036 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002037
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002038 :returns: The number of secret bits of the currently used cipher
2039 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002040 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002041 """
2042 cipher = _lib.SSL_get_current_cipher(self._ssl)
2043 if cipher == _ffi.NULL:
2044 return None
2045 else:
2046 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2047
2048 def get_cipher_version(self):
2049 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002050 Obtain the protocol version of the currently used cipher.
2051
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002052 :returns: The protocol name of the currently used cipher
2053 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002054 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002055 """
2056 cipher = _lib.SSL_get_current_cipher(self._ssl)
2057 if cipher == _ffi.NULL:
2058 return None
2059 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002060 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002061 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002062
Jim Shaverabff1882015-05-27 09:15:55 -04002063 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002064 """
2065 Obtain the protocol version of the current connection.
2066
2067 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002068 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002069 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002070 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002071 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002072 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002073 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002074
Jim Shaver208438c2015-05-28 09:52:38 -04002075 def get_protocol_version(self):
2076 """
2077 Obtain the protocol version of the current connection.
2078
2079 :returns: The TLS version of the current connection, for example
2080 the value for TLS 1 would be 0x769.
2081 :rtype: :py:class:`int`
2082 """
2083 version = _lib.SSL_version(self._ssl)
2084 return version
2085
Cory Benfield10b277f2015-04-13 17:12:42 -04002086 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002087 def get_next_proto_negotiated(self):
2088 """
2089 Get the protocol that was negotiated by NPN.
2090 """
2091 data = _ffi.new("unsigned char **")
2092 data_len = _ffi.new("unsigned int *")
2093
2094 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2095
Cory Benfieldcd010f62014-05-15 19:00:27 +01002096 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002097
Cory Benfield7907e332015-04-13 17:18:25 -04002098 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002099 def set_alpn_protos(self, protos):
2100 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002101 Specify the client's ALPN protocol list.
2102
2103 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002104
2105 :param protos: A list of the protocols to be offered to the server.
2106 This list should be a Python list of bytestrings representing the
2107 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2108 """
2109 # Take the list of protocols and join them together, prefixing them
2110 # with their lengths.
2111 protostr = b''.join(
2112 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2113 )
2114
2115 # Build a C string from the list. We don't need to save this off
2116 # because OpenSSL immediately copies the data out.
2117 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04002118 input_str_len = _ffi.cast("unsigned", len(protostr))
2119 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01002120
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002121 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002122 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002123 """
2124 Get the protocol that was negotiated by ALPN.
2125 """
Cory Benfield12eae892014-06-07 15:42:56 +01002126 data = _ffi.new("unsigned char **")
2127 data_len = _ffi.new("unsigned int *")
2128
2129 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2130
Cory Benfielde8e9c382015-04-11 17:33:48 -04002131 if not data_len:
2132 return b''
2133
Cory Benfield12eae892014-06-07 15:42:56 +01002134 return _ffi.buffer(data[0], data_len[0])[:]
2135
Cory Benfield496652a2017-01-24 11:42:56 +00002136 def request_ocsp(self):
2137 """
2138 Called to request that the server sends stapled OCSP data, if
2139 available. If this is not called on the client side then the server
2140 will not send OCSP data. Should be used in conjunction with
2141 :meth:`Context.set_ocsp_client_callback`.
2142 """
2143 rc = _lib.SSL_set_tlsext_status_type(
2144 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2145 )
2146 _openssl_assert(rc == 1)
2147
Cory Benfield12eae892014-06-07 15:42:56 +01002148
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002149ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002150
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002151# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2152# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002153_lib.SSL_library_init()