blob: 3f97ccbe578fd513ca292767059193f32cbd026d [file] [log] [blame]
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02002from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05003from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01004from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08005from weakref import WeakValueDictionary
6from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08007
Cory Benfield63759dc2015-04-12 08:57:03 -04008from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -08009from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010010from six import int2byte, indexbytes
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050011
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050012from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010013 UNSPECIFIED as _UNSPECIFIED,
14 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015 ffi as _ffi,
16 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010017 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010018 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040019 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040021)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080022
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080023from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050024 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080025
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050026try:
27 _memoryview = memoryview
28except NameError:
29 class _memoryview(object):
30 pass
31
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020032try:
33 _buffer = buffer
34except NameError:
35 class _buffer(object):
36 pass
37
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050038OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
39SSLEAY_VERSION = _lib.SSLEAY_VERSION
40SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
41SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
42SSLEAY_DIR = _lib.SSLEAY_DIR
43SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080044
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050045SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
46RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080047
48SSLv2_METHOD = 1
49SSLv3_METHOD = 2
50SSLv23_METHOD = 3
51TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050052TLSv1_1_METHOD = 5
53TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080054
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050055OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
56OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
57OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050058
59OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
60OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080061
Alex Gaynorbf012872016-06-04 13:18:39 -070062MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080063
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050064OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090065OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050066OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
67OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
68OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040069OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
70 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
71)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050072OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
73OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040074OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
76OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
77OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
78OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
79OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
80OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
81OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
82OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
83OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040084OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
85 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
86)
Alex Gaynorbf012872016-06-04 13:18:39 -070087OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080088
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050089OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
90OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040091OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080092
Alex Gaynorc4889812015-09-04 08:43:17 -040093OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080094
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050095VERIFY_PEER = _lib.SSL_VERIFY_PEER
96VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
97VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
98VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080099
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500100SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
101SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
102SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
103SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
104SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
105SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
106SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
107SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800108
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500109SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
110SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
111SSL_ST_MASK = _lib.SSL_ST_MASK
112SSL_ST_INIT = _lib.SSL_ST_INIT
113SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
114SSL_ST_OK = _lib.SSL_ST_OK
115SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800116
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500117SSL_CB_LOOP = _lib.SSL_CB_LOOP
118SSL_CB_EXIT = _lib.SSL_CB_EXIT
119SSL_CB_READ = _lib.SSL_CB_READ
120SSL_CB_WRITE = _lib.SSL_CB_WRITE
121SSL_CB_ALERT = _lib.SSL_CB_ALERT
122SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
123SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
124SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
125SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
126SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
127SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
128SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
129SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800130
Alex Gaynor83284952015-09-05 10:43:30 -0400131
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500132class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500133 """
134 An error occurred in an `OpenSSL.SSL` API.
135 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500136
137
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500138_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100139_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500140
141
142class WantReadError(Error):
143 pass
144
145
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500146class WantWriteError(Error):
147 pass
148
149
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500150class WantX509LookupError(Error):
151 pass
152
153
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500154class ZeroReturnError(Error):
155 pass
156
157
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158class SysCallError(Error):
159 pass
160
161
Cory Benfield0ea76e72015-03-22 09:05:28 +0000162class _CallbackExceptionHelper(object):
163 """
164 A base class for wrapper classes that allow for intelligent exception
165 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500166
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400167 :ivar list _problems: Any exceptions that occurred while executing in a
168 context where they could not be raised in the normal way. Typically
169 this is because OpenSSL has called into some Python code and requires a
170 return value. The exceptions are saved to be raised later when it is
171 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000172 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400173
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400174 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800175 self._problems = []
176
Cory Benfield0ea76e72015-03-22 09:05:28 +0000177 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400178 """
179 Raise an exception from the OpenSSL error queue or that was previously
180 captured whe running a callback.
181 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000182 if self._problems:
183 try:
184 _raise_current_error()
185 except Error:
186 pass
187 raise self._problems.pop(0)
188
189
190class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400191 """
192 Wrap a callback such that it can be used as a certificate verification
193 callback.
194 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400195
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800196 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400197 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800198
199 @wraps(callback)
200 def wrapper(ok, store_ctx):
201 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500202 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
203 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
204 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800205
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400206 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
207 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
208 connection = Connection._reverse_mapping[ssl]
209
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800210 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400211 result = callback(
212 connection, cert, error_number, error_depth, ok
213 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800214 except Exception as e:
215 self._problems.append(e)
216 return 0
217 else:
218 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500219 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800220 return 1
221 else:
222 return 0
223
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500224 self.callback = _ffi.callback(
225 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800226
227
Cory Benfield0ea76e72015-03-22 09:05:28 +0000228class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400229 """
230 Wrap a callback such that it can be used as an NPN advertisement callback.
231 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400232
Cory Benfield0ea76e72015-03-22 09:05:28 +0000233 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400234 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800235
Cory Benfield0ea76e72015-03-22 09:05:28 +0000236 @wraps(callback)
237 def wrapper(ssl, out, outlen, arg):
238 try:
239 conn = Connection._reverse_mapping[ssl]
240 protos = callback(conn)
241
242 # Join the protocols into a Python bytestring, length-prefixing
243 # each element.
244 protostr = b''.join(
245 chain.from_iterable((int2byte(len(p)), p) for p in protos)
246 )
247
248 # Save our callback arguments on the connection object. This is
249 # done to make sure that they don't get freed before OpenSSL
250 # uses them. Then, return them appropriately in the output
251 # parameters.
252 conn._npn_advertise_callback_args = [
253 _ffi.new("unsigned int *", len(protostr)),
254 _ffi.new("unsigned char[]", protostr),
255 ]
256 outlen[0] = conn._npn_advertise_callback_args[0][0]
257 out[0] = conn._npn_advertise_callback_args[1]
258 return 0
259 except Exception as e:
260 self._problems.append(e)
261 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
262
263 self.callback = _ffi.callback(
264 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
265 wrapper
266 )
267
268
269class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400270 """
271 Wrap a callback such that it can be used as an NPN selection callback.
272 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400273
Cory Benfield0ea76e72015-03-22 09:05:28 +0000274 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400275 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000276
277 @wraps(callback)
278 def wrapper(ssl, out, outlen, in_, inlen, arg):
279 try:
280 conn = Connection._reverse_mapping[ssl]
281
282 # The string passed to us is actually made up of multiple
283 # length-prefixed bytestrings. We need to split that into a
284 # list.
285 instr = _ffi.buffer(in_, inlen)[:]
286 protolist = []
287 while instr:
288 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400289 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000290 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400291 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000292
293 # Call the callback
294 outstr = callback(conn, protolist)
295
296 # Save our callback arguments on the connection object. This is
297 # done to make sure that they don't get freed before OpenSSL
298 # uses them. Then, return them appropriately in the output
299 # parameters.
300 conn._npn_select_callback_args = [
301 _ffi.new("unsigned char *", len(outstr)),
302 _ffi.new("unsigned char[]", outstr),
303 ]
304 outlen[0] = conn._npn_select_callback_args[0][0]
305 out[0] = conn._npn_select_callback_args[1]
306 return 0
307 except Exception as e:
308 self._problems.append(e)
309 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
310
311 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400312 ("int (*)(SSL *, unsigned char **, unsigned char *, "
313 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000314 wrapper
315 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800316
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800317
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400318class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400319 """
320 Wrap a callback such that it can be used as an ALPN selection callback.
321 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400322
Cory Benfieldf1177e72015-04-12 09:11:49 -0400323 def __init__(self, callback):
324 _CallbackExceptionHelper.__init__(self)
325
326 @wraps(callback)
327 def wrapper(ssl, out, outlen, in_, inlen, arg):
328 try:
329 conn = Connection._reverse_mapping[ssl]
330
331 # The string passed to us is made up of multiple
332 # length-prefixed bytestrings. We need to split that into a
333 # list.
334 instr = _ffi.buffer(in_, inlen)[:]
335 protolist = []
336 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400337 encoded_len = indexbytes(instr, 0)
338 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400339 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400340 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400341
342 # Call the callback
343 outstr = callback(conn, protolist)
344
345 if not isinstance(outstr, _binary_type):
346 raise TypeError("ALPN callback must return a bytestring.")
347
348 # Save our callback arguments on the connection object to make
349 # sure that they don't get freed before OpenSSL can use them.
350 # Then, return them in the appropriate output parameters.
351 conn._alpn_select_callback_args = [
352 _ffi.new("unsigned char *", len(outstr)),
353 _ffi.new("unsigned char[]", outstr),
354 ]
355 outlen[0] = conn._alpn_select_callback_args[0][0]
356 out[0] = conn._alpn_select_callback_args[1]
357 return 0
358 except Exception as e:
359 self._problems.append(e)
360 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
361
362 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400363 ("int (*)(SSL *, unsigned char **, unsigned char *, "
364 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400365 wrapper
366 )
367
368
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800369def _asFileDescriptor(obj):
370 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800371 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800372 meth = getattr(obj, "fileno", None)
373 if meth is not None:
374 obj = meth()
375
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800376 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800377 fd = obj
378
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800379 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800380 raise TypeError("argument must be an int, or have a fileno() method.")
381 elif fd < 0:
382 raise ValueError(
383 "file descriptor cannot be a negative integer (%i)" % (fd,))
384
385 return fd
386
387
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800388def SSLeay_version(type):
389 """
390 Return a string describing the version of OpenSSL in use.
391
392 :param type: One of the SSLEAY_ constants defined in this module.
393 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500394 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800395
396
Cory Benfieldef404df2016-03-29 15:32:48 +0100397def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400398 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100399 Builds a decorator that ensures that functions that rely on OpenSSL
400 functions that are not present in this build raise NotImplementedError,
401 rather than AttributeError coming out of cryptography.
402
403 :param flag: A cryptography flag that guards the functions, e.g.
404 ``Cryptography_HAS_NEXTPROTONEG``.
405 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400406 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100407 def _requires_decorator(func):
408 if not flag:
409 @wraps(func)
410 def explode(*args, **kwargs):
411 raise NotImplementedError(error)
412 return explode
413 else:
414 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400415
Cory Benfieldef404df2016-03-29 15:32:48 +0100416 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400417
418
Cory Benfieldef404df2016-03-29 15:32:48 +0100419_requires_npn = _make_requires(
420 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
421)
Cory Benfield7907e332015-04-13 17:18:25 -0400422
423
Cory Benfieldef404df2016-03-29 15:32:48 +0100424_requires_alpn = _make_requires(
425 _lib.Cryptography_HAS_ALPN, "ALPN not available"
426)
Cory Benfielde6f35882016-03-29 11:21:04 +0100427
Cory Benfielde6f35882016-03-29 11:21:04 +0100428
Cory Benfieldef404df2016-03-29 15:32:48 +0100429_requires_sni = _make_requires(
430 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
431)
Cory Benfielde6f35882016-03-29 11:21:04 +0100432
433
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800434class Session(object):
435 pass
436
437
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800438class Context(object):
439 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100440 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400441 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800442 """
443 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800444 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500445 SSLv3_METHOD: "SSLv3_method",
446 SSLv23_METHOD: "SSLv23_method",
447 TLSv1_METHOD: "TLSv1_method",
448 TLSv1_1_METHOD: "TLSv1_1_method",
449 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400450 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500451 _methods = dict(
452 (identifier, getattr(_lib, name))
453 for (identifier, name) in _methods.items()
454 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800455
456 def __init__(self, method):
457 """
458 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
459 TLSv1_METHOD.
460 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500461 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800462 raise TypeError("method must be an integer")
463
464 try:
465 method_func = self._methods[method]
466 except KeyError:
467 raise ValueError("No such protocol")
468
469 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700470 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800471
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500472 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700473 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500474 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800475
476 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800477 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800478 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800479 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800480 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800481 self._verify_callback = None
482 self._info_callback = None
483 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800484 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000485 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100486 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000487 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100488 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400489 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100490 self._alpn_select_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800491
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800492 # SSL_CTX_set_app_data(self->ctx, self);
493 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
494 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
495 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500496 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800497
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800498 def load_verify_locations(self, cafile, capath=None):
499 """
500 Let SSL know where we can find trusted certificates for the certificate
501 chain
502
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400503 :param cafile: In which file we can find the certificates (``bytes`` or
504 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800505 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400506 (``bytes`` or ``unicode``).
507
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800508 :return: None
509 """
510 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500511 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400512 else:
513 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800514
515 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500516 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400517 else:
518 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800519
Alex Gaynor62da94d2015-09-05 14:37:34 -0400520 load_result = _lib.SSL_CTX_load_verify_locations(
521 self._context, cafile, capath
522 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800523 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500524 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800525
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800526 def _wrap_callback(self, callback):
527 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800528 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800529 return callback(size, verify, self._passphrase_userdata)
530 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800531 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800532
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800533 def set_passwd_cb(self, callback, userdata=None):
534 """
535 Set the passphrase callback
536
537 :param callback: The Python callback to use
538 :param userdata: (optional) A Python object which will be given as
539 argument to the callback
540 :return: None
541 """
542 if not callable(callback):
543 raise TypeError("callback must be callable")
544
545 self._passphrase_helper = self._wrap_callback(callback)
546 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500547 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800548 self._context, self._passphrase_callback)
549 self._passphrase_userdata = userdata
550
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800551 def set_default_verify_paths(self):
552 """
553 Use the platform-specific CA certificate locations
554
555 :return: None
556 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500557 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400558 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800559
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800560 def use_certificate_chain_file(self, certfile):
561 """
562 Load a certificate chain from a file
563
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400564 :param certfile: The name of the certificate chain file (``bytes`` or
565 ``unicode``).
566
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800567 :return: None
568 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400569 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800570
Alex Gaynor62da94d2015-09-05 14:37:34 -0400571 result = _lib.SSL_CTX_use_certificate_chain_file(
572 self._context, certfile
573 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800574 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500575 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800576
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800577 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800578 """
579 Load a certificate from a file
580
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400581 :param certfile: The name of the certificate file (``bytes`` or
582 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800583 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400584
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800585 :return: None
586 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400587 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500588 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800589 raise TypeError("filetype must be an integer")
590
Alex Gaynor62da94d2015-09-05 14:37:34 -0400591 use_result = _lib.SSL_CTX_use_certificate_file(
592 self._context, certfile, filetype
593 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800594 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500595 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800596
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800597 def use_certificate(self, cert):
598 """
599 Load a certificate from a X509 object
600
601 :param cert: The X509 object
602 :return: None
603 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800604 if not isinstance(cert, X509):
605 raise TypeError("cert must be an X509 instance")
606
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500607 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800608 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500609 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800610
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800611 def add_extra_chain_cert(self, certobj):
612 """
613 Add certificate to chain
614
615 :param certobj: The X509 certificate object to add to the chain
616 :return: None
617 """
618 if not isinstance(certobj, X509):
619 raise TypeError("certobj must be an X509 instance")
620
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500621 copy = _lib.X509_dup(certobj._x509)
622 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800623 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500624 # TODO: This is untested.
625 _lib.X509_free(copy)
626 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800627
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800628 def _raise_passphrase_exception(self):
629 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500630 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800631 exception = self._passphrase_helper.raise_if_problem(Error)
632 if exception is not None:
633 raise exception
634
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400635 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800636 """
637 Load a private key from a file
638
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400639 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800640 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400641
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800642 :return: None
643 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400644 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400646 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800647 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500648 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800649 raise TypeError("filetype must be an integer")
650
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500651 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800652 self._context, keyfile, filetype)
653 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800654 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656 def use_privatekey(self, pkey):
657 """
658 Load a private key from a PKey object
659
660 :param pkey: The PKey object
661 :return: None
662 """
663 if not isinstance(pkey, PKey):
664 raise TypeError("pkey must be a PKey instance")
665
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500666 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800668 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800669
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670 def check_privatekey(self):
671 """
672 Check that the private key and certificate match up
673
674 :return: None (raises an exception if something's wrong)
675 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500676 if not _lib.SSL_CTX_check_private_key(self._context):
677 _raise_current_error()
678
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800679 def load_client_ca(self, cafile):
680 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100681 Load the trusted certificates that will be sent to the client. Does
682 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400683 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100685 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800686 :return: None
687 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100688 ca_list = _lib.SSL_load_client_CA_file(
689 _text_to_bytes_and_warn("cafile", cafile)
690 )
691 _openssl_assert(ca_list != _ffi.NULL)
692 # SSL_CTX_set_client_CA_list doesn't return anything.
693 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800694
695 def set_session_id(self, buf):
696 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100697 Set the session id to *buf* within which a session can be reused for
698 this Context object. This is needed when doing session resumption,
699 because there is no way for a stored session to know which Context
700 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800701
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100702 :param bytes buf: The session id.
703
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800704 :returns: None
705 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100706 buf = _text_to_bytes_and_warn("buf", buf)
707 _openssl_assert(
708 _lib.SSL_CTX_set_session_id_context(
709 self._context,
710 buf,
711 len(buf),
712 ) == 1
713 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714
715 def set_session_cache_mode(self, mode):
716 """
717 Enable/disable session caching and specify the mode used.
718
719 :param mode: One or more of the SESS_CACHE_* flags (combine using
720 bitwise or)
721 :returns: The previously set caching mode.
722 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500723 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800724 raise TypeError("mode must be an integer")
725
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800727
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800728 def get_session_cache_mode(self):
729 """
730 :returns: The currently used cache mode.
731 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500732 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800733
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800734 def set_verify(self, mode, callback):
735 """
736 Set the verify mode and verify callback
737
738 :param mode: The verify mode, this is either VERIFY_NONE or
739 VERIFY_PEER combined with possible other flags
740 :param callback: The Python callback to use
741 :return: None
742
743 See SSL_CTX_set_verify(3SSL) for further details.
744 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500745 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800746 raise TypeError("mode must be an integer")
747
748 if not callable(callback):
749 raise TypeError("callback must be callable")
750
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400751 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800752 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500753 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800754
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800755 def set_verify_depth(self, depth):
756 """
757 Set the verify depth
758
759 :param depth: An integer specifying the verify depth
760 :return: None
761 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500762 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800763 raise TypeError("depth must be an integer")
764
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500765 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800766
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800767 def get_verify_mode(self):
768 """
769 Get the verify mode
770
771 :return: The verify mode
772 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500773 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800774
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800775 def get_verify_depth(self):
776 """
777 Get the verify depth
778
779 :return: The verify depth
780 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500781 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800782
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800783 def load_tmp_dh(self, dhfile):
784 """
785 Load parameters for Ephemeral Diffie-Hellman
786
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -0400787 :param dhfile: The file to load EDH parameters from (``bytes`` or
788 ``unicode``).
789
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800790 :return: None
791 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -0400792 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800793
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500794 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500795 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500796 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500797 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500799 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
800 dh = _ffi.gc(dh, _lib.DH_free)
801 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800802
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -0400803 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600804 """
Andy Lutomirski76a61332014-03-12 15:02:56 -0700805 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600806
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400807 :param curve: A curve object to use as returned by either
808 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
809 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -0700810
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600811 :return: None
812 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400813 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600814
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800815 def set_cipher_list(self, cipher_list):
816 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100817 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800818
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100819 See the OpenSSL manual for more information (e.g.
820 :manpage:`ciphers(1)`).
821
822 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800823 :return: None
824 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100825 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500826
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800827 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +0100828 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800829
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100830 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +0100831 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100832 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800833
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800834 def set_client_ca_list(self, certificate_authorities):
835 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400836 Set the list of preferred client certificate signers for this server
837 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800838
Alex Gaynor62da94d2015-09-05 14:37:34 -0400839 This list of certificate authorities will be sent to the client when
840 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800841
842 :param certificate_authorities: a sequence of X509Names.
843 :return: None
844 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500845 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -0700846 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800847
848 try:
849 for ca_name in certificate_authorities:
850 if not isinstance(ca_name, X509Name):
851 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400852 "client CAs must be X509Name objects, not %s "
853 "objects" % (
854 type(ca_name).__name__,
855 )
856 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500857 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -0700858 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500859 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800860 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500861 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500862 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800863 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500864 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800865 raise
866
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500867 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800868
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800869 def add_client_ca(self, certificate_authority):
870 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400871 Add the CA certificate to the list of preferred signers for this
872 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873
874 The list of certificate authorities will be sent to the client when the
875 server requests a client certificate.
876
877 :param certificate_authority: certificate authority's X509 certificate.
878 :return: None
879 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800880 if not isinstance(certificate_authority, X509):
881 raise TypeError("certificate_authority must be an X509 instance")
882
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500883 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800884 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400885 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800886
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800887 def set_timeout(self, timeout):
888 """
889 Set session timeout
890
891 :param timeout: The timeout in seconds
892 :return: The previous session timeout
893 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500894 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800895 raise TypeError("timeout must be an integer")
896
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500897 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800899 def get_timeout(self):
900 """
901 Get the session timeout
902
903 :return: The session timeout
904 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500905 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800906
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 def set_info_callback(self, callback):
908 """
909 Set the info callback
910
911 :param callback: The Python callback to use
912 :return: None
913 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800914 @wraps(callback)
915 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500916 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500917 self._info_callback = _ffi.callback(
918 "void (*)(const SSL *, int, int)", wrapper)
919 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800920
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800921 def get_app_data(self):
922 """
923 Get the application data (supplied via set_app_data())
924
925 :return: The application data
926 """
927 return self._app_data
928
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929 def set_app_data(self, data):
930 """
931 Set the application data (will be returned from get_app_data())
932
933 :param data: Any Python object
934 :return: None
935 """
936 self._app_data = data
937
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800938 def get_cert_store(self):
939 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500940 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800941
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500942 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800943 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500944 store = _lib.SSL_CTX_get_cert_store(self._context)
945 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500946 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800947 return None
948
949 pystore = X509Store.__new__(X509Store)
950 pystore._store = store
951 return pystore
952
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800953 def set_options(self, options):
954 """
955 Add options. Options set before are not cleared!
956
957 :param options: The options to add.
958 :return: The new option bitmask.
959 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500960 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800961 raise TypeError("options must be an integer")
962
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500963 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800964
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800965 def set_mode(self, mode):
966 """
967 Add modes via bitmask. Modes set before are not cleared!
968
969 :param mode: The mode to add.
970 :return: The new mode bitmask.
971 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500972 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800973 raise TypeError("mode must be an integer")
974
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500975 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800976
Cory Benfielde6f35882016-03-29 11:21:04 +0100977 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978 def set_tlsext_servername_callback(self, callback):
979 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400980 Specify a callback function to be called when clients specify a server
981 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800982
983 :param callback: The callback function. It will be invoked with one
984 argument, the Connection instance.
985 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800986 @wraps(callback)
987 def wrapper(ssl, alert, arg):
988 callback(Connection._reverse_mapping[ssl])
989 return 0
990
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 self._tlsext_servername_callback = _ffi.callback(
992 "int (*)(const SSL *, int *, void *)", wrapper)
993 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800994 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800995
Cory Benfield10b277f2015-04-13 17:12:42 -0400996 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +0100997 def set_npn_advertise_callback(self, callback):
998 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +0100999 Specify a callback function that will be called when offering `Next
1000 Protocol Negotiation
1001 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001002
1003 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001004 argument, the Connection instance. It should return a list of
1005 bytestrings representing the advertised protocols, like
1006 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001007 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001008 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1009 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001010 _lib.SSL_CTX_set_next_protos_advertised_cb(
1011 self._context, self._npn_advertise_callback, _ffi.NULL)
1012
Cory Benfield10b277f2015-04-13 17:12:42 -04001013 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001014 def set_npn_select_callback(self, callback):
1015 """
1016 Specify a callback function that will be called when a server offers
1017 Next Protocol Negotiation options.
1018
1019 :param callback: The callback function. It will be invoked with two
1020 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001021 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1022 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001023 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001024 self._npn_select_helper = _NpnSelectHelper(callback)
1025 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001026 _lib.SSL_CTX_set_next_proto_select_cb(
1027 self._context, self._npn_select_callback, _ffi.NULL)
1028
Cory Benfield7907e332015-04-13 17:18:25 -04001029 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001030 def set_alpn_protos(self, protos):
1031 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001032 Specify the clients ALPN protocol list.
1033
1034 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001035
1036 :param protos: A list of the protocols to be offered to the server.
1037 This list should be a Python list of bytestrings representing the
1038 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1039 """
1040 # Take the list of protocols and join them together, prefixing them
1041 # with their lengths.
1042 protostr = b''.join(
1043 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1044 )
1045
1046 # Build a C string from the list. We don't need to save this off
1047 # because OpenSSL immediately copies the data out.
1048 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001049 input_str_len = _ffi.cast("unsigned", len(protostr))
1050 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001051
Cory Benfield7907e332015-04-13 17:18:25 -04001052 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001053 def set_alpn_select_callback(self, callback):
1054 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001055 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001056
1057 :param callback: The callback function. It will be invoked with two
1058 arguments: the Connection, and a list of offered protocols as
1059 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001060 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001061 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001062 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001063 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001064 _lib.SSL_CTX_set_alpn_select_cb(
1065 self._context, self._alpn_select_callback, _ffi.NULL)
1066
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001067ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001068
1069
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001070class Connection(object):
1071 """
1072 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001073 _reverse_mapping = WeakValueDictionary()
1074
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001075 def __init__(self, context, socket=None):
1076 """
1077 Create a new Connection object, using the given OpenSSL.SSL.Context
1078 instance and socket.
1079
1080 :param context: An SSL Context to use for this connection
1081 :param socket: The socket to use for transport layer
1082 """
1083 if not isinstance(context, Context):
1084 raise TypeError("context must be a Context instance")
1085
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001086 ssl = _lib.SSL_new(context._context)
1087 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001088 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001089 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001090
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001091 # References to strings used for Next Protocol Negotiation. OpenSSL's
1092 # header files suggest that these might get copied at some point, but
1093 # doesn't specify when, so we store them here to make sure they don't
1094 # get freed before OpenSSL uses them.
1095 self._npn_advertise_callback_args = None
1096 self._npn_select_callback_args = None
1097
Cory Benfield12eae892014-06-07 15:42:56 +01001098 # References to strings used for Application Layer Protocol
1099 # Negotiation. These strings get copied at some point but it's well
1100 # after the callback returns, so we have to hang them somewhere to
1101 # avoid them getting freed.
1102 self._alpn_select_callback_args = None
1103
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001104 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001105
1106 if socket is None:
1107 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001108 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001110 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001111
Alex Gaynora829e902016-06-04 18:16:01 -07001112 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1113 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001114
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001115 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001116 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001117 self._into_ssl = None
1118 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001119 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001120 set_result = _lib.SSL_set_fd(
1121 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001122 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001123
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001124 def __getattr__(self, name):
1125 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001126 Look up attributes on the wrapped socket object if they are not found
1127 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001128 """
kjav0b66fa12015-09-02 11:51:26 +01001129 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001130 raise AttributeError("'%s' object has no attribute '%s'" % (
1131 self.__class__.__name__, name
1132 ))
kjav0b66fa12015-09-02 11:51:26 +01001133 else:
1134 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001135
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001136 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001137 if self._context._verify_helper is not None:
1138 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001139 if self._context._npn_advertise_helper is not None:
1140 self._context._npn_advertise_helper.raise_if_problem()
1141 if self._context._npn_select_helper is not None:
1142 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001143 if self._context._alpn_select_helper is not None:
1144 self._context._alpn_select_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001145
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001146 error = _lib.SSL_get_error(ssl, result)
1147 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001148 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001150 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001151 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001152 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001153 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001154 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001155 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 elif error == _lib.SSL_ERROR_SYSCALL:
1157 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001158 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001159 if platform == "win32":
1160 errno = _ffi.getwinerror()[0]
1161 else:
1162 errno = _ffi.errno
Glyph3afdba82015-04-14 17:30:53 -04001163 raise SysCallError(errno, errorcode.get(errno))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001164 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001165 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001166 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001167 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001168 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001170 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001171 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001172 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001173
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001174 def get_context(self):
1175 """
1176 Get session context
1177 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001178 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001179
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001180 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001181 """
1182 Switch this connection to a new session context
1183
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001184 :param context: A :py:class:`Context` instance giving the new session
1185 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001186 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001187 if not isinstance(context, Context):
1188 raise TypeError("context must be a Context instance")
1189
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001190 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001191 self._context = context
1192
Cory Benfielde6f35882016-03-29 11:21:04 +01001193 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001194 def get_servername(self):
1195 """
1196 Retrieve the servername extension value if provided in the client hello
1197 message, or None if there wasn't one.
1198
1199 :return: A byte string giving the server name or :py:data:`None`.
1200 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001201 name = _lib.SSL_get_servername(
1202 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1203 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001205 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001206
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001207 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001208
Cory Benfielde6f35882016-03-29 11:21:04 +01001209 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001210 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001211 """
1212 Set the value of the servername extension to send in the client hello.
1213
1214 :param name: A byte string giving the name.
1215 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001216 if not isinstance(name, bytes):
1217 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001218 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001219 raise TypeError("name must not contain NUL byte")
1220
1221 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001222 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001223
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001224 def pending(self):
1225 """
1226 Get the number of bytes that can be safely read from the connection
1227
1228 :return: The number of bytes available in the receive buffer.
1229 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001230 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001231
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001232 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001233 """
1234 Send data on the connection. NOTE: If you get one of the WantRead,
1235 WantWrite or WantX509Lookup exceptions on this, you have to call the
1236 method again with the SAME buffer.
1237
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001238 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001239 :param flags: (optional) Included for compatibility with the socket
1240 API, the value is ignored
1241 :return: The number of bytes written
1242 """
Abraham Martine82326c2015-02-04 10:18:10 +00001243 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001244 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001245
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001246 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001247 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001248 if isinstance(buf, _buffer):
1249 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001250 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001251 raise TypeError("data must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001252
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001253 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001254 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001255 return result
1256 write = send
1257
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001258 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001259 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001260 Send "all" data on the connection. This calls send() repeatedly until
1261 all data is sent. If an error occurs, it's impossible to tell how much
1262 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001263
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001264 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001265 :param flags: (optional) Included for compatibility with the socket
1266 API, the value is ignored
1267 :return: The number of bytes written
1268 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001269 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001270
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001271 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001272 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001273 if isinstance(buf, _buffer):
1274 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001275 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001276 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001277
1278 left_to_send = len(buf)
1279 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001280 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281
1282 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001283 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001284 self._raise_ssl_error(self._ssl, result)
1285 total_sent += result
1286 left_to_send -= result
1287
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001288 def recv(self, bufsiz, flags=None):
1289 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001290 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001291
1292 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001293 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1294 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001295 :return: The string read from the Connection
1296 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001297 buf = _ffi.new("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001298 if flags is not None and flags & socket.MSG_PEEK:
1299 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1300 else:
1301 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001302 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001304 read = recv
1305
Cory Benfield62d10332014-06-15 10:03:41 +01001306 def recv_into(self, buffer, nbytes=None, flags=None):
1307 """
1308 Receive data on the connection and store the data into a buffer rather
1309 than creating a new string.
1310
1311 :param buffer: The buffer to copy into.
1312 :param nbytes: (optional) The maximum number of bytes to read into the
1313 buffer. If not present, defaults to the size of the buffer. If
1314 larger than the size of the buffer, is reduced to the size of the
1315 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001316 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1317 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001318 :return: The number of bytes read into the buffer.
1319 """
1320 if nbytes is None:
1321 nbytes = len(buffer)
1322 else:
1323 nbytes = min(nbytes, len(buffer))
1324
1325 # We need to create a temporary buffer. This is annoying, it would be
1326 # better if we could pass memoryviews straight into the SSL_read call,
1327 # but right now we can't. Revisit this if CFFI gets that ability.
1328 buf = _ffi.new("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001329 if flags is not None and flags & socket.MSG_PEEK:
1330 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1331 else:
1332 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001333 self._raise_ssl_error(self._ssl, result)
1334
1335 # This strange line is all to avoid a memory copy. The buffer protocol
1336 # should allow us to assign a CFFI buffer to the LHS of this line, but
1337 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1338 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1339 # memoryview type.
1340 try:
1341 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1342 except NameError:
1343 buffer[:result] = _ffi.buffer(buf, result)
1344
1345 return result
1346
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001347 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001348 if _lib.BIO_should_retry(bio):
1349 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001350 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001351 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001352 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001353 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001355 # TODO: This is untested. I think io_special means the socket
1356 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001357 raise ValueError("BIO_should_io_special")
1358 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001359 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001360 raise ValueError("unknown bio failure")
1361 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001362 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001363 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001364
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001365 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001366 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367 When using non-socket connections this function reads the "dirty" data
1368 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001369
1370 :param bufsiz: The maximum number of bytes to read
1371 :return: The string read.
1372 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001373 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001374 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001375
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001376 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001377 raise TypeError("bufsiz must be an integer")
1378
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001379 buf = _ffi.new("char[]", bufsiz)
1380 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001381 if result <= 0:
1382 self._handle_bio_errors(self._from_ssl, result)
1383
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001384 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001385
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001386 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001387 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001388 When using non-socket connections this function sends "dirty" data that
1389 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390
1391 :param buf: The string to put into the memory BIO.
1392 :return: The number of bytes written
1393 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001394 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001395
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001396 if self._into_ssl is None:
1397 raise TypeError("Connection sock was not None")
1398
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001399 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001400 if result <= 0:
1401 self._handle_bio_errors(self._into_ssl, result)
1402 return result
1403
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001404 def renegotiate(self):
1405 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001406 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001407
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001408 :return: True if the renegotiation can be started, False otherwise
1409 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001410 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001411 if not self.renegotiate_pending():
1412 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1413 return True
1414 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001415
1416 def do_handshake(self):
1417 """
1418 Perform an SSL handshake (usually called after renegotiate() or one of
1419 set_*_state()). This can raise the same exceptions as send and recv.
1420
1421 :return: None.
1422 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001423 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001424 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001425
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001426 def renegotiate_pending(self):
1427 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001428 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001429 a renegotiation is finished.
1430
1431 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001432 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001433 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001434 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001435
1436 def total_renegotiations(self):
1437 """
1438 Find out the total number of renegotiations.
1439
1440 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001441 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001442 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001443 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001444
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001445 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001446 """
1447 Connect to remote host and set up client-side SSL
1448
1449 :param addr: A remote address
1450 :return: What the socket's connect method returns
1451 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001452 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001453 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001454
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001455 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001456 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001457 Connect to remote host and set up client-side SSL. Note that if the
1458 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001459
1460 :param addr: A remove address
1461 :return: What the socket's connect_ex method returns
1462 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001463 connect_ex = self._socket.connect_ex
1464 self.set_connect_state()
1465 return connect_ex(addr)
1466
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001467 def accept(self):
1468 """
1469 Accept incoming connection and set up SSL on it
1470
1471 :return: A (conn,addr) pair where conn is a Connection and addr is an
1472 address
1473 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001474 client, addr = self._socket.accept()
1475 conn = Connection(self._context, client)
1476 conn.set_accept_state()
1477 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001478
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001479 def bio_shutdown(self):
1480 """
1481 When using non-socket connections this function signals end of
1482 data on the input for this connection.
1483
1484 :return: None
1485 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001486 if self._from_ssl is None:
1487 raise TypeError("Connection sock was not None")
1488
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001489 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001491 def shutdown(self):
1492 """
1493 Send closure alert
1494
1495 :return: True if the shutdown completed successfully (i.e. both sides
1496 have sent closure alerts), false otherwise (i.e. you have to
1497 wait for a ZeroReturnError on a recv() method call
1498 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001499 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001500 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001501 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001502 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001504 else:
1505 return False
1506
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001507 def get_cipher_list(self):
1508 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001509 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001510
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001511 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 """
1513 ciphers = []
1514 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001515 result = _lib.SSL_get_cipher_list(self._ssl, i)
1516 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001517 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001518 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001519 return ciphers
1520
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521 def get_client_ca_list(self):
1522 """
1523 Get CAs whose certificates are suggested for client authentication.
1524
Alex Gaynor62da94d2015-09-05 14:37:34 -04001525 :return: If this is a server connection, a list of X509Names
1526 representing the acceptable CAs as set by
1527 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1528 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1529 connection, the list of such X509Names sent by the server, or an
1530 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001531 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001532 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1533 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001534 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001535 return []
1536
1537 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001538 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1539 name = _lib.sk_X509_NAME_value(ca_names, i)
1540 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001541 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542
1543 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001544 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001545 result.append(pyname)
1546 return result
1547
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001548 def makefile(self):
1549 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001550 The makefile() method is not implemented, since there is no dup
1551 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001552
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001553 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001554 """
Alex Gaynor83284952015-09-05 10:43:30 -04001555 raise NotImplementedError(
1556 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001557
1558 def get_app_data(self):
1559 """
1560 Get application data
1561
1562 :return: The application data
1563 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001564 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001567 """
1568 Set application data
1569
1570 :param data - The application data
1571 :return: None
1572 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 self._app_data = data
1574
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001575 def get_shutdown(self):
1576 """
1577 Get shutdown state
1578
Alex Gaynor62da94d2015-09-05 14:37:34 -04001579 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1580 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001582 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001583
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001584 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585 """
1586 Set shutdown state
1587
1588 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1589 :return: None
1590 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001591 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 raise TypeError("state must be an integer")
1593
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001594 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001595
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001596 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001597 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001598 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001599
1600 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001601 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001602 """
kjavc704a2e2015-09-07 12:12:27 +01001603 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001604
1605 def server_random(self):
1606 """
1607 Get a copy of the server hello nonce.
1608
1609 :return: A string representing the state
1610 """
Alex Gaynor93603062016-06-01 20:13:09 -07001611 session = _lib.SSL_get_session(self._ssl)
1612 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001613 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001614 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1615 assert length > 0
1616 outp = _ffi.new("char[]", length)
1617 _lib.SSL_get_server_random(self._ssl, outp, length)
1618 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001619
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001620 def client_random(self):
1621 """
1622 Get a copy of the client hello nonce.
1623
1624 :return: A string representing the state
1625 """
Alex Gaynor93603062016-06-01 20:13:09 -07001626 session = _lib.SSL_get_session(self._ssl)
1627 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001628 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001629
1630 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1631 assert length > 0
1632 outp = _ffi.new("char[]", length)
1633 _lib.SSL_get_client_random(self._ssl, outp, length)
1634 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001635
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001636 def master_key(self):
1637 """
1638 Get a copy of the master key.
1639
1640 :return: A string representing the state
1641 """
Alex Gaynor93603062016-06-01 20:13:09 -07001642 session = _lib.SSL_get_session(self._ssl)
1643 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001644 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001645
1646 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1647 assert length > 0
1648 outp = _ffi.new("char[]", length)
1649 _lib.SSL_SESSION_get_master_key(session, outp, length)
1650 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001651
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001652 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001653 """
1654 See shutdown(2)
1655
1656 :return: What the socket's shutdown() method returns
1657 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001658 return self._socket.shutdown(*args, **kwargs)
1659
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001660 def get_peer_certificate(self):
1661 """
1662 Retrieve the other side's certificate (if any)
1663
1664 :return: The peer's certificate
1665 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001666 cert = _lib.SSL_get_peer_certificate(self._ssl)
1667 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001668 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001669 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001670 return pycert
1671 return None
1672
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001673 def get_peer_cert_chain(self):
1674 """
1675 Retrieve the other side's certificate (if any)
1676
1677 :return: A list of X509 instances giving the peer's certificate chain,
1678 or None if it does not have one.
1679 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001680 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1681 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001682 return None
1683
1684 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001685 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001686 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001687 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001688 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001690 result.append(pycert)
1691 return result
1692
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001693 def want_read(self):
1694 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001695 Checks if more data has to be read from the transport layer to complete
1696 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697
1698 :return: True iff more data has to be read
1699 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001700 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001701
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001702 def want_write(self):
1703 """
1704 Checks if there is data to write to the transport layer to complete an
1705 operation.
1706
1707 :return: True iff there is data to write
1708 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001710
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711 def set_accept_state(self):
1712 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001713 Set the connection to work in server mode. The handshake will be
1714 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715
1716 :return: None
1717 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001720 def set_connect_state(self):
1721 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001722 Set the connection to work in client mode. The handshake will be
1723 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001724
1725 :return: None
1726 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001727 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001728
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001729 def get_session(self):
1730 """
1731 Returns the Session currently used.
1732
Alex Gaynor62da94d2015-09-05 14:37:34 -04001733 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
1734 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001735 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001736 session = _lib.SSL_get1_session(self._ssl)
1737 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001738 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001739
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001740 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001741 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 return pysession
1743
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001744 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001745 """
1746 Set the session to be used when the TLS/SSL connection is established.
1747
1748 :param session: A Session instance representing the session to use.
1749 :returns: None
1750 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 if not isinstance(session, Session):
1752 raise TypeError("session must be a Session instance")
1753
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001755 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001756 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001757
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001758 def _get_finished_message(self, function):
1759 """
1760 Helper to implement :py:meth:`get_finished` and
1761 :py:meth:`get_peer_finished`.
1762
1763 :param function: Either :py:data:`SSL_get_finished`: or
1764 :py:data:`SSL_get_peer_finished`.
1765
1766 :return: :py:data:`None` if the desired message has not yet been
1767 received, otherwise the contents of the message.
1768 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1769 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04001770 # The OpenSSL documentation says nothing about what might happen if the
1771 # count argument given is zero. Specifically, it doesn't say whether
1772 # the output buffer may be NULL in that case or not. Inspection of the
1773 # implementation reveals that it calls memcpy() unconditionally.
1774 # Section 7.1.4, paragraph 1 of the C standard suggests that
1775 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
1776 # alone desirable) behavior (though it probably does on just about
1777 # every implementation...)
1778 #
1779 # Allocate a tiny buffer to pass in (instead of just passing NULL as
1780 # one might expect) for the initial call so as to be safe against this
1781 # potentially undefined behavior.
1782 empty = _ffi.new("char[]", 0)
1783 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001784 if size == 0:
1785 # No Finished message so far.
1786 return None
1787
1788 buf = _ffi.new("char[]", size)
1789 function(self._ssl, buf, size)
1790 return _ffi.buffer(buf, size)[:]
1791
Fedor Brunner5747b932014-03-05 14:22:34 +01001792 def get_finished(self):
1793 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001794 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001795
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001796 :return: The contents of the message or :py:obj:`None` if the TLS
1797 handshake has not yet completed.
1798 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001799 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001800 return self._get_finished_message(_lib.SSL_get_finished)
1801
Fedor Brunner5747b932014-03-05 14:22:34 +01001802 def get_peer_finished(self):
1803 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001804 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01001805
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001806 :return: The contents of the message or :py:obj:`None` if the TLS
1807 handshake has not yet completed.
1808 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01001809 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04001810 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01001811
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001812 def get_cipher_name(self):
1813 """
1814 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001815
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001816 :returns: The name of the currently used cipher or :py:obj:`None`
1817 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001818 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001819 """
1820 cipher = _lib.SSL_get_current_cipher(self._ssl)
1821 if cipher == _ffi.NULL:
1822 return None
1823 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001824 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
1825 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001826
1827 def get_cipher_bits(self):
1828 """
1829 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001830
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001831 :returns: The number of secret bits of the currently used cipher
1832 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001833 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001834 """
1835 cipher = _lib.SSL_get_current_cipher(self._ssl)
1836 if cipher == _ffi.NULL:
1837 return None
1838 else:
1839 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
1840
1841 def get_cipher_version(self):
1842 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04001843 Obtain the protocol version of the currently used cipher.
1844
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001845 :returns: The protocol name of the currently used cipher
1846 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001847 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001848 """
1849 cipher = _lib.SSL_get_current_cipher(self._ssl)
1850 if cipher == _ffi.NULL:
1851 return None
1852 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04001853 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04001854 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001855
Jim Shaverabff1882015-05-27 09:15:55 -04001856 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04001857 """
1858 Obtain the protocol version of the current connection.
1859
1860 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04001861 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04001862 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04001863 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04001864 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04001865 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04001866 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04001867
Jim Shaver208438c2015-05-28 09:52:38 -04001868 def get_protocol_version(self):
1869 """
1870 Obtain the protocol version of the current connection.
1871
1872 :returns: The TLS version of the current connection, for example
1873 the value for TLS 1 would be 0x769.
1874 :rtype: :py:class:`int`
1875 """
1876 version = _lib.SSL_version(self._ssl)
1877 return version
1878
Cory Benfield10b277f2015-04-13 17:12:42 -04001879 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001880 def get_next_proto_negotiated(self):
1881 """
1882 Get the protocol that was negotiated by NPN.
1883 """
1884 data = _ffi.new("unsigned char **")
1885 data_len = _ffi.new("unsigned int *")
1886
1887 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
1888
Cory Benfieldcd010f62014-05-15 19:00:27 +01001889 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01001890
Cory Benfield7907e332015-04-13 17:18:25 -04001891 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001892 def set_alpn_protos(self, protos):
1893 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001894 Specify the client's ALPN protocol list.
1895
1896 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001897
1898 :param protos: A list of the protocols to be offered to the server.
1899 This list should be a Python list of bytestrings representing the
1900 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1901 """
1902 # Take the list of protocols and join them together, prefixing them
1903 # with their lengths.
1904 protostr = b''.join(
1905 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1906 )
1907
1908 # Build a C string from the list. We don't need to save this off
1909 # because OpenSSL immediately copies the data out.
1910 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04001911 input_str_len = _ffi.cast("unsigned", len(protostr))
1912 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001913
Maximilian Hils66ded6a2015-08-26 06:02:03 +02001914 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001915 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04001916 """
1917 Get the protocol that was negotiated by ALPN.
1918 """
Cory Benfield12eae892014-06-07 15:42:56 +01001919 data = _ffi.new("unsigned char **")
1920 data_len = _ffi.new("unsigned int *")
1921
1922 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
1923
Cory Benfielde8e9c382015-04-11 17:33:48 -04001924 if not data_len:
1925 return b''
1926
Cory Benfield12eae892014-06-07 15:42:56 +01001927 return _ffi.buffer(data[0], data_len[0])[:]
1928
1929
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001930ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001931
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001932# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1933# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001934_lib.SSL_library_init()