blob: f8f5e02e449c05cc5680eddddc7e7506f68a6047 [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
1086
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001087 # References to strings used for Next Protocol Negotiation. OpenSSL's
1088 # header files suggest that these might get copied at some point, but
1089 # doesn't specify when, so we store them here to make sure they don't
1090 # get freed before OpenSSL uses them.
1091 self._npn_advertise_callback_args = None
1092 self._npn_select_callback_args = None
1093
Cory Benfield12eae892014-06-07 15:42:56 +01001094 # References to strings used for Application Layer Protocol
1095 # Negotiation. These strings get copied at some point but it's well
1096 # after the callback returns, so we have to hang them somewhere to
1097 # avoid them getting freed.
1098 self._alpn_select_callback_args = None
1099
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001100 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001101
1102 if socket is None:
1103 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001104 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001105 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1106 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001107
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001108 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001109 # TODO: This is untested.
1110 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001112 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001113 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001114 self._into_ssl = None
1115 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001116 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001117 set_result = _lib.SSL_set_fd(
1118 self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001119 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001120 # TODO: This is untested.
1121 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001122
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123 def __getattr__(self, name):
1124 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001125 Look up attributes on the wrapped socket object if they are not found
1126 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001127 """
kjav0b66fa12015-09-02 11:51:26 +01001128 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001129 raise AttributeError("'%s' object has no attribute '%s'" % (
1130 self.__class__.__name__, name
1131 ))
kjav0b66fa12015-09-02 11:51:26 +01001132 else:
1133 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001134
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001135 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001136 if self._context._verify_helper is not None:
1137 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001138 if self._context._npn_advertise_helper is not None:
1139 self._context._npn_advertise_helper.raise_if_problem()
1140 if self._context._npn_select_helper is not None:
1141 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001142 if self._context._alpn_select_helper is not None:
1143 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001144
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 error = _lib.SSL_get_error(ssl, result)
1146 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001147 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001149 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001150 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001151 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001153 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001154 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 elif error == _lib.SSL_ERROR_SYSCALL:
1156 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001157 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001158 if platform == "win32":
1159 errno = _ffi.getwinerror()[0]
1160 else:
1161 errno = _ffi.errno
Glyph3afdba82015-04-14 17:30:53 -04001162 raise SysCallError(errno, errorcode.get(errno))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001163 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001164 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001165 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001166 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001167 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001169 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001170 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001171 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001172
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001173 def get_context(self):
1174 """
1175 Get session context
1176 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001177 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001178
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001179 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001180 """
1181 Switch this connection to a new session context
1182
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001183 :param context: A :py:class:`Context` instance giving the new session
1184 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001185 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001186 if not isinstance(context, Context):
1187 raise TypeError("context must be a Context instance")
1188
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001189 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001190 self._context = context
1191
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001192 def get_servername(self):
1193 """
1194 Retrieve the servername extension value if provided in the client hello
1195 message, or None if there wasn't one.
1196
1197 :return: A byte string giving the server name or :py:data:`None`.
1198 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001199 name = _lib.SSL_get_servername(
1200 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1201 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001202 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001203 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001204
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001205 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001206
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001207 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001208 """
1209 Set the value of the servername extension to send in the client hello.
1210
1211 :param name: A byte string giving the name.
1212 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001213 if not isinstance(name, bytes):
1214 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001215 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001216 raise TypeError("name must not contain NUL byte")
1217
1218 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001219 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001220
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001221 def pending(self):
1222 """
1223 Get the number of bytes that can be safely read from the connection
1224
1225 :return: The number of bytes available in the receive buffer.
1226 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001227 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001228
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001229 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001230 """
1231 Send data on the connection. NOTE: If you get one of the WantRead,
1232 WantWrite or WantX509Lookup exceptions on this, you have to call the
1233 method again with the SAME buffer.
1234
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001235 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001236 :param flags: (optional) Included for compatibility with the socket
1237 API, the value is ignored
1238 :return: The number of bytes written
1239 """
Abraham Martine82326c2015-02-04 10:18:10 +00001240 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001241 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001242
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001243 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001244 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001245 if isinstance(buf, _buffer):
1246 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001247 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001248 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001249
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001250 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001251 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001252 return result
1253 write = send
1254
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001255 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001256 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001257 Send "all" data on the connection. This calls send() repeatedly until
1258 all data is sent. If an error occurs, it's impossible to tell how much
1259 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001260
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001261 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001262 :param flags: (optional) Included for compatibility with the socket
1263 API, the value is ignored
1264 :return: The number of bytes written
1265 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001266 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001267
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001268 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001269 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001270 if isinstance(buf, _buffer):
1271 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001272 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001273 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001274
1275 left_to_send = len(buf)
1276 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001277 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001278
1279 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001280 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281 self._raise_ssl_error(self._ssl, result)
1282 total_sent += result
1283 left_to_send -= result
1284
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001285 def recv(self, bufsiz, flags=None):
1286 """
1287 Receive data on the connection. NOTE: If you get one of the WantRead,
1288 WantWrite or WantX509Lookup exceptions on this, you have to call the
1289 method again with the SAME buffer.
1290
1291 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001292 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1293 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001294 :return: The string read from the Connection
1295 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001296 buf = _ffi.new("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001297 if flags is not None and flags & socket.MSG_PEEK:
1298 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1299 else:
1300 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001301 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001302 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001303 read = recv
1304
Cory Benfield62d10332014-06-15 10:03:41 +01001305 def recv_into(self, buffer, nbytes=None, flags=None):
1306 """
1307 Receive data on the connection and store the data into a buffer rather
1308 than creating a new string.
1309
1310 :param buffer: The buffer to copy into.
1311 :param nbytes: (optional) The maximum number of bytes to read into the
1312 buffer. If not present, defaults to the size of the buffer. If
1313 larger than the size of the buffer, is reduced to the size of the
1314 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001315 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1316 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001317 :return: The number of bytes read into the buffer.
1318 """
1319 if nbytes is None:
1320 nbytes = len(buffer)
1321 else:
1322 nbytes = min(nbytes, len(buffer))
1323
1324 # We need to create a temporary buffer. This is annoying, it would be
1325 # better if we could pass memoryviews straight into the SSL_read call,
1326 # but right now we can't. Revisit this if CFFI gets that ability.
1327 buf = _ffi.new("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001328 if flags is not None and flags & socket.MSG_PEEK:
1329 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1330 else:
1331 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001332 self._raise_ssl_error(self._ssl, result)
1333
1334 # This strange line is all to avoid a memory copy. The buffer protocol
1335 # should allow us to assign a CFFI buffer to the LHS of this line, but
1336 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1337 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1338 # memoryview type.
1339 try:
1340 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1341 except NameError:
1342 buffer[:result] = _ffi.buffer(buf, result)
1343
1344 return result
1345
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001346 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001347 if _lib.BIO_should_retry(bio):
1348 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001349 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001350 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001351 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001352 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001353 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001354 # TODO: This is untested. I think io_special means the socket
1355 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001356 raise ValueError("BIO_should_io_special")
1357 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001358 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001359 raise ValueError("unknown bio failure")
1360 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001361 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001362 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001363
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001364 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001365 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001366 When using non-socket connections this function reads the "dirty" data
1367 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001368
1369 :param bufsiz: The maximum number of bytes to read
1370 :return: The string read.
1371 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001372 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001373 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001374
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001375 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001376 raise TypeError("bufsiz must be an integer")
1377
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001378 buf = _ffi.new("char[]", bufsiz)
1379 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001380 if result <= 0:
1381 self._handle_bio_errors(self._from_ssl, result)
1382
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001383 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001384
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001386 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001387 When using non-socket connections this function sends "dirty" data that
1388 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001389
1390 :param buf: The string to put into the memory BIO.
1391 :return: The number of bytes written
1392 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001393 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001394
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001395 if self._into_ssl is None:
1396 raise TypeError("Connection sock was not None")
1397
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001398 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001399 if result <= 0:
1400 self._handle_bio_errors(self._into_ssl, result)
1401 return result
1402
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001403 def renegotiate(self):
1404 """
1405 Renegotiate the session
1406
1407 :return: True if the renegotiation can be started, false otherwise
1408 """
1409
1410 def do_handshake(self):
1411 """
1412 Perform an SSL handshake (usually called after renegotiate() or one of
1413 set_*_state()). This can raise the same exceptions as send and recv.
1414
1415 :return: None.
1416 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001417 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001418 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001419
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001420 def renegotiate_pending(self):
1421 """
1422 Check if there's a renegotiation in progress, it will return false once
1423 a renegotiation is finished.
1424
1425 :return: Whether there's a renegotiation in progress
1426 """
1427
1428 def total_renegotiations(self):
1429 """
1430 Find out the total number of renegotiations.
1431
1432 :return: The number of renegotiations.
1433 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001434 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001435
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001436 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001437 """
1438 Connect to remote host and set up client-side SSL
1439
1440 :param addr: A remote address
1441 :return: What the socket's connect method returns
1442 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001443 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001444 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001445
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001446 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001447 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001448 Connect to remote host and set up client-side SSL. Note that if the
1449 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001450
1451 :param addr: A remove address
1452 :return: What the socket's connect_ex method returns
1453 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001454 connect_ex = self._socket.connect_ex
1455 self.set_connect_state()
1456 return connect_ex(addr)
1457
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001458 def accept(self):
1459 """
1460 Accept incoming connection and set up SSL on it
1461
1462 :return: A (conn,addr) pair where conn is a Connection and addr is an
1463 address
1464 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465 client, addr = self._socket.accept()
1466 conn = Connection(self._context, client)
1467 conn.set_accept_state()
1468 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470 def bio_shutdown(self):
1471 """
1472 When using non-socket connections this function signals end of
1473 data on the input for this connection.
1474
1475 :return: None
1476 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001477 if self._from_ssl is None:
1478 raise TypeError("Connection sock was not None")
1479
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001480 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001481
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001482 def shutdown(self):
1483 """
1484 Send closure alert
1485
1486 :return: True if the shutdown completed successfully (i.e. both sides
1487 have sent closure alerts), false otherwise (i.e. you have to
1488 wait for a ZeroReturnError on a recv() method call
1489 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001490 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001491 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001492 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001493 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495 else:
1496 return False
1497
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001498 def get_cipher_list(self):
1499 """
1500 Get the session cipher list
1501
1502 :return: A list of cipher strings
1503 """
1504 ciphers = []
1505 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001506 result = _lib.SSL_get_cipher_list(self._ssl, i)
1507 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001508 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001509 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510 return ciphers
1511
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 def get_client_ca_list(self):
1513 """
1514 Get CAs whose certificates are suggested for client authentication.
1515
Alex Gaynor62da94d2015-09-05 14:37:34 -04001516 :return: If this is a server connection, a list of X509Names
1517 representing the acceptable CAs as set by
1518 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1519 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1520 connection, the list of such X509Names sent by the server, or an
1521 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001522 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001523 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1524 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001525 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001526 return []
1527
1528 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001529 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1530 name = _lib.sk_X509_NAME_value(ca_names, i)
1531 copy = _lib.X509_NAME_dup(name)
1532 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001533 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001534 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001535
1536 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001537 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538 result.append(pyname)
1539 return result
1540
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001541 def makefile(self):
1542 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001543 The makefile() method is not implemented, since there is no dup
1544 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001546 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001547 """
Alex Gaynor83284952015-09-05 10:43:30 -04001548 raise NotImplementedError(
1549 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001550
1551 def get_app_data(self):
1552 """
1553 Get application data
1554
1555 :return: The application data
1556 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001557 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001558
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001559 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001560 """
1561 Set application data
1562
1563 :param data - The application data
1564 :return: None
1565 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 self._app_data = data
1567
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001568 def get_shutdown(self):
1569 """
1570 Get shutdown state
1571
Alex Gaynor62da94d2015-09-05 14:37:34 -04001572 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1573 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001575 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001576
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578 """
1579 Set shutdown state
1580
1581 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1582 :return: None
1583 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001584 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001585 raise TypeError("state must be an integer")
1586
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001587 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001588
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001589 def state_string(self):
1590 """
1591 Get a verbose state description
1592
1593 :return: A string representing the state
1594 """
1595
1596 def server_random(self):
1597 """
1598 Get a copy of the server hello nonce.
1599
1600 :return: A string representing the state
1601 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001602 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001603 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001604 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001606 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608 def client_random(self):
1609 """
1610 Get a copy of the client hello nonce.
1611
1612 :return: A string representing the state
1613 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001614 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001615 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001616 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001618 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620 def master_key(self):
1621 """
1622 Get a copy of the master key.
1623
1624 :return: A string representing the state
1625 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001626 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001627 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001629 self._ssl.session.master_key,
1630 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001631
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633 """
1634 See shutdown(2)
1635
1636 :return: What the socket's shutdown() method returns
1637 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001638 return self._socket.shutdown(*args, **kwargs)
1639
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001640 def get_peer_certificate(self):
1641 """
1642 Retrieve the other side's certificate (if any)
1643
1644 :return: The peer's certificate
1645 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001646 cert = _lib.SSL_get_peer_certificate(self._ssl)
1647 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001648 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001649 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001650 return pycert
1651 return None
1652
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001653 def get_peer_cert_chain(self):
1654 """
1655 Retrieve the other side's certificate (if any)
1656
1657 :return: A list of X509 instances giving the peer's certificate chain,
1658 or None if it does not have one.
1659 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001660 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1661 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 return None
1663
1664 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001665 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001666 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001667 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001668 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001669 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670 result.append(pycert)
1671 return result
1672
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 def want_read(self):
1674 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001675 Checks if more data has to be read from the transport layer to complete
1676 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677
1678 :return: True iff more data has to be read
1679 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001680 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682 def want_write(self):
1683 """
1684 Checks if there is data to write to the transport layer to complete an
1685 operation.
1686
1687 :return: True iff there is data to write
1688 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001690
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001691 def set_accept_state(self):
1692 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001693 Set the connection to work in server mode. The handshake will be
1694 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001695
1696 :return: None
1697 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001698 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001699
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001700 def set_connect_state(self):
1701 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001702 Set the connection to work in client mode. The handshake will be
1703 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001704
1705 :return: None
1706 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001707 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001708
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001709 def get_session(self):
1710 """
1711 Returns the Session currently used.
1712
Alex Gaynor62da94d2015-09-05 14:37:34 -04001713 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1714 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001716 session = _lib.SSL_get1_session(self._ssl)
1717 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001718 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001721 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001722 return pysession
1723
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001724 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 """
1726 Set the session to be used when the TLS/SSL connection is established.
1727
1728 :param session: A Session instance representing the session to use.
1729 :returns: None
1730 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001731 if not isinstance(session, Session):
1732 raise TypeError("session must be a Session instance")
1733
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001734 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001735 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001736 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001737
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001738 def _get_finished_message(self, function):
1739 """
1740 Helper to implement :py:meth:`get_finished` and
1741 :py:meth:`get_peer_finished`.
1742
1743 :param function: Either :py:data:`SSL_get_finished`: or
1744 :py:data:`SSL_get_peer_finished`.
1745
1746 :return: :py:data:`None` if the desired message has not yet been
1747 received, otherwise the contents of the message.
1748 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1749 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001750 # The OpenSSL documentation says nothing about what might happen if the
1751 # count argument given is zero. Specifically, it doesn't say whether
1752 # the output buffer may be NULL in that case or not. Inspection of the
1753 # implementation reveals that it calls memcpy() unconditionally.
1754 # Section 7.1.4, paragraph 1 of the C standard suggests that
1755 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1756 # alone desirable) behavior (though it probably does on just about
1757 # every implementation...)
1758 #
1759 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1760 # one might expect) for the initial call so as to be safe against this
1761 # potentially undefined behavior.
1762 empty = _ffi.new("char[]", 0)
1763 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001764 if size == 0:
1765 # No Finished message so far.
1766 return None
1767
1768 buf = _ffi.new("char[]", size)
1769 function(self._ssl, buf, size)
1770 return _ffi.buffer(buf, size)[:]
1771
Fedor Brunner5747b932014-03-05 14:22:34 +01001772 def get_finished(self):
1773 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001774 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001775
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001776 :return: The contents of the message or :py:obj:`None` if the TLS
1777 handshake has not yet completed.
1778 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001779 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001780 return self._get_finished_message(_lib.SSL_get_finished)
1781
Fedor Brunner5747b932014-03-05 14:22:34 +01001782 def get_peer_finished(self):
1783 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001784 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001785
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001786 :return: The contents of the message or :py:obj:`None` if the TLS
1787 handshake has not yet completed.
1788 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001789 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001790 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001791
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001792 def get_cipher_name(self):
1793 """
1794 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001795
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001796 :returns: The name of the currently used cipher or :py:obj:`None`
1797 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001798 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001799 """
1800 cipher = _lib.SSL_get_current_cipher(self._ssl)
1801 if cipher == _ffi.NULL:
1802 return None
1803 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001804 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1805 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001806
1807 def get_cipher_bits(self):
1808 """
1809 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001810
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001811 :returns: The number of secret bits of the currently used cipher
1812 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001813 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001814 """
1815 cipher = _lib.SSL_get_current_cipher(self._ssl)
1816 if cipher == _ffi.NULL:
1817 return None
1818 else:
1819 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1820
1821 def get_cipher_version(self):
1822 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001823 Obtain the protocol version of the currently used cipher.
1824
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001825 :returns: The protocol name of the currently used cipher
1826 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001827 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001828 """
1829 cipher = _lib.SSL_get_current_cipher(self._ssl)
1830 if cipher == _ffi.NULL:
1831 return None
1832 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001833 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001834 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001835
Jim Shaverabff1882015-05-27 09:15:55 -04001836 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001837 """
1838 Obtain the protocol version of the current connection.
1839
1840 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001841 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001842 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001843 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001844 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001845 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001846 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001847
Jim Shaver208438c2015-05-28 09:52:38 -04001848 def get_protocol_version(self):
1849 """
1850 Obtain the protocol version of the current connection.
1851
1852 :returns: The TLS version of the current connection, for example
1853 the value for TLS 1 would be 0x769.
1854 :rtype: :py:class:`int`
1855 """
1856 version = _lib.SSL_version(self._ssl)
1857 return version
1858
Cory Benfield10b277f2015-04-13 17:12:42 -04001859 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001860 def get_next_proto_negotiated(self):
1861 """
1862 Get the protocol that was negotiated by NPN.
1863 """
1864 data = _ffi.new("unsigned char **")
1865 data_len = _ffi.new("unsigned int *")
1866
1867 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1868
Cory Benfieldcd010f62014-05-15 19:00:27 +01001869 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001870
Cory Benfield7907e332015-04-13 17:18:25 -04001871 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001872 def set_alpn_protos(self, protos):
1873 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001874 Specify the client's ALPN protocol list.
1875
1876 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001877
1878 :param protos: A list of the protocols to be offered to the server.
1879 This list should be a Python list of bytestrings representing the
1880 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1881 """
1882 # Take the list of protocols and join them together, prefixing them
1883 # with their lengths.
1884 protostr = b''.join(
1885 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1886 )
1887
1888 # Build a C string from the list. We don't need to save this off
1889 # because OpenSSL immediately copies the data out.
1890 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001891 input_str_len = _ffi.cast("unsigned", len(protostr))
1892 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001893
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001894 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001895 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001896 """
1897 Get the protocol that was negotiated by ALPN.
1898 """
Cory Benfield12eae892014-06-07 15:42:56 +01001899 data = _ffi.new("unsigned char **")
1900 data_len = _ffi.new("unsigned int *")
1901
1902 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1903
Cory Benfielde8e9c382015-04-11 17:33:48 -04001904 if not data_len:
1905 return b''
1906
Cory Benfield12eae892014-06-07 15:42:56 +01001907 return _ffi.buffer(data[0], data_len[0])[:]
1908
1909
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001910ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001911
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001912# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1913# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001914_lib.SSL_library_init()