blob: 0dbabc1a7b7c5b266c0556ae81413b7524157a60 [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
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05008from six import text_type as _text_type
Cory Benfield63759dc2015-04-12 08:57:03 -04009from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -080010from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010011from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050012
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050013from OpenSSL._util import (
14 ffi as _ffi,
15 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050016 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040017 native as _native,
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)
151
152
153class WantReadError(Error):
154 pass
155
156
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500157class WantWriteError(Error):
158 pass
159
160
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500161class WantX509LookupError(Error):
162 pass
163
164
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500165class ZeroReturnError(Error):
166 pass
167
168
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500169class SysCallError(Error):
170 pass
171
172
Cory Benfield0ea76e72015-03-22 09:05:28 +0000173class _CallbackExceptionHelper(object):
174 """
175 A base class for wrapper classes that allow for intelligent exception
176 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500177
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400178 :ivar list _problems: Any exceptions that occurred while executing in a
179 context where they could not be raised in the normal way. Typically
180 this is because OpenSSL has called into some Python code and requires a
181 return value. The exceptions are saved to be raised later when it is
182 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000183 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400184
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400185 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800186 self._problems = []
187
Cory Benfield0ea76e72015-03-22 09:05:28 +0000188 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400189 """
190 Raise an exception from the OpenSSL error queue or that was previously
191 captured whe running a callback.
192 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000193 if self._problems:
194 try:
195 _raise_current_error()
196 except Error:
197 pass
198 raise self._problems.pop(0)
199
200
201class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400202 """
203 Wrap a callback such that it can be used as a certificate verification
204 callback.
205 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400206
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800207 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400208 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800209
210 @wraps(callback)
211 def wrapper(ok, store_ctx):
212 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500213 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
214 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
215 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800216
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400217 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
218 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
219 connection = Connection._reverse_mapping[ssl]
220
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800221 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400222 result = callback(
223 connection, cert, error_number, error_depth, ok
224 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800225 except Exception as e:
226 self._problems.append(e)
227 return 0
228 else:
229 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500230 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800231 return 1
232 else:
233 return 0
234
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500235 self.callback = _ffi.callback(
236 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800237
238
Cory Benfield0ea76e72015-03-22 09:05:28 +0000239class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400240 """
241 Wrap a callback such that it can be used as an NPN advertisement callback.
242 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400243
Cory Benfield0ea76e72015-03-22 09:05:28 +0000244 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400245 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800246
Cory Benfield0ea76e72015-03-22 09:05:28 +0000247 @wraps(callback)
248 def wrapper(ssl, out, outlen, arg):
249 try:
250 conn = Connection._reverse_mapping[ssl]
251 protos = callback(conn)
252
253 # Join the protocols into a Python bytestring, length-prefixing
254 # each element.
255 protostr = b''.join(
256 chain.from_iterable((int2byte(len(p)), p) for p in protos)
257 )
258
259 # Save our callback arguments on the connection object. This is
260 # done to make sure that they don't get freed before OpenSSL
261 # uses them. Then, return them appropriately in the output
262 # parameters.
263 conn._npn_advertise_callback_args = [
264 _ffi.new("unsigned int *", len(protostr)),
265 _ffi.new("unsigned char[]", protostr),
266 ]
267 outlen[0] = conn._npn_advertise_callback_args[0][0]
268 out[0] = conn._npn_advertise_callback_args[1]
269 return 0
270 except Exception as e:
271 self._problems.append(e)
272 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
273
274 self.callback = _ffi.callback(
275 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
276 wrapper
277 )
278
279
280class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400281 """
282 Wrap a callback such that it can be used as an NPN selection callback.
283 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400284
Cory Benfield0ea76e72015-03-22 09:05:28 +0000285 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400286 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000287
288 @wraps(callback)
289 def wrapper(ssl, out, outlen, in_, inlen, arg):
290 try:
291 conn = Connection._reverse_mapping[ssl]
292
293 # The string passed to us is actually made up of multiple
294 # length-prefixed bytestrings. We need to split that into a
295 # list.
296 instr = _ffi.buffer(in_, inlen)[:]
297 protolist = []
298 while instr:
299 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400300 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000301 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400302 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000303
304 # Call the callback
305 outstr = callback(conn, protolist)
306
307 # Save our callback arguments on the connection object. This is
308 # done to make sure that they don't get freed before OpenSSL
309 # uses them. Then, return them appropriately in the output
310 # parameters.
311 conn._npn_select_callback_args = [
312 _ffi.new("unsigned char *", len(outstr)),
313 _ffi.new("unsigned char[]", outstr),
314 ]
315 outlen[0] = conn._npn_select_callback_args[0][0]
316 out[0] = conn._npn_select_callback_args[1]
317 return 0
318 except Exception as e:
319 self._problems.append(e)
320 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
321
322 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400323 ("int (*)(SSL *, unsigned char **, unsigned char *, "
324 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000325 wrapper
326 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800327
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800328
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400329class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400330 """
331 Wrap a callback such that it can be used as an ALPN selection callback.
332 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400333
Cory Benfieldf1177e72015-04-12 09:11:49 -0400334 def __init__(self, callback):
335 _CallbackExceptionHelper.__init__(self)
336
337 @wraps(callback)
338 def wrapper(ssl, out, outlen, in_, inlen, arg):
339 try:
340 conn = Connection._reverse_mapping[ssl]
341
342 # The string passed to us is made up of multiple
343 # length-prefixed bytestrings. We need to split that into a
344 # list.
345 instr = _ffi.buffer(in_, inlen)[:]
346 protolist = []
347 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400348 encoded_len = indexbytes(instr, 0)
349 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400350 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400351 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400352
353 # Call the callback
354 outstr = callback(conn, protolist)
355
356 if not isinstance(outstr, _binary_type):
357 raise TypeError("ALPN callback must return a bytestring.")
358
359 # Save our callback arguments on the connection object to make
360 # sure that they don't get freed before OpenSSL can use them.
361 # Then, return them in the appropriate output parameters.
362 conn._alpn_select_callback_args = [
363 _ffi.new("unsigned char *", len(outstr)),
364 _ffi.new("unsigned char[]", outstr),
365 ]
366 outlen[0] = conn._alpn_select_callback_args[0][0]
367 out[0] = conn._alpn_select_callback_args[1]
368 return 0
369 except Exception as e:
370 self._problems.append(e)
371 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
372
373 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400374 ("int (*)(SSL *, unsigned char **, unsigned char *, "
375 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400376 wrapper
377 )
378
379
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800380def _asFileDescriptor(obj):
381 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800382 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800383 meth = getattr(obj, "fileno", None)
384 if meth is not None:
385 obj = meth()
386
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800387 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800388 fd = obj
389
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800390 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800391 raise TypeError("argument must be an int, or have a fileno() method.")
392 elif fd < 0:
393 raise ValueError(
394 "file descriptor cannot be a negative integer (%i)" % (fd,))
395
396 return fd
397
398
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800399def SSLeay_version(type):
400 """
401 Return a string describing the version of OpenSSL in use.
402
403 :param type: One of the SSLEAY_ constants defined in this module.
404 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500405 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800406
407
Cory Benfield10b277f2015-04-13 17:12:42 -0400408def _requires_npn(func):
Cory Benfielda876cef2015-04-13 17:29:12 -0400409 """
410 Wraps any function that requires NPN support in OpenSSL, ensuring that
411 NotImplementedError is raised if NPN is not present.
412 """
Cory Benfield10b277f2015-04-13 17:12:42 -0400413 @wraps(func)
414 def wrapper(*args, **kwargs):
415 if not _lib.Cryptography_HAS_NEXTPROTONEG:
416 raise NotImplementedError("NPN not available.")
417
418 return func(*args, **kwargs)
419
420 return wrapper
421
422
Cory Benfield7907e332015-04-13 17:18:25 -0400423def _requires_alpn(func):
Cory Benfield9d80a762015-04-13 17:47:33 -0400424 """
425 Wraps any function that requires ALPN support in OpenSSL, ensuring that
426 NotImplementedError is raised if ALPN support is not present.
427 """
Cory Benfield7907e332015-04-13 17:18:25 -0400428 @wraps(func)
429 def wrapper(*args, **kwargs):
430 if not _lib.Cryptography_HAS_ALPN:
431 raise NotImplementedError("ALPN not available.")
432
433 return func(*args, **kwargs)
434
435 return wrapper
436
437
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800438class Session(object):
439 pass
440
441
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800442class Context(object):
443 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400444 :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting
445 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800446 """
447 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800448 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500449 SSLv3_METHOD: "SSLv3_method",
450 SSLv23_METHOD: "SSLv23_method",
451 TLSv1_METHOD: "TLSv1_method",
452 TLSv1_1_METHOD: "TLSv1_1_method",
453 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400454 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500455 _methods = dict(
456 (identifier, getattr(_lib, name))
457 for (identifier, name) in _methods.items()
458 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800459
460 def __init__(self, method):
461 """
462 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
463 TLSv1_METHOD.
464 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500465 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800466 raise TypeError("method must be an integer")
467
468 try:
469 method_func = self._methods[method]
470 except KeyError:
471 raise ValueError("No such protocol")
472
473 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500474 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500475 # TODO: This is untested.
476 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800477
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500478 context = _lib.SSL_CTX_new(method_obj)
479 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500480 # TODO: This is untested.
481 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500482 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800483
484 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800485 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800486 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800487 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800488 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800489 self._verify_callback = None
490 self._info_callback = None
491 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800492 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000493 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100494 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000495 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100496 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400497 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100498 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800499
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800500 # SSL_CTX_set_app_data(self->ctx, self);
501 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
502 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
503 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500504 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800505
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800506 def load_verify_locations(self, cafile, capath=None):
507 """
508 Let SSL know where we can find trusted certificates for the certificate
509 chain
510
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400511 :param cafile: In which file we can find the certificates (``bytes`` or
512 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800513 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400514 (``bytes`` or ``unicode``).
515
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800516 :return: None
517 """
518 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500519 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400520 else:
521 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800522
523 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500524 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400525 else:
526 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800527
Alex Gaynor62da94d2015-09-05 14:37:34 -0400528 load_result = _lib.SSL_CTX_load_verify_locations(
529 self._context, cafile, capath
530 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800531 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500532 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800533
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800534 def _wrap_callback(self, callback):
535 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800536 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800537 return callback(size, verify, self._passphrase_userdata)
538 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800539 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800540
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800541 def set_passwd_cb(self, callback, userdata=None):
542 """
543 Set the passphrase callback
544
545 :param callback: The Python callback to use
546 :param userdata: (optional) A Python object which will be given as
547 argument to the callback
548 :return: None
549 """
550 if not callable(callback):
551 raise TypeError("callback must be callable")
552
553 self._passphrase_helper = self._wrap_callback(callback)
554 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500555 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800556 self._context, self._passphrase_callback)
557 self._passphrase_userdata = userdata
558
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800559 def set_default_verify_paths(self):
560 """
561 Use the platform-specific CA certificate locations
562
563 :return: None
564 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500565 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800566 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500567 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500568 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800569
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800570 def use_certificate_chain_file(self, certfile):
571 """
572 Load a certificate chain from a file
573
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400574 :param certfile: The name of the certificate chain file (``bytes`` or
575 ``unicode``).
576
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800577 :return: None
578 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400579 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800580
Alex Gaynor62da94d2015-09-05 14:37:34 -0400581 result = _lib.SSL_CTX_use_certificate_chain_file(
582 self._context, certfile
583 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800584 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500585 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800586
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800587 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800588 """
589 Load a certificate from a file
590
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400591 :param certfile: The name of the certificate file (``bytes`` or
592 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800593 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400594
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800595 :return: None
596 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400597 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500598 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800599 raise TypeError("filetype must be an integer")
600
Alex Gaynor62da94d2015-09-05 14:37:34 -0400601 use_result = _lib.SSL_CTX_use_certificate_file(
602 self._context, certfile, filetype
603 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800604 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500605 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800606
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800607 def use_certificate(self, cert):
608 """
609 Load a certificate from a X509 object
610
611 :param cert: The X509 object
612 :return: None
613 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800614 if not isinstance(cert, X509):
615 raise TypeError("cert must be an X509 instance")
616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500617 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800618 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500619 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800620
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800621 def add_extra_chain_cert(self, certobj):
622 """
623 Add certificate to chain
624
625 :param certobj: The X509 certificate object to add to the chain
626 :return: None
627 """
628 if not isinstance(certobj, X509):
629 raise TypeError("certobj must be an X509 instance")
630
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500631 copy = _lib.X509_dup(certobj._x509)
632 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800633 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500634 # TODO: This is untested.
635 _lib.X509_free(copy)
636 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800637
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800638 def _raise_passphrase_exception(self):
639 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500640 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800641 exception = self._passphrase_helper.raise_if_problem(Error)
642 if exception is not None:
643 raise exception
644
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400645 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800646 """
647 Load a private key from a file
648
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400649 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800650 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400651
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800652 :return: None
653 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400654 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400656 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500658 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800659 raise TypeError("filetype must be an integer")
660
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500661 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800662 self._context, keyfile, filetype)
663 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800664 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800665
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666 def use_privatekey(self, pkey):
667 """
668 Load a private key from a PKey object
669
670 :param pkey: The PKey object
671 :return: None
672 """
673 if not isinstance(pkey, PKey):
674 raise TypeError("pkey must be a PKey instance")
675
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500676 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800677 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800678 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800679
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680 def check_privatekey(self):
681 """
682 Check that the private key and certificate match up
683
684 :return: None (raises an exception if something's wrong)
685 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500686 if not _lib.SSL_CTX_check_private_key(self._context):
687 _raise_current_error()
688
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800689 def load_client_ca(self, cafile):
690 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400691 Load the trusted certificates that will be sent to the client
692 (basically telling the client "These are the guys I trust"). Does not
693 actually imply any of the certificates are trusted; that must be
694 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695
696 :param cafile: The name of the certificates file
697 :return: None
698 """
699
700 def set_session_id(self, buf):
701 """
702 Set the session identifier. This is needed if you want to do session
703 resumption.
704
705 :param buf: A Python object that can be safely converted to a string
706 :returns: None
707 """
708
709 def set_session_cache_mode(self, mode):
710 """
711 Enable/disable session caching and specify the mode used.
712
713 :param mode: One or more of the SESS_CACHE_* flags (combine using
714 bitwise or)
715 :returns: The previously set caching mode.
716 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500717 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800718 raise TypeError("mode must be an integer")
719
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500720 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800721
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800722 def get_session_cache_mode(self):
723 """
724 :returns: The currently used cache mode.
725 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800727
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728 def set_verify(self, mode, callback):
729 """
730 Set the verify mode and verify callback
731
732 :param mode: The verify mode, this is either VERIFY_NONE or
733 VERIFY_PEER combined with possible other flags
734 :param callback: The Python callback to use
735 :return: None
736
737 See SSL_CTX_set_verify(3SSL) for further details.
738 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500739 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800740 raise TypeError("mode must be an integer")
741
742 if not callable(callback):
743 raise TypeError("callback must be callable")
744
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400745 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800746 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500747 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800749 def set_verify_depth(self, depth):
750 """
751 Set the verify depth
752
753 :param depth: An integer specifying the verify depth
754 :return: None
755 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500756 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757 raise TypeError("depth must be an integer")
758
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500759 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800760
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761 def get_verify_mode(self):
762 """
763 Get the verify mode
764
765 :return: The verify mode
766 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800768
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769 def get_verify_depth(self):
770 """
771 Get the verify depth
772
773 :return: The verify depth
774 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500775 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777 def load_tmp_dh(self, dhfile):
778 """
779 Load parameters for Ephemeral Diffie-Hellman
780
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400781 :param dhfile: The file to load EDH parameters from (``bytes`` or
782 ``unicode``).
783
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800784 :return: None
785 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400786 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500788 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500789 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500790 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500791 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500793 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
794 dh = _ffi.gc(dh, _lib.DH_free)
795 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800796
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400797 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600798 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700799 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600800
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400801 :param curve: A curve object to use as returned by either
802 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
803 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700804
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600805 :return: None
806 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400807 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600808
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809 def set_cipher_list(self, cipher_list):
810 """
811 Change the cipher list
812
813 :param cipher_list: A cipher list, see ciphers(1)
814 :return: None
815 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500816 if isinstance(cipher_list, _text_type):
817 cipher_list = cipher_list.encode("ascii")
818
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800819 if not isinstance(cipher_list, bytes):
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500820 raise TypeError("cipher_list must be bytes or unicode")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800821
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500822 result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800823 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500824 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800825
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800826 def set_client_ca_list(self, certificate_authorities):
827 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400828 Set the list of preferred client certificate signers for this server
829 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800830
Alex Gaynor62da94d2015-09-05 14:37:34 -0400831 This list of certificate authorities will be sent to the client when
832 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800833
834 :param certificate_authorities: a sequence of X509Names.
835 :return: None
836 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500837 name_stack = _lib.sk_X509_NAME_new_null()
838 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500839 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500840 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800841
842 try:
843 for ca_name in certificate_authorities:
844 if not isinstance(ca_name, X509Name):
845 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400846 "client CAs must be X509Name objects, not %s "
847 "objects" % (
848 type(ca_name).__name__,
849 )
850 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500851 copy = _lib.X509_NAME_dup(ca_name._name)
852 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500853 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500854 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500855 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800856 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500857 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500858 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800859 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500860 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800861 raise
862
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500863 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800864
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800865 def add_client_ca(self, certificate_authority):
866 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400867 Add the CA certificate to the list of preferred signers for this
868 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800869
870 The list of certificate authorities will be sent to the client when the
871 server requests a client certificate.
872
873 :param certificate_authority: certificate authority's X509 certificate.
874 :return: None
875 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800876 if not isinstance(certificate_authority, X509):
877 raise TypeError("certificate_authority must be an X509 instance")
878
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500879 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800880 self._context, certificate_authority._x509)
881 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500882 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500883 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800884
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800885 def set_timeout(self, timeout):
886 """
887 Set session timeout
888
889 :param timeout: The timeout in seconds
890 :return: The previous session timeout
891 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500892 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800893 raise TypeError("timeout must be an integer")
894
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500895 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800896
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800897 def get_timeout(self):
898 """
899 Get the session timeout
900
901 :return: The session timeout
902 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500903 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800904
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905 def set_info_callback(self, callback):
906 """
907 Set the info callback
908
909 :param callback: The Python callback to use
910 :return: None
911 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800912 @wraps(callback)
913 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500914 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500915 self._info_callback = _ffi.callback(
916 "void (*)(const SSL *, int, int)", wrapper)
917 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800918
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919 def get_app_data(self):
920 """
921 Get the application data (supplied via set_app_data())
922
923 :return: The application data
924 """
925 return self._app_data
926
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927 def set_app_data(self, data):
928 """
929 Set the application data (will be returned from get_app_data())
930
931 :param data: Any Python object
932 :return: None
933 """
934 self._app_data = data
935
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800936 def get_cert_store(self):
937 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500938 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500940 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800941 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500942 store = _lib.SSL_CTX_get_cert_store(self._context)
943 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500944 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800945 return None
946
947 pystore = X509Store.__new__(X509Store)
948 pystore._store = store
949 return pystore
950
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951 def set_options(self, options):
952 """
953 Add options. Options set before are not cleared!
954
955 :param options: The options to add.
956 :return: The new option bitmask.
957 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500958 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800959 raise TypeError("options must be an integer")
960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800963 def set_mode(self, mode):
964 """
965 Add modes via bitmask. Modes set before are not cleared!
966
967 :param mode: The mode to add.
968 :return: The new mode bitmask.
969 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500970 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800971 raise TypeError("mode must be an integer")
972
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500973 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975 def set_tlsext_servername_callback(self, callback):
976 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400977 Specify a callback function to be called when clients specify a server
978 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979
980 :param callback: The callback function. It will be invoked with one
981 argument, the Connection instance.
982 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800983 @wraps(callback)
984 def wrapper(ssl, alert, arg):
985 callback(Connection._reverse_mapping[ssl])
986 return 0
987
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 self._tlsext_servername_callback = _ffi.callback(
989 "int (*)(const SSL *, int *, void *)", wrapper)
990 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800991 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992
Cory Benfield10b277f2015-04-13 17:12:42 -0400993 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +0100994 def set_npn_advertise_callback(self, callback):
995 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +0100996 Specify a callback function that will be called when offering `Next
997 Protocol Negotiation
998 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +0100999
1000 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001001 argument, the Connection instance. It should return a list of
1002 bytestrings representing the advertised protocols, like
1003 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001004 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001005 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1006 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001007 _lib.SSL_CTX_set_next_protos_advertised_cb(
1008 self._context, self._npn_advertise_callback, _ffi.NULL)
1009
Cory Benfield10b277f2015-04-13 17:12:42 -04001010 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001011 def set_npn_select_callback(self, callback):
1012 """
1013 Specify a callback function that will be called when a server offers
1014 Next Protocol Negotiation options.
1015
1016 :param callback: The callback function. It will be invoked with two
1017 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001018 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1019 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001020 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001021 self._npn_select_helper = _NpnSelectHelper(callback)
1022 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001023 _lib.SSL_CTX_set_next_proto_select_cb(
1024 self._context, self._npn_select_callback, _ffi.NULL)
1025
Cory Benfield7907e332015-04-13 17:18:25 -04001026 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001027 def set_alpn_protos(self, protos):
1028 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001029 Specify the clients ALPN protocol list.
1030
1031 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001032
1033 :param protos: A list of the protocols to be offered to the server.
1034 This list should be a Python list of bytestrings representing the
1035 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1036 """
1037 # Take the list of protocols and join them together, prefixing them
1038 # with their lengths.
1039 protostr = b''.join(
1040 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1041 )
1042
1043 # Build a C string from the list. We don't need to save this off
1044 # because OpenSSL immediately copies the data out.
1045 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001046 input_str_len = _ffi.cast("unsigned", len(protostr))
1047 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001048
Cory Benfield7907e332015-04-13 17:18:25 -04001049 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001050 def set_alpn_select_callback(self, callback):
1051 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001052 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001053
1054 :param callback: The callback function. It will be invoked with two
1055 arguments: the Connection, and a list of offered protocols as
1056 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001057 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001058 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001059 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001060 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001061 _lib.SSL_CTX_set_alpn_select_cb(
1062 self._context, self._alpn_select_callback, _ffi.NULL)
1063
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001065
1066
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001067class Connection(object):
1068 """
1069 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001070 _reverse_mapping = WeakValueDictionary()
1071
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001072 def __init__(self, context, socket=None):
1073 """
1074 Create a new Connection object, using the given OpenSSL.SSL.Context
1075 instance and socket.
1076
1077 :param context: An SSL Context to use for this connection
1078 :param socket: The socket to use for transport layer
1079 """
1080 if not isinstance(context, Context):
1081 raise TypeError("context must be a Context instance")
1082
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001083 ssl = _lib.SSL_new(context._context)
1084 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001085 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001086 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001087
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001088 # References to strings used for Next Protocol Negotiation. OpenSSL's
1089 # header files suggest that these might get copied at some point, but
1090 # doesn't specify when, so we store them here to make sure they don't
1091 # get freed before OpenSSL uses them.
1092 self._npn_advertise_callback_args = None
1093 self._npn_select_callback_args = None
1094
Cory Benfield12eae892014-06-07 15:42:56 +01001095 # References to strings used for Application Layer Protocol
1096 # Negotiation. These strings get copied at some point but it's well
1097 # after the callback returns, so we have to hang them somewhere to
1098 # avoid them getting freed.
1099 self._alpn_select_callback_args = None
1100
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001101 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001102
1103 if socket is None:
1104 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001105 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001106 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1107 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001108
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001110 # TODO: This is untested.
1111 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001112
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001113 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001114 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001115 self._into_ssl = None
1116 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001118 set_result = _lib.SSL_set_fd(
1119 self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001120 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001121 # TODO: This is untested.
1122 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001124 def __getattr__(self, name):
1125 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001126 Look up attributes on the wrapped socket object if they are not found
1127 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001128 """
kjav0b66fa12015-09-02 11:51:26 +01001129 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001130 raise AttributeError("'%s' object has no attribute '%s'" % (
1131 self.__class__.__name__, name
1132 ))
kjav0b66fa12015-09-02 11:51:26 +01001133 else:
1134 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001135
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001136 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001137 if self._context._verify_helper is not None:
1138 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001139 if self._context._npn_advertise_helper is not None:
1140 self._context._npn_advertise_helper.raise_if_problem()
1141 if self._context._npn_select_helper is not None:
1142 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001143 if self._context._alpn_select_helper is not None:
1144 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001145
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001146 error = _lib.SSL_get_error(ssl, result)
1147 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001148 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001150 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001151 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001152 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001153 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001154 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001155 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 elif error == _lib.SSL_ERROR_SYSCALL:
1157 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001158 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001159 if platform == "win32":
1160 errno = _ffi.getwinerror()[0]
1161 else:
1162 errno = _ffi.errno
Glyph3afdba82015-04-14 17:30:53 -04001163 raise SysCallError(errno, errorcode.get(errno))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001164 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001165 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001166 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001167 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001168 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001170 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001171 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001172 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001173
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001174 def get_context(self):
1175 """
1176 Get session context
1177 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001178 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001179
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001180 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001181 """
1182 Switch this connection to a new session context
1183
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001184 :param context: A :py:class:`Context` instance giving the new session
1185 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001186 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001187 if not isinstance(context, Context):
1188 raise TypeError("context must be a Context instance")
1189
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001190 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191 self._context = context
1192
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001193 def get_servername(self):
1194 """
1195 Retrieve the servername extension value if provided in the client hello
1196 message, or None if there wasn't one.
1197
1198 :return: A byte string giving the server name or :py:data:`None`.
1199 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001200 name = _lib.SSL_get_servername(
1201 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1202 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001203 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001204 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001205
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001206 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001207
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001208 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001209 """
1210 Set the value of the servername extension to send in the client hello.
1211
1212 :param name: A byte string giving the name.
1213 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001214 if not isinstance(name, bytes):
1215 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001216 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001217 raise TypeError("name must not contain NUL byte")
1218
1219 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001220 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001221
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001222 def pending(self):
1223 """
1224 Get the number of bytes that can be safely read from the connection
1225
1226 :return: The number of bytes available in the receive buffer.
1227 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001228 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001229
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001230 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001231 """
1232 Send data on the connection. NOTE: If you get one of the WantRead,
1233 WantWrite or WantX509Lookup exceptions on this, you have to call the
1234 method again with the SAME buffer.
1235
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001236 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001237 :param flags: (optional) Included for compatibility with the socket
1238 API, the value is ignored
1239 :return: The number of bytes written
1240 """
Abraham Martine82326c2015-02-04 10:18:10 +00001241 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001242 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001243
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001244 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001245 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001246 if isinstance(buf, _buffer):
1247 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001248 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001249 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001250
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001251 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001252 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001253 return result
1254 write = send
1255
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001256 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001257 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001258 Send "all" data on the connection. This calls send() repeatedly until
1259 all data is sent. If an error occurs, it's impossible to tell how much
1260 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001261
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001262 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001263 :param flags: (optional) Included for compatibility with the socket
1264 API, the value is ignored
1265 :return: The number of bytes written
1266 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001267 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001268
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001269 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001270 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001271 if isinstance(buf, _buffer):
1272 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001273 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001274 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001275
1276 left_to_send = len(buf)
1277 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001279
1280 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001281 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001282 self._raise_ssl_error(self._ssl, result)
1283 total_sent += result
1284 left_to_send -= result
1285
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001286 def recv(self, bufsiz, flags=None):
1287 """
1288 Receive data on the connection. NOTE: If you get one of the WantRead,
1289 WantWrite or WantX509Lookup exceptions on this, you have to call the
1290 method again with the SAME buffer.
1291
1292 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001293 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1294 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295 :return: The string read from the Connection
1296 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001297 buf = _ffi.new("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001298 if flags is not None and flags & socket.MSG_PEEK:
1299 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1300 else:
1301 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001302 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001304 read = recv
1305
Cory Benfield62d10332014-06-15 10:03:41 +01001306 def recv_into(self, buffer, nbytes=None, flags=None):
1307 """
1308 Receive data on the connection and store the data into a buffer rather
1309 than creating a new string.
1310
1311 :param buffer: The buffer to copy into.
1312 :param nbytes: (optional) The maximum number of bytes to read into the
1313 buffer. If not present, defaults to the size of the buffer. If
1314 larger than the size of the buffer, is reduced to the size of the
1315 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001316 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1317 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001318 :return: The number of bytes read into the buffer.
1319 """
1320 if nbytes is None:
1321 nbytes = len(buffer)
1322 else:
1323 nbytes = min(nbytes, len(buffer))
1324
1325 # We need to create a temporary buffer. This is annoying, it would be
1326 # better if we could pass memoryviews straight into the SSL_read call,
1327 # but right now we can't. Revisit this if CFFI gets that ability.
1328 buf = _ffi.new("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001329 if flags is not None and flags & socket.MSG_PEEK:
1330 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1331 else:
1332 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001333 self._raise_ssl_error(self._ssl, result)
1334
1335 # This strange line is all to avoid a memory copy. The buffer protocol
1336 # should allow us to assign a CFFI buffer to the LHS of this line, but
1337 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1338 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1339 # memoryview type.
1340 try:
1341 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1342 except NameError:
1343 buffer[:result] = _ffi.buffer(buf, result)
1344
1345 return result
1346
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001347 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001348 if _lib.BIO_should_retry(bio):
1349 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001350 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001352 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001353 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001355 # TODO: This is untested. I think io_special means the socket
1356 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001357 raise ValueError("BIO_should_io_special")
1358 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001359 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001360 raise ValueError("unknown bio failure")
1361 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001362 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001363 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001364
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001365 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001366 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367 When using non-socket connections this function reads the "dirty" data
1368 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001369
1370 :param bufsiz: The maximum number of bytes to read
1371 :return: The string read.
1372 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001373 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001374 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001375
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001376 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001377 raise TypeError("bufsiz must be an integer")
1378
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001379 buf = _ffi.new("char[]", bufsiz)
1380 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001381 if result <= 0:
1382 self._handle_bio_errors(self._from_ssl, result)
1383
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001384 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001386 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001387 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001388 When using non-socket connections this function sends "dirty" data that
1389 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390
1391 :param buf: The string to put into the memory BIO.
1392 :return: The number of bytes written
1393 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001394 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001395
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001396 if self._into_ssl is None:
1397 raise TypeError("Connection sock was not None")
1398
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001399 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001400 if result <= 0:
1401 self._handle_bio_errors(self._into_ssl, result)
1402 return result
1403
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001404 def renegotiate(self):
1405 """
1406 Renegotiate the session
1407
1408 :return: True if the renegotiation can be started, false otherwise
1409 """
1410
1411 def do_handshake(self):
1412 """
1413 Perform an SSL handshake (usually called after renegotiate() or one of
1414 set_*_state()). This can raise the same exceptions as send and recv.
1415
1416 :return: None.
1417 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001418 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001419 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001420
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001421 def renegotiate_pending(self):
1422 """
1423 Check if there's a renegotiation in progress, it will return false once
1424 a renegotiation is finished.
1425
1426 :return: Whether there's a renegotiation in progress
1427 """
1428
1429 def total_renegotiations(self):
1430 """
1431 Find out the total number of renegotiations.
1432
1433 :return: The number of renegotiations.
1434 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001435 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001436
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001437 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001438 """
1439 Connect to remote host and set up client-side SSL
1440
1441 :param addr: A remote address
1442 :return: What the socket's connect method returns
1443 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001444 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001445 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001446
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001447 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001448 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001449 Connect to remote host and set up client-side SSL. Note that if the
1450 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001451
1452 :param addr: A remove address
1453 :return: What the socket's connect_ex method returns
1454 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001455 connect_ex = self._socket.connect_ex
1456 self.set_connect_state()
1457 return connect_ex(addr)
1458
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001459 def accept(self):
1460 """
1461 Accept incoming connection and set up SSL on it
1462
1463 :return: A (conn,addr) pair where conn is a Connection and addr is an
1464 address
1465 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 client, addr = self._socket.accept()
1467 conn = Connection(self._context, client)
1468 conn.set_accept_state()
1469 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001471 def bio_shutdown(self):
1472 """
1473 When using non-socket connections this function signals end of
1474 data on the input for this connection.
1475
1476 :return: None
1477 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001478 if self._from_ssl is None:
1479 raise TypeError("Connection sock was not None")
1480
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001481 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001482
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001483 def shutdown(self):
1484 """
1485 Send closure alert
1486
1487 :return: True if the shutdown completed successfully (i.e. both sides
1488 have sent closure alerts), false otherwise (i.e. you have to
1489 wait for a ZeroReturnError on a recv() method call
1490 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001491 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001492 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001493 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001495 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001496 else:
1497 return False
1498
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001499 def get_cipher_list(self):
1500 """
1501 Get the session cipher list
1502
1503 :return: A list of cipher strings
1504 """
1505 ciphers = []
1506 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001507 result = _lib.SSL_get_cipher_list(self._ssl, i)
1508 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001509 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001510 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001511 return ciphers
1512
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513 def get_client_ca_list(self):
1514 """
1515 Get CAs whose certificates are suggested for client authentication.
1516
Alex Gaynor62da94d2015-09-05 14:37:34 -04001517 :return: If this is a server connection, a list of X509Names
1518 representing the acceptable CAs as set by
1519 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1520 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1521 connection, the list of such X509Names sent by the server, or an
1522 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001524 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1525 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001526 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001527 return []
1528
1529 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001530 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1531 name = _lib.sk_X509_NAME_value(ca_names, i)
1532 copy = _lib.X509_NAME_dup(name)
1533 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001534 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001535 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001536
1537 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001538 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001539 result.append(pyname)
1540 return result
1541
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001542 def makefile(self):
1543 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001544 The makefile() method is not implemented, since there is no dup
1545 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001546
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001547 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001548 """
Alex Gaynor83284952015-09-05 10:43:30 -04001549 raise NotImplementedError(
1550 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001551
1552 def get_app_data(self):
1553 """
1554 Get application data
1555
1556 :return: The application data
1557 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001558 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001560 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001561 """
1562 Set application data
1563
1564 :param data - The application data
1565 :return: None
1566 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567 self._app_data = data
1568
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001569 def get_shutdown(self):
1570 """
1571 Get shutdown state
1572
Alex Gaynor62da94d2015-09-05 14:37:34 -04001573 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1574 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001575 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001576 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001577
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001578 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579 """
1580 Set shutdown state
1581
1582 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1583 :return: None
1584 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001585 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 raise TypeError("state must be an integer")
1587
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001588 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001589
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001590 def state_string(self):
1591 """
1592 Get a verbose state description
1593
1594 :return: A string representing the state
1595 """
kjavc704a2e2015-09-07 12:12:27 +01001596 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597
1598 def server_random(self):
1599 """
1600 Get a copy of the server hello nonce.
1601
1602 :return: A string representing the state
1603 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001604 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001606 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001608 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001609
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610 def client_random(self):
1611 """
1612 Get a copy of the client hello nonce.
1613
1614 :return: A string representing the state
1615 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001616 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001618 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001620 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001621
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001622 def master_key(self):
1623 """
1624 Get a copy of the master key.
1625
1626 :return: A string representing the state
1627 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001629 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001630 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001631 self._ssl.session.master_key,
1632 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001634 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001635 """
1636 See shutdown(2)
1637
1638 :return: What the socket's shutdown() method returns
1639 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001640 return self._socket.shutdown(*args, **kwargs)
1641
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001642 def get_peer_certificate(self):
1643 """
1644 Retrieve the other side's certificate (if any)
1645
1646 :return: The peer's certificate
1647 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001648 cert = _lib.SSL_get_peer_certificate(self._ssl)
1649 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001652 return pycert
1653 return None
1654
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655 def get_peer_cert_chain(self):
1656 """
1657 Retrieve the other side's certificate (if any)
1658
1659 :return: A list of X509 instances giving the peer's certificate chain,
1660 or None if it does not have one.
1661 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001662 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1663 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 return None
1665
1666 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001667 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001668 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001669 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001671 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001672 result.append(pycert)
1673 return result
1674
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001675 def want_read(self):
1676 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001677 Checks if more data has to be read from the transport layer to complete
1678 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001679
1680 :return: True iff more data has to be read
1681 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001682 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001683
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684 def want_write(self):
1685 """
1686 Checks if there is data to write to the transport layer to complete an
1687 operation.
1688
1689 :return: True iff there is data to write
1690 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001691 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001692
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001693 def set_accept_state(self):
1694 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001695 Set the connection to work in server mode. The handshake will be
1696 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697
1698 :return: None
1699 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001700 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 def set_connect_state(self):
1703 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001704 Set the connection to work in client mode. The handshake will be
1705 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001706
1707 :return: None
1708 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 def get_session(self):
1712 """
1713 Returns the Session currently used.
1714
Alex Gaynor62da94d2015-09-05 14:37:34 -04001715 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1716 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001717 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 session = _lib.SSL_get1_session(self._ssl)
1719 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001722 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001723 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001724 return pysession
1725
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001726 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001727 """
1728 Set the session to be used when the TLS/SSL connection is established.
1729
1730 :param session: A Session instance representing the session to use.
1731 :returns: None
1732 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001733 if not isinstance(session, Session):
1734 raise TypeError("session must be a Session instance")
1735
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001736 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001737 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001738 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001739
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001740 def _get_finished_message(self, function):
1741 """
1742 Helper to implement :py:meth:`get_finished` and
1743 :py:meth:`get_peer_finished`.
1744
1745 :param function: Either :py:data:`SSL_get_finished`: or
1746 :py:data:`SSL_get_peer_finished`.
1747
1748 :return: :py:data:`None` if the desired message has not yet been
1749 received, otherwise the contents of the message.
1750 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1751 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001752 # The OpenSSL documentation says nothing about what might happen if the
1753 # count argument given is zero. Specifically, it doesn't say whether
1754 # the output buffer may be NULL in that case or not. Inspection of the
1755 # implementation reveals that it calls memcpy() unconditionally.
1756 # Section 7.1.4, paragraph 1 of the C standard suggests that
1757 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1758 # alone desirable) behavior (though it probably does on just about
1759 # every implementation...)
1760 #
1761 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1762 # one might expect) for the initial call so as to be safe against this
1763 # potentially undefined behavior.
1764 empty = _ffi.new("char[]", 0)
1765 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001766 if size == 0:
1767 # No Finished message so far.
1768 return None
1769
1770 buf = _ffi.new("char[]", size)
1771 function(self._ssl, buf, size)
1772 return _ffi.buffer(buf, size)[:]
1773
Fedor Brunner5747b932014-03-05 14:22:34 +01001774 def get_finished(self):
1775 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001776 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001777
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001778 :return: The contents of the message or :py:obj:`None` if the TLS
1779 handshake has not yet completed.
1780 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001781 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001782 return self._get_finished_message(_lib.SSL_get_finished)
1783
Fedor Brunner5747b932014-03-05 14:22:34 +01001784 def get_peer_finished(self):
1785 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001786 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001787
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001788 :return: The contents of the message or :py:obj:`None` if the TLS
1789 handshake has not yet completed.
1790 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001791 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001792 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001793
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001794 def get_cipher_name(self):
1795 """
1796 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001797
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001798 :returns: The name of the currently used cipher or :py:obj:`None`
1799 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001800 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001801 """
1802 cipher = _lib.SSL_get_current_cipher(self._ssl)
1803 if cipher == _ffi.NULL:
1804 return None
1805 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001806 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1807 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001808
1809 def get_cipher_bits(self):
1810 """
1811 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001812
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001813 :returns: The number of secret bits of the currently used cipher
1814 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001815 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001816 """
1817 cipher = _lib.SSL_get_current_cipher(self._ssl)
1818 if cipher == _ffi.NULL:
1819 return None
1820 else:
1821 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1822
1823 def get_cipher_version(self):
1824 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001825 Obtain the protocol version of the currently used cipher.
1826
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001827 :returns: The protocol name of the currently used cipher
1828 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001829 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001830 """
1831 cipher = _lib.SSL_get_current_cipher(self._ssl)
1832 if cipher == _ffi.NULL:
1833 return None
1834 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001835 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001836 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001837
Jim Shaverabff1882015-05-27 09:15:55 -04001838 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001839 """
1840 Obtain the protocol version of the current connection.
1841
1842 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001843 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001844 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001845 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001846 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001847 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001848 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001849
Jim Shaver208438c2015-05-28 09:52:38 -04001850 def get_protocol_version(self):
1851 """
1852 Obtain the protocol version of the current connection.
1853
1854 :returns: The TLS version of the current connection, for example
1855 the value for TLS 1 would be 0x769.
1856 :rtype: :py:class:`int`
1857 """
1858 version = _lib.SSL_version(self._ssl)
1859 return version
1860
Cory Benfield10b277f2015-04-13 17:12:42 -04001861 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001862 def get_next_proto_negotiated(self):
1863 """
1864 Get the protocol that was negotiated by NPN.
1865 """
1866 data = _ffi.new("unsigned char **")
1867 data_len = _ffi.new("unsigned int *")
1868
1869 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1870
Cory Benfieldcd010f62014-05-15 19:00:27 +01001871 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001872
Cory Benfield7907e332015-04-13 17:18:25 -04001873 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001874 def set_alpn_protos(self, protos):
1875 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001876 Specify the client's ALPN protocol list.
1877
1878 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001879
1880 :param protos: A list of the protocols to be offered to the server.
1881 This list should be a Python list of bytestrings representing the
1882 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1883 """
1884 # Take the list of protocols and join them together, prefixing them
1885 # with their lengths.
1886 protostr = b''.join(
1887 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1888 )
1889
1890 # Build a C string from the list. We don't need to save this off
1891 # because OpenSSL immediately copies the data out.
1892 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001893 input_str_len = _ffi.cast("unsigned", len(protostr))
1894 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001895
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001896 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001897 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001898 """
1899 Get the protocol that was negotiated by ALPN.
1900 """
Cory Benfield12eae892014-06-07 15:42:56 +01001901 data = _ffi.new("unsigned char **")
1902 data_len = _ffi.new("unsigned int *")
1903
1904 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1905
Cory Benfielde8e9c382015-04-11 17:33:48 -04001906 if not data_len:
1907 return b''
1908
Cory Benfield12eae892014-06-07 15:42:56 +01001909 return _ffi.buffer(data[0], data_len[0])[:]
1910
1911
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001912ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001913
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001914# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1915# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001916_lib.SSL_library_init()