blob: 63a0b7e85f419d525be0855ff00dc21b58d387b0 [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
478 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800479 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800480 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800481 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800482 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800483 self._verify_callback = None
484 self._info_callback = None
485 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800486 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000487 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100488 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000489 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100490 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400491 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100492 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800493
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800494 # SSL_CTX_set_app_data(self->ctx, self);
495 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
496 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
497 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500498 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800499
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800500 def load_verify_locations(self, cafile, capath=None):
501 """
502 Let SSL know where we can find trusted certificates for the certificate
503 chain
504
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400505 :param cafile: In which file we can find the certificates (``bytes`` or
506 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800507 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400508 (``bytes`` or ``unicode``).
509
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800510 :return: None
511 """
512 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500513 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400514 else:
515 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800516
517 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500518 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400519 else:
520 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800521
Alex Gaynor62da94d2015-09-05 14:37:34 -0400522 load_result = _lib.SSL_CTX_load_verify_locations(
523 self._context, cafile, capath
524 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800525 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500526 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800527
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800528 def _wrap_callback(self, callback):
529 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800530 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800531 return callback(size, verify, self._passphrase_userdata)
532 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800533 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800534
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800535 def set_passwd_cb(self, callback, userdata=None):
536 """
537 Set the passphrase callback
538
539 :param callback: The Python callback to use
540 :param userdata: (optional) A Python object which will be given as
541 argument to the callback
542 :return: None
543 """
544 if not callable(callback):
545 raise TypeError("callback must be callable")
546
547 self._passphrase_helper = self._wrap_callback(callback)
548 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500549 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800550 self._context, self._passphrase_callback)
551 self._passphrase_userdata = userdata
552
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800553 def set_default_verify_paths(self):
554 """
555 Use the platform-specific CA certificate locations
556
557 :return: None
558 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500559 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400560 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800561
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800562 def use_certificate_chain_file(self, certfile):
563 """
564 Load a certificate chain from a file
565
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400566 :param certfile: The name of the certificate chain file (``bytes`` or
567 ``unicode``).
568
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800569 :return: None
570 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400571 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800572
Alex Gaynor62da94d2015-09-05 14:37:34 -0400573 result = _lib.SSL_CTX_use_certificate_chain_file(
574 self._context, certfile
575 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800576 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500577 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800578
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800579 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800580 """
581 Load a certificate from a file
582
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400583 :param certfile: The name of the certificate file (``bytes`` or
584 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800585 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400586
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800587 :return: None
588 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400589 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500590 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800591 raise TypeError("filetype must be an integer")
592
Alex Gaynor62da94d2015-09-05 14:37:34 -0400593 use_result = _lib.SSL_CTX_use_certificate_file(
594 self._context, certfile, filetype
595 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800596 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500597 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800598
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800599 def use_certificate(self, cert):
600 """
601 Load a certificate from a X509 object
602
603 :param cert: The X509 object
604 :return: None
605 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800606 if not isinstance(cert, X509):
607 raise TypeError("cert must be an X509 instance")
608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500609 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800610 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500611 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800612
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800613 def add_extra_chain_cert(self, certobj):
614 """
615 Add certificate to chain
616
617 :param certobj: The X509 certificate object to add to the chain
618 :return: None
619 """
620 if not isinstance(certobj, X509):
621 raise TypeError("certobj must be an X509 instance")
622
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500623 copy = _lib.X509_dup(certobj._x509)
624 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800625 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500626 # TODO: This is untested.
627 _lib.X509_free(copy)
628 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800629
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800630 def _raise_passphrase_exception(self):
631 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500632 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800633 exception = self._passphrase_helper.raise_if_problem(Error)
634 if exception is not None:
635 raise exception
636
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400637 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638 """
639 Load a private key from a file
640
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400641 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800642 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400643
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644 :return: None
645 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400646 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800647
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400648 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800649 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500650 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800651 raise TypeError("filetype must be an integer")
652
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500653 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800654 self._context, keyfile, filetype)
655 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800656 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658 def use_privatekey(self, pkey):
659 """
660 Load a private key from a PKey object
661
662 :param pkey: The PKey object
663 :return: None
664 """
665 if not isinstance(pkey, PKey):
666 raise TypeError("pkey must be a PKey instance")
667
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500668 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800669 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800670 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800671
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672 def check_privatekey(self):
673 """
674 Check that the private key and certificate match up
675
676 :return: None (raises an exception if something's wrong)
677 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500678 if not _lib.SSL_CTX_check_private_key(self._context):
679 _raise_current_error()
680
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800681 def load_client_ca(self, cafile):
682 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100683 Load the trusted certificates that will be sent to the client. Does
684 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400685 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800686
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100687 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800688 :return: None
689 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100690 ca_list = _lib.SSL_load_client_CA_file(
691 _text_to_bytes_and_warn("cafile", cafile)
692 )
693 _openssl_assert(ca_list != _ffi.NULL)
694 # SSL_CTX_set_client_CA_list doesn't return anything.
695 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696
697 def set_session_id(self, buf):
698 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100699 Set the session id to *buf* within which a session can be reused for
700 this Context object. This is needed when doing session resumption,
701 because there is no way for a stored session to know which Context
702 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800703
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100704 :param bytes buf: The session id.
705
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800706 :returns: None
707 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100708 buf = _text_to_bytes_and_warn("buf", buf)
709 _openssl_assert(
710 _lib.SSL_CTX_set_session_id_context(
711 self._context,
712 buf,
713 len(buf),
714 ) == 1
715 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800716
717 def set_session_cache_mode(self, mode):
718 """
719 Enable/disable session caching and specify the mode used.
720
721 :param mode: One or more of the SESS_CACHE_* flags (combine using
722 bitwise or)
723 :returns: The previously set caching mode.
724 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500725 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800726 raise TypeError("mode must be an integer")
727
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500728 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800729
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730 def get_session_cache_mode(self):
731 """
732 :returns: The currently used cache mode.
733 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500734 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800735
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800736 def set_verify(self, mode, callback):
737 """
738 Set the verify mode and verify callback
739
740 :param mode: The verify mode, this is either VERIFY_NONE or
741 VERIFY_PEER combined with possible other flags
742 :param callback: The Python callback to use
743 :return: None
744
745 See SSL_CTX_set_verify(3SSL) for further details.
746 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500747 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800748 raise TypeError("mode must be an integer")
749
750 if not callable(callback):
751 raise TypeError("callback must be callable")
752
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400753 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800754 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500755 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800756
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800757 def set_verify_depth(self, depth):
758 """
759 Set the verify depth
760
761 :param depth: An integer specifying the verify depth
762 :return: None
763 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500764 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800765 raise TypeError("depth must be an integer")
766
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800768
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800769 def get_verify_mode(self):
770 """
771 Get the verify mode
772
773 :return: The verify mode
774 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500775 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800776
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800777 def get_verify_depth(self):
778 """
779 Get the verify depth
780
781 :return: The verify depth
782 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500783 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800784
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785 def load_tmp_dh(self, dhfile):
786 """
787 Load parameters for Ephemeral Diffie-Hellman
788
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400789 :param dhfile: The file to load EDH parameters from (``bytes`` or
790 ``unicode``).
791
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792 :return: None
793 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400794 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800795
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500796 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500797 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500798 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500799 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800800
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500801 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
802 dh = _ffi.gc(dh, _lib.DH_free)
803 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800804
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400805 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600806 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700807 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600808
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400809 :param curve: A curve object to use as returned by either
810 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
811 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700812
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600813 :return: None
814 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400815 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600816
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817 def set_cipher_list(self, cipher_list):
818 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100819 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800820
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100821 See the OpenSSL manual for more information (e.g.
822 :manpage:`ciphers(1)`).
823
824 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825 :return: None
826 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100827 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500828
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800829 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100830 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800831
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100832 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100833 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100834 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800835
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800836 def set_client_ca_list(self, certificate_authorities):
837 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400838 Set the list of preferred client certificate signers for this server
839 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800840
Alex Gaynor62da94d2015-09-05 14:37:34 -0400841 This list of certificate authorities will be sent to the client when
842 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800843
844 :param certificate_authorities: a sequence of X509Names.
845 :return: None
846 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500847 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700848 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800849
850 try:
851 for ca_name in certificate_authorities:
852 if not isinstance(ca_name, X509Name):
853 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400854 "client CAs must be X509Name objects, not %s "
855 "objects" % (
856 type(ca_name).__name__,
857 )
858 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500859 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -0700860 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500861 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800862 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500863 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500864 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800865 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500866 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800867 raise
868
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500869 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800870
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800871 def add_client_ca(self, certificate_authority):
872 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400873 Add the CA certificate to the list of preferred signers for this
874 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800875
876 The list of certificate authorities will be sent to the client when the
877 server requests a client certificate.
878
879 :param certificate_authority: certificate authority's X509 certificate.
880 :return: None
881 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800882 if not isinstance(certificate_authority, X509):
883 raise TypeError("certificate_authority must be an X509 instance")
884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500885 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800886 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400887 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800888
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800889 def set_timeout(self, timeout):
890 """
891 Set session timeout
892
893 :param timeout: The timeout in seconds
894 :return: The previous session timeout
895 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500896 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800897 raise TypeError("timeout must be an integer")
898
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500899 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800900
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800901 def get_timeout(self):
902 """
903 Get the session timeout
904
905 :return: The session timeout
906 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500907 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 def set_info_callback(self, callback):
910 """
911 Set the info callback
912
913 :param callback: The Python callback to use
914 :return: None
915 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800916 @wraps(callback)
917 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500918 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500919 self._info_callback = _ffi.callback(
920 "void (*)(const SSL *, int, int)", wrapper)
921 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800922
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800923 def get_app_data(self):
924 """
925 Get the application data (supplied via set_app_data())
926
927 :return: The application data
928 """
929 return self._app_data
930
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800931 def set_app_data(self, data):
932 """
933 Set the application data (will be returned from get_app_data())
934
935 :param data: Any Python object
936 :return: None
937 """
938 self._app_data = data
939
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800940 def get_cert_store(self):
941 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500942 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500944 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800945 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500946 store = _lib.SSL_CTX_get_cert_store(self._context)
947 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500948 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800949 return None
950
951 pystore = X509Store.__new__(X509Store)
952 pystore._store = store
953 return pystore
954
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800955 def set_options(self, options):
956 """
957 Add options. Options set before are not cleared!
958
959 :param options: The options to add.
960 :return: The new option bitmask.
961 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500962 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800963 raise TypeError("options must be an integer")
964
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500965 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800966
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800967 def set_mode(self, mode):
968 """
969 Add modes via bitmask. Modes set before are not cleared!
970
971 :param mode: The mode to add.
972 :return: The new mode bitmask.
973 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500974 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800975 raise TypeError("mode must be an integer")
976
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500977 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978
Cory Benfielde6f35882016-03-29 11:21:04 +0100979 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800980 def set_tlsext_servername_callback(self, callback):
981 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400982 Specify a callback function to be called when clients specify a server
983 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984
985 :param callback: The callback function. It will be invoked with one
986 argument, the Connection instance.
987 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800988 @wraps(callback)
989 def wrapper(ssl, alert, arg):
990 callback(Connection._reverse_mapping[ssl])
991 return 0
992
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 self._tlsext_servername_callback = _ffi.callback(
994 "int (*)(const SSL *, int *, void *)", wrapper)
995 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800996 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997
Cory Benfield10b277f2015-04-13 17:12:42 -0400998 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +0100999 def set_npn_advertise_callback(self, callback):
1000 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001001 Specify a callback function that will be called when offering `Next
1002 Protocol Negotiation
1003 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001004
1005 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001006 argument, the Connection instance. It should return a list of
1007 bytestrings representing the advertised protocols, like
1008 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001009 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001010 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1011 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001012 _lib.SSL_CTX_set_next_protos_advertised_cb(
1013 self._context, self._npn_advertise_callback, _ffi.NULL)
1014
Cory Benfield10b277f2015-04-13 17:12:42 -04001015 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001016 def set_npn_select_callback(self, callback):
1017 """
1018 Specify a callback function that will be called when a server offers
1019 Next Protocol Negotiation options.
1020
1021 :param callback: The callback function. It will be invoked with two
1022 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001023 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1024 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001025 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001026 self._npn_select_helper = _NpnSelectHelper(callback)
1027 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001028 _lib.SSL_CTX_set_next_proto_select_cb(
1029 self._context, self._npn_select_callback, _ffi.NULL)
1030
Cory Benfield7907e332015-04-13 17:18:25 -04001031 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001032 def set_alpn_protos(self, protos):
1033 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001034 Specify the clients ALPN protocol list.
1035
1036 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001037
1038 :param protos: A list of the protocols to be offered to the server.
1039 This list should be a Python list of bytestrings representing the
1040 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1041 """
1042 # Take the list of protocols and join them together, prefixing them
1043 # with their lengths.
1044 protostr = b''.join(
1045 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1046 )
1047
1048 # Build a C string from the list. We don't need to save this off
1049 # because OpenSSL immediately copies the data out.
1050 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001051 input_str_len = _ffi.cast("unsigned", len(protostr))
1052 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001053
Cory Benfield7907e332015-04-13 17:18:25 -04001054 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001055 def set_alpn_select_callback(self, callback):
1056 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001057 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001058
1059 :param callback: The callback function. It will be invoked with two
1060 arguments: the Connection, and a list of offered protocols as
1061 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001062 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001063 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001064 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001065 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001066 _lib.SSL_CTX_set_alpn_select_cb(
1067 self._context, self._alpn_select_callback, _ffi.NULL)
1068
Alex Chanc6077062016-11-18 13:53:39 +00001069
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001070ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001071
1072
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001073class Connection(object):
1074 """
1075 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001076 _reverse_mapping = WeakValueDictionary()
1077
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001078 def __init__(self, context, socket=None):
1079 """
1080 Create a new Connection object, using the given OpenSSL.SSL.Context
1081 instance and socket.
1082
1083 :param context: An SSL Context to use for this connection
1084 :param socket: The socket to use for transport layer
1085 """
1086 if not isinstance(context, Context):
1087 raise TypeError("context must be a Context instance")
1088
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001089 ssl = _lib.SSL_new(context._context)
1090 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001091 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001092 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001093
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001094 # References to strings used for Next Protocol Negotiation. OpenSSL's
1095 # header files suggest that these might get copied at some point, but
1096 # doesn't specify when, so we store them here to make sure they don't
1097 # get freed before OpenSSL uses them.
1098 self._npn_advertise_callback_args = None
1099 self._npn_select_callback_args = None
1100
Cory Benfield12eae892014-06-07 15:42:56 +01001101 # References to strings used for Application Layer Protocol
1102 # Negotiation. These strings get copied at some point but it's well
1103 # after the callback returns, so we have to hang them somewhere to
1104 # avoid them getting freed.
1105 self._alpn_select_callback_args = None
1106
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001107 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001108
1109 if socket is None:
1110 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001111 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001112 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001113 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001114
Alex Gaynora829e902016-06-04 18:16:01 -07001115 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1116 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001118 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001119 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001120 self._into_ssl = None
1121 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001122 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001123 set_result = _lib.SSL_set_fd(
1124 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001125 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001126
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001127 def __getattr__(self, name):
1128 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001129 Look up attributes on the wrapped socket object if they are not found
1130 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131 """
kjav0b66fa12015-09-02 11:51:26 +01001132 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001133 raise AttributeError("'%s' object has no attribute '%s'" % (
1134 self.__class__.__name__, name
1135 ))
kjav0b66fa12015-09-02 11:51:26 +01001136 else:
1137 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001139 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001140 if self._context._verify_helper is not None:
1141 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001142 if self._context._npn_advertise_helper is not None:
1143 self._context._npn_advertise_helper.raise_if_problem()
1144 if self._context._npn_select_helper is not None:
1145 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001146 if self._context._alpn_select_helper is not None:
1147 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 error = _lib.SSL_get_error(ssl, result)
1150 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001151 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001153 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001155 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001157 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001158 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 elif error == _lib.SSL_ERROR_SYSCALL:
1160 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001161 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001162 if platform == "win32":
1163 errno = _ffi.getwinerror()[0]
1164 else:
1165 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001166
1167 if errno != 0:
1168 raise SysCallError(errno, errorcode.get(errno))
1169 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001171 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001172 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001174 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001175 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001176 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001177
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001178 def get_context(self):
1179 """
1180 Get session context
1181 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001182 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001183
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001184 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001185 """
1186 Switch this connection to a new session context
1187
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001188 :param context: A :py:class:`Context` instance giving the new session
1189 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001190 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191 if not isinstance(context, Context):
1192 raise TypeError("context must be a Context instance")
1193
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001194 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001195 self._context = context
1196
Cory Benfielde6f35882016-03-29 11:21:04 +01001197 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001198 def get_servername(self):
1199 """
1200 Retrieve the servername extension value if provided in the client hello
1201 message, or None if there wasn't one.
1202
1203 :return: A byte string giving the server name or :py:data:`None`.
1204 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001205 name = _lib.SSL_get_servername(
1206 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1207 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001208 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001209 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001210
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001211 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001212
Cory Benfielde6f35882016-03-29 11:21:04 +01001213 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001214 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001215 """
1216 Set the value of the servername extension to send in the client hello.
1217
1218 :param name: A byte string giving the name.
1219 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001220 if not isinstance(name, bytes):
1221 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001222 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001223 raise TypeError("name must not contain NUL byte")
1224
1225 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001226 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001227
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001228 def pending(self):
1229 """
1230 Get the number of bytes that can be safely read from the connection
1231
1232 :return: The number of bytes available in the receive buffer.
1233 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001234 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001235
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001236 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001237 """
1238 Send data on the connection. NOTE: If you get one of the WantRead,
1239 WantWrite or WantX509Lookup exceptions on this, you have to call the
1240 method again with the SAME buffer.
1241
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001242 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001243 :param flags: (optional) Included for compatibility with the socket
1244 API, the value is ignored
1245 :return: The number of bytes written
1246 """
Abraham Martine82326c2015-02-04 10:18:10 +00001247 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001248 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001249
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001250 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001251 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001252 if isinstance(buf, _buffer):
1253 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001254 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001255 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001256
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001257 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001258 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001259 return result
1260 write = send
1261
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001262 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001263 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001264 Send "all" data on the connection. This calls send() repeatedly until
1265 all data is sent. If an error occurs, it's impossible to tell how much
1266 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001267
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001268 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001269 :param flags: (optional) Included for compatibility with the socket
1270 API, the value is ignored
1271 :return: The number of bytes written
1272 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001273 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001274
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001275 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001276 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001277 if isinstance(buf, _buffer):
1278 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001279 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001280 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281
1282 left_to_send = len(buf)
1283 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001285
1286 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001288 self._raise_ssl_error(self._ssl, result)
1289 total_sent += result
1290 left_to_send -= result
1291
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001292 def recv(self, bufsiz, flags=None):
1293 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001294 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295
1296 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001297 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1298 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001299 :return: The string read from the Connection
1300 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001301 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001302 if flags is not None and flags & socket.MSG_PEEK:
1303 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1304 else:
1305 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001306 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001307 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001308 read = recv
1309
Cory Benfield62d10332014-06-15 10:03:41 +01001310 def recv_into(self, buffer, nbytes=None, flags=None):
1311 """
1312 Receive data on the connection and store the data into a buffer rather
1313 than creating a new string.
1314
1315 :param buffer: The buffer to copy into.
1316 :param nbytes: (optional) The maximum number of bytes to read into the
1317 buffer. If not present, defaults to the size of the buffer. If
1318 larger than the size of the buffer, is reduced to the size of the
1319 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001320 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1321 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001322 :return: The number of bytes read into the buffer.
1323 """
1324 if nbytes is None:
1325 nbytes = len(buffer)
1326 else:
1327 nbytes = min(nbytes, len(buffer))
1328
1329 # We need to create a temporary buffer. This is annoying, it would be
1330 # better if we could pass memoryviews straight into the SSL_read call,
1331 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001332 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001333 if flags is not None and flags & socket.MSG_PEEK:
1334 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1335 else:
1336 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001337 self._raise_ssl_error(self._ssl, result)
1338
1339 # This strange line is all to avoid a memory copy. The buffer protocol
1340 # should allow us to assign a CFFI buffer to the LHS of this line, but
1341 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1342 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1343 # memoryview type.
1344 try:
1345 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1346 except NameError:
1347 buffer[:result] = _ffi.buffer(buf, result)
1348
1349 return result
1350
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001351 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001352 if _lib.BIO_should_retry(bio):
1353 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001354 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001355 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001356 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001357 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001358 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001359 # TODO: This is untested. I think io_special means the socket
1360 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001361 raise ValueError("BIO_should_io_special")
1362 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001363 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001364 raise ValueError("unknown bio failure")
1365 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001366 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001367 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001368
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001369 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001370 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001371 When using non-socket connections this function reads the "dirty" data
1372 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001373
1374 :param bufsiz: The maximum number of bytes to read
1375 :return: The string read.
1376 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001377 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001378 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001379
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001380 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001381 raise TypeError("bufsiz must be an integer")
1382
Cory Benfielde62840e2016-11-28 12:17:08 +00001383 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001384 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385 if result <= 0:
1386 self._handle_bio_errors(self._from_ssl, result)
1387
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001388 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001389
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001391 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001392 When using non-socket connections this function sends "dirty" data that
1393 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001394
1395 :param buf: The string to put into the memory BIO.
1396 :return: The number of bytes written
1397 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001398 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001399
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001400 if self._into_ssl is None:
1401 raise TypeError("Connection sock was not None")
1402
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001403 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001404 if result <= 0:
1405 self._handle_bio_errors(self._into_ssl, result)
1406 return result
1407
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001408 def renegotiate(self):
1409 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001410 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001411
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001412 :return: True if the renegotiation can be started, False otherwise
1413 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001414 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001415 if not self.renegotiate_pending():
1416 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1417 return True
1418 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001419
1420 def do_handshake(self):
1421 """
1422 Perform an SSL handshake (usually called after renegotiate() or one of
1423 set_*_state()). This can raise the same exceptions as send and recv.
1424
1425 :return: None.
1426 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001427 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001428 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001429
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001430 def renegotiate_pending(self):
1431 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001432 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001433 a renegotiation is finished.
1434
1435 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001436 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001437 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001438 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001439
1440 def total_renegotiations(self):
1441 """
1442 Find out the total number of renegotiations.
1443
1444 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001445 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001446 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001447 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001448
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001449 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001450 """
1451 Connect to remote host and set up client-side SSL
1452
1453 :param addr: A remote address
1454 :return: What the socket's connect method returns
1455 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001456 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001457 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001458
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001459 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001460 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001461 Connect to remote host and set up client-side SSL. Note that if the
1462 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463
1464 :param addr: A remove address
1465 :return: What the socket's connect_ex method returns
1466 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 connect_ex = self._socket.connect_ex
1468 self.set_connect_state()
1469 return connect_ex(addr)
1470
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001471 def accept(self):
1472 """
1473 Accept incoming connection and set up SSL on it
1474
1475 :return: A (conn,addr) pair where conn is a Connection and addr is an
1476 address
1477 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001478 client, addr = self._socket.accept()
1479 conn = Connection(self._context, client)
1480 conn.set_accept_state()
1481 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001482
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001483 def bio_shutdown(self):
1484 """
1485 When using non-socket connections this function signals end of
1486 data on the input for this connection.
1487
1488 :return: None
1489 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490 if self._from_ssl is None:
1491 raise TypeError("Connection sock was not None")
1492
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001493 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495 def shutdown(self):
1496 """
1497 Send closure alert
1498
1499 :return: True if the shutdown completed successfully (i.e. both sides
1500 have sent closure alerts), false otherwise (i.e. you have to
1501 wait for a ZeroReturnError on a recv() method call
1502 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001503 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001505 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001506 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001507 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001508 else:
1509 return False
1510
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001511 def get_cipher_list(self):
1512 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001513 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001515 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001516 """
1517 ciphers = []
1518 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001519 result = _lib.SSL_get_cipher_list(self._ssl, i)
1520 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001522 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523 return ciphers
1524
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001525 def get_client_ca_list(self):
1526 """
1527 Get CAs whose certificates are suggested for client authentication.
1528
Alex Gaynor62da94d2015-09-05 14:37:34 -04001529 :return: If this is a server connection, a list of X509Names
1530 representing the acceptable CAs as set by
1531 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1532 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1533 connection, the list of such X509Names sent by the server, or an
1534 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001535 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001536 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1537 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001538 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001539 return []
1540
1541 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1543 name = _lib.sk_X509_NAME_value(ca_names, i)
1544 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001545 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001546
1547 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001548 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001549 result.append(pyname)
1550 return result
1551
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001552 def makefile(self):
1553 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001554 The makefile() method is not implemented, since there is no dup
1555 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001556
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001557 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001558 """
Alex Gaynor83284952015-09-05 10:43:30 -04001559 raise NotImplementedError(
1560 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001561
1562 def get_app_data(self):
1563 """
1564 Get application data
1565
1566 :return: The application data
1567 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001568 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001569
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001570 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001571 """
1572 Set application data
1573
1574 :param data - The application data
1575 :return: None
1576 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 self._app_data = data
1578
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001579 def get_shutdown(self):
1580 """
1581 Get shutdown state
1582
Alex Gaynor62da94d2015-09-05 14:37:34 -04001583 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1584 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001586 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001588 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001589 """
1590 Set shutdown state
1591
1592 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1593 :return: None
1594 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001595 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001596 raise TypeError("state must be an integer")
1597
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001598 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001599
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001600 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001601 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001602 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001603
1604 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001605 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001606 """
kjavc704a2e2015-09-07 12:12:27 +01001607 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001608
1609 def server_random(self):
1610 """
1611 Get a copy of the server hello nonce.
1612
1613 :return: A string representing the state
1614 """
Alex Gaynor93603062016-06-01 20:13:09 -07001615 session = _lib.SSL_get_session(self._ssl)
1616 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001617 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001618 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1619 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001620 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001621 _lib.SSL_get_server_random(self._ssl, outp, length)
1622 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001623
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001624 def client_random(self):
1625 """
1626 Get a copy of the client hello nonce.
1627
1628 :return: A string representing the state
1629 """
Alex Gaynor93603062016-06-01 20:13:09 -07001630 session = _lib.SSL_get_session(self._ssl)
1631 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001632 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001633
1634 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1635 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001636 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001637 _lib.SSL_get_client_random(self._ssl, outp, length)
1638 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001639
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001640 def master_key(self):
1641 """
1642 Get a copy of the master key.
1643
1644 :return: A string representing the state
1645 """
Alex Gaynor93603062016-06-01 20:13:09 -07001646 session = _lib.SSL_get_session(self._ssl)
1647 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001648 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001649
1650 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1651 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001652 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001653 _lib.SSL_SESSION_get_master_key(session, outp, length)
1654 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001655
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001656 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001657 """
1658 See shutdown(2)
1659
1660 :return: What the socket's shutdown() method returns
1661 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 return self._socket.shutdown(*args, **kwargs)
1663
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001664 def get_peer_certificate(self):
1665 """
1666 Retrieve the other side's certificate (if any)
1667
1668 :return: The peer's certificate
1669 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001670 cert = _lib.SSL_get_peer_certificate(self._ssl)
1671 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001672 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001673 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001674 return pycert
1675 return None
1676
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677 def get_peer_cert_chain(self):
1678 """
1679 Retrieve the other side's certificate (if any)
1680
1681 :return: A list of X509 instances giving the peer's certificate chain,
1682 or None if it does not have one.
1683 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001684 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1685 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001686 return None
1687
1688 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001690 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001691 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001692 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001694 result.append(pycert)
1695 return result
1696
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697 def want_read(self):
1698 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001699 Checks if more data has to be read from the transport layer to complete
1700 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701
1702 :return: True iff more data has to be read
1703 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001704 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001705
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001706 def want_write(self):
1707 """
1708 Checks if there is data to write to the transport layer to complete an
1709 operation.
1710
1711 :return: True iff there is data to write
1712 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001713 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001714
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715 def set_accept_state(self):
1716 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001717 Set the connection to work in server mode. The handshake will be
1718 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719
1720 :return: None
1721 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001722 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001723
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724 def set_connect_state(self):
1725 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001726 Set the connection to work in client 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_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001733 def get_session(self):
1734 """
1735 Returns the Session currently used.
1736
Alex Gaynor62da94d2015-09-05 14:37:34 -04001737 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1738 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001739 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001740 session = _lib.SSL_get1_session(self._ssl)
1741 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001743
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001744 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001746 return pysession
1747
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001748 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749 """
1750 Set the session to be used when the TLS/SSL connection is established.
1751
1752 :param session: A Session instance representing the session to use.
1753 :returns: None
1754 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755 if not isinstance(session, Session):
1756 raise TypeError("session must be a Session instance")
1757
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001758 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001759 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001760 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001761
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001762 def _get_finished_message(self, function):
1763 """
1764 Helper to implement :py:meth:`get_finished` and
1765 :py:meth:`get_peer_finished`.
1766
1767 :param function: Either :py:data:`SSL_get_finished`: or
1768 :py:data:`SSL_get_peer_finished`.
1769
1770 :return: :py:data:`None` if the desired message has not yet been
1771 received, otherwise the contents of the message.
1772 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1773 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001774 # The OpenSSL documentation says nothing about what might happen if the
1775 # count argument given is zero. Specifically, it doesn't say whether
1776 # the output buffer may be NULL in that case or not. Inspection of the
1777 # implementation reveals that it calls memcpy() unconditionally.
1778 # Section 7.1.4, paragraph 1 of the C standard suggests that
1779 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1780 # alone desirable) behavior (though it probably does on just about
1781 # every implementation...)
1782 #
1783 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1784 # one might expect) for the initial call so as to be safe against this
1785 # potentially undefined behavior.
1786 empty = _ffi.new("char[]", 0)
1787 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001788 if size == 0:
1789 # No Finished message so far.
1790 return None
1791
Cory Benfielde62840e2016-11-28 12:17:08 +00001792 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001793 function(self._ssl, buf, size)
1794 return _ffi.buffer(buf, size)[:]
1795
Fedor Brunner5747b932014-03-05 14:22:34 +01001796 def get_finished(self):
1797 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001798 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001799
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001800 :return: The contents of the message or :py:obj:`None` if the TLS
1801 handshake has not yet completed.
1802 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001803 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001804 return self._get_finished_message(_lib.SSL_get_finished)
1805
Fedor Brunner5747b932014-03-05 14:22:34 +01001806 def get_peer_finished(self):
1807 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001808 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001809
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001810 :return: The contents of the message or :py:obj:`None` if the TLS
1811 handshake has not yet completed.
1812 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001813 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001814 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001815
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001816 def get_cipher_name(self):
1817 """
1818 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001819
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001820 :returns: The name of the currently used cipher or :py:obj:`None`
1821 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001822 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001823 """
1824 cipher = _lib.SSL_get_current_cipher(self._ssl)
1825 if cipher == _ffi.NULL:
1826 return None
1827 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001828 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1829 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001830
1831 def get_cipher_bits(self):
1832 """
1833 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001834
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001835 :returns: The number of secret bits of the currently used cipher
1836 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001837 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001838 """
1839 cipher = _lib.SSL_get_current_cipher(self._ssl)
1840 if cipher == _ffi.NULL:
1841 return None
1842 else:
1843 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1844
1845 def get_cipher_version(self):
1846 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001847 Obtain the protocol version of the currently used cipher.
1848
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001849 :returns: The protocol name of the currently used cipher
1850 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001851 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001852 """
1853 cipher = _lib.SSL_get_current_cipher(self._ssl)
1854 if cipher == _ffi.NULL:
1855 return None
1856 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001857 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001858 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001859
Jim Shaverabff1882015-05-27 09:15:55 -04001860 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001861 """
1862 Obtain the protocol version of the current connection.
1863
1864 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001865 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001866 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001867 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001868 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001869 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001870 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001871
Jim Shaver208438c2015-05-28 09:52:38 -04001872 def get_protocol_version(self):
1873 """
1874 Obtain the protocol version of the current connection.
1875
1876 :returns: The TLS version of the current connection, for example
1877 the value for TLS 1 would be 0x769.
1878 :rtype: :py:class:`int`
1879 """
1880 version = _lib.SSL_version(self._ssl)
1881 return version
1882
Cory Benfield10b277f2015-04-13 17:12:42 -04001883 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001884 def get_next_proto_negotiated(self):
1885 """
1886 Get the protocol that was negotiated by NPN.
1887 """
1888 data = _ffi.new("unsigned char **")
1889 data_len = _ffi.new("unsigned int *")
1890
1891 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1892
Cory Benfieldcd010f62014-05-15 19:00:27 +01001893 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001894
Cory Benfield7907e332015-04-13 17:18:25 -04001895 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001896 def set_alpn_protos(self, protos):
1897 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001898 Specify the client's ALPN protocol list.
1899
1900 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001901
1902 :param protos: A list of the protocols to be offered to the server.
1903 This list should be a Python list of bytestrings representing the
1904 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1905 """
1906 # Take the list of protocols and join them together, prefixing them
1907 # with their lengths.
1908 protostr = b''.join(
1909 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1910 )
1911
1912 # Build a C string from the list. We don't need to save this off
1913 # because OpenSSL immediately copies the data out.
1914 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001915 input_str_len = _ffi.cast("unsigned", len(protostr))
1916 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001917
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001918 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001919 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001920 """
1921 Get the protocol that was negotiated by ALPN.
1922 """
Cory Benfield12eae892014-06-07 15:42:56 +01001923 data = _ffi.new("unsigned char **")
1924 data_len = _ffi.new("unsigned int *")
1925
1926 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1927
Cory Benfielde8e9c382015-04-11 17:33:48 -04001928 if not data_len:
1929 return b''
1930
Cory Benfield12eae892014-06-07 15:42:56 +01001931 return _ffi.buffer(data[0], data_len[0])[:]
1932
1933
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001934ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001935
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001936# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1937# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001938_lib.SSL_library_init()