blob: 10116edc626250bd7b171ec0b780aa0e79d9366d [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 (
13 ffi as _ffi,
14 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050015 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040016 native as _native,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040018 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040020 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040021)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080022
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080023from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050024 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050026try:
27 _memoryview = memoryview
28except NameError:
29 class _memoryview(object):
30 pass
31
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020032try:
33 _buffer = buffer
34except NameError:
35 class _buffer(object):
36 pass
37
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050038OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
39SSLEAY_VERSION = _lib.SSLEAY_VERSION
40SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
41SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
42SSLEAY_DIR = _lib.SSLEAY_DIR
43SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080044
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050045SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
46RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080047
48SSLv2_METHOD = 1
49SSLv3_METHOD = 2
50SSLv23_METHOD = 3
51TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050052TLSv1_1_METHOD = 5
53TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080054
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050055OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
56OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
57OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050058
59OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
60OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080061
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050062try:
63 MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
64except AttributeError:
65 pass
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090068OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050069OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
70OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
71OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040072OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
73 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
74)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
76OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050077try:
78 OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
79except AttributeError:
80 pass
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050081OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
82OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
83OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
84OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
85OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
86OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
87OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
88OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
89OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040090OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
91 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
92)
Jean-Paul Calderonec1780342014-01-08 16:59:03 -050093try:
94 OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
95except AttributeError:
96 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
99OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Arturo Filastò5f8c7a82014-03-09 20:01:25 +0100100try:
101 OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
102except AttributeError:
103 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800104
Alex Gaynorc4889812015-09-04 08:43:17 -0400105OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500107VERIFY_PEER = _lib.SSL_VERIFY_PEER
108VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
109VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
110VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500112SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
113SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
114SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
115SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
116SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
117SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
118SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
119SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
122SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
123SSL_ST_MASK = _lib.SSL_ST_MASK
124SSL_ST_INIT = _lib.SSL_ST_INIT
125SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
126SSL_ST_OK = _lib.SSL_ST_OK
127SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500129SSL_CB_LOOP = _lib.SSL_CB_LOOP
130SSL_CB_EXIT = _lib.SSL_CB_EXIT
131SSL_CB_READ = _lib.SSL_CB_READ
132SSL_CB_WRITE = _lib.SSL_CB_WRITE
133SSL_CB_ALERT = _lib.SSL_CB_ALERT
134SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
135SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
136SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
137SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
138SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
139SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
140SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
141SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800142
Alex Gaynor83284952015-09-05 10:43:30 -0400143
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500144class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500145 """
146 An error occurred in an `OpenSSL.SSL` API.
147 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500148
149
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500150_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100151_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500152
153
154class WantReadError(Error):
155 pass
156
157
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158class WantWriteError(Error):
159 pass
160
161
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500162class WantX509LookupError(Error):
163 pass
164
165
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500166class ZeroReturnError(Error):
167 pass
168
169
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500170class SysCallError(Error):
171 pass
172
173
Cory Benfield0ea76e72015-03-22 09:05:28 +0000174class _CallbackExceptionHelper(object):
175 """
176 A base class for wrapper classes that allow for intelligent exception
177 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500178
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400179 :ivar list _problems: Any exceptions that occurred while executing in a
180 context where they could not be raised in the normal way. Typically
181 this is because OpenSSL has called into some Python code and requires a
182 return value. The exceptions are saved to be raised later when it is
183 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000184 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400185
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400186 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800187 self._problems = []
188
Cory Benfield0ea76e72015-03-22 09:05:28 +0000189 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400190 """
191 Raise an exception from the OpenSSL error queue or that was previously
192 captured whe running a callback.
193 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000194 if self._problems:
195 try:
196 _raise_current_error()
197 except Error:
198 pass
199 raise self._problems.pop(0)
200
201
202class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400203 """
204 Wrap a callback such that it can be used as a certificate verification
205 callback.
206 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400207
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800208 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400209 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800210
211 @wraps(callback)
212 def wrapper(ok, store_ctx):
213 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500214 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
215 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
216 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800217
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400218 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
219 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
220 connection = Connection._reverse_mapping[ssl]
221
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800222 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400223 result = callback(
224 connection, cert, error_number, error_depth, ok
225 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800226 except Exception as e:
227 self._problems.append(e)
228 return 0
229 else:
230 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500231 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800232 return 1
233 else:
234 return 0
235
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500236 self.callback = _ffi.callback(
237 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800238
239
Cory Benfield0ea76e72015-03-22 09:05:28 +0000240class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400241 """
242 Wrap a callback such that it can be used as an NPN advertisement callback.
243 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400244
Cory Benfield0ea76e72015-03-22 09:05:28 +0000245 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400246 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800247
Cory Benfield0ea76e72015-03-22 09:05:28 +0000248 @wraps(callback)
249 def wrapper(ssl, out, outlen, arg):
250 try:
251 conn = Connection._reverse_mapping[ssl]
252 protos = callback(conn)
253
254 # Join the protocols into a Python bytestring, length-prefixing
255 # each element.
256 protostr = b''.join(
257 chain.from_iterable((int2byte(len(p)), p) for p in protos)
258 )
259
260 # Save our callback arguments on the connection object. This is
261 # done to make sure that they don't get freed before OpenSSL
262 # uses them. Then, return them appropriately in the output
263 # parameters.
264 conn._npn_advertise_callback_args = [
265 _ffi.new("unsigned int *", len(protostr)),
266 _ffi.new("unsigned char[]", protostr),
267 ]
268 outlen[0] = conn._npn_advertise_callback_args[0][0]
269 out[0] = conn._npn_advertise_callback_args[1]
270 return 0
271 except Exception as e:
272 self._problems.append(e)
273 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
274
275 self.callback = _ffi.callback(
276 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
277 wrapper
278 )
279
280
281class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400282 """
283 Wrap a callback such that it can be used as an NPN selection callback.
284 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400285
Cory Benfield0ea76e72015-03-22 09:05:28 +0000286 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400287 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288
289 @wraps(callback)
290 def wrapper(ssl, out, outlen, in_, inlen, arg):
291 try:
292 conn = Connection._reverse_mapping[ssl]
293
294 # The string passed to us is actually made up of multiple
295 # length-prefixed bytestrings. We need to split that into a
296 # list.
297 instr = _ffi.buffer(in_, inlen)[:]
298 protolist = []
299 while instr:
300 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400301 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000302 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400303 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000304
305 # Call the callback
306 outstr = callback(conn, protolist)
307
308 # Save our callback arguments on the connection object. This is
309 # done to make sure that they don't get freed before OpenSSL
310 # uses them. Then, return them appropriately in the output
311 # parameters.
312 conn._npn_select_callback_args = [
313 _ffi.new("unsigned char *", len(outstr)),
314 _ffi.new("unsigned char[]", outstr),
315 ]
316 outlen[0] = conn._npn_select_callback_args[0][0]
317 out[0] = conn._npn_select_callback_args[1]
318 return 0
319 except Exception as e:
320 self._problems.append(e)
321 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
322
323 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400324 ("int (*)(SSL *, unsigned char **, unsigned char *, "
325 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000326 wrapper
327 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800328
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800329
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400330class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400331 """
332 Wrap a callback such that it can be used as an ALPN selection callback.
333 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400334
Cory Benfieldf1177e72015-04-12 09:11:49 -0400335 def __init__(self, callback):
336 _CallbackExceptionHelper.__init__(self)
337
338 @wraps(callback)
339 def wrapper(ssl, out, outlen, in_, inlen, arg):
340 try:
341 conn = Connection._reverse_mapping[ssl]
342
343 # The string passed to us is made up of multiple
344 # length-prefixed bytestrings. We need to split that into a
345 # list.
346 instr = _ffi.buffer(in_, inlen)[:]
347 protolist = []
348 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400349 encoded_len = indexbytes(instr, 0)
350 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400351 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400352 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400353
354 # Call the callback
355 outstr = callback(conn, protolist)
356
357 if not isinstance(outstr, _binary_type):
358 raise TypeError("ALPN callback must return a bytestring.")
359
360 # Save our callback arguments on the connection object to make
361 # sure that they don't get freed before OpenSSL can use them.
362 # Then, return them in the appropriate output parameters.
363 conn._alpn_select_callback_args = [
364 _ffi.new("unsigned char *", len(outstr)),
365 _ffi.new("unsigned char[]", outstr),
366 ]
367 outlen[0] = conn._alpn_select_callback_args[0][0]
368 out[0] = conn._alpn_select_callback_args[1]
369 return 0
370 except Exception as e:
371 self._problems.append(e)
372 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
373
374 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400375 ("int (*)(SSL *, unsigned char **, unsigned char *, "
376 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400377 wrapper
378 )
379
380
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800381def _asFileDescriptor(obj):
382 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800383 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800384 meth = getattr(obj, "fileno", None)
385 if meth is not None:
386 obj = meth()
387
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800388 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800389 fd = obj
390
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800391 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800392 raise TypeError("argument must be an int, or have a fileno() method.")
393 elif fd < 0:
394 raise ValueError(
395 "file descriptor cannot be a negative integer (%i)" % (fd,))
396
397 return fd
398
399
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800400def SSLeay_version(type):
401 """
402 Return a string describing the version of OpenSSL in use.
403
404 :param type: One of the SSLEAY_ constants defined in this module.
405 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500406 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800407
408
Cory Benfield10b277f2015-04-13 17:12:42 -0400409def _requires_npn(func):
Cory Benfielda876cef2015-04-13 17:29:12 -0400410 """
411 Wraps any function that requires NPN support in OpenSSL, ensuring that
412 NotImplementedError is raised if NPN is not present.
413 """
Cory Benfield10b277f2015-04-13 17:12:42 -0400414 @wraps(func)
415 def wrapper(*args, **kwargs):
416 if not _lib.Cryptography_HAS_NEXTPROTONEG:
417 raise NotImplementedError("NPN not available.")
418
419 return func(*args, **kwargs)
420
421 return wrapper
422
423
Cory Benfield7907e332015-04-13 17:18:25 -0400424def _requires_alpn(func):
Cory Benfield9d80a762015-04-13 17:47:33 -0400425 """
426 Wraps any function that requires ALPN support in OpenSSL, ensuring that
427 NotImplementedError is raised if ALPN support is not present.
428 """
Cory Benfield7907e332015-04-13 17:18:25 -0400429 @wraps(func)
430 def wrapper(*args, **kwargs):
431 if not _lib.Cryptography_HAS_ALPN:
432 raise NotImplementedError("ALPN not available.")
433
434 return func(*args, **kwargs)
435
436 return wrapper
437
438
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800439class Session(object):
440 pass
441
442
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800443class Context(object):
444 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100445 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400446 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800447 """
448 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800449 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500450 SSLv3_METHOD: "SSLv3_method",
451 SSLv23_METHOD: "SSLv23_method",
452 TLSv1_METHOD: "TLSv1_method",
453 TLSv1_1_METHOD: "TLSv1_1_method",
454 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400455 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500456 _methods = dict(
457 (identifier, getattr(_lib, name))
458 for (identifier, name) in _methods.items()
459 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800460
461 def __init__(self, method):
462 """
463 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
464 TLSv1_METHOD.
465 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500466 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800467 raise TypeError("method must be an integer")
468
469 try:
470 method_func = self._methods[method]
471 except KeyError:
472 raise ValueError("No such protocol")
473
474 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500475 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500476 # TODO: This is untested.
477 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800478
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500479 context = _lib.SSL_CTX_new(method_obj)
480 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500481 # TODO: This is untested.
482 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500483 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800484
485 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800486 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800487 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800488 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800489 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800490 self._verify_callback = None
491 self._info_callback = None
492 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800493 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000494 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100495 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000496 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100497 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400498 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100499 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800500
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800501 # SSL_CTX_set_app_data(self->ctx, self);
502 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
503 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
504 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500505 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800506
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800507 def load_verify_locations(self, cafile, capath=None):
508 """
509 Let SSL know where we can find trusted certificates for the certificate
510 chain
511
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400512 :param cafile: In which file we can find the certificates (``bytes`` or
513 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800514 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400515 (``bytes`` or ``unicode``).
516
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800517 :return: None
518 """
519 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500520 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400521 else:
522 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800523
524 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500525 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400526 else:
527 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800528
Alex Gaynor62da94d2015-09-05 14:37:34 -0400529 load_result = _lib.SSL_CTX_load_verify_locations(
530 self._context, cafile, capath
531 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800532 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500533 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800534
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800535 def _wrap_callback(self, callback):
536 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800537 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800538 return callback(size, verify, self._passphrase_userdata)
539 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800540 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800541
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800542 def set_passwd_cb(self, callback, userdata=None):
543 """
544 Set the passphrase callback
545
546 :param callback: The Python callback to use
547 :param userdata: (optional) A Python object which will be given as
548 argument to the callback
549 :return: None
550 """
551 if not callable(callback):
552 raise TypeError("callback must be callable")
553
554 self._passphrase_helper = self._wrap_callback(callback)
555 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500556 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800557 self._context, self._passphrase_callback)
558 self._passphrase_userdata = userdata
559
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800560 def set_default_verify_paths(self):
561 """
562 Use the platform-specific CA certificate locations
563
564 :return: None
565 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500566 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800567 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500568 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500569 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800570
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800571 def use_certificate_chain_file(self, certfile):
572 """
573 Load a certificate chain from a file
574
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400575 :param certfile: The name of the certificate chain file (``bytes`` or
576 ``unicode``).
577
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800578 :return: None
579 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400580 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800581
Alex Gaynor62da94d2015-09-05 14:37:34 -0400582 result = _lib.SSL_CTX_use_certificate_chain_file(
583 self._context, certfile
584 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800585 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500586 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800587
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800588 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800589 """
590 Load a certificate from a file
591
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400592 :param certfile: The name of the certificate file (``bytes`` or
593 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800594 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400595
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800596 :return: None
597 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400598 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500599 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800600 raise TypeError("filetype must be an integer")
601
Alex Gaynor62da94d2015-09-05 14:37:34 -0400602 use_result = _lib.SSL_CTX_use_certificate_file(
603 self._context, certfile, filetype
604 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800605 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500606 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800607
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608 def use_certificate(self, cert):
609 """
610 Load a certificate from a X509 object
611
612 :param cert: The X509 object
613 :return: None
614 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800615 if not isinstance(cert, X509):
616 raise TypeError("cert must be an X509 instance")
617
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500618 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500620 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800621
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800622 def add_extra_chain_cert(self, certobj):
623 """
624 Add certificate to chain
625
626 :param certobj: The X509 certificate object to add to the chain
627 :return: None
628 """
629 if not isinstance(certobj, X509):
630 raise TypeError("certobj must be an X509 instance")
631
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 copy = _lib.X509_dup(certobj._x509)
633 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800634 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500635 # TODO: This is untested.
636 _lib.X509_free(copy)
637 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800639 def _raise_passphrase_exception(self):
640 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500641 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800642 exception = self._passphrase_helper.raise_if_problem(Error)
643 if exception is not None:
644 raise exception
645
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400646 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800647 """
648 Load a private key from a file
649
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400650 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800651 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400652
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800653 :return: None
654 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400655 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400657 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500659 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800660 raise TypeError("filetype must be an integer")
661
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500662 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800663 self._context, keyfile, filetype)
664 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800665 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 def use_privatekey(self, pkey):
668 """
669 Load a private key from a PKey object
670
671 :param pkey: The PKey object
672 :return: None
673 """
674 if not isinstance(pkey, PKey):
675 raise TypeError("pkey must be a PKey instance")
676
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500677 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800678 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800679 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800681 def check_privatekey(self):
682 """
683 Check that the private key and certificate match up
684
685 :return: None (raises an exception if something's wrong)
686 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500687 if not _lib.SSL_CTX_check_private_key(self._context):
688 _raise_current_error()
689
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690 def load_client_ca(self, cafile):
691 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400692 Load the trusted certificates that will be sent to the client
693 (basically telling the client "These are the guys I trust"). Does not
694 actually imply any of the certificates are trusted; that must be
695 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696
697 :param cafile: The name of the certificates file
698 :return: None
699 """
700
701 def set_session_id(self, buf):
702 """
703 Set the session identifier. This is needed if you want to do session
704 resumption.
705
706 :param buf: A Python object that can be safely converted to a string
707 :returns: None
708 """
709
710 def set_session_cache_mode(self, mode):
711 """
712 Enable/disable session caching and specify the mode used.
713
714 :param mode: One or more of the SESS_CACHE_* flags (combine using
715 bitwise or)
716 :returns: The previously set caching mode.
717 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500718 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800719 raise TypeError("mode must be an integer")
720
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500721 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800722
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800723 def get_session_cache_mode(self):
724 """
725 :returns: The currently used cache mode.
726 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500727 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729 def set_verify(self, mode, callback):
730 """
731 Set the verify mode and verify callback
732
733 :param mode: The verify mode, this is either VERIFY_NONE or
734 VERIFY_PEER combined with possible other flags
735 :param callback: The Python callback to use
736 :return: None
737
738 See SSL_CTX_set_verify(3SSL) for further details.
739 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500740 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741 raise TypeError("mode must be an integer")
742
743 if not callable(callback):
744 raise TypeError("callback must be callable")
745
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400746 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800747 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500748 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800749
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750 def set_verify_depth(self, depth):
751 """
752 Set the verify depth
753
754 :param depth: An integer specifying the verify depth
755 :return: None
756 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500757 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800758 raise TypeError("depth must be an integer")
759
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500760 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800762 def get_verify_mode(self):
763 """
764 Get the verify mode
765
766 :return: The verify mode
767 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500768 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800770 def get_verify_depth(self):
771 """
772 Get the verify depth
773
774 :return: The verify depth
775 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500776 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800778 def load_tmp_dh(self, dhfile):
779 """
780 Load parameters for Ephemeral Diffie-Hellman
781
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400782 :param dhfile: The file to load EDH parameters from (``bytes`` or
783 ``unicode``).
784
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785 :return: None
786 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400787 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800788
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500789 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500790 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500791 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500792 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500794 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
795 dh = _ffi.gc(dh, _lib.DH_free)
796 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800797
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400798 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600799 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700800 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600801
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400802 :param curve: A curve object to use as returned by either
803 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
804 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700805
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600806 :return: None
807 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400808 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600809
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800810 def set_cipher_list(self, cipher_list):
811 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100812 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800813
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100814 See the OpenSSL manual for more information (e.g.
815 :manpage:`ciphers(1)`).
816
817 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818 :return: None
819 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100820 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500821
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800822 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100823 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800824
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100825 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100826 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100827 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800828
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829 def set_client_ca_list(self, certificate_authorities):
830 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400831 Set the list of preferred client certificate signers for this server
832 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800833
Alex Gaynor62da94d2015-09-05 14:37:34 -0400834 This list of certificate authorities will be sent to the client when
835 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800836
837 :param certificate_authorities: a sequence of X509Names.
838 :return: None
839 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500840 name_stack = _lib.sk_X509_NAME_new_null()
841 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500842 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500843 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800844
845 try:
846 for ca_name in certificate_authorities:
847 if not isinstance(ca_name, X509Name):
848 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400849 "client CAs must be X509Name objects, not %s "
850 "objects" % (
851 type(ca_name).__name__,
852 )
853 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500854 copy = _lib.X509_NAME_dup(ca_name._name)
855 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500856 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500857 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500858 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800859 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500860 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500861 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800862 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500863 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800864 raise
865
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500866 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800867
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868 def add_client_ca(self, certificate_authority):
869 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400870 Add the CA certificate to the list of preferred signers for this
871 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800872
873 The list of certificate authorities will be sent to the client when the
874 server requests a client certificate.
875
876 :param certificate_authority: certificate authority's X509 certificate.
877 :return: None
878 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800879 if not isinstance(certificate_authority, X509):
880 raise TypeError("certificate_authority must be an X509 instance")
881
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500882 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800883 self._context, certificate_authority._x509)
884 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500885 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500886 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800887
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800888 def set_timeout(self, timeout):
889 """
890 Set session timeout
891
892 :param timeout: The timeout in seconds
893 :return: The previous session timeout
894 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500895 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800896 raise TypeError("timeout must be an integer")
897
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500898 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900 def get_timeout(self):
901 """
902 Get the session timeout
903
904 :return: The session timeout
905 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500906 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908 def set_info_callback(self, callback):
909 """
910 Set the info callback
911
912 :param callback: The Python callback to use
913 :return: None
914 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800915 @wraps(callback)
916 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500917 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500918 self._info_callback = _ffi.callback(
919 "void (*)(const SSL *, int, int)", wrapper)
920 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800921
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 def get_app_data(self):
923 """
924 Get the application data (supplied via set_app_data())
925
926 :return: The application data
927 """
928 return self._app_data
929
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800930 def set_app_data(self, data):
931 """
932 Set the application data (will be returned from get_app_data())
933
934 :param data: Any Python object
935 :return: None
936 """
937 self._app_data = data
938
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939 def get_cert_store(self):
940 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500941 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500943 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800944 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500945 store = _lib.SSL_CTX_get_cert_store(self._context)
946 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500947 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800948 return None
949
950 pystore = X509Store.__new__(X509Store)
951 pystore._store = store
952 return pystore
953
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800954 def set_options(self, options):
955 """
956 Add options. Options set before are not cleared!
957
958 :param options: The options to add.
959 :return: The new option bitmask.
960 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500961 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 raise TypeError("options must be an integer")
963
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500964 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800965
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966 def set_mode(self, mode):
967 """
968 Add modes via bitmask. Modes set before are not cleared!
969
970 :param mode: The mode to add.
971 :return: The new mode bitmask.
972 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500973 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974 raise TypeError("mode must be an integer")
975
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500976 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800977
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978 def set_tlsext_servername_callback(self, callback):
979 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400980 Specify a callback function to be called when clients specify a server
981 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800982
983 :param callback: The callback function. It will be invoked with one
984 argument, the Connection instance.
985 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800986 @wraps(callback)
987 def wrapper(ssl, alert, arg):
988 callback(Connection._reverse_mapping[ssl])
989 return 0
990
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 self._tlsext_servername_callback = _ffi.callback(
992 "int (*)(const SSL *, int *, void *)", wrapper)
993 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800994 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Cory Benfield10b277f2015-04-13 17:12:42 -0400996 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +0100997 def set_npn_advertise_callback(self, callback):
998 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +0100999 Specify a callback function that will be called when offering `Next
1000 Protocol Negotiation
1001 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001002
1003 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001004 argument, the Connection instance. It should return a list of
1005 bytestrings representing the advertised protocols, like
1006 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001007 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001008 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1009 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001010 _lib.SSL_CTX_set_next_protos_advertised_cb(
1011 self._context, self._npn_advertise_callback, _ffi.NULL)
1012
Cory Benfield10b277f2015-04-13 17:12:42 -04001013 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001014 def set_npn_select_callback(self, callback):
1015 """
1016 Specify a callback function that will be called when a server offers
1017 Next Protocol Negotiation options.
1018
1019 :param callback: The callback function. It will be invoked with two
1020 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001021 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1022 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001023 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001024 self._npn_select_helper = _NpnSelectHelper(callback)
1025 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001026 _lib.SSL_CTX_set_next_proto_select_cb(
1027 self._context, self._npn_select_callback, _ffi.NULL)
1028
Cory Benfield7907e332015-04-13 17:18:25 -04001029 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001030 def set_alpn_protos(self, protos):
1031 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001032 Specify the clients ALPN protocol list.
1033
1034 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001035
1036 :param protos: A list of the protocols to be offered to the server.
1037 This list should be a Python list of bytestrings representing the
1038 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1039 """
1040 # Take the list of protocols and join them together, prefixing them
1041 # with their lengths.
1042 protostr = b''.join(
1043 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1044 )
1045
1046 # Build a C string from the list. We don't need to save this off
1047 # because OpenSSL immediately copies the data out.
1048 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001049 input_str_len = _ffi.cast("unsigned", len(protostr))
1050 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001051
Cory Benfield7907e332015-04-13 17:18:25 -04001052 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001053 def set_alpn_select_callback(self, callback):
1054 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001055 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001056
1057 :param callback: The callback function. It will be invoked with two
1058 arguments: the Connection, and a list of offered protocols as
1059 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001060 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001061 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001062 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001063 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001064 _lib.SSL_CTX_set_alpn_select_cb(
1065 self._context, self._alpn_select_callback, _ffi.NULL)
1066
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001068
1069
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001070class Connection(object):
1071 """
1072 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001073 _reverse_mapping = WeakValueDictionary()
1074
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001075 def __init__(self, context, socket=None):
1076 """
1077 Create a new Connection object, using the given OpenSSL.SSL.Context
1078 instance and socket.
1079
1080 :param context: An SSL Context to use for this connection
1081 :param socket: The socket to use for transport layer
1082 """
1083 if not isinstance(context, Context):
1084 raise TypeError("context must be a Context instance")
1085
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001086 ssl = _lib.SSL_new(context._context)
1087 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001088 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001089 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001090
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001091 # References to strings used for Next Protocol Negotiation. OpenSSL's
1092 # header files suggest that these might get copied at some point, but
1093 # doesn't specify when, so we store them here to make sure they don't
1094 # get freed before OpenSSL uses them.
1095 self._npn_advertise_callback_args = None
1096 self._npn_select_callback_args = None
1097
Cory Benfield12eae892014-06-07 15:42:56 +01001098 # References to strings used for Application Layer Protocol
1099 # Negotiation. These strings get copied at some point but it's well
1100 # after the callback returns, so we have to hang them somewhere to
1101 # avoid them getting freed.
1102 self._alpn_select_callback_args = None
1103
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001104 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001105
1106 if socket is None:
1107 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001108 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1110 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001112 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001113 # TODO: This is untested.
1114 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001115
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001116 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001118 self._into_ssl = None
1119 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001120 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001121 set_result = _lib.SSL_set_fd(
1122 self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001124 # TODO: This is untested.
1125 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001126
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001127 def __getattr__(self, name):
1128 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001129 Look up attributes on the wrapped socket object if they are not found
1130 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131 """
kjav0b66fa12015-09-02 11:51:26 +01001132 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001133 raise AttributeError("'%s' object has no attribute '%s'" % (
1134 self.__class__.__name__, name
1135 ))
kjav0b66fa12015-09-02 11:51:26 +01001136 else:
1137 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001139 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001140 if self._context._verify_helper is not None:
1141 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001142 if self._context._npn_advertise_helper is not None:
1143 self._context._npn_advertise_helper.raise_if_problem()
1144 if self._context._npn_select_helper is not None:
1145 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001146 if self._context._alpn_select_helper is not None:
1147 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 error = _lib.SSL_get_error(ssl, result)
1150 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001151 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001153 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001155 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001157 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001158 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 elif error == _lib.SSL_ERROR_SYSCALL:
1160 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001161 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001162 if platform == "win32":
1163 errno = _ffi.getwinerror()[0]
1164 else:
1165 errno = _ffi.errno
Glyph3afdba82015-04-14 17:30:53 -04001166 raise SysCallError(errno, errorcode.get(errno))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001167 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001168 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001169 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001170 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001171 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001172 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001173 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001174 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001175 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001176
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001177 def get_context(self):
1178 """
1179 Get session context
1180 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001181 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001182
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001183 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001184 """
1185 Switch this connection to a new session context
1186
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001187 :param context: A :py:class:`Context` instance giving the new session
1188 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001189 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001190 if not isinstance(context, Context):
1191 raise TypeError("context must be a Context instance")
1192
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001193 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001194 self._context = context
1195
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001196 def get_servername(self):
1197 """
1198 Retrieve the servername extension value if provided in the client hello
1199 message, or None if there wasn't one.
1200
1201 :return: A byte string giving the server name or :py:data:`None`.
1202 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001203 name = _lib.SSL_get_servername(
1204 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1205 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001206 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001207 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001208
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001209 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001210
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001211 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001212 """
1213 Set the value of the servername extension to send in the client hello.
1214
1215 :param name: A byte string giving the name.
1216 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001217 if not isinstance(name, bytes):
1218 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001219 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001220 raise TypeError("name must not contain NUL byte")
1221
1222 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001223 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001224
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001225 def pending(self):
1226 """
1227 Get the number of bytes that can be safely read from the connection
1228
1229 :return: The number of bytes available in the receive buffer.
1230 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001231 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001232
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001233 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001234 """
1235 Send data on the connection. NOTE: If you get one of the WantRead,
1236 WantWrite or WantX509Lookup exceptions on this, you have to call the
1237 method again with the SAME buffer.
1238
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001239 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001240 :param flags: (optional) Included for compatibility with the socket
1241 API, the value is ignored
1242 :return: The number of bytes written
1243 """
Abraham Martine82326c2015-02-04 10:18:10 +00001244 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001245 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001246
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001247 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001248 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001249 if isinstance(buf, _buffer):
1250 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001251 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001252 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001253
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001254 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001255 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001256 return result
1257 write = send
1258
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001259 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001260 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001261 Send "all" data on the connection. This calls send() repeatedly until
1262 all data is sent. If an error occurs, it's impossible to tell how much
1263 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001264
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001265 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001266 :param flags: (optional) Included for compatibility with the socket
1267 API, the value is ignored
1268 :return: The number of bytes written
1269 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001270 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001271
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001272 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001273 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001274 if isinstance(buf, _buffer):
1275 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001276 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001277 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001278
1279 left_to_send = len(buf)
1280 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001281 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001282
1283 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001285 self._raise_ssl_error(self._ssl, result)
1286 total_sent += result
1287 left_to_send -= result
1288
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001289 def recv(self, bufsiz, flags=None):
1290 """
1291 Receive data on the connection. NOTE: If you get one of the WantRead,
1292 WantWrite or WantX509Lookup exceptions on this, you have to call the
1293 method again with the SAME buffer.
1294
1295 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001296 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1297 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001298 :return: The string read from the Connection
1299 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001300 buf = _ffi.new("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001301 if flags is not None and flags & socket.MSG_PEEK:
1302 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1303 else:
1304 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001305 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001306 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001307 read = recv
1308
Cory Benfield62d10332014-06-15 10:03:41 +01001309 def recv_into(self, buffer, nbytes=None, flags=None):
1310 """
1311 Receive data on the connection and store the data into a buffer rather
1312 than creating a new string.
1313
1314 :param buffer: The buffer to copy into.
1315 :param nbytes: (optional) The maximum number of bytes to read into the
1316 buffer. If not present, defaults to the size of the buffer. If
1317 larger than the size of the buffer, is reduced to the size of the
1318 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001319 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1320 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001321 :return: The number of bytes read into the buffer.
1322 """
1323 if nbytes is None:
1324 nbytes = len(buffer)
1325 else:
1326 nbytes = min(nbytes, len(buffer))
1327
1328 # We need to create a temporary buffer. This is annoying, it would be
1329 # better if we could pass memoryviews straight into the SSL_read call,
1330 # but right now we can't. Revisit this if CFFI gets that ability.
1331 buf = _ffi.new("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001332 if flags is not None and flags & socket.MSG_PEEK:
1333 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1334 else:
1335 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001336 self._raise_ssl_error(self._ssl, result)
1337
1338 # This strange line is all to avoid a memory copy. The buffer protocol
1339 # should allow us to assign a CFFI buffer to the LHS of this line, but
1340 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1341 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1342 # memoryview type.
1343 try:
1344 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1345 except NameError:
1346 buffer[:result] = _ffi.buffer(buf, result)
1347
1348 return result
1349
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001350 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 if _lib.BIO_should_retry(bio):
1352 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001353 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001355 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001356 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001357 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001358 # TODO: This is untested. I think io_special means the socket
1359 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001360 raise ValueError("BIO_should_io_special")
1361 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001362 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001363 raise ValueError("unknown bio failure")
1364 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001365 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001366 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001368 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001369 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001370 When using non-socket connections this function reads the "dirty" data
1371 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001372
1373 :param bufsiz: The maximum number of bytes to read
1374 :return: The string read.
1375 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001376 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001377 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001378
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001379 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001380 raise TypeError("bufsiz must be an integer")
1381
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001382 buf = _ffi.new("char[]", bufsiz)
1383 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001384 if result <= 0:
1385 self._handle_bio_errors(self._from_ssl, result)
1386
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001387 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001388
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001389 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001391 When using non-socket connections this function sends "dirty" data that
1392 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001393
1394 :param buf: The string to put into the memory BIO.
1395 :return: The number of bytes written
1396 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001397 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001398
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001399 if self._into_ssl is None:
1400 raise TypeError("Connection sock was not None")
1401
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001402 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001403 if result <= 0:
1404 self._handle_bio_errors(self._into_ssl, result)
1405 return result
1406
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001407 def renegotiate(self):
1408 """
1409 Renegotiate the session
1410
1411 :return: True if the renegotiation can be started, false otherwise
1412 """
1413
1414 def do_handshake(self):
1415 """
1416 Perform an SSL handshake (usually called after renegotiate() or one of
1417 set_*_state()). This can raise the same exceptions as send and recv.
1418
1419 :return: None.
1420 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001421 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001422 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001423
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001424 def renegotiate_pending(self):
1425 """
1426 Check if there's a renegotiation in progress, it will return false once
1427 a renegotiation is finished.
1428
1429 :return: Whether there's a renegotiation in progress
1430 """
1431
1432 def total_renegotiations(self):
1433 """
1434 Find out the total number of renegotiations.
1435
1436 :return: The number of renegotiations.
1437 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001438 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001439
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001440 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001441 """
1442 Connect to remote host and set up client-side SSL
1443
1444 :param addr: A remote address
1445 :return: What the socket's connect method returns
1446 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001447 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001448 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001449
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001451 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001452 Connect to remote host and set up client-side SSL. Note that if the
1453 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001454
1455 :param addr: A remove address
1456 :return: What the socket's connect_ex method returns
1457 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001458 connect_ex = self._socket.connect_ex
1459 self.set_connect_state()
1460 return connect_ex(addr)
1461
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001462 def accept(self):
1463 """
1464 Accept incoming connection and set up SSL on it
1465
1466 :return: A (conn,addr) pair where conn is a Connection and addr is an
1467 address
1468 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001469 client, addr = self._socket.accept()
1470 conn = Connection(self._context, client)
1471 conn.set_accept_state()
1472 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001473
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001474 def bio_shutdown(self):
1475 """
1476 When using non-socket connections this function signals end of
1477 data on the input for this connection.
1478
1479 :return: None
1480 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001481 if self._from_ssl is None:
1482 raise TypeError("Connection sock was not None")
1483
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001484 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001485
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001486 def shutdown(self):
1487 """
1488 Send closure alert
1489
1490 :return: True if the shutdown completed successfully (i.e. both sides
1491 have sent closure alerts), false otherwise (i.e. you have to
1492 wait for a ZeroReturnError on a recv() method call
1493 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001494 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001496 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001497 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001498 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001499 else:
1500 return False
1501
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001502 def get_cipher_list(self):
1503 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001504 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001505
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001506 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507 """
1508 ciphers = []
1509 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001510 result = _lib.SSL_get_cipher_list(self._ssl, i)
1511 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001513 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514 return ciphers
1515
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516 def get_client_ca_list(self):
1517 """
1518 Get CAs whose certificates are suggested for client authentication.
1519
Alex Gaynor62da94d2015-09-05 14:37:34 -04001520 :return: If this is a server connection, a list of X509Names
1521 representing the acceptable CAs as set by
1522 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1523 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1524 connection, the list of such X509Names sent by the server, or an
1525 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001526 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001527 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1528 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001529 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001530 return []
1531
1532 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001533 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1534 name = _lib.sk_X509_NAME_value(ca_names, i)
1535 copy = _lib.X509_NAME_dup(name)
1536 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001537 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001538 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001539
1540 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001541 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542 result.append(pyname)
1543 return result
1544
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545 def makefile(self):
1546 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001547 The makefile() method is not implemented, since there is no dup
1548 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001549
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001550 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001551 """
Alex Gaynor83284952015-09-05 10:43:30 -04001552 raise NotImplementedError(
1553 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001554
1555 def get_app_data(self):
1556 """
1557 Get application data
1558
1559 :return: The application data
1560 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001561 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001562
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001563 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001564 """
1565 Set application data
1566
1567 :param data - The application data
1568 :return: None
1569 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001570 self._app_data = data
1571
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 def get_shutdown(self):
1573 """
1574 Get shutdown state
1575
Alex Gaynor62da94d2015-09-05 14:37:34 -04001576 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1577 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001579 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001580
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001582 """
1583 Set shutdown state
1584
1585 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1586 :return: None
1587 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001588 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001589 raise TypeError("state must be an integer")
1590
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001591 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001593 def state_string(self):
1594 """
1595 Get a verbose state description
1596
1597 :return: A string representing the state
1598 """
kjavc704a2e2015-09-07 12:12:27 +01001599 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001600
1601 def server_random(self):
1602 """
1603 Get a copy of the server hello nonce.
1604
1605 :return: A string representing the state
1606 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001607 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001608 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001609 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001610 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001611 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001612
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001613 def client_random(self):
1614 """
1615 Get a copy of the client hello nonce.
1616
1617 :return: A string representing the state
1618 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001619 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001620 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001621 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001622 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001623 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001624
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625 def master_key(self):
1626 """
1627 Get a copy of the master key.
1628
1629 :return: A string representing the state
1630 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001631 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001633 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001634 self._ssl.session.master_key,
1635 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001636
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001637 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001638 """
1639 See shutdown(2)
1640
1641 :return: What the socket's shutdown() method returns
1642 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001643 return self._socket.shutdown(*args, **kwargs)
1644
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001645 def get_peer_certificate(self):
1646 """
1647 Retrieve the other side's certificate (if any)
1648
1649 :return: The peer's certificate
1650 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 cert = _lib.SSL_get_peer_certificate(self._ssl)
1652 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001653 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001654 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655 return pycert
1656 return None
1657
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001658 def get_peer_cert_chain(self):
1659 """
1660 Retrieve the other side's certificate (if any)
1661
1662 :return: A list of X509 instances giving the peer's certificate chain,
1663 or None if it does not have one.
1664 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001665 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1666 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001667 return None
1668
1669 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001670 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001671 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001672 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001673 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001674 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675 result.append(pycert)
1676 return result
1677
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001678 def want_read(self):
1679 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001680 Checks if more data has to be read from the transport layer to complete
1681 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682
1683 :return: True iff more data has to be read
1684 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001685 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001686
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001687 def want_write(self):
1688 """
1689 Checks if there is data to write to the transport layer to complete an
1690 operation.
1691
1692 :return: True iff there is data to write
1693 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001695
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001696 def set_accept_state(self):
1697 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001698 Set the connection to work in server mode. The handshake will be
1699 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001700
1701 :return: None
1702 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001704
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705 def set_connect_state(self):
1706 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001707 Set the connection to work in client mode. The handshake will be
1708 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001709
1710 :return: None
1711 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001712 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001713
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001714 def get_session(self):
1715 """
1716 Returns the Session currently used.
1717
Alex Gaynor62da94d2015-09-05 14:37:34 -04001718 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1719 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001720 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001721 session = _lib.SSL_get1_session(self._ssl)
1722 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001723 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001725 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001726 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001727 return pysession
1728
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001729 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001730 """
1731 Set the session to be used when the TLS/SSL connection is established.
1732
1733 :param session: A Session instance representing the session to use.
1734 :returns: None
1735 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001736 if not isinstance(session, Session):
1737 raise TypeError("session must be a Session instance")
1738
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001740 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001741 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001742
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001743 def _get_finished_message(self, function):
1744 """
1745 Helper to implement :py:meth:`get_finished` and
1746 :py:meth:`get_peer_finished`.
1747
1748 :param function: Either :py:data:`SSL_get_finished`: or
1749 :py:data:`SSL_get_peer_finished`.
1750
1751 :return: :py:data:`None` if the desired message has not yet been
1752 received, otherwise the contents of the message.
1753 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1754 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001755 # The OpenSSL documentation says nothing about what might happen if the
1756 # count argument given is zero. Specifically, it doesn't say whether
1757 # the output buffer may be NULL in that case or not. Inspection of the
1758 # implementation reveals that it calls memcpy() unconditionally.
1759 # Section 7.1.4, paragraph 1 of the C standard suggests that
1760 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1761 # alone desirable) behavior (though it probably does on just about
1762 # every implementation...)
1763 #
1764 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1765 # one might expect) for the initial call so as to be safe against this
1766 # potentially undefined behavior.
1767 empty = _ffi.new("char[]", 0)
1768 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001769 if size == 0:
1770 # No Finished message so far.
1771 return None
1772
1773 buf = _ffi.new("char[]", size)
1774 function(self._ssl, buf, size)
1775 return _ffi.buffer(buf, size)[:]
1776
Fedor Brunner5747b932014-03-05 14:22:34 +01001777 def get_finished(self):
1778 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001779 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001780
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001781 :return: The contents of the message or :py:obj:`None` if the TLS
1782 handshake has not yet completed.
1783 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001784 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001785 return self._get_finished_message(_lib.SSL_get_finished)
1786
Fedor Brunner5747b932014-03-05 14:22:34 +01001787 def get_peer_finished(self):
1788 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001789 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001790
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001791 :return: The contents of the message or :py:obj:`None` if the TLS
1792 handshake has not yet completed.
1793 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001794 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001795 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001796
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001797 def get_cipher_name(self):
1798 """
1799 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001800
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001801 :returns: The name of the currently used cipher or :py:obj:`None`
1802 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001803 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001804 """
1805 cipher = _lib.SSL_get_current_cipher(self._ssl)
1806 if cipher == _ffi.NULL:
1807 return None
1808 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001809 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1810 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001811
1812 def get_cipher_bits(self):
1813 """
1814 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001815
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001816 :returns: The number of secret bits of the currently used cipher
1817 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001818 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001819 """
1820 cipher = _lib.SSL_get_current_cipher(self._ssl)
1821 if cipher == _ffi.NULL:
1822 return None
1823 else:
1824 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1825
1826 def get_cipher_version(self):
1827 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001828 Obtain the protocol version of the currently used cipher.
1829
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001830 :returns: The protocol name of the currently used cipher
1831 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001832 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001833 """
1834 cipher = _lib.SSL_get_current_cipher(self._ssl)
1835 if cipher == _ffi.NULL:
1836 return None
1837 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001838 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001839 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001840
Jim Shaverabff1882015-05-27 09:15:55 -04001841 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001842 """
1843 Obtain the protocol version of the current connection.
1844
1845 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001846 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001847 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001848 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001849 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001850 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001851 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001852
Jim Shaver208438c2015-05-28 09:52:38 -04001853 def get_protocol_version(self):
1854 """
1855 Obtain the protocol version of the current connection.
1856
1857 :returns: The TLS version of the current connection, for example
1858 the value for TLS 1 would be 0x769.
1859 :rtype: :py:class:`int`
1860 """
1861 version = _lib.SSL_version(self._ssl)
1862 return version
1863
Cory Benfield10b277f2015-04-13 17:12:42 -04001864 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001865 def get_next_proto_negotiated(self):
1866 """
1867 Get the protocol that was negotiated by NPN.
1868 """
1869 data = _ffi.new("unsigned char **")
1870 data_len = _ffi.new("unsigned int *")
1871
1872 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1873
Cory Benfieldcd010f62014-05-15 19:00:27 +01001874 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001875
Cory Benfield7907e332015-04-13 17:18:25 -04001876 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001877 def set_alpn_protos(self, protos):
1878 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001879 Specify the client's ALPN protocol list.
1880
1881 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001882
1883 :param protos: A list of the protocols to be offered to the server.
1884 This list should be a Python list of bytestrings representing the
1885 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1886 """
1887 # Take the list of protocols and join them together, prefixing them
1888 # with their lengths.
1889 protostr = b''.join(
1890 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1891 )
1892
1893 # Build a C string from the list. We don't need to save this off
1894 # because OpenSSL immediately copies the data out.
1895 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001896 input_str_len = _ffi.cast("unsigned", len(protostr))
1897 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001898
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001899 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001900 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001901 """
1902 Get the protocol that was negotiated by ALPN.
1903 """
Cory Benfield12eae892014-06-07 15:42:56 +01001904 data = _ffi.new("unsigned char **")
1905 data_len = _ffi.new("unsigned int *")
1906
1907 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1908
Cory Benfielde8e9c382015-04-11 17:33:48 -04001909 if not data_len:
1910 return b''
1911
Cory Benfield12eae892014-06-07 15:42:56 +01001912 return _ffi.buffer(data[0], data_len[0])[:]
1913
1914
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001915ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001916
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001917# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1918# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001919_lib.SSL_library_init()