blob: eb0de10fe2abe725dd7606cfc1781af0cecc2379 [file] [log] [blame]
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05003from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01004from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08005from weakref import WeakValueDictionary
6from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08007
Cory Benfield63759dc2015-04-12 08:57:03 -04008from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -08009from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010010from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
16 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000021 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080023
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080024from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050025 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080026
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050027try:
28 _memoryview = memoryview
29except NameError:
30 class _memoryview(object):
31 pass
32
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020033try:
34 _buffer = buffer
35except NameError:
36 class _buffer(object):
37 pass
38
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050039OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
40SSLEAY_VERSION = _lib.SSLEAY_VERSION
41SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
42SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
43SSLEAY_DIR = _lib.SSLEAY_DIR
44SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080045
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050046SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
47RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080048
49SSLv2_METHOD = 1
50SSLv3_METHOD = 2
51SSLv23_METHOD = 3
52TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050053TLSv1_1_METHOD = 5
54TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080055
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050056OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
57OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
58OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050059
60OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
61OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080062
Alex Gaynorbf012872016-06-04 13:18:39 -070063MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080064
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050065OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090066OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
68OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
69OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040070OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
71 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
72)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050073OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
74OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040075OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050076OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
77OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
78OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
79OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
80OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
81OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
82OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
83OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
84OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040085OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
86 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
87)
Alex Gaynorbf012872016-06-04 13:18:39 -070088OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050090OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
91OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040092OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080093
Alex Gaynorc4889812015-09-04 08:43:17 -040094OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080095
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050096VERIFY_PEER = _lib.SSL_VERIFY_PEER
97VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
98VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
99VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800100
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500101SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
102SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
103SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
104SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
105SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
106SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
107SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
108SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800109
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500110SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
111SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
112SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400113if _lib.Cryptography_HAS_SSL_ST:
114 SSL_ST_INIT = _lib.SSL_ST_INIT
115 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
116 SSL_ST_OK = _lib.SSL_ST_OK
117 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500119SSL_CB_LOOP = _lib.SSL_CB_LOOP
120SSL_CB_EXIT = _lib.SSL_CB_EXIT
121SSL_CB_READ = _lib.SSL_CB_READ
122SSL_CB_WRITE = _lib.SSL_CB_WRITE
123SSL_CB_ALERT = _lib.SSL_CB_ALERT
124SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
125SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
126SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
127SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
128SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
129SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
130SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
131SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800132
Alex Gaynor83284952015-09-05 10:43:30 -0400133
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500134class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500135 """
136 An error occurred in an `OpenSSL.SSL` API.
137 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500138
139
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500140_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100141_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500142
143
144class WantReadError(Error):
145 pass
146
147
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500148class WantWriteError(Error):
149 pass
150
151
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500152class WantX509LookupError(Error):
153 pass
154
155
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500156class ZeroReturnError(Error):
157 pass
158
159
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500160class SysCallError(Error):
161 pass
162
163
Cory Benfield0ea76e72015-03-22 09:05:28 +0000164class _CallbackExceptionHelper(object):
165 """
166 A base class for wrapper classes that allow for intelligent exception
167 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500168
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400169 :ivar list _problems: Any exceptions that occurred while executing in a
170 context where they could not be raised in the normal way. Typically
171 this is because OpenSSL has called into some Python code and requires a
172 return value. The exceptions are saved to be raised later when it is
173 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000174 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400175
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400176 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800177 self._problems = []
178
Cory Benfield0ea76e72015-03-22 09:05:28 +0000179 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400180 """
181 Raise an exception from the OpenSSL error queue or that was previously
182 captured whe running a callback.
183 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000184 if self._problems:
185 try:
186 _raise_current_error()
187 except Error:
188 pass
189 raise self._problems.pop(0)
190
191
192class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400193 """
194 Wrap a callback such that it can be used as a certificate verification
195 callback.
196 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400197
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800198 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400199 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800200
201 @wraps(callback)
202 def wrapper(ok, store_ctx):
203 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500204 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
205 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
206 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800207
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400208 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
209 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
210 connection = Connection._reverse_mapping[ssl]
211
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800212 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400213 result = callback(
214 connection, cert, error_number, error_depth, ok
215 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800216 except Exception as e:
217 self._problems.append(e)
218 return 0
219 else:
220 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500221 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800222 return 1
223 else:
224 return 0
225
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500226 self.callback = _ffi.callback(
227 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800228
229
Cory Benfield0ea76e72015-03-22 09:05:28 +0000230class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400231 """
232 Wrap a callback such that it can be used as an NPN advertisement callback.
233 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400234
Cory Benfield0ea76e72015-03-22 09:05:28 +0000235 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400236 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800237
Cory Benfield0ea76e72015-03-22 09:05:28 +0000238 @wraps(callback)
239 def wrapper(ssl, out, outlen, arg):
240 try:
241 conn = Connection._reverse_mapping[ssl]
242 protos = callback(conn)
243
244 # Join the protocols into a Python bytestring, length-prefixing
245 # each element.
246 protostr = b''.join(
247 chain.from_iterable((int2byte(len(p)), p) for p in protos)
248 )
249
250 # Save our callback arguments on the connection object. This is
251 # done to make sure that they don't get freed before OpenSSL
252 # uses them. Then, return them appropriately in the output
253 # parameters.
254 conn._npn_advertise_callback_args = [
255 _ffi.new("unsigned int *", len(protostr)),
256 _ffi.new("unsigned char[]", protostr),
257 ]
258 outlen[0] = conn._npn_advertise_callback_args[0][0]
259 out[0] = conn._npn_advertise_callback_args[1]
260 return 0
261 except Exception as e:
262 self._problems.append(e)
263 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
264
265 self.callback = _ffi.callback(
266 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
267 wrapper
268 )
269
270
271class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400272 """
273 Wrap a callback such that it can be used as an NPN selection callback.
274 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400275
Cory Benfield0ea76e72015-03-22 09:05:28 +0000276 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400277 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000278
279 @wraps(callback)
280 def wrapper(ssl, out, outlen, in_, inlen, arg):
281 try:
282 conn = Connection._reverse_mapping[ssl]
283
284 # The string passed to us is actually made up of multiple
285 # length-prefixed bytestrings. We need to split that into a
286 # list.
287 instr = _ffi.buffer(in_, inlen)[:]
288 protolist = []
289 while instr:
290 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400291 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400293 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000294
295 # Call the callback
296 outstr = callback(conn, protolist)
297
298 # Save our callback arguments on the connection object. This is
299 # done to make sure that they don't get freed before OpenSSL
300 # uses them. Then, return them appropriately in the output
301 # parameters.
302 conn._npn_select_callback_args = [
303 _ffi.new("unsigned char *", len(outstr)),
304 _ffi.new("unsigned char[]", outstr),
305 ]
306 outlen[0] = conn._npn_select_callback_args[0][0]
307 out[0] = conn._npn_select_callback_args[1]
308 return 0
309 except Exception as e:
310 self._problems.append(e)
311 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
312
313 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400314 ("int (*)(SSL *, unsigned char **, unsigned char *, "
315 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000316 wrapper
317 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800318
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800319
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400320class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400321 """
322 Wrap a callback such that it can be used as an ALPN selection callback.
323 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400324
Cory Benfieldf1177e72015-04-12 09:11:49 -0400325 def __init__(self, callback):
326 _CallbackExceptionHelper.__init__(self)
327
328 @wraps(callback)
329 def wrapper(ssl, out, outlen, in_, inlen, arg):
330 try:
331 conn = Connection._reverse_mapping[ssl]
332
333 # The string passed to us is made up of multiple
334 # length-prefixed bytestrings. We need to split that into a
335 # list.
336 instr = _ffi.buffer(in_, inlen)[:]
337 protolist = []
338 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400339 encoded_len = indexbytes(instr, 0)
340 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400341 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400342 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400343
344 # Call the callback
345 outstr = callback(conn, protolist)
346
347 if not isinstance(outstr, _binary_type):
348 raise TypeError("ALPN callback must return a bytestring.")
349
350 # Save our callback arguments on the connection object to make
351 # sure that they don't get freed before OpenSSL can use them.
352 # Then, return them in the appropriate output parameters.
353 conn._alpn_select_callback_args = [
354 _ffi.new("unsigned char *", len(outstr)),
355 _ffi.new("unsigned char[]", outstr),
356 ]
357 outlen[0] = conn._alpn_select_callback_args[0][0]
358 out[0] = conn._alpn_select_callback_args[1]
359 return 0
360 except Exception as e:
361 self._problems.append(e)
362 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
363
364 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400365 ("int (*)(SSL *, unsigned char **, unsigned char *, "
366 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400367 wrapper
368 )
369
370
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800371def _asFileDescriptor(obj):
372 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800373 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800374 meth = getattr(obj, "fileno", None)
375 if meth is not None:
376 obj = meth()
377
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800378 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800379 fd = obj
380
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800381 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800382 raise TypeError("argument must be an int, or have a fileno() method.")
383 elif fd < 0:
384 raise ValueError(
385 "file descriptor cannot be a negative integer (%i)" % (fd,))
386
387 return fd
388
389
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800390def SSLeay_version(type):
391 """
392 Return a string describing the version of OpenSSL in use.
393
394 :param type: One of the SSLEAY_ constants defined in this module.
395 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500396 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800397
398
Cory Benfieldef404df2016-03-29 15:32:48 +0100399def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400400 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100401 Builds a decorator that ensures that functions that rely on OpenSSL
402 functions that are not present in this build raise NotImplementedError,
403 rather than AttributeError coming out of cryptography.
404
405 :param flag: A cryptography flag that guards the functions, e.g.
406 ``Cryptography_HAS_NEXTPROTONEG``.
407 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400408 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100409 def _requires_decorator(func):
410 if not flag:
411 @wraps(func)
412 def explode(*args, **kwargs):
413 raise NotImplementedError(error)
414 return explode
415 else:
416 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400417
Cory Benfieldef404df2016-03-29 15:32:48 +0100418 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400419
420
Cory Benfieldef404df2016-03-29 15:32:48 +0100421_requires_npn = _make_requires(
422 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
423)
Cory Benfield7907e332015-04-13 17:18:25 -0400424
425
Cory Benfieldef404df2016-03-29 15:32:48 +0100426_requires_alpn = _make_requires(
427 _lib.Cryptography_HAS_ALPN, "ALPN not available"
428)
Cory Benfielde6f35882016-03-29 11:21:04 +0100429
Cory Benfielde6f35882016-03-29 11:21:04 +0100430
Cory Benfieldef404df2016-03-29 15:32:48 +0100431_requires_sni = _make_requires(
432 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
433)
Cory Benfielde6f35882016-03-29 11:21:04 +0100434
435
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800436class Session(object):
437 pass
438
439
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800440class Context(object):
441 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100442 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400443 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800444 """
445 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800446 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500447 SSLv3_METHOD: "SSLv3_method",
448 SSLv23_METHOD: "SSLv23_method",
449 TLSv1_METHOD: "TLSv1_method",
450 TLSv1_1_METHOD: "TLSv1_1_method",
451 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400452 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500453 _methods = dict(
454 (identifier, getattr(_lib, name))
455 for (identifier, name) in _methods.items()
456 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800457
458 def __init__(self, method):
459 """
460 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
461 TLSv1_METHOD.
462 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500463 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800464 raise TypeError("method must be an integer")
465
466 try:
467 method_func = self._methods[method]
468 except KeyError:
469 raise ValueError("No such protocol")
470
471 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700472 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800473
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500474 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700475 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500476 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800477
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600478 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
479 # will be auto-selected. This function was added in 1.0.2 and made a
480 # noop in 1.1.0+ (where it is set automatically).
481 try:
482 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
483 _openssl_assert(res == 1)
484 except AttributeError:
485 pass
486
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800487 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800488 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800489 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800490 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800491 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800492 self._verify_callback = None
493 self._info_callback = None
494 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800495 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000496 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100497 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000498 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100499 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400500 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100501 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800502
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800503 # SSL_CTX_set_app_data(self->ctx, self);
504 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
505 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
506 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500507 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800508
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800509 def load_verify_locations(self, cafile, capath=None):
510 """
511 Let SSL know where we can find trusted certificates for the certificate
512 chain
513
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400514 :param cafile: In which file we can find the certificates (``bytes`` or
515 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800516 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400517 (``bytes`` or ``unicode``).
518
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800519 :return: None
520 """
521 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500522 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400523 else:
524 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800525
526 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500527 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400528 else:
529 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800530
Alex Gaynor62da94d2015-09-05 14:37:34 -0400531 load_result = _lib.SSL_CTX_load_verify_locations(
532 self._context, cafile, capath
533 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800534 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500535 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800536
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800537 def _wrap_callback(self, callback):
538 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800539 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800540 return callback(size, verify, self._passphrase_userdata)
541 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800542 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800543
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800544 def set_passwd_cb(self, callback, userdata=None):
545 """
546 Set the passphrase callback
547
548 :param callback: The Python callback to use
549 :param userdata: (optional) A Python object which will be given as
550 argument to the callback
551 :return: None
552 """
553 if not callable(callback):
554 raise TypeError("callback must be callable")
555
556 self._passphrase_helper = self._wrap_callback(callback)
557 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500558 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800559 self._context, self._passphrase_callback)
560 self._passphrase_userdata = userdata
561
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800562 def set_default_verify_paths(self):
563 """
564 Use the platform-specific CA certificate locations
565
566 :return: None
567 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500568 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400569 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800570
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800571 def use_certificate_chain_file(self, certfile):
572 """
573 Load a certificate chain from a file
574
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400575 :param certfile: The name of the certificate chain file (``bytes`` or
576 ``unicode``).
577
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800578 :return: None
579 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400580 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800581
Alex Gaynor62da94d2015-09-05 14:37:34 -0400582 result = _lib.SSL_CTX_use_certificate_chain_file(
583 self._context, certfile
584 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800585 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500586 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800587
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800588 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800589 """
590 Load a certificate from a file
591
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400592 :param certfile: The name of the certificate file (``bytes`` or
593 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800594 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400595
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800596 :return: None
597 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400598 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500599 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800600 raise TypeError("filetype must be an integer")
601
Alex Gaynor62da94d2015-09-05 14:37:34 -0400602 use_result = _lib.SSL_CTX_use_certificate_file(
603 self._context, certfile, filetype
604 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800605 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500606 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800607
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608 def use_certificate(self, cert):
609 """
610 Load a certificate from a X509 object
611
612 :param cert: The X509 object
613 :return: None
614 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800615 if not isinstance(cert, X509):
616 raise TypeError("cert must be an X509 instance")
617
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500618 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800619 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500620 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800621
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800622 def add_extra_chain_cert(self, certobj):
623 """
624 Add certificate to chain
625
626 :param certobj: The X509 certificate object to add to the chain
627 :return: None
628 """
629 if not isinstance(certobj, X509):
630 raise TypeError("certobj must be an X509 instance")
631
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 copy = _lib.X509_dup(certobj._x509)
633 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800634 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500635 # TODO: This is untested.
636 _lib.X509_free(copy)
637 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800639 def _raise_passphrase_exception(self):
640 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500641 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800642 exception = self._passphrase_helper.raise_if_problem(Error)
643 if exception is not None:
644 raise exception
645
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400646 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800647 """
648 Load a private key from a file
649
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400650 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800651 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400652
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800653 :return: None
654 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400655 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400657 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500659 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800660 raise TypeError("filetype must be an integer")
661
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500662 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800663 self._context, keyfile, filetype)
664 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800665 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800666
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 def use_privatekey(self, pkey):
668 """
669 Load a private key from a PKey object
670
671 :param pkey: The PKey object
672 :return: None
673 """
674 if not isinstance(pkey, PKey):
675 raise TypeError("pkey must be a PKey instance")
676
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500677 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800678 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800679 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800680
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800681 def check_privatekey(self):
682 """
683 Check that the private key and certificate match up
684
685 :return: None (raises an exception if something's wrong)
686 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500687 if not _lib.SSL_CTX_check_private_key(self._context):
688 _raise_current_error()
689
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690 def load_client_ca(self, cafile):
691 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100692 Load the trusted certificates that will be sent to the client. Does
693 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400694 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100696 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 :return: None
698 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100699 ca_list = _lib.SSL_load_client_CA_file(
700 _text_to_bytes_and_warn("cafile", cafile)
701 )
702 _openssl_assert(ca_list != _ffi.NULL)
703 # SSL_CTX_set_client_CA_list doesn't return anything.
704 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800705
706 def set_session_id(self, buf):
707 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100708 Set the session id to *buf* within which a session can be reused for
709 this Context object. This is needed when doing session resumption,
710 because there is no way for a stored session to know which Context
711 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100713 :param bytes buf: The session id.
714
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800715 :returns: None
716 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100717 buf = _text_to_bytes_and_warn("buf", buf)
718 _openssl_assert(
719 _lib.SSL_CTX_set_session_id_context(
720 self._context,
721 buf,
722 len(buf),
723 ) == 1
724 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800725
726 def set_session_cache_mode(self, mode):
727 """
728 Enable/disable session caching and specify the mode used.
729
730 :param mode: One or more of the SESS_CACHE_* flags (combine using
731 bitwise or)
732 :returns: The previously set caching mode.
733 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500734 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735 raise TypeError("mode must be an integer")
736
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500737 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800738
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800739 def get_session_cache_mode(self):
740 """
741 :returns: The currently used cache mode.
742 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500743 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800744
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800745 def set_verify(self, mode, callback):
746 """
747 Set the verify mode and verify callback
748
749 :param mode: The verify mode, this is either VERIFY_NONE or
750 VERIFY_PEER combined with possible other flags
751 :param callback: The Python callback to use
752 :return: None
753
754 See SSL_CTX_set_verify(3SSL) for further details.
755 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500756 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757 raise TypeError("mode must be an integer")
758
759 if not callable(callback):
760 raise TypeError("callback must be callable")
761
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400762 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800763 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500764 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800765
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800766 def set_verify_depth(self, depth):
767 """
768 Set the verify depth
769
770 :param depth: An integer specifying the verify depth
771 :return: None
772 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500773 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800774 raise TypeError("depth must be an integer")
775
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500776 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800778 def get_verify_mode(self):
779 """
780 Get the verify mode
781
782 :return: The verify mode
783 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500784 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800786 def get_verify_depth(self):
787 """
788 Get the verify depth
789
790 :return: The verify depth
791 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500792 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800794 def load_tmp_dh(self, dhfile):
795 """
796 Load parameters for Ephemeral Diffie-Hellman
797
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400798 :param dhfile: The file to load EDH parameters from (``bytes`` or
799 ``unicode``).
800
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800801 :return: None
802 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400803 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800804
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500805 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500806 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500807 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500808 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500810 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
811 dh = _ffi.gc(dh, _lib.DH_free)
812 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800813
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400814 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600815 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700816 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600817
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400818 :param curve: A curve object to use as returned by either
819 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
820 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700821
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600822 :return: None
823 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400824 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600825
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800826 def set_cipher_list(self, cipher_list):
827 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100828 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800829
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100830 See the OpenSSL manual for more information (e.g.
831 :manpage:`ciphers(1)`).
832
833 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800834 :return: None
835 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100836 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500837
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800838 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100839 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800840
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100841 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100842 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100843 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800844
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845 def set_client_ca_list(self, certificate_authorities):
846 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400847 Set the list of preferred client certificate signers for this server
848 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800849
Alex Gaynor62da94d2015-09-05 14:37:34 -0400850 This list of certificate authorities will be sent to the client when
851 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800852
853 :param certificate_authorities: a sequence of X509Names.
854 :return: None
855 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500856 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700857 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800858
859 try:
860 for ca_name in certificate_authorities:
861 if not isinstance(ca_name, X509Name):
862 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400863 "client CAs must be X509Name objects, not %s "
864 "objects" % (
865 type(ca_name).__name__,
866 )
867 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500868 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -0700869 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500870 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800871 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500872 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500873 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800874 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500875 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800876 raise
877
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500878 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800879
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800880 def add_client_ca(self, certificate_authority):
881 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400882 Add the CA certificate to the list of preferred signers for this
883 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800884
885 The list of certificate authorities will be sent to the client when the
886 server requests a client certificate.
887
888 :param certificate_authority: certificate authority's X509 certificate.
889 :return: None
890 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800891 if not isinstance(certificate_authority, X509):
892 raise TypeError("certificate_authority must be an X509 instance")
893
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500894 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800895 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400896 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800897
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 def set_timeout(self, timeout):
899 """
900 Set session timeout
901
902 :param timeout: The timeout in seconds
903 :return: The previous session timeout
904 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500905 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800906 raise TypeError("timeout must be an integer")
907
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500908 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910 def get_timeout(self):
911 """
912 Get the session timeout
913
914 :return: The session timeout
915 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500916 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800917
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800918 def set_info_callback(self, callback):
919 """
920 Set the info callback
921
922 :param callback: The Python callback to use
923 :return: None
924 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800925 @wraps(callback)
926 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500927 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500928 self._info_callback = _ffi.callback(
929 "void (*)(const SSL *, int, int)", wrapper)
930 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800931
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800932 def get_app_data(self):
933 """
934 Get the application data (supplied via set_app_data())
935
936 :return: The application data
937 """
938 return self._app_data
939
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940 def set_app_data(self, data):
941 """
942 Set the application data (will be returned from get_app_data())
943
944 :param data: Any Python object
945 :return: None
946 """
947 self._app_data = data
948
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800949 def get_cert_store(self):
950 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500951 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500953 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800954 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500955 store = _lib.SSL_CTX_get_cert_store(self._context)
956 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500957 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800958 return None
959
960 pystore = X509Store.__new__(X509Store)
961 pystore._store = store
962 return pystore
963
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800964 def set_options(self, options):
965 """
966 Add options. Options set before are not cleared!
967
968 :param options: The options to add.
969 :return: The new option bitmask.
970 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500971 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800972 raise TypeError("options must be an integer")
973
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500974 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800976 def set_mode(self, mode):
977 """
978 Add modes via bitmask. Modes set before are not cleared!
979
980 :param mode: The mode to add.
981 :return: The new mode bitmask.
982 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500983 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984 raise TypeError("mode must be an integer")
985
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500986 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987
Cory Benfielde6f35882016-03-29 11:21:04 +0100988 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989 def set_tlsext_servername_callback(self, callback):
990 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400991 Specify a callback function to be called when clients specify a server
992 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800993
994 :param callback: The callback function. It will be invoked with one
995 argument, the Connection instance.
996 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800997 @wraps(callback)
998 def wrapper(ssl, alert, arg):
999 callback(Connection._reverse_mapping[ssl])
1000 return 0
1001
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001002 self._tlsext_servername_callback = _ffi.callback(
1003 "int (*)(const SSL *, int *, void *)", wrapper)
1004 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001005 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006
Cory Benfield10b277f2015-04-13 17:12:42 -04001007 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001008 def set_npn_advertise_callback(self, callback):
1009 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001010 Specify a callback function that will be called when offering `Next
1011 Protocol Negotiation
1012 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001013
1014 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001015 argument, the Connection instance. It should return a list of
1016 bytestrings representing the advertised protocols, like
1017 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001018 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001019 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1020 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001021 _lib.SSL_CTX_set_next_protos_advertised_cb(
1022 self._context, self._npn_advertise_callback, _ffi.NULL)
1023
Cory Benfield10b277f2015-04-13 17:12:42 -04001024 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001025 def set_npn_select_callback(self, callback):
1026 """
1027 Specify a callback function that will be called when a server offers
1028 Next Protocol Negotiation options.
1029
1030 :param callback: The callback function. It will be invoked with two
1031 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001032 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1033 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001034 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001035 self._npn_select_helper = _NpnSelectHelper(callback)
1036 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001037 _lib.SSL_CTX_set_next_proto_select_cb(
1038 self._context, self._npn_select_callback, _ffi.NULL)
1039
Cory Benfield7907e332015-04-13 17:18:25 -04001040 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001041 def set_alpn_protos(self, protos):
1042 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001043 Specify the clients ALPN protocol list.
1044
1045 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001046
1047 :param protos: A list of the protocols to be offered to the server.
1048 This list should be a Python list of bytestrings representing the
1049 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1050 """
1051 # Take the list of protocols and join them together, prefixing them
1052 # with their lengths.
1053 protostr = b''.join(
1054 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1055 )
1056
1057 # Build a C string from the list. We don't need to save this off
1058 # because OpenSSL immediately copies the data out.
1059 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001060 input_str_len = _ffi.cast("unsigned", len(protostr))
1061 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001062
Cory Benfield7907e332015-04-13 17:18:25 -04001063 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001064 def set_alpn_select_callback(self, callback):
1065 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001066 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001067
1068 :param callback: The callback function. It will be invoked with two
1069 arguments: the Connection, and a list of offered protocols as
1070 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001071 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001072 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001073 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001074 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001075 _lib.SSL_CTX_set_alpn_select_cb(
1076 self._context, self._alpn_select_callback, _ffi.NULL)
1077
Alex Chanc6077062016-11-18 13:53:39 +00001078
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001079ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001080
1081
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001082class Connection(object):
1083 """
1084 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001085 _reverse_mapping = WeakValueDictionary()
1086
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001087 def __init__(self, context, socket=None):
1088 """
1089 Create a new Connection object, using the given OpenSSL.SSL.Context
1090 instance and socket.
1091
1092 :param context: An SSL Context to use for this connection
1093 :param socket: The socket to use for transport layer
1094 """
1095 if not isinstance(context, Context):
1096 raise TypeError("context must be a Context instance")
1097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001098 ssl = _lib.SSL_new(context._context)
1099 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001100 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001101 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001102
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001103 # References to strings used for Next Protocol Negotiation. OpenSSL's
1104 # header files suggest that these might get copied at some point, but
1105 # doesn't specify when, so we store them here to make sure they don't
1106 # get freed before OpenSSL uses them.
1107 self._npn_advertise_callback_args = None
1108 self._npn_select_callback_args = None
1109
Cory Benfield12eae892014-06-07 15:42:56 +01001110 # References to strings used for Application Layer Protocol
1111 # Negotiation. These strings get copied at some point but it's well
1112 # after the callback returns, so we have to hang them somewhere to
1113 # avoid them getting freed.
1114 self._alpn_select_callback_args = None
1115
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001116 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117
1118 if socket is None:
1119 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001120 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001121 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001122 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123
Alex Gaynora829e902016-06-04 18:16:01 -07001124 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1125 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001127 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001128 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001129 self._into_ssl = None
1130 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001132 set_result = _lib.SSL_set_fd(
1133 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001134 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001135
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001136 def __getattr__(self, name):
1137 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001138 Look up attributes on the wrapped socket object if they are not found
1139 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001140 """
kjav0b66fa12015-09-02 11:51:26 +01001141 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001142 raise AttributeError("'%s' object has no attribute '%s'" % (
1143 self.__class__.__name__, name
1144 ))
kjav0b66fa12015-09-02 11:51:26 +01001145 else:
1146 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001147
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001148 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001149 if self._context._verify_helper is not None:
1150 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001151 if self._context._npn_advertise_helper is not None:
1152 self._context._npn_advertise_helper.raise_if_problem()
1153 if self._context._npn_select_helper is not None:
1154 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001155 if self._context._alpn_select_helper is not None:
1156 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001157
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001158 error = _lib.SSL_get_error(ssl, result)
1159 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001160 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001162 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001164 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001165 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001166 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001167 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 elif error == _lib.SSL_ERROR_SYSCALL:
1169 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001171 if platform == "win32":
1172 errno = _ffi.getwinerror()[0]
1173 else:
1174 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001175
1176 if errno != 0:
1177 raise SysCallError(errno, errorcode.get(errno))
1178 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001179 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001180 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001181 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001183 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001184 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001185 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001186
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001187 def get_context(self):
1188 """
1189 Get session context
1190 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001192
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001193 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001194 """
1195 Switch this connection to a new session context
1196
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001197 :param context: A :py:class:`Context` instance giving the new session
1198 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001199 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001200 if not isinstance(context, Context):
1201 raise TypeError("context must be a Context instance")
1202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001203 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001204 self._context = context
1205
Cory Benfielde6f35882016-03-29 11:21:04 +01001206 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001207 def get_servername(self):
1208 """
1209 Retrieve the servername extension value if provided in the client hello
1210 message, or None if there wasn't one.
1211
1212 :return: A byte string giving the server name or :py:data:`None`.
1213 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001214 name = _lib.SSL_get_servername(
1215 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1216 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001217 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001218 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001219
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001220 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001221
Cory Benfielde6f35882016-03-29 11:21:04 +01001222 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001223 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001224 """
1225 Set the value of the servername extension to send in the client hello.
1226
1227 :param name: A byte string giving the name.
1228 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001229 if not isinstance(name, bytes):
1230 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001231 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001232 raise TypeError("name must not contain NUL byte")
1233
1234 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001235 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001236
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001237 def pending(self):
1238 """
1239 Get the number of bytes that can be safely read from the connection
1240
1241 :return: The number of bytes available in the receive buffer.
1242 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001244
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001245 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001246 """
1247 Send data on the connection. NOTE: If you get one of the WantRead,
1248 WantWrite or WantX509Lookup exceptions on this, you have to call the
1249 method again with the SAME buffer.
1250
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001251 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001252 :param flags: (optional) Included for compatibility with the socket
1253 API, the value is ignored
1254 :return: The number of bytes written
1255 """
Abraham Martine82326c2015-02-04 10:18:10 +00001256 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001257 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001258
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001259 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001260 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001261 if isinstance(buf, _buffer):
1262 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001263 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001264 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001265
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001266 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001267 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001268 return result
1269 write = send
1270
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001271 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001272 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001273 Send "all" data on the connection. This calls send() repeatedly until
1274 all data is sent. If an error occurs, it's impossible to tell how much
1275 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001276
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001277 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001278 :param flags: (optional) Included for compatibility with the socket
1279 API, the value is ignored
1280 :return: The number of bytes written
1281 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001282 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001283
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001284 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001285 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001286 if isinstance(buf, _buffer):
1287 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001288 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001289 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001290
1291 left_to_send = len(buf)
1292 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001293 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001294
1295 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001296 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001297 self._raise_ssl_error(self._ssl, result)
1298 total_sent += result
1299 left_to_send -= result
1300
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001301 def recv(self, bufsiz, flags=None):
1302 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001303 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001304
1305 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001306 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1307 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001308 :return: The string read from the Connection
1309 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001310 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001311 if flags is not None and flags & socket.MSG_PEEK:
1312 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1313 else:
1314 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001315 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001316 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001317 read = recv
1318
Cory Benfield62d10332014-06-15 10:03:41 +01001319 def recv_into(self, buffer, nbytes=None, flags=None):
1320 """
1321 Receive data on the connection and store the data into a buffer rather
1322 than creating a new string.
1323
1324 :param buffer: The buffer to copy into.
1325 :param nbytes: (optional) The maximum number of bytes to read into the
1326 buffer. If not present, defaults to the size of the buffer. If
1327 larger than the size of the buffer, is reduced to the size of the
1328 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001329 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1330 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001331 :return: The number of bytes read into the buffer.
1332 """
1333 if nbytes is None:
1334 nbytes = len(buffer)
1335 else:
1336 nbytes = min(nbytes, len(buffer))
1337
1338 # We need to create a temporary buffer. This is annoying, it would be
1339 # better if we could pass memoryviews straight into the SSL_read call,
1340 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001341 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001342 if flags is not None and flags & socket.MSG_PEEK:
1343 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1344 else:
1345 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001346 self._raise_ssl_error(self._ssl, result)
1347
1348 # This strange line is all to avoid a memory copy. The buffer protocol
1349 # should allow us to assign a CFFI buffer to the LHS of this line, but
1350 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1351 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1352 # memoryview type.
1353 try:
1354 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1355 except NameError:
1356 buffer[:result] = _ffi.buffer(buf, result)
1357
1358 return result
1359
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001360 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 if _lib.BIO_should_retry(bio):
1362 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001363 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001364 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001365 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001366 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001367 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001368 # TODO: This is untested. I think io_special means the socket
1369 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001370 raise ValueError("BIO_should_io_special")
1371 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001372 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001373 raise ValueError("unknown bio failure")
1374 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001375 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001376 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001377
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001378 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001379 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001380 When using non-socket connections this function reads the "dirty" data
1381 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001382
1383 :param bufsiz: The maximum number of bytes to read
1384 :return: The string read.
1385 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001386 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001387 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001388
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001389 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 raise TypeError("bufsiz must be an integer")
1391
Cory Benfielde62840e2016-11-28 12:17:08 +00001392 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001393 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001394 if result <= 0:
1395 self._handle_bio_errors(self._from_ssl, result)
1396
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001397 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001398
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001399 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001400 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001401 When using non-socket connections this function sends "dirty" data that
1402 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001403
1404 :param buf: The string to put into the memory BIO.
1405 :return: The number of bytes written
1406 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001407 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001408
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001409 if self._into_ssl is None:
1410 raise TypeError("Connection sock was not None")
1411
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001412 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001413 if result <= 0:
1414 self._handle_bio_errors(self._into_ssl, result)
1415 return result
1416
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001417 def renegotiate(self):
1418 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001419 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001420
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001421 :return: True if the renegotiation can be started, False otherwise
1422 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001423 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001424 if not self.renegotiate_pending():
1425 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1426 return True
1427 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001428
1429 def do_handshake(self):
1430 """
1431 Perform an SSL handshake (usually called after renegotiate() or one of
1432 set_*_state()). This can raise the same exceptions as send and recv.
1433
1434 :return: None.
1435 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001436 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001437 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001438
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001439 def renegotiate_pending(self):
1440 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001441 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001442 a renegotiation is finished.
1443
1444 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001445 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001446 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001447 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001448
1449 def total_renegotiations(self):
1450 """
1451 Find out the total number of renegotiations.
1452
1453 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001454 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001455 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001456 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001457
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001458 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001459 """
1460 Connect to remote host and set up client-side SSL
1461
1462 :param addr: A remote address
1463 :return: What the socket's connect method returns
1464 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001465 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001467
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001468 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001470 Connect to remote host and set up client-side SSL. Note that if the
1471 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001472
1473 :param addr: A remove address
1474 :return: What the socket's connect_ex method returns
1475 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001476 connect_ex = self._socket.connect_ex
1477 self.set_connect_state()
1478 return connect_ex(addr)
1479
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001480 def accept(self):
1481 """
1482 Accept incoming connection and set up SSL on it
1483
1484 :return: A (conn,addr) pair where conn is a Connection and addr is an
1485 address
1486 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001487 client, addr = self._socket.accept()
1488 conn = Connection(self._context, client)
1489 conn.set_accept_state()
1490 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001491
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001492 def bio_shutdown(self):
1493 """
1494 When using non-socket connections this function signals end of
1495 data on the input for this connection.
1496
1497 :return: None
1498 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001499 if self._from_ssl is None:
1500 raise TypeError("Connection sock was not None")
1501
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001502 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504 def shutdown(self):
1505 """
1506 Send closure alert
1507
1508 :return: True if the shutdown completed successfully (i.e. both sides
1509 have sent closure alerts), false otherwise (i.e. you have to
1510 wait for a ZeroReturnError on a recv() method call
1511 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001512 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001514 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001515 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001516 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517 else:
1518 return False
1519
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001520 def get_cipher_list(self):
1521 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001522 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001524 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001525 """
1526 ciphers = []
1527 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001528 result = _lib.SSL_get_cipher_list(self._ssl, i)
1529 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001530 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001531 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001532 return ciphers
1533
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001534 def get_client_ca_list(self):
1535 """
1536 Get CAs whose certificates are suggested for client authentication.
1537
Alex Gaynor62da94d2015-09-05 14:37:34 -04001538 :return: If this is a server connection, a list of X509Names
1539 representing the acceptable CAs as set by
1540 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1541 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1542 connection, the list of such X509Names sent by the server, or an
1543 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001544 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001545 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1546 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001547 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001548 return []
1549
1550 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001551 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1552 name = _lib.sk_X509_NAME_value(ca_names, i)
1553 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001554 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001555
1556 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001557 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001558 result.append(pyname)
1559 return result
1560
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001561 def makefile(self):
1562 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001563 The makefile() method is not implemented, since there is no dup
1564 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001566 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 """
Alex Gaynor83284952015-09-05 10:43:30 -04001568 raise NotImplementedError(
1569 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001570
1571 def get_app_data(self):
1572 """
1573 Get application data
1574
1575 :return: The application data
1576 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001579 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001580 """
1581 Set application data
1582
1583 :param data - The application data
1584 :return: None
1585 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586 self._app_data = data
1587
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588 def get_shutdown(self):
1589 """
1590 Get shutdown state
1591
Alex Gaynor62da94d2015-09-05 14:37:34 -04001592 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1593 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001595 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001596
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001597 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001598 """
1599 Set shutdown state
1600
1601 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1602 :return: None
1603 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001604 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001605 raise TypeError("state must be an integer")
1606
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001607 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001608
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001609 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001610 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001611 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001612
1613 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001614 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001615 """
kjavc704a2e2015-09-07 12:12:27 +01001616 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001617
1618 def server_random(self):
1619 """
1620 Get a copy of the server hello nonce.
1621
1622 :return: A string representing the state
1623 """
Alex Gaynor93603062016-06-01 20:13:09 -07001624 session = _lib.SSL_get_session(self._ssl)
1625 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001626 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001627 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1628 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001629 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001630 _lib.SSL_get_server_random(self._ssl, outp, length)
1631 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001633 def client_random(self):
1634 """
1635 Get a copy of the client hello nonce.
1636
1637 :return: A string representing the state
1638 """
Alex Gaynor93603062016-06-01 20:13:09 -07001639 session = _lib.SSL_get_session(self._ssl)
1640 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001641 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001642
1643 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1644 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001645 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001646 _lib.SSL_get_client_random(self._ssl, outp, length)
1647 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001648
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001649 def master_key(self):
1650 """
1651 Get a copy of the master key.
1652
1653 :return: A string representing the state
1654 """
Alex Gaynor93603062016-06-01 20:13:09 -07001655 session = _lib.SSL_get_session(self._ssl)
1656 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001658
1659 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1660 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001661 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001662 _lib.SSL_SESSION_get_master_key(session, outp, length)
1663 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001664
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001665 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001666 """
1667 See shutdown(2)
1668
1669 :return: What the socket's shutdown() method returns
1670 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671 return self._socket.shutdown(*args, **kwargs)
1672
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 def get_peer_certificate(self):
1674 """
1675 Retrieve the other side's certificate (if any)
1676
1677 :return: The peer's certificate
1678 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001679 cert = _lib.SSL_get_peer_certificate(self._ssl)
1680 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001681 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001682 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001683 return pycert
1684 return None
1685
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686 def get_peer_cert_chain(self):
1687 """
1688 Retrieve the other side's certificate (if any)
1689
1690 :return: A list of X509 instances giving the peer's certificate chain,
1691 or None if it does not have one.
1692 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1694 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001695 return None
1696
1697 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001698 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001699 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001700 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001701 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001702 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001703 result.append(pycert)
1704 return result
1705
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001706 def want_read(self):
1707 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001708 Checks if more data has to be read from the transport layer to complete
1709 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001710
1711 :return: True iff more data has to be read
1712 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001713 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001714
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715 def want_write(self):
1716 """
1717 Checks if there is data to write to the transport layer to complete an
1718 operation.
1719
1720 :return: True iff there is data to write
1721 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001722 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001723
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724 def set_accept_state(self):
1725 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001726 Set the connection to work in server mode. The handshake will be
1727 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001728
1729 :return: None
1730 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001731 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001733 def set_connect_state(self):
1734 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001735 Set the connection to work in client mode. The handshake will be
1736 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001737
1738 :return: None
1739 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001740 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001741
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001742 def get_session(self):
1743 """
1744 Returns the Session currently used.
1745
Alex Gaynor62da94d2015-09-05 14:37:34 -04001746 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1747 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001748 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001749 session = _lib.SSL_get1_session(self._ssl)
1750 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001752
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001753 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755 return pysession
1756
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001757 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001758 """
1759 Set the session to be used when the TLS/SSL connection is established.
1760
1761 :param session: A Session instance representing the session to use.
1762 :returns: None
1763 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001764 if not isinstance(session, Session):
1765 raise TypeError("session must be a Session instance")
1766
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001767 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001768 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001769 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001770
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001771 def _get_finished_message(self, function):
1772 """
1773 Helper to implement :py:meth:`get_finished` and
1774 :py:meth:`get_peer_finished`.
1775
1776 :param function: Either :py:data:`SSL_get_finished`: or
1777 :py:data:`SSL_get_peer_finished`.
1778
1779 :return: :py:data:`None` if the desired message has not yet been
1780 received, otherwise the contents of the message.
1781 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1782 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001783 # The OpenSSL documentation says nothing about what might happen if the
1784 # count argument given is zero. Specifically, it doesn't say whether
1785 # the output buffer may be NULL in that case or not. Inspection of the
1786 # implementation reveals that it calls memcpy() unconditionally.
1787 # Section 7.1.4, paragraph 1 of the C standard suggests that
1788 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1789 # alone desirable) behavior (though it probably does on just about
1790 # every implementation...)
1791 #
1792 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1793 # one might expect) for the initial call so as to be safe against this
1794 # potentially undefined behavior.
1795 empty = _ffi.new("char[]", 0)
1796 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001797 if size == 0:
1798 # No Finished message so far.
1799 return None
1800
Cory Benfielde62840e2016-11-28 12:17:08 +00001801 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001802 function(self._ssl, buf, size)
1803 return _ffi.buffer(buf, size)[:]
1804
Fedor Brunner5747b932014-03-05 14:22:34 +01001805 def get_finished(self):
1806 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001807 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001808
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001809 :return: The contents of the message or :py:obj:`None` if the TLS
1810 handshake has not yet completed.
1811 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001812 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001813 return self._get_finished_message(_lib.SSL_get_finished)
1814
Fedor Brunner5747b932014-03-05 14:22:34 +01001815 def get_peer_finished(self):
1816 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001817 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001818
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001819 :return: The contents of the message or :py:obj:`None` if the TLS
1820 handshake has not yet completed.
1821 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001822 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001823 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001824
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001825 def get_cipher_name(self):
1826 """
1827 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001828
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001829 :returns: The name of the currently used cipher or :py:obj:`None`
1830 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001831 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001832 """
1833 cipher = _lib.SSL_get_current_cipher(self._ssl)
1834 if cipher == _ffi.NULL:
1835 return None
1836 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001837 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1838 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001839
1840 def get_cipher_bits(self):
1841 """
1842 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001843
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001844 :returns: The number of secret bits of the currently used cipher
1845 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001846 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001847 """
1848 cipher = _lib.SSL_get_current_cipher(self._ssl)
1849 if cipher == _ffi.NULL:
1850 return None
1851 else:
1852 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1853
1854 def get_cipher_version(self):
1855 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001856 Obtain the protocol version of the currently used cipher.
1857
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001858 :returns: The protocol name of the currently used cipher
1859 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001860 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001861 """
1862 cipher = _lib.SSL_get_current_cipher(self._ssl)
1863 if cipher == _ffi.NULL:
1864 return None
1865 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001866 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001867 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001868
Jim Shaverabff1882015-05-27 09:15:55 -04001869 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001870 """
1871 Obtain the protocol version of the current connection.
1872
1873 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001874 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001875 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001876 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001877 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001878 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001879 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001880
Jim Shaver208438c2015-05-28 09:52:38 -04001881 def get_protocol_version(self):
1882 """
1883 Obtain the protocol version of the current connection.
1884
1885 :returns: The TLS version of the current connection, for example
1886 the value for TLS 1 would be 0x769.
1887 :rtype: :py:class:`int`
1888 """
1889 version = _lib.SSL_version(self._ssl)
1890 return version
1891
Cory Benfield10b277f2015-04-13 17:12:42 -04001892 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001893 def get_next_proto_negotiated(self):
1894 """
1895 Get the protocol that was negotiated by NPN.
1896 """
1897 data = _ffi.new("unsigned char **")
1898 data_len = _ffi.new("unsigned int *")
1899
1900 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1901
Cory Benfieldcd010f62014-05-15 19:00:27 +01001902 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001903
Cory Benfield7907e332015-04-13 17:18:25 -04001904 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001905 def set_alpn_protos(self, protos):
1906 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001907 Specify the client's ALPN protocol list.
1908
1909 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001910
1911 :param protos: A list of the protocols to be offered to the server.
1912 This list should be a Python list of bytestrings representing the
1913 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1914 """
1915 # Take the list of protocols and join them together, prefixing them
1916 # with their lengths.
1917 protostr = b''.join(
1918 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1919 )
1920
1921 # Build a C string from the list. We don't need to save this off
1922 # because OpenSSL immediately copies the data out.
1923 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001924 input_str_len = _ffi.cast("unsigned", len(protostr))
1925 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001926
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001927 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001928 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001929 """
1930 Get the protocol that was negotiated by ALPN.
1931 """
Cory Benfield12eae892014-06-07 15:42:56 +01001932 data = _ffi.new("unsigned char **")
1933 data_len = _ffi.new("unsigned int *")
1934
1935 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1936
Cory Benfielde8e9c382015-04-11 17:33:48 -04001937 if not data_len:
1938 return b''
1939
Cory Benfield12eae892014-06-07 15:42:56 +01001940 return _ffi.buffer(data[0], data_len[0])[:]
1941
1942
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001944
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001945# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1946# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001947_lib.SSL_library_init()