blob: 9eac1664c37a571964a1da40a6a7786ceb81b070 [file] [log] [blame]
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05003from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01004from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08005from weakref import WeakValueDictionary
6from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08007
Cory Benfield63759dc2015-04-12 08:57:03 -04008from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -08009from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010010from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
16 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040021)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080022
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080023from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050024 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050026try:
27 _memoryview = memoryview
28except NameError:
29 class _memoryview(object):
30 pass
31
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020032try:
33 _buffer = buffer
34except NameError:
35 class _buffer(object):
36 pass
37
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050038OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
39SSLEAY_VERSION = _lib.SSLEAY_VERSION
40SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
41SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
42SSLEAY_DIR = _lib.SSLEAY_DIR
43SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080044
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050045SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
46RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080047
48SSLv2_METHOD = 1
49SSLv3_METHOD = 2
50SSLv23_METHOD = 3
51TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050052TLSv1_1_METHOD = 5
53TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080054
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050055OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
56OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
57OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050058
59OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
60OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080061
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050062try:
63 MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
64except AttributeError:
65 pass
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090068OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050069OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
70OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
71OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040072OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
73 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
74)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
76OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050077try:
78 OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
79except AttributeError:
80 pass
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050081OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
82OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
83OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
84OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
85OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
86OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
87OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
88OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
89OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040090OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
91 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
92)
Jean-Paul Calderonec1780342014-01-08 16:59:03 -050093try:
94 OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
95except AttributeError:
96 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
99OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Arturo Filastò5f8c7a82014-03-09 20:01:25 +0100100try:
101 OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
102except AttributeError:
103 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800104
Alex Gaynorc4889812015-09-04 08:43:17 -0400105OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500107VERIFY_PEER = _lib.SSL_VERIFY_PEER
108VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
109VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
110VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500112SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
113SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
114SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
115SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
116SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
117SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
118SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
119SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
122SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
123SSL_ST_MASK = _lib.SSL_ST_MASK
124SSL_ST_INIT = _lib.SSL_ST_INIT
125SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
126SSL_ST_OK = _lib.SSL_ST_OK
127SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500129SSL_CB_LOOP = _lib.SSL_CB_LOOP
130SSL_CB_EXIT = _lib.SSL_CB_EXIT
131SSL_CB_READ = _lib.SSL_CB_READ
132SSL_CB_WRITE = _lib.SSL_CB_WRITE
133SSL_CB_ALERT = _lib.SSL_CB_ALERT
134SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
135SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
136SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
137SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
138SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
139SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
140SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
141SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800142
Alex Gaynor83284952015-09-05 10:43:30 -0400143
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500144class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500145 """
146 An error occurred in an `OpenSSL.SSL` API.
147 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500148
149
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500150_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100151_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500152
153
154class WantReadError(Error):
155 pass
156
157
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158class WantWriteError(Error):
159 pass
160
161
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500162class WantX509LookupError(Error):
163 pass
164
165
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500166class ZeroReturnError(Error):
167 pass
168
169
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500170class SysCallError(Error):
171 pass
172
173
Cory Benfield0ea76e72015-03-22 09:05:28 +0000174class _CallbackExceptionHelper(object):
175 """
176 A base class for wrapper classes that allow for intelligent exception
177 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500178
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400179 :ivar list _problems: Any exceptions that occurred while executing in a
180 context where they could not be raised in the normal way. Typically
181 this is because OpenSSL has called into some Python code and requires a
182 return value. The exceptions are saved to be raised later when it is
183 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000184 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400185
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400186 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800187 self._problems = []
188
Cory Benfield0ea76e72015-03-22 09:05:28 +0000189 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400190 """
191 Raise an exception from the OpenSSL error queue or that was previously
192 captured whe running a callback.
193 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000194 if self._problems:
195 try:
196 _raise_current_error()
197 except Error:
198 pass
199 raise self._problems.pop(0)
200
201
202class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400203 """
204 Wrap a callback such that it can be used as a certificate verification
205 callback.
206 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400207
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800208 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400209 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800210
211 @wraps(callback)
212 def wrapper(ok, store_ctx):
213 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500214 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
215 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
216 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800217
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400218 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
219 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
220 connection = Connection._reverse_mapping[ssl]
221
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800222 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400223 result = callback(
224 connection, cert, error_number, error_depth, ok
225 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800226 except Exception as e:
227 self._problems.append(e)
228 return 0
229 else:
230 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500231 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800232 return 1
233 else:
234 return 0
235
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500236 self.callback = _ffi.callback(
237 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800238
239
Cory Benfield0ea76e72015-03-22 09:05:28 +0000240class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400241 """
242 Wrap a callback such that it can be used as an NPN advertisement callback.
243 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400244
Cory Benfield0ea76e72015-03-22 09:05:28 +0000245 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400246 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800247
Cory Benfield0ea76e72015-03-22 09:05:28 +0000248 @wraps(callback)
249 def wrapper(ssl, out, outlen, arg):
250 try:
251 conn = Connection._reverse_mapping[ssl]
252 protos = callback(conn)
253
254 # Join the protocols into a Python bytestring, length-prefixing
255 # each element.
256 protostr = b''.join(
257 chain.from_iterable((int2byte(len(p)), p) for p in protos)
258 )
259
260 # Save our callback arguments on the connection object. This is
261 # done to make sure that they don't get freed before OpenSSL
262 # uses them. Then, return them appropriately in the output
263 # parameters.
264 conn._npn_advertise_callback_args = [
265 _ffi.new("unsigned int *", len(protostr)),
266 _ffi.new("unsigned char[]", protostr),
267 ]
268 outlen[0] = conn._npn_advertise_callback_args[0][0]
269 out[0] = conn._npn_advertise_callback_args[1]
270 return 0
271 except Exception as e:
272 self._problems.append(e)
273 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
274
275 self.callback = _ffi.callback(
276 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
277 wrapper
278 )
279
280
281class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400282 """
283 Wrap a callback such that it can be used as an NPN selection callback.
284 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400285
Cory Benfield0ea76e72015-03-22 09:05:28 +0000286 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400287 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000288
289 @wraps(callback)
290 def wrapper(ssl, out, outlen, in_, inlen, arg):
291 try:
292 conn = Connection._reverse_mapping[ssl]
293
294 # The string passed to us is actually made up of multiple
295 # length-prefixed bytestrings. We need to split that into a
296 # list.
297 instr = _ffi.buffer(in_, inlen)[:]
298 protolist = []
299 while instr:
300 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400301 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000302 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400303 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000304
305 # Call the callback
306 outstr = callback(conn, protolist)
307
308 # Save our callback arguments on the connection object. This is
309 # done to make sure that they don't get freed before OpenSSL
310 # uses them. Then, return them appropriately in the output
311 # parameters.
312 conn._npn_select_callback_args = [
313 _ffi.new("unsigned char *", len(outstr)),
314 _ffi.new("unsigned char[]", outstr),
315 ]
316 outlen[0] = conn._npn_select_callback_args[0][0]
317 out[0] = conn._npn_select_callback_args[1]
318 return 0
319 except Exception as e:
320 self._problems.append(e)
321 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
322
323 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400324 ("int (*)(SSL *, unsigned char **, unsigned char *, "
325 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000326 wrapper
327 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800328
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800329
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400330class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400331 """
332 Wrap a callback such that it can be used as an ALPN selection callback.
333 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400334
Cory Benfieldf1177e72015-04-12 09:11:49 -0400335 def __init__(self, callback):
336 _CallbackExceptionHelper.__init__(self)
337
338 @wraps(callback)
339 def wrapper(ssl, out, outlen, in_, inlen, arg):
340 try:
341 conn = Connection._reverse_mapping[ssl]
342
343 # The string passed to us is made up of multiple
344 # length-prefixed bytestrings. We need to split that into a
345 # list.
346 instr = _ffi.buffer(in_, inlen)[:]
347 protolist = []
348 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400349 encoded_len = indexbytes(instr, 0)
350 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400351 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400352 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400353
354 # Call the callback
355 outstr = callback(conn, protolist)
356
357 if not isinstance(outstr, _binary_type):
358 raise TypeError("ALPN callback must return a bytestring.")
359
360 # Save our callback arguments on the connection object to make
361 # sure that they don't get freed before OpenSSL can use them.
362 # Then, return them in the appropriate output parameters.
363 conn._alpn_select_callback_args = [
364 _ffi.new("unsigned char *", len(outstr)),
365 _ffi.new("unsigned char[]", outstr),
366 ]
367 outlen[0] = conn._alpn_select_callback_args[0][0]
368 out[0] = conn._alpn_select_callback_args[1]
369 return 0
370 except Exception as e:
371 self._problems.append(e)
372 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
373
374 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400375 ("int (*)(SSL *, unsigned char **, unsigned char *, "
376 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400377 wrapper
378 )
379
380
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800381def _asFileDescriptor(obj):
382 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800383 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800384 meth = getattr(obj, "fileno", None)
385 if meth is not None:
386 obj = meth()
387
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800388 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800389 fd = obj
390
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800391 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800392 raise TypeError("argument must be an int, or have a fileno() method.")
393 elif fd < 0:
394 raise ValueError(
395 "file descriptor cannot be a negative integer (%i)" % (fd,))
396
397 return fd
398
399
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800400def SSLeay_version(type):
401 """
402 Return a string describing the version of OpenSSL in use.
403
404 :param type: One of the SSLEAY_ constants defined in this module.
405 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500406 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800407
408
Cory Benfield10b277f2015-04-13 17:12:42 -0400409def _requires_npn(func):
Cory Benfielda876cef2015-04-13 17:29:12 -0400410 """
411 Wraps any function that requires NPN support in OpenSSL, ensuring that
412 NotImplementedError is raised if NPN is not present.
413 """
Cory Benfield10b277f2015-04-13 17:12:42 -0400414 @wraps(func)
415 def wrapper(*args, **kwargs):
416 if not _lib.Cryptography_HAS_NEXTPROTONEG:
417 raise NotImplementedError("NPN not available.")
418
419 return func(*args, **kwargs)
420
421 return wrapper
422
423
Cory Benfield7907e332015-04-13 17:18:25 -0400424def _requires_alpn(func):
Cory Benfield9d80a762015-04-13 17:47:33 -0400425 """
426 Wraps any function that requires ALPN support in OpenSSL, ensuring that
427 NotImplementedError is raised if ALPN support is not present.
428 """
Cory Benfield7907e332015-04-13 17:18:25 -0400429 @wraps(func)
430 def wrapper(*args, **kwargs):
431 if not _lib.Cryptography_HAS_ALPN:
432 raise NotImplementedError("ALPN not available.")
433
434 return func(*args, **kwargs)
435
436 return wrapper
437
438
Cory Benfielde6f35882016-03-29 11:21:04 +0100439def _requires_sni(func):
440 """
441 Wraps any function that requires SNI support in OpenSSL, ensuring that
442 NotImplementedError is raised if SNI support is not present. This applies
443 to OpenSSL versions older than 1.0.0.
444 """
445 @wraps(func)
446 def wrapper(*args, **kwargs):
447 if not _lib.Cryptography_HAS_TLSEXT_HOSTNAME:
448 raise NotImplementedError("SNI not available: OpenSSL too old.")
449
450 return func(*args, **kwargs)
451
452 return wrapper
453
454
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800455class Session(object):
456 pass
457
458
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800459class Context(object):
460 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100461 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400462 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800463 """
464 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800465 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500466 SSLv3_METHOD: "SSLv3_method",
467 SSLv23_METHOD: "SSLv23_method",
468 TLSv1_METHOD: "TLSv1_method",
469 TLSv1_1_METHOD: "TLSv1_1_method",
470 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400471 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500472 _methods = dict(
473 (identifier, getattr(_lib, name))
474 for (identifier, name) in _methods.items()
475 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800476
477 def __init__(self, method):
478 """
479 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
480 TLSv1_METHOD.
481 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500482 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800483 raise TypeError("method must be an integer")
484
485 try:
486 method_func = self._methods[method]
487 except KeyError:
488 raise ValueError("No such protocol")
489
490 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500491 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500492 # TODO: This is untested.
493 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800494
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500495 context = _lib.SSL_CTX_new(method_obj)
496 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500497 # TODO: This is untested.
498 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500499 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800500
501 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800502 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800503 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800504 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800505 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800506 self._verify_callback = None
507 self._info_callback = None
508 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800509 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000510 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100511 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000512 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100513 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400514 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100515 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800516
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800517 # SSL_CTX_set_app_data(self->ctx, self);
518 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
519 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
520 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500521 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800522
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800523 def load_verify_locations(self, cafile, capath=None):
524 """
525 Let SSL know where we can find trusted certificates for the certificate
526 chain
527
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400528 :param cafile: In which file we can find the certificates (``bytes`` or
529 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800530 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400531 (``bytes`` or ``unicode``).
532
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800533 :return: None
534 """
535 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500536 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400537 else:
538 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800539
540 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500541 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400542 else:
543 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800544
Alex Gaynor62da94d2015-09-05 14:37:34 -0400545 load_result = _lib.SSL_CTX_load_verify_locations(
546 self._context, cafile, capath
547 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800548 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500549 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800550
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800551 def _wrap_callback(self, callback):
552 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800553 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800554 return callback(size, verify, self._passphrase_userdata)
555 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800556 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800557
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800558 def set_passwd_cb(self, callback, userdata=None):
559 """
560 Set the passphrase callback
561
562 :param callback: The Python callback to use
563 :param userdata: (optional) A Python object which will be given as
564 argument to the callback
565 :return: None
566 """
567 if not callable(callback):
568 raise TypeError("callback must be callable")
569
570 self._passphrase_helper = self._wrap_callback(callback)
571 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500572 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800573 self._context, self._passphrase_callback)
574 self._passphrase_userdata = userdata
575
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800576 def set_default_verify_paths(self):
577 """
578 Use the platform-specific CA certificate locations
579
580 :return: None
581 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500582 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800583 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500584 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500585 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800586
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800587 def use_certificate_chain_file(self, certfile):
588 """
589 Load a certificate chain from a file
590
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400591 :param certfile: The name of the certificate chain file (``bytes`` or
592 ``unicode``).
593
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800594 :return: None
595 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400596 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800597
Alex Gaynor62da94d2015-09-05 14:37:34 -0400598 result = _lib.SSL_CTX_use_certificate_chain_file(
599 self._context, certfile
600 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800601 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500602 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800603
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800604 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800605 """
606 Load a certificate from a file
607
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400608 :param certfile: The name of the certificate file (``bytes`` or
609 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800610 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400611
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800612 :return: None
613 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400614 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500615 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800616 raise TypeError("filetype must be an integer")
617
Alex Gaynor62da94d2015-09-05 14:37:34 -0400618 use_result = _lib.SSL_CTX_use_certificate_file(
619 self._context, certfile, filetype
620 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800621 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500622 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800623
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800624 def use_certificate(self, cert):
625 """
626 Load a certificate from a X509 object
627
628 :param cert: The X509 object
629 :return: None
630 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800631 if not isinstance(cert, X509):
632 raise TypeError("cert must be an X509 instance")
633
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500634 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800635 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500636 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800637
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638 def add_extra_chain_cert(self, certobj):
639 """
640 Add certificate to chain
641
642 :param certobj: The X509 certificate object to add to the chain
643 :return: None
644 """
645 if not isinstance(certobj, X509):
646 raise TypeError("certobj must be an X509 instance")
647
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500648 copy = _lib.X509_dup(certobj._x509)
649 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800650 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500651 # TODO: This is untested.
652 _lib.X509_free(copy)
653 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800654
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800655 def _raise_passphrase_exception(self):
656 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500657 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800658 exception = self._passphrase_helper.raise_if_problem(Error)
659 if exception is not None:
660 raise exception
661
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400662 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800663 """
664 Load a private key from a file
665
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400666 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400668
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800669 :return: None
670 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400671 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400673 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800674 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500675 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800676 raise TypeError("filetype must be an integer")
677
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500678 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800679 self._context, keyfile, filetype)
680 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800681 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800683 def use_privatekey(self, pkey):
684 """
685 Load a private key from a PKey object
686
687 :param pkey: The PKey object
688 :return: None
689 """
690 if not isinstance(pkey, PKey):
691 raise TypeError("pkey must be a PKey instance")
692
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500693 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800695 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 def check_privatekey(self):
698 """
699 Check that the private key and certificate match up
700
701 :return: None (raises an exception if something's wrong)
702 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500703 if not _lib.SSL_CTX_check_private_key(self._context):
704 _raise_current_error()
705
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800706 def load_client_ca(self, cafile):
707 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100708 Load the trusted certificates that will be sent to the client. Does
709 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400710 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800711
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100712 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800713 :return: None
714 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100715 ca_list = _lib.SSL_load_client_CA_file(
716 _text_to_bytes_and_warn("cafile", cafile)
717 )
718 _openssl_assert(ca_list != _ffi.NULL)
719 # SSL_CTX_set_client_CA_list doesn't return anything.
720 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800721
722 def set_session_id(self, buf):
723 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100724 Set the session id to *buf* within which a session can be reused for
725 this Context object. This is needed when doing session resumption,
726 because there is no way for a stored session to know which Context
727 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100729 :param bytes buf: The session id.
730
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800731 :returns: None
732 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100733 buf = _text_to_bytes_and_warn("buf", buf)
734 _openssl_assert(
735 _lib.SSL_CTX_set_session_id_context(
736 self._context,
737 buf,
738 len(buf),
739 ) == 1
740 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741
742 def set_session_cache_mode(self, mode):
743 """
744 Enable/disable session caching and specify the mode used.
745
746 :param mode: One or more of the SESS_CACHE_* flags (combine using
747 bitwise or)
748 :returns: The previously set caching mode.
749 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500750 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800751 raise TypeError("mode must be an integer")
752
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500753 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800754
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800755 def get_session_cache_mode(self):
756 """
757 :returns: The currently used cache mode.
758 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500759 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800760
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800761 def set_verify(self, mode, callback):
762 """
763 Set the verify mode and verify callback
764
765 :param mode: The verify mode, this is either VERIFY_NONE or
766 VERIFY_PEER combined with possible other flags
767 :param callback: The Python callback to use
768 :return: None
769
770 See SSL_CTX_set_verify(3SSL) for further details.
771 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500772 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800773 raise TypeError("mode must be an integer")
774
775 if not callable(callback):
776 raise TypeError("callback must be callable")
777
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400778 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800779 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500780 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800781
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782 def set_verify_depth(self, depth):
783 """
784 Set the verify depth
785
786 :param depth: An integer specifying the verify depth
787 :return: None
788 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500789 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790 raise TypeError("depth must be an integer")
791
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500792 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 def get_verify_mode(self):
795 """
796 Get the verify mode
797
798 :return: The verify mode
799 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500800 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800802 def get_verify_depth(self):
803 """
804 Get the verify depth
805
806 :return: The verify depth
807 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500808 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800810 def load_tmp_dh(self, dhfile):
811 """
812 Load parameters for Ephemeral Diffie-Hellman
813
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400814 :param dhfile: The file to load EDH parameters from (``bytes`` or
815 ``unicode``).
816
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817 :return: None
818 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400819 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800820
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500821 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500822 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500823 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500824 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500826 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
827 dh = _ffi.gc(dh, _lib.DH_free)
828 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400830 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600831 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700832 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600833
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400834 :param curve: A curve object to use as returned by either
835 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
836 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700837
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600838 :return: None
839 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400840 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600841
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800842 def set_cipher_list(self, cipher_list):
843 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100844 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100846 See the OpenSSL manual for more information (e.g.
847 :manpage:`ciphers(1)`).
848
849 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800850 :return: None
851 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100852 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500853
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800854 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100855 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800856
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100857 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100858 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100859 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800860
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800861 def set_client_ca_list(self, certificate_authorities):
862 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400863 Set the list of preferred client certificate signers for this server
864 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800865
Alex Gaynor62da94d2015-09-05 14:37:34 -0400866 This list of certificate authorities will be sent to the client when
867 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868
869 :param certificate_authorities: a sequence of X509Names.
870 :return: None
871 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 name_stack = _lib.sk_X509_NAME_new_null()
873 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500874 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500875 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800876
877 try:
878 for ca_name in certificate_authorities:
879 if not isinstance(ca_name, X509Name):
880 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400881 "client CAs must be X509Name objects, not %s "
882 "objects" % (
883 type(ca_name).__name__,
884 )
885 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500886 copy = _lib.X509_NAME_dup(ca_name._name)
887 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500888 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500889 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500890 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800891 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500892 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500893 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800894 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500895 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800896 raise
897
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500898 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800899
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900 def add_client_ca(self, certificate_authority):
901 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400902 Add the CA certificate to the list of preferred signers for this
903 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800904
905 The list of certificate authorities will be sent to the client when the
906 server requests a client certificate.
907
908 :param certificate_authority: certificate authority's X509 certificate.
909 :return: None
910 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800911 if not isinstance(certificate_authority, X509):
912 raise TypeError("certificate_authority must be an X509 instance")
913
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500914 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800915 self._context, certificate_authority._x509)
916 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500917 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500918 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800919
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920 def set_timeout(self, timeout):
921 """
922 Set session timeout
923
924 :param timeout: The timeout in seconds
925 :return: The previous session timeout
926 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500927 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800928 raise TypeError("timeout must be an integer")
929
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500930 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800931
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800932 def get_timeout(self):
933 """
934 Get the session timeout
935
936 :return: The session timeout
937 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500938 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940 def set_info_callback(self, callback):
941 """
942 Set the info callback
943
944 :param callback: The Python callback to use
945 :return: None
946 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800947 @wraps(callback)
948 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500949 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500950 self._info_callback = _ffi.callback(
951 "void (*)(const SSL *, int, int)", wrapper)
952 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800953
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800954 def get_app_data(self):
955 """
956 Get the application data (supplied via set_app_data())
957
958 :return: The application data
959 """
960 return self._app_data
961
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800962 def set_app_data(self, data):
963 """
964 Set the application data (will be returned from get_app_data())
965
966 :param data: Any Python object
967 :return: None
968 """
969 self._app_data = data
970
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800971 def get_cert_store(self):
972 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500973 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800974
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500975 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800976 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500977 store = _lib.SSL_CTX_get_cert_store(self._context)
978 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500979 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800980 return None
981
982 pystore = X509Store.__new__(X509Store)
983 pystore._store = store
984 return pystore
985
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986 def set_options(self, options):
987 """
988 Add options. Options set before are not cleared!
989
990 :param options: The options to add.
991 :return: The new option bitmask.
992 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500993 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800994 raise TypeError("options must be an integer")
995
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500996 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800998 def set_mode(self, mode):
999 """
1000 Add modes via bitmask. Modes set before are not cleared!
1001
1002 :param mode: The mode to add.
1003 :return: The new mode bitmask.
1004 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001005 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006 raise TypeError("mode must be an integer")
1007
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001008 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001009
Cory Benfielde6f35882016-03-29 11:21:04 +01001010 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011 def set_tlsext_servername_callback(self, callback):
1012 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001013 Specify a callback function to be called when clients specify a server
1014 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001015
1016 :param callback: The callback function. It will be invoked with one
1017 argument, the Connection instance.
1018 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001019 @wraps(callback)
1020 def wrapper(ssl, alert, arg):
1021 callback(Connection._reverse_mapping[ssl])
1022 return 0
1023
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001024 self._tlsext_servername_callback = _ffi.callback(
1025 "int (*)(const SSL *, int *, void *)", wrapper)
1026 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001027 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001028
Cory Benfield10b277f2015-04-13 17:12:42 -04001029 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001030 def set_npn_advertise_callback(self, callback):
1031 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001032 Specify a callback function that will be called when offering `Next
1033 Protocol Negotiation
1034 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001035
1036 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001037 argument, the Connection instance. It should return a list of
1038 bytestrings representing the advertised protocols, like
1039 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001040 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001041 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1042 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001043 _lib.SSL_CTX_set_next_protos_advertised_cb(
1044 self._context, self._npn_advertise_callback, _ffi.NULL)
1045
Cory Benfield10b277f2015-04-13 17:12:42 -04001046 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001047 def set_npn_select_callback(self, callback):
1048 """
1049 Specify a callback function that will be called when a server offers
1050 Next Protocol Negotiation options.
1051
1052 :param callback: The callback function. It will be invoked with two
1053 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001054 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1055 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001056 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001057 self._npn_select_helper = _NpnSelectHelper(callback)
1058 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001059 _lib.SSL_CTX_set_next_proto_select_cb(
1060 self._context, self._npn_select_callback, _ffi.NULL)
1061
Cory Benfield7907e332015-04-13 17:18:25 -04001062 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001063 def set_alpn_protos(self, protos):
1064 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001065 Specify the clients ALPN protocol list.
1066
1067 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001068
1069 :param protos: A list of the protocols to be offered to the server.
1070 This list should be a Python list of bytestrings representing the
1071 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1072 """
1073 # Take the list of protocols and join them together, prefixing them
1074 # with their lengths.
1075 protostr = b''.join(
1076 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1077 )
1078
1079 # Build a C string from the list. We don't need to save this off
1080 # because OpenSSL immediately copies the data out.
1081 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001082 input_str_len = _ffi.cast("unsigned", len(protostr))
1083 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001084
Cory Benfield7907e332015-04-13 17:18:25 -04001085 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001086 def set_alpn_select_callback(self, callback):
1087 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001088 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001089
1090 :param callback: The callback function. It will be invoked with two
1091 arguments: the Connection, and a list of offered protocols as
1092 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001093 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001094 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001095 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001096 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001097 _lib.SSL_CTX_set_alpn_select_cb(
1098 self._context, self._alpn_select_callback, _ffi.NULL)
1099
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001100ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001101
1102
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001103class Connection(object):
1104 """
1105 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001106 _reverse_mapping = WeakValueDictionary()
1107
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001108 def __init__(self, context, socket=None):
1109 """
1110 Create a new Connection object, using the given OpenSSL.SSL.Context
1111 instance and socket.
1112
1113 :param context: An SSL Context to use for this connection
1114 :param socket: The socket to use for transport layer
1115 """
1116 if not isinstance(context, Context):
1117 raise TypeError("context must be a Context instance")
1118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001119 ssl = _lib.SSL_new(context._context)
1120 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001121 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001122 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001123
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001124 # References to strings used for Next Protocol Negotiation. OpenSSL's
1125 # header files suggest that these might get copied at some point, but
1126 # doesn't specify when, so we store them here to make sure they don't
1127 # get freed before OpenSSL uses them.
1128 self._npn_advertise_callback_args = None
1129 self._npn_select_callback_args = None
1130
Cory Benfield12eae892014-06-07 15:42:56 +01001131 # References to strings used for Application Layer Protocol
1132 # Negotiation. These strings get copied at some point but it's well
1133 # after the callback returns, so we have to hang them somewhere to
1134 # avoid them getting freed.
1135 self._alpn_select_callback_args = None
1136
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001137 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138
1139 if socket is None:
1140 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001141 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001142 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1143 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001144
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001146 # TODO: This is untested.
1147 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001150 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001151 self._into_ssl = None
1152 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001153 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001154 set_result = _lib.SSL_set_fd(
1155 self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001156 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001157 # TODO: This is untested.
1158 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001159
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001160 def __getattr__(self, name):
1161 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001162 Look up attributes on the wrapped socket object if they are not found
1163 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001164 """
kjav0b66fa12015-09-02 11:51:26 +01001165 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001166 raise AttributeError("'%s' object has no attribute '%s'" % (
1167 self.__class__.__name__, name
1168 ))
kjav0b66fa12015-09-02 11:51:26 +01001169 else:
1170 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001171
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001172 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001173 if self._context._verify_helper is not None:
1174 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001175 if self._context._npn_advertise_helper is not None:
1176 self._context._npn_advertise_helper.raise_if_problem()
1177 if self._context._npn_select_helper is not None:
1178 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001179 if self._context._alpn_select_helper is not None:
1180 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001181
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 error = _lib.SSL_get_error(ssl, result)
1183 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001184 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001185 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001186 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001187 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001188 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001189 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001190 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001191 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001192 elif error == _lib.SSL_ERROR_SYSCALL:
1193 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001194 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001195 if platform == "win32":
1196 errno = _ffi.getwinerror()[0]
1197 else:
1198 errno = _ffi.errno
Glyph3afdba82015-04-14 17:30:53 -04001199 raise SysCallError(errno, errorcode.get(errno))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001200 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001201 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001202 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001203 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001204 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001205 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001206 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001207 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001208 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001209
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001210 def get_context(self):
1211 """
1212 Get session context
1213 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001214 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001215
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001216 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001217 """
1218 Switch this connection to a new session context
1219
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001220 :param context: A :py:class:`Context` instance giving the new session
1221 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001222 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001223 if not isinstance(context, Context):
1224 raise TypeError("context must be a Context instance")
1225
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001226 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001227 self._context = context
1228
Cory Benfielde6f35882016-03-29 11:21:04 +01001229 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001230 def get_servername(self):
1231 """
1232 Retrieve the servername extension value if provided in the client hello
1233 message, or None if there wasn't one.
1234
1235 :return: A byte string giving the server name or :py:data:`None`.
1236 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001237 name = _lib.SSL_get_servername(
1238 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1239 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001241 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001242
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001244
Cory Benfielde6f35882016-03-29 11:21:04 +01001245 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001246 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001247 """
1248 Set the value of the servername extension to send in the client hello.
1249
1250 :param name: A byte string giving the name.
1251 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001252 if not isinstance(name, bytes):
1253 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001254 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001255 raise TypeError("name must not contain NUL byte")
1256
1257 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001258 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001259
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001260 def pending(self):
1261 """
1262 Get the number of bytes that can be safely read from the connection
1263
1264 :return: The number of bytes available in the receive buffer.
1265 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001266 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001267
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001268 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001269 """
1270 Send data on the connection. NOTE: If you get one of the WantRead,
1271 WantWrite or WantX509Lookup exceptions on this, you have to call the
1272 method again with the SAME buffer.
1273
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001274 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001275 :param flags: (optional) Included for compatibility with the socket
1276 API, the value is ignored
1277 :return: The number of bytes written
1278 """
Abraham Martine82326c2015-02-04 10:18:10 +00001279 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001280 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001281
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001282 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001283 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001284 if isinstance(buf, _buffer):
1285 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001286 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001287 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001288
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001289 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001290 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001291 return result
1292 write = send
1293
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001294 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001296 Send "all" data on the connection. This calls send() repeatedly until
1297 all data is sent. If an error occurs, it's impossible to tell how much
1298 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001299
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001300 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001301 :param flags: (optional) Included for compatibility with the socket
1302 API, the value is ignored
1303 :return: The number of bytes written
1304 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001305 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001306
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001307 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001308 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001309 if isinstance(buf, _buffer):
1310 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001311 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001312 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001313
1314 left_to_send = len(buf)
1315 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001316 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001317
1318 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001319 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001320 self._raise_ssl_error(self._ssl, result)
1321 total_sent += result
1322 left_to_send -= result
1323
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001324 def recv(self, bufsiz, flags=None):
1325 """
1326 Receive data on the connection. NOTE: If you get one of the WantRead,
1327 WantWrite or WantX509Lookup exceptions on this, you have to call the
1328 method again with the SAME buffer.
1329
1330 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001331 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1332 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001333 :return: The string read from the Connection
1334 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001335 buf = _ffi.new("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001336 if flags is not None and flags & socket.MSG_PEEK:
1337 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1338 else:
1339 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001340 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001341 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001342 read = recv
1343
Cory Benfield62d10332014-06-15 10:03:41 +01001344 def recv_into(self, buffer, nbytes=None, flags=None):
1345 """
1346 Receive data on the connection and store the data into a buffer rather
1347 than creating a new string.
1348
1349 :param buffer: The buffer to copy into.
1350 :param nbytes: (optional) The maximum number of bytes to read into the
1351 buffer. If not present, defaults to the size of the buffer. If
1352 larger than the size of the buffer, is reduced to the size of the
1353 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001354 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1355 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001356 :return: The number of bytes read into the buffer.
1357 """
1358 if nbytes is None:
1359 nbytes = len(buffer)
1360 else:
1361 nbytes = min(nbytes, len(buffer))
1362
1363 # We need to create a temporary buffer. This is annoying, it would be
1364 # better if we could pass memoryviews straight into the SSL_read call,
1365 # but right now we can't. Revisit this if CFFI gets that ability.
1366 buf = _ffi.new("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001367 if flags is not None and flags & socket.MSG_PEEK:
1368 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1369 else:
1370 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001371 self._raise_ssl_error(self._ssl, result)
1372
1373 # This strange line is all to avoid a memory copy. The buffer protocol
1374 # should allow us to assign a CFFI buffer to the LHS of this line, but
1375 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1376 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1377 # memoryview type.
1378 try:
1379 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1380 except NameError:
1381 buffer[:result] = _ffi.buffer(buf, result)
1382
1383 return result
1384
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001386 if _lib.BIO_should_retry(bio):
1387 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001388 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001389 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001390 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001391 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001392 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001393 # TODO: This is untested. I think io_special means the socket
1394 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001395 raise ValueError("BIO_should_io_special")
1396 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001397 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001398 raise ValueError("unknown bio failure")
1399 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001400 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001401 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001402
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001403 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001404 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001405 When using non-socket connections this function reads the "dirty" data
1406 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001407
1408 :param bufsiz: The maximum number of bytes to read
1409 :return: The string read.
1410 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001411 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001412 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001413
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001414 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001415 raise TypeError("bufsiz must be an integer")
1416
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001417 buf = _ffi.new("char[]", bufsiz)
1418 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001419 if result <= 0:
1420 self._handle_bio_errors(self._from_ssl, result)
1421
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001422 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001423
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001424 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001425 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001426 When using non-socket connections this function sends "dirty" data that
1427 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001428
1429 :param buf: The string to put into the memory BIO.
1430 :return: The number of bytes written
1431 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001432 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001433
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001434 if self._into_ssl is None:
1435 raise TypeError("Connection sock was not None")
1436
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001437 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001438 if result <= 0:
1439 self._handle_bio_errors(self._into_ssl, result)
1440 return result
1441
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001442 def renegotiate(self):
1443 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001444 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001445
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001446 :return: True if the renegotiation can be started, False otherwise
1447 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001448 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001449 if not self.renegotiate_pending():
1450 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1451 return True
1452 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001453
1454 def do_handshake(self):
1455 """
1456 Perform an SSL handshake (usually called after renegotiate() or one of
1457 set_*_state()). This can raise the same exceptions as send and recv.
1458
1459 :return: None.
1460 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001461 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001462 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001464 def renegotiate_pending(self):
1465 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001466 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001467 a renegotiation is finished.
1468
1469 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001470 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001471 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001472 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001473
1474 def total_renegotiations(self):
1475 """
1476 Find out the total number of renegotiations.
1477
1478 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001479 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001480 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001481 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001482
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001483 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001484 """
1485 Connect to remote host and set up client-side SSL
1486
1487 :param addr: A remote address
1488 :return: What the socket's connect method returns
1489 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001490 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001491 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001492
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001493 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001495 Connect to remote host and set up client-side SSL. Note that if the
1496 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001497
1498 :param addr: A remove address
1499 :return: What the socket's connect_ex method returns
1500 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001501 connect_ex = self._socket.connect_ex
1502 self.set_connect_state()
1503 return connect_ex(addr)
1504
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001505 def accept(self):
1506 """
1507 Accept incoming connection and set up SSL on it
1508
1509 :return: A (conn,addr) pair where conn is a Connection and addr is an
1510 address
1511 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001512 client, addr = self._socket.accept()
1513 conn = Connection(self._context, client)
1514 conn.set_accept_state()
1515 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517 def bio_shutdown(self):
1518 """
1519 When using non-socket connections this function signals end of
1520 data on the input for this connection.
1521
1522 :return: None
1523 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001524 if self._from_ssl is None:
1525 raise TypeError("Connection sock was not None")
1526
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001527 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001528
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001529 def shutdown(self):
1530 """
1531 Send closure alert
1532
1533 :return: True if the shutdown completed successfully (i.e. both sides
1534 have sent closure alerts), false otherwise (i.e. you have to
1535 wait for a ZeroReturnError on a recv() method call
1536 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001537 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001538 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001539 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001540 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001541 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001542 else:
1543 return False
1544
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545 def get_cipher_list(self):
1546 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001547 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001548
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001549 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001550 """
1551 ciphers = []
1552 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001553 result = _lib.SSL_get_cipher_list(self._ssl, i)
1554 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001555 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001556 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001557 return ciphers
1558
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001559 def get_client_ca_list(self):
1560 """
1561 Get CAs whose certificates are suggested for client authentication.
1562
Alex Gaynor62da94d2015-09-05 14:37:34 -04001563 :return: If this is a server connection, a list of X509Names
1564 representing the acceptable CAs as set by
1565 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1566 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1567 connection, the list of such X509Names sent by the server, or an
1568 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001569 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001570 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1571 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001572 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 return []
1574
1575 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001576 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1577 name = _lib.sk_X509_NAME_value(ca_names, i)
1578 copy = _lib.X509_NAME_dup(name)
1579 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001580 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001581 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582
1583 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001584 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001585 result.append(pyname)
1586 return result
1587
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 def makefile(self):
1589 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001590 The makefile() method is not implemented, since there is no dup
1591 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001592
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001593 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 """
Alex Gaynor83284952015-09-05 10:43:30 -04001595 raise NotImplementedError(
1596 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597
1598 def get_app_data(self):
1599 """
1600 Get application data
1601
1602 :return: The application data
1603 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001604 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001605
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001606 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001607 """
1608 Set application data
1609
1610 :param data - The application data
1611 :return: None
1612 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 self._app_data = data
1614
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001615 def get_shutdown(self):
1616 """
1617 Get shutdown state
1618
Alex Gaynor62da94d2015-09-05 14:37:34 -04001619 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1620 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001621 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001622 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001623
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001624 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001625 """
1626 Set shutdown state
1627
1628 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1629 :return: None
1630 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001631 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 raise TypeError("state must be an integer")
1633
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001634 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001636 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001637 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001638 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001639
1640 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001641 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001642 """
kjavc704a2e2015-09-07 12:12:27 +01001643 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001644
1645 def server_random(self):
1646 """
1647 Get a copy of the server hello nonce.
1648
1649 :return: A string representing the state
1650 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001652 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001653 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001654 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001655 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001657 def client_random(self):
1658 """
1659 Get a copy of the client hello nonce.
1660
1661 :return: A string representing the state
1662 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001663 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001665 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001666 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001667 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001668
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001669 def master_key(self):
1670 """
1671 Get a copy of the master key.
1672
1673 :return: A string representing the state
1674 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001675 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001676 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001677 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 self._ssl.session.master_key,
1679 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001680
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001682 """
1683 See shutdown(2)
1684
1685 :return: What the socket's shutdown() method returns
1686 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001687 return self._socket.shutdown(*args, **kwargs)
1688
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001689 def get_peer_certificate(self):
1690 """
1691 Retrieve the other side's certificate (if any)
1692
1693 :return: The peer's certificate
1694 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001695 cert = _lib.SSL_get_peer_certificate(self._ssl)
1696 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001698 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001699 return pycert
1700 return None
1701
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 def get_peer_cert_chain(self):
1703 """
1704 Retrieve the other side's certificate (if any)
1705
1706 :return: A list of X509 instances giving the peer's certificate chain,
1707 or None if it does not have one.
1708 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1710 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001711 return None
1712
1713 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001714 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001715 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001716 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001717 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001719 result.append(pycert)
1720 return result
1721
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001722 def want_read(self):
1723 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001724 Checks if more data has to be read from the transport layer to complete
1725 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726
1727 :return: True iff more data has to be read
1728 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001729 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001730
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001731 def want_write(self):
1732 """
1733 Checks if there is data to write to the transport layer to complete an
1734 operation.
1735
1736 :return: True iff there is data to write
1737 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001738 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001739
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001740 def set_accept_state(self):
1741 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001742 Set the connection to work in server mode. The handshake will be
1743 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001744
1745 :return: None
1746 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001747 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001748
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749 def set_connect_state(self):
1750 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001751 Set the connection to work in client mode. The handshake will be
1752 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001753
1754 :return: None
1755 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001756 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001757
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001758 def get_session(self):
1759 """
1760 Returns the Session currently used.
1761
Alex Gaynor62da94d2015-09-05 14:37:34 -04001762 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1763 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001764 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001765 session = _lib.SSL_get1_session(self._ssl)
1766 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001767 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001769 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001770 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001771 return pysession
1772
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001773 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001774 """
1775 Set the session to be used when the TLS/SSL connection is established.
1776
1777 :param session: A Session instance representing the session to use.
1778 :returns: None
1779 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780 if not isinstance(session, Session):
1781 raise TypeError("session must be a Session instance")
1782
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001783 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001784 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001785 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001786
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001787 def _get_finished_message(self, function):
1788 """
1789 Helper to implement :py:meth:`get_finished` and
1790 :py:meth:`get_peer_finished`.
1791
1792 :param function: Either :py:data:`SSL_get_finished`: or
1793 :py:data:`SSL_get_peer_finished`.
1794
1795 :return: :py:data:`None` if the desired message has not yet been
1796 received, otherwise the contents of the message.
1797 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1798 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001799 # The OpenSSL documentation says nothing about what might happen if the
1800 # count argument given is zero. Specifically, it doesn't say whether
1801 # the output buffer may be NULL in that case or not. Inspection of the
1802 # implementation reveals that it calls memcpy() unconditionally.
1803 # Section 7.1.4, paragraph 1 of the C standard suggests that
1804 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1805 # alone desirable) behavior (though it probably does on just about
1806 # every implementation...)
1807 #
1808 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1809 # one might expect) for the initial call so as to be safe against this
1810 # potentially undefined behavior.
1811 empty = _ffi.new("char[]", 0)
1812 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001813 if size == 0:
1814 # No Finished message so far.
1815 return None
1816
1817 buf = _ffi.new("char[]", size)
1818 function(self._ssl, buf, size)
1819 return _ffi.buffer(buf, size)[:]
1820
Fedor Brunner5747b932014-03-05 14:22:34 +01001821 def get_finished(self):
1822 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001823 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001824
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001825 :return: The contents of the message or :py:obj:`None` if the TLS
1826 handshake has not yet completed.
1827 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001828 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001829 return self._get_finished_message(_lib.SSL_get_finished)
1830
Fedor Brunner5747b932014-03-05 14:22:34 +01001831 def get_peer_finished(self):
1832 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001833 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001834
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001835 :return: The contents of the message or :py:obj:`None` if the TLS
1836 handshake has not yet completed.
1837 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001838 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001839 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001840
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001841 def get_cipher_name(self):
1842 """
1843 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001844
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001845 :returns: The name of the currently used cipher or :py:obj:`None`
1846 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001847 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001848 """
1849 cipher = _lib.SSL_get_current_cipher(self._ssl)
1850 if cipher == _ffi.NULL:
1851 return None
1852 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001853 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1854 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001855
1856 def get_cipher_bits(self):
1857 """
1858 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001859
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001860 :returns: The number of secret bits of the currently used cipher
1861 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001862 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001863 """
1864 cipher = _lib.SSL_get_current_cipher(self._ssl)
1865 if cipher == _ffi.NULL:
1866 return None
1867 else:
1868 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1869
1870 def get_cipher_version(self):
1871 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001872 Obtain the protocol version of the currently used cipher.
1873
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001874 :returns: The protocol name of the currently used cipher
1875 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001876 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001877 """
1878 cipher = _lib.SSL_get_current_cipher(self._ssl)
1879 if cipher == _ffi.NULL:
1880 return None
1881 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001882 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001883 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001884
Jim Shaverabff1882015-05-27 09:15:55 -04001885 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001886 """
1887 Obtain the protocol version of the current connection.
1888
1889 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001890 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001891 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001892 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001893 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001894 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001895 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001896
Jim Shaver208438c2015-05-28 09:52:38 -04001897 def get_protocol_version(self):
1898 """
1899 Obtain the protocol version of the current connection.
1900
1901 :returns: The TLS version of the current connection, for example
1902 the value for TLS 1 would be 0x769.
1903 :rtype: :py:class:`int`
1904 """
1905 version = _lib.SSL_version(self._ssl)
1906 return version
1907
Cory Benfield10b277f2015-04-13 17:12:42 -04001908 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001909 def get_next_proto_negotiated(self):
1910 """
1911 Get the protocol that was negotiated by NPN.
1912 """
1913 data = _ffi.new("unsigned char **")
1914 data_len = _ffi.new("unsigned int *")
1915
1916 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1917
Cory Benfieldcd010f62014-05-15 19:00:27 +01001918 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001919
Cory Benfield7907e332015-04-13 17:18:25 -04001920 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001921 def set_alpn_protos(self, protos):
1922 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001923 Specify the client's ALPN protocol list.
1924
1925 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001926
1927 :param protos: A list of the protocols to be offered to the server.
1928 This list should be a Python list of bytestrings representing the
1929 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1930 """
1931 # Take the list of protocols and join them together, prefixing them
1932 # with their lengths.
1933 protostr = b''.join(
1934 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1935 )
1936
1937 # Build a C string from the list. We don't need to save this off
1938 # because OpenSSL immediately copies the data out.
1939 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001940 input_str_len = _ffi.cast("unsigned", len(protostr))
1941 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001942
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001943 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001944 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001945 """
1946 Get the protocol that was negotiated by ALPN.
1947 """
Cory Benfield12eae892014-06-07 15:42:56 +01001948 data = _ffi.new("unsigned char **")
1949 data_len = _ffi.new("unsigned int *")
1950
1951 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1952
Cory Benfielde8e9c382015-04-11 17:33:48 -04001953 if not data_len:
1954 return b''
1955
Cory Benfield12eae892014-06-07 15:42:56 +01001956 return _ffi.buffer(data[0], data_len[0])[:]
1957
1958
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001959ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001960
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001961# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1962# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001963_lib.SSL_library_init()