blob: 9ac9651390573910e5df3ce0518b9f6406468ed1 [file] [log] [blame]
Paul Kehrer55fb3412017-06-29 18:44:08 -05001import os
Maximilian Hils1d95dea2015-08-17 19:27:20 +02002import socket
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02003from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import wraps, partial
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01005from itertools import count, chain
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08006from weakref import WeakValueDictionary
7from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08008
Alex Gaynor10d30832017-06-29 15:31:39 -07009from cryptography.utils import deprecated
10
Alex Gaynor336d8022017-06-29 21:46:42 -070011from six import (
12 binary_type as _binary_type, integer_types as integer_types, int2byte,
13 indexbytes)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -050014
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
Hynek Schlawackaa861212016-03-13 13:53:48 +010016 UNSPECIFIED as _UNSPECIFIED,
17 exception_from_error_queue as _exception_from_error_queue,
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050018 ffi as _ffi,
19 lib as _lib,
Hynek Schlawackf90e3682016-03-11 11:21:13 +010020 make_assert as _make_assert,
Hynek Schlawackaa861212016-03-13 13:53:48 +010021 native as _native,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040022 path_string as _path_string,
Hynek Schlawackaa861212016-03-13 13:53:48 +010023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Cory Benfielde62840e2016-11-28 12:17:08 +000024 no_zero_allocator as _no_zero_allocator,
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -040025)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080026
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080027from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080029
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050030try:
31 _memoryview = memoryview
32except NameError:
33 class _memoryview(object):
34 pass
35
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +020036try:
37 _buffer = buffer
38except NameError:
39 class _buffer(object):
40 pass
41
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050042OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
43SSLEAY_VERSION = _lib.SSLEAY_VERSION
44SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
45SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
46SSLEAY_DIR = _lib.SSLEAY_DIR
47SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080048
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050049SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
50RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080051
52SSLv2_METHOD = 1
53SSLv3_METHOD = 2
54SSLv23_METHOD = 3
55TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050056TLSv1_1_METHOD = 5
57TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080058
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050059OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
60OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
61OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Alex Gaynor336d8022017-06-29 21:46:42 -070062OP_NO_TLSv1_1 = _lib.SSL_OP_NO_TLSv1_1
63OP_NO_TLSv1_2 = _lib.SSL_OP_NO_TLSv1_2
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080064
Alex Gaynorbf012872016-06-04 13:18:39 -070065MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090068OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050069OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
70OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
71OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040072OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
73 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
74)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050075OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
76OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040077OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050078OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
79OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
80OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
81OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
82OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
83OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
84OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
85OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
86OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040087OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
88 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
89)
Alex Gaynorbf012872016-06-04 13:18:39 -070090OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080091
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050092OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
93OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040094OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080095
Alex Gaynorc4889812015-09-04 08:43:17 -040096OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050098VERIFY_PEER = _lib.SSL_VERIFY_PEER
99VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
100VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
101VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500103SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
104SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
105SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
106SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
107SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
108SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
109SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
110SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500112SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
113SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
114SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400115if _lib.Cryptography_HAS_SSL_ST:
116 SSL_ST_INIT = _lib.SSL_ST_INIT
117 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
118 SSL_ST_OK = _lib.SSL_ST_OK
119 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500121SSL_CB_LOOP = _lib.SSL_CB_LOOP
122SSL_CB_EXIT = _lib.SSL_CB_EXIT
123SSL_CB_READ = _lib.SSL_CB_READ
124SSL_CB_WRITE = _lib.SSL_CB_WRITE
125SSL_CB_ALERT = _lib.SSL_CB_ALERT
126SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
127SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
128SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
129SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
130SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
131SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
132SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
133SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800134
Paul Kehrer55fb3412017-06-29 18:44:08 -0500135# Taken from https://golang.org/src/crypto/x509/root_linux.go
136_CERTIFICATE_FILE_LOCATIONS = [
137 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
138 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
139 "/etc/ssl/ca-bundle.pem", # OpenSUSE
140 "/etc/pki/tls/cacert.pem", # OpenELEC
141 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
142]
143
144_CERTIFICATE_PATH_LOCATIONS = [
145 "/etc/ssl/certs", # SLES10/SLES11
146]
147
148_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = "/opt/pyca/cryptography/openssl/certs"
149_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = "/opt/pyca/cryptography/openssl/cert.pem"
150
Alex Gaynor83284952015-09-05 10:43:30 -0400151
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500152class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500153 """
154 An error occurred in an `OpenSSL.SSL` API.
155 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500156
157
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500158_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100159_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500160
161
162class WantReadError(Error):
163 pass
164
165
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500166class WantWriteError(Error):
167 pass
168
169
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500170class WantX509LookupError(Error):
171 pass
172
173
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500174class ZeroReturnError(Error):
175 pass
176
177
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500178class SysCallError(Error):
179 pass
180
181
Cory Benfield0ea76e72015-03-22 09:05:28 +0000182class _CallbackExceptionHelper(object):
183 """
184 A base class for wrapper classes that allow for intelligent exception
185 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500186
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400187 :ivar list _problems: Any exceptions that occurred while executing in a
188 context where they could not be raised in the normal way. Typically
189 this is because OpenSSL has called into some Python code and requires a
190 return value. The exceptions are saved to be raised later when it is
191 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000192 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400193
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400194 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800195 self._problems = []
196
Cory Benfield0ea76e72015-03-22 09:05:28 +0000197 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400198 """
199 Raise an exception from the OpenSSL error queue or that was previously
200 captured whe running a callback.
201 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000202 if self._problems:
203 try:
204 _raise_current_error()
205 except Error:
206 pass
207 raise self._problems.pop(0)
208
209
210class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400211 """
212 Wrap a callback such that it can be used as a certificate verification
213 callback.
214 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400215
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800216 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400217 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800218
219 @wraps(callback)
220 def wrapper(ok, store_ctx):
221 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500222 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
223 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
224 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800225
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400226 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
227 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
228 connection = Connection._reverse_mapping[ssl]
229
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800230 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400231 result = callback(
232 connection, cert, error_number, error_depth, ok
233 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800234 except Exception as e:
235 self._problems.append(e)
236 return 0
237 else:
238 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500239 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800240 return 1
241 else:
242 return 0
243
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500244 self.callback = _ffi.callback(
245 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800246
247
Cory Benfield0ea76e72015-03-22 09:05:28 +0000248class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400249 """
250 Wrap a callback such that it can be used as an NPN advertisement callback.
251 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400252
Cory Benfield0ea76e72015-03-22 09:05:28 +0000253 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400254 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800255
Cory Benfield0ea76e72015-03-22 09:05:28 +0000256 @wraps(callback)
257 def wrapper(ssl, out, outlen, arg):
258 try:
259 conn = Connection._reverse_mapping[ssl]
260 protos = callback(conn)
261
262 # Join the protocols into a Python bytestring, length-prefixing
263 # each element.
264 protostr = b''.join(
265 chain.from_iterable((int2byte(len(p)), p) for p in protos)
266 )
267
268 # Save our callback arguments on the connection object. This is
269 # done to make sure that they don't get freed before OpenSSL
270 # uses them. Then, return them appropriately in the output
271 # parameters.
272 conn._npn_advertise_callback_args = [
273 _ffi.new("unsigned int *", len(protostr)),
274 _ffi.new("unsigned char[]", protostr),
275 ]
276 outlen[0] = conn._npn_advertise_callback_args[0][0]
277 out[0] = conn._npn_advertise_callback_args[1]
278 return 0
279 except Exception as e:
280 self._problems.append(e)
281 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
282
283 self.callback = _ffi.callback(
284 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
285 wrapper
286 )
287
288
289class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400290 """
291 Wrap a callback such that it can be used as an NPN selection callback.
292 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400293
Cory Benfield0ea76e72015-03-22 09:05:28 +0000294 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400295 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000296
297 @wraps(callback)
298 def wrapper(ssl, out, outlen, in_, inlen, arg):
299 try:
300 conn = Connection._reverse_mapping[ssl]
301
302 # The string passed to us is actually made up of multiple
303 # length-prefixed bytestrings. We need to split that into a
304 # list.
305 instr = _ffi.buffer(in_, inlen)[:]
306 protolist = []
307 while instr:
308 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400309 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000310 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400311 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000312
313 # Call the callback
314 outstr = callback(conn, protolist)
315
316 # Save our callback arguments on the connection object. This is
317 # done to make sure that they don't get freed before OpenSSL
318 # uses them. Then, return them appropriately in the output
319 # parameters.
320 conn._npn_select_callback_args = [
321 _ffi.new("unsigned char *", len(outstr)),
322 _ffi.new("unsigned char[]", outstr),
323 ]
324 outlen[0] = conn._npn_select_callback_args[0][0]
325 out[0] = conn._npn_select_callback_args[1]
326 return 0
327 except Exception as e:
328 self._problems.append(e)
329 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
330
331 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400332 ("int (*)(SSL *, unsigned char **, unsigned char *, "
333 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000334 wrapper
335 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800336
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800337
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400338class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400339 """
340 Wrap a callback such that it can be used as an ALPN selection callback.
341 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400342
Cory Benfieldf1177e72015-04-12 09:11:49 -0400343 def __init__(self, callback):
344 _CallbackExceptionHelper.__init__(self)
345
346 @wraps(callback)
347 def wrapper(ssl, out, outlen, in_, inlen, arg):
348 try:
349 conn = Connection._reverse_mapping[ssl]
350
351 # The string passed to us is made up of multiple
352 # length-prefixed bytestrings. We need to split that into a
353 # list.
354 instr = _ffi.buffer(in_, inlen)[:]
355 protolist = []
356 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400357 encoded_len = indexbytes(instr, 0)
358 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400359 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400360 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400361
362 # Call the callback
363 outstr = callback(conn, protolist)
364
365 if not isinstance(outstr, _binary_type):
366 raise TypeError("ALPN callback must return a bytestring.")
367
368 # Save our callback arguments on the connection object to make
369 # sure that they don't get freed before OpenSSL can use them.
370 # Then, return them in the appropriate output parameters.
371 conn._alpn_select_callback_args = [
372 _ffi.new("unsigned char *", len(outstr)),
373 _ffi.new("unsigned char[]", outstr),
374 ]
375 outlen[0] = conn._alpn_select_callback_args[0][0]
376 out[0] = conn._alpn_select_callback_args[1]
377 return 0
378 except Exception as e:
379 self._problems.append(e)
380 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
381
382 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400383 ("int (*)(SSL *, unsigned char **, unsigned char *, "
384 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400385 wrapper
386 )
387
388
Cory Benfield496652a2017-01-24 11:42:56 +0000389class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
390 """
391 Wrap a callback such that it can be used as an OCSP callback for the server
392 side.
393
394 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
395 ways. For servers, that callback is expected to retrieve some OCSP data and
396 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
397 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
398 is expected to check the OCSP data, and returns a negative value on error,
399 0 if the response is not acceptable, or positive if it is. These are
400 mutually exclusive return code behaviours, and they mean that we need two
401 helpers so that we always return an appropriate error code if the user's
402 code throws an exception.
403
404 Given that we have to have two helpers anyway, these helpers are a bit more
405 helpery than most: specifically, they hide a few more of the OpenSSL
406 functions so that the user has an easier time writing these callbacks.
407
408 This helper implements the server side.
409 """
410
411 def __init__(self, callback):
412 _CallbackExceptionHelper.__init__(self)
413
414 @wraps(callback)
415 def wrapper(ssl, cdata):
416 try:
417 conn = Connection._reverse_mapping[ssl]
418
419 # Extract the data if any was provided.
420 if cdata != _ffi.NULL:
421 data = _ffi.from_handle(cdata)
422 else:
423 data = None
424
425 # Call the callback.
426 ocsp_data = callback(conn, data)
427
428 if not isinstance(ocsp_data, _binary_type):
429 raise TypeError("OCSP callback must return a bytestring.")
430
431 # If the OCSP data was provided, we will pass it to OpenSSL.
432 # However, we have an early exit here: if no OCSP data was
433 # provided we will just exit out and tell OpenSSL that there
434 # is nothing to do.
435 if not ocsp_data:
436 return 3 # SSL_TLSEXT_ERR_NOACK
437
438 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
439 # private copy of this data, so we need to keep it alive, but
440 # it *does* want to free it itself if it gets replaced. This
441 # somewhat bonkers behaviour means we need to use
442 # OPENSSL_malloc directly, which is a pain in the butt to work
443 # with. It's ok for us to "leak" the memory here because
444 # OpenSSL now owns it and will free it.
445 ocsp_data_length = len(ocsp_data)
446 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
447 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
448
449 _lib.SSL_set_tlsext_status_ocsp_resp(
450 ssl, data_ptr, ocsp_data_length
451 )
452
453 return 0
454 except Exception as e:
455 self._problems.append(e)
456 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
457
458 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
459
460
461class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
462 """
463 Wrap a callback such that it can be used as an OCSP callback for the client
464 side.
465
466 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
467 ways. For servers, that callback is expected to retrieve some OCSP data and
468 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
469 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
470 is expected to check the OCSP data, and returns a negative value on error,
471 0 if the response is not acceptable, or positive if it is. These are
472 mutually exclusive return code behaviours, and they mean that we need two
473 helpers so that we always return an appropriate error code if the user's
474 code throws an exception.
475
476 Given that we have to have two helpers anyway, these helpers are a bit more
477 helpery than most: specifically, they hide a few more of the OpenSSL
478 functions so that the user has an easier time writing these callbacks.
479
480 This helper implements the client side.
481 """
482
483 def __init__(self, callback):
484 _CallbackExceptionHelper.__init__(self)
485
486 @wraps(callback)
487 def wrapper(ssl, cdata):
488 try:
489 conn = Connection._reverse_mapping[ssl]
490
491 # Extract the data if any was provided.
492 if cdata != _ffi.NULL:
493 data = _ffi.from_handle(cdata)
494 else:
495 data = None
496
497 # Get the OCSP data.
498 ocsp_ptr = _ffi.new("unsigned char **")
499 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
500 if ocsp_len < 0:
501 # No OCSP data.
502 ocsp_data = b''
503 else:
504 # Copy the OCSP data, then pass it to the callback.
505 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
506
507 valid = callback(conn, ocsp_data, data)
508
509 # Return 1 on success or 0 on error.
510 return int(bool(valid))
511
512 except Exception as e:
513 self._problems.append(e)
514 # Return negative value if an exception is hit.
515 return -1
516
517 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
518
519
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800520def _asFileDescriptor(obj):
521 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800522 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800523 meth = getattr(obj, "fileno", None)
524 if meth is not None:
525 obj = meth()
526
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800527 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800528 fd = obj
529
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800530 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800531 raise TypeError("argument must be an int, or have a fileno() method.")
532 elif fd < 0:
533 raise ValueError(
534 "file descriptor cannot be a negative integer (%i)" % (fd,))
535
536 return fd
537
538
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800539def SSLeay_version(type):
540 """
541 Return a string describing the version of OpenSSL in use.
542
543 :param type: One of the SSLEAY_ constants defined in this module.
544 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500545 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800546
547
Cory Benfieldef404df2016-03-29 15:32:48 +0100548def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400549 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100550 Builds a decorator that ensures that functions that rely on OpenSSL
551 functions that are not present in this build raise NotImplementedError,
552 rather than AttributeError coming out of cryptography.
553
554 :param flag: A cryptography flag that guards the functions, e.g.
555 ``Cryptography_HAS_NEXTPROTONEG``.
556 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400557 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100558 def _requires_decorator(func):
559 if not flag:
560 @wraps(func)
561 def explode(*args, **kwargs):
562 raise NotImplementedError(error)
563 return explode
564 else:
565 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400566
Cory Benfieldef404df2016-03-29 15:32:48 +0100567 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400568
569
Cory Benfieldef404df2016-03-29 15:32:48 +0100570_requires_npn = _make_requires(
571 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
572)
Cory Benfield7907e332015-04-13 17:18:25 -0400573
574
Cory Benfieldef404df2016-03-29 15:32:48 +0100575_requires_alpn = _make_requires(
576 _lib.Cryptography_HAS_ALPN, "ALPN not available"
577)
Cory Benfielde6f35882016-03-29 11:21:04 +0100578
Cory Benfielde6f35882016-03-29 11:21:04 +0100579
Cory Benfieldef404df2016-03-29 15:32:48 +0100580_requires_sni = _make_requires(
581 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
582)
Cory Benfielde6f35882016-03-29 11:21:04 +0100583
584
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800585class Session(object):
586 pass
587
588
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800589class Context(object):
590 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100591 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400592 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800593 """
594 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800595 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500596 SSLv3_METHOD: "SSLv3_method",
597 SSLv23_METHOD: "SSLv23_method",
598 TLSv1_METHOD: "TLSv1_method",
599 TLSv1_1_METHOD: "TLSv1_1_method",
600 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400601 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500602 _methods = dict(
603 (identifier, getattr(_lib, name))
604 for (identifier, name) in _methods.items()
605 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800606
607 def __init__(self, method):
608 """
609 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
610 TLSv1_METHOD.
611 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500612 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800613 raise TypeError("method must be an integer")
614
615 try:
616 method_func = self._methods[method]
617 except KeyError:
618 raise ValueError("No such protocol")
619
620 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700621 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800622
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500623 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700624 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500625 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800626
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600627 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
628 # will be auto-selected. This function was added in 1.0.2 and made a
629 # noop in 1.1.0+ (where it is set automatically).
630 try:
631 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
632 _openssl_assert(res == 1)
633 except AttributeError:
634 pass
635
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800636 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800637 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800638 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800639 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800640 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800641 self._verify_callback = None
642 self._info_callback = None
643 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800644 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000645 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100646 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000647 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100648 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400649 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100650 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000651 self._ocsp_helper = None
652 self._ocsp_callback = None
653 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800654
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500655 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800656
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800657 def load_verify_locations(self, cafile, capath=None):
658 """
659 Let SSL know where we can find trusted certificates for the certificate
660 chain
661
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400662 :param cafile: In which file we can find the certificates (``bytes`` or
663 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800664 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400665 (``bytes`` or ``unicode``).
666
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 :return: None
668 """
669 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500670 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400671 else:
672 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800673
674 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500675 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400676 else:
677 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800678
Alex Gaynor62da94d2015-09-05 14:37:34 -0400679 load_result = _lib.SSL_CTX_load_verify_locations(
680 self._context, cafile, capath
681 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500683 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800684
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800685 def _wrap_callback(self, callback):
686 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800687 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800688 return callback(size, verify, self._passphrase_userdata)
689 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800690 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800692 def set_passwd_cb(self, callback, userdata=None):
693 """
694 Set the passphrase callback
695
696 :param callback: The Python callback to use
697 :param userdata: (optional) A Python object which will be given as
698 argument to the callback
699 :return: None
700 """
701 if not callable(callback):
702 raise TypeError("callback must be callable")
703
704 self._passphrase_helper = self._wrap_callback(callback)
705 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500706 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800707 self._context, self._passphrase_callback)
708 self._passphrase_userdata = userdata
709
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800710 def set_default_verify_paths(self):
711 """
712 Use the platform-specific CA certificate locations
713
714 :return: None
715 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500716 # SSL_CTX_set_default_verify_paths will attempt to load certs from
717 # both a cafile and capath that are set at compile time. However,
718 # it will first check environment variables and, if present, load
719 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500720 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400721 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500722 # After attempting to set default_verify_paths we need to know whether
723 # to go down the fallback path.
724 # First we'll check to see if any env vars have been set. If so,
725 # we won't try to do anything else because the user has set the path
726 # themselves.
727 dir_env_var = _ffi.string(
728 _lib.X509_get_default_cert_dir_env()
729 ).decode("ascii")
730 file_env_var = _ffi.string(
731 _lib.X509_get_default_cert_file_env()
732 ).decode("ascii")
733 if not self._check_env_vars_set(dir_env_var, file_env_var):
734 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
735 default_file = _ffi.string(_lib.X509_get_default_cert_file())
736 # Now we check to see if the default_dir and default_file are set
737 # to the exact values we use in our manylinux1 builds. If they are
738 # then we know to load the fallbacks
739 if (
740 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
741 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
742 ):
743 # This is manylinux1, let's load our fallback paths
744 self._fallback_default_verify_paths(
745 _CERTIFICATE_FILE_LOCATIONS,
746 _CERTIFICATE_PATH_LOCATIONS
747 )
748
749 def _check_env_vars_set(self, dir_env_var, file_env_var):
750 """
751 Check to see if the default cert dir/file environment vars are present.
752
753 :return: bool
754 """
755 return (
756 os.environ.get(file_env_var) is not None or
757 os.environ.get(dir_env_var) is not None
758 )
759
760 def _fallback_default_verify_paths(self, file_path, dir_path):
761 """
762 Default verify paths are based on the compiled version of OpenSSL.
763 However, when pyca/cryptography is compiled as a manylinux1 wheel
764 that compiled location can potentially be wrong. So, like Go, we
765 will try a predefined set of paths and attempt to load roots
766 from there.
767
768 :return: None
769 """
770 for cafile in file_path:
771 if os.path.isfile(cafile):
772 self.load_verify_locations(cafile)
773 break
774
775 for capath in dir_path:
776 if os.path.isdir(capath):
777 self.load_verify_locations(None, capath)
778 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800779
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780 def use_certificate_chain_file(self, certfile):
781 """
782 Load a certificate chain from a file
783
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400784 :param certfile: The name of the certificate chain file (``bytes`` or
785 ``unicode``).
786
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800787 :return: None
788 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400789 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800790
Alex Gaynor62da94d2015-09-05 14:37:34 -0400791 result = _lib.SSL_CTX_use_certificate_chain_file(
792 self._context, certfile
793 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800794 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500795 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800796
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800797 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800798 """
799 Load a certificate from a file
800
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400801 :param certfile: The name of the certificate file (``bytes`` or
802 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800803 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400804
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800805 :return: None
806 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400807 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500808 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800809 raise TypeError("filetype must be an integer")
810
Alex Gaynor62da94d2015-09-05 14:37:34 -0400811 use_result = _lib.SSL_CTX_use_certificate_file(
812 self._context, certfile, filetype
813 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800814 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500815 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800816
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800817 def use_certificate(self, cert):
818 """
819 Load a certificate from a X509 object
820
821 :param cert: The X509 object
822 :return: None
823 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800824 if not isinstance(cert, X509):
825 raise TypeError("cert must be an X509 instance")
826
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500827 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800828 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500829 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800830
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800831 def add_extra_chain_cert(self, certobj):
832 """
833 Add certificate to chain
834
835 :param certobj: The X509 certificate object to add to the chain
836 :return: None
837 """
838 if not isinstance(certobj, X509):
839 raise TypeError("certobj must be an X509 instance")
840
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500841 copy = _lib.X509_dup(certobj._x509)
842 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800843 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500844 # TODO: This is untested.
845 _lib.X509_free(copy)
846 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800847
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800848 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500849 if self._passphrase_helper is not None:
850 self._passphrase_helper.raise_if_problem(Error)
851
852 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800853
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400854 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800855 """
856 Load a private key from a file
857
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400858 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800859 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400860
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800861 :return: None
862 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400863 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800864
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400865 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800866 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500867 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868 raise TypeError("filetype must be an integer")
869
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500870 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800871 self._context, keyfile, filetype)
872 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800873 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800874
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800875 def use_privatekey(self, pkey):
876 """
877 Load a private key from a PKey object
878
879 :param pkey: The PKey object
880 :return: None
881 """
882 if not isinstance(pkey, PKey):
883 raise TypeError("pkey must be a PKey instance")
884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500885 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800886 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800887 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800888
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800889 def check_privatekey(self):
890 """
891 Check that the private key and certificate match up
892
893 :return: None (raises an exception if something's wrong)
894 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500895 if not _lib.SSL_CTX_check_private_key(self._context):
896 _raise_current_error()
897
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 def load_client_ca(self, cafile):
899 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100900 Load the trusted certificates that will be sent to the client. Does
901 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400902 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800903
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100904 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905 :return: None
906 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100907 ca_list = _lib.SSL_load_client_CA_file(
908 _text_to_bytes_and_warn("cafile", cafile)
909 )
910 _openssl_assert(ca_list != _ffi.NULL)
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100911 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800912
913 def set_session_id(self, buf):
914 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100915 Set the session id to *buf* within which a session can be reused for
916 this Context object. This is needed when doing session resumption,
917 because there is no way for a stored session to know which Context
918 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800919
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100920 :param bytes buf: The session id.
921
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800922 :returns: None
923 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100924 buf = _text_to_bytes_and_warn("buf", buf)
925 _openssl_assert(
926 _lib.SSL_CTX_set_session_id_context(
927 self._context,
928 buf,
929 len(buf),
930 ) == 1
931 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800932
933 def set_session_cache_mode(self, mode):
934 """
935 Enable/disable session caching and specify the mode used.
936
937 :param mode: One or more of the SESS_CACHE_* flags (combine using
938 bitwise or)
939 :returns: The previously set caching mode.
940 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500941 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942 raise TypeError("mode must be an integer")
943
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500944 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800945
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800946 def get_session_cache_mode(self):
947 """
948 :returns: The currently used cache mode.
949 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500950 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952 def set_verify(self, mode, callback):
953 """
954 Set the verify mode and verify callback
955
956 :param mode: The verify mode, this is either VERIFY_NONE or
957 VERIFY_PEER combined with possible other flags
958 :param callback: The Python callback to use
959 :return: None
960
961 See SSL_CTX_set_verify(3SSL) for further details.
962 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500963 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800964 raise TypeError("mode must be an integer")
965
966 if not callable(callback):
967 raise TypeError("callback must be callable")
968
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400969 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800970 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500971 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800972
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800973 def set_verify_depth(self, depth):
974 """
975 Set the verify depth
976
977 :param depth: An integer specifying the verify depth
978 :return: None
979 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500980 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800981 raise TypeError("depth must be an integer")
982
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500983 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800984
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800985 def get_verify_mode(self):
986 """
987 Get the verify mode
988
989 :return: The verify mode
990 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800992
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800993 def get_verify_depth(self):
994 """
995 Get the verify depth
996
997 :return: The verify depth
998 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500999 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001000
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001001 def load_tmp_dh(self, dhfile):
1002 """
1003 Load parameters for Ephemeral Diffie-Hellman
1004
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001005 :param dhfile: The file to load EDH parameters from (``bytes`` or
1006 ``unicode``).
1007
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001008 :return: None
1009 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001010 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001011
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001012 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001013 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001014 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001015 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001016
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001017 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1018 dh = _ffi.gc(dh, _lib.DH_free)
1019 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001020
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001021 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001022 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001023 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001024
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001025 :param curve: A curve object to use as returned by either
1026 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
1027 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001028
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001029 :return: None
1030 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001031 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001032
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001033 def set_cipher_list(self, cipher_list):
1034 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001035 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001036
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001037 See the OpenSSL manual for more information (e.g.
1038 :manpage:`ciphers(1)`).
1039
1040 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041 :return: None
1042 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001043 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001044
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001045 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001046 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001047
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001048 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001049 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001050 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001051
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001052 def set_client_ca_list(self, certificate_authorities):
1053 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001054 Set the list of preferred client certificate signers for this server
1055 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001056
Alex Gaynor62da94d2015-09-05 14:37:34 -04001057 This list of certificate authorities will be sent to the client when
1058 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001059
1060 :param certificate_authorities: a sequence of X509Names.
1061 :return: None
1062 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001063 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001064 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001065
1066 try:
1067 for ca_name in certificate_authorities:
1068 if not isinstance(ca_name, X509Name):
1069 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001070 "client CAs must be X509Name objects, not %s "
1071 "objects" % (
1072 type(ca_name).__name__,
1073 )
1074 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001075 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001076 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001078 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001079 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001080 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001081 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001083 raise
1084
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001086
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001087 def add_client_ca(self, certificate_authority):
1088 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001089 Add the CA certificate to the list of preferred signers for this
1090 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001091
1092 The list of certificate authorities will be sent to the client when the
1093 server requests a client certificate.
1094
1095 :param certificate_authority: certificate authority's X509 certificate.
1096 :return: None
1097 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001098 if not isinstance(certificate_authority, X509):
1099 raise TypeError("certificate_authority must be an X509 instance")
1100
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001101 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001102 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001103 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001104
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001105 def set_timeout(self, timeout):
1106 """
1107 Set session timeout
1108
1109 :param timeout: The timeout in seconds
1110 :return: The previous session timeout
1111 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001112 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001113 raise TypeError("timeout must be an integer")
1114
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001115 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001116
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001117 def get_timeout(self):
1118 """
1119 Get the session timeout
1120
1121 :return: The session timeout
1122 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001123 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001124
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001125 def set_info_callback(self, callback):
1126 """
1127 Set the info callback
1128
1129 :param callback: The Python callback to use
1130 :return: None
1131 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001132 @wraps(callback)
1133 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001134 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001135 self._info_callback = _ffi.callback(
1136 "void (*)(const SSL *, int, int)", wrapper)
1137 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001139 def get_app_data(self):
1140 """
1141 Get the application data (supplied via set_app_data())
1142
1143 :return: The application data
1144 """
1145 return self._app_data
1146
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001147 def set_app_data(self, data):
1148 """
1149 Set the application data (will be returned from get_app_data())
1150
1151 :param data: Any Python object
1152 :return: None
1153 """
1154 self._app_data = data
1155
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001156 def get_cert_store(self):
1157 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001158 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001159
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001160 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 store = _lib.SSL_CTX_get_cert_store(self._context)
1163 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001164 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001165 return None
1166
1167 pystore = X509Store.__new__(X509Store)
1168 pystore._store = store
1169 return pystore
1170
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001171 def set_options(self, options):
1172 """
1173 Add options. Options set before are not cleared!
1174
1175 :param options: The options to add.
1176 :return: The new option bitmask.
1177 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001178 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001179 raise TypeError("options must be an integer")
1180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001182
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001183 def set_mode(self, mode):
1184 """
1185 Add modes via bitmask. Modes set before are not cleared!
1186
1187 :param mode: The mode to add.
1188 :return: The new mode bitmask.
1189 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001190 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001191 raise TypeError("mode must be an integer")
1192
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001193 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001194
Cory Benfielde6f35882016-03-29 11:21:04 +01001195 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001196 def set_tlsext_servername_callback(self, callback):
1197 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001198 Specify a callback function to be called when clients specify a server
1199 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001200
1201 :param callback: The callback function. It will be invoked with one
1202 argument, the Connection instance.
1203 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001204 @wraps(callback)
1205 def wrapper(ssl, alert, arg):
1206 callback(Connection._reverse_mapping[ssl])
1207 return 0
1208
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001209 self._tlsext_servername_callback = _ffi.callback(
1210 "int (*)(const SSL *, int *, void *)", wrapper)
1211 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001212 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001213
Cory Benfield10b277f2015-04-13 17:12:42 -04001214 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001215 def set_npn_advertise_callback(self, callback):
1216 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001217 Specify a callback function that will be called when offering `Next
1218 Protocol Negotiation
1219 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001220
1221 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001222 argument, the Connection instance. It should return a list of
1223 bytestrings representing the advertised protocols, like
1224 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001225 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001226 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1227 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001228 _lib.SSL_CTX_set_next_protos_advertised_cb(
1229 self._context, self._npn_advertise_callback, _ffi.NULL)
1230
Cory Benfield10b277f2015-04-13 17:12:42 -04001231 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001232 def set_npn_select_callback(self, callback):
1233 """
1234 Specify a callback function that will be called when a server offers
1235 Next Protocol Negotiation options.
1236
1237 :param callback: The callback function. It will be invoked with two
1238 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001239 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1240 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001241 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001242 self._npn_select_helper = _NpnSelectHelper(callback)
1243 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001244 _lib.SSL_CTX_set_next_proto_select_cb(
1245 self._context, self._npn_select_callback, _ffi.NULL)
1246
Cory Benfield7907e332015-04-13 17:18:25 -04001247 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001248 def set_alpn_protos(self, protos):
1249 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001250 Specify the clients ALPN protocol list.
1251
1252 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001253
1254 :param protos: A list of the protocols to be offered to the server.
1255 This list should be a Python list of bytestrings representing the
1256 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1257 """
1258 # Take the list of protocols and join them together, prefixing them
1259 # with their lengths.
1260 protostr = b''.join(
1261 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1262 )
1263
1264 # Build a C string from the list. We don't need to save this off
1265 # because OpenSSL immediately copies the data out.
1266 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07001267 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01001268
Cory Benfield7907e332015-04-13 17:18:25 -04001269 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001270 def set_alpn_select_callback(self, callback):
1271 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001272 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001273
1274 :param callback: The callback function. It will be invoked with two
1275 arguments: the Connection, and a list of offered protocols as
1276 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001277 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001278 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001279 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001280 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001281 _lib.SSL_CTX_set_alpn_select_cb(
1282 self._context, self._alpn_select_callback, _ffi.NULL)
1283
Cory Benfield496652a2017-01-24 11:42:56 +00001284 def _set_ocsp_callback(self, helper, data):
1285 """
1286 This internal helper does the common work for
1287 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1288 almost all of it.
1289 """
1290 self._ocsp_helper = helper
1291 self._ocsp_callback = helper.callback
1292 if data is None:
1293 self._ocsp_data = _ffi.NULL
1294 else:
1295 self._ocsp_data = _ffi.new_handle(data)
1296
1297 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1298 self._context, self._ocsp_callback
1299 )
1300 _openssl_assert(rc == 1)
1301 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1302 _openssl_assert(rc == 1)
1303
1304 def set_ocsp_server_callback(self, callback, data=None):
1305 """
1306 Set a callback to provide OCSP data to be stapled to the TLS handshake
1307 on the server side.
1308
1309 :param callback: The callback function. It will be invoked with two
1310 arguments: the Connection, and the optional arbitrary data you have
1311 provided. The callback must return a bytestring that contains the
1312 OCSP data to staple to the handshake. If no OCSP data is available
1313 for this connection, return the empty bytestring.
1314 :param data: Some opaque data that will be passed into the callback
1315 function when called. This can be used to avoid needing to do
1316 complex data lookups or to keep track of what context is being
1317 used. This parameter is optional.
1318 """
1319 helper = _OCSPServerCallbackHelper(callback)
1320 self._set_ocsp_callback(helper, data)
1321
1322 def set_ocsp_client_callback(self, callback, data=None):
1323 """
1324 Set a callback to validate OCSP data stapled to the TLS handshake on
1325 the client side.
1326
1327 :param callback: The callback function. It will be invoked with three
1328 arguments: the Connection, a bytestring containing the stapled OCSP
1329 assertion, and the optional arbitrary data you have provided. The
1330 callback must return a boolean that indicates the result of
1331 validating the OCSP data: ``True`` if the OCSP data is valid and
1332 the certificate can be trusted, or ``False`` if either the OCSP
1333 data is invalid or the certificate has been revoked.
1334 :param data: Some opaque data that will be passed into the callback
1335 function when called. This can be used to avoid needing to do
1336 complex data lookups or to keep track of what context is being
1337 used. This parameter is optional.
1338 """
1339 helper = _OCSPClientCallbackHelper(callback)
1340 self._set_ocsp_callback(helper, data)
1341
Alex Chanc6077062016-11-18 13:53:39 +00001342
Alex Gaynor10d30832017-06-29 15:31:39 -07001343ContextType = deprecated(
1344 Context, __name__,
1345 "ContextType has been deprecated, use Context instead", DeprecationWarning
1346)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001347
1348
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001349class Connection(object):
1350 """
1351 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001352 _reverse_mapping = WeakValueDictionary()
1353
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001354 def __init__(self, context, socket=None):
1355 """
1356 Create a new Connection object, using the given OpenSSL.SSL.Context
1357 instance and socket.
1358
1359 :param context: An SSL Context to use for this connection
1360 :param socket: The socket to use for transport layer
1361 """
1362 if not isinstance(context, Context):
1363 raise TypeError("context must be a Context instance")
1364
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001365 ssl = _lib.SSL_new(context._context)
1366 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001368 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001369
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001370 # References to strings used for Next Protocol Negotiation. OpenSSL's
1371 # header files suggest that these might get copied at some point, but
1372 # doesn't specify when, so we store them here to make sure they don't
1373 # get freed before OpenSSL uses them.
1374 self._npn_advertise_callback_args = None
1375 self._npn_select_callback_args = None
1376
Cory Benfield12eae892014-06-07 15:42:56 +01001377 # References to strings used for Application Layer Protocol
1378 # Negotiation. These strings get copied at some point but it's well
1379 # after the callback returns, so we have to hang them somewhere to
1380 # avoid them getting freed.
1381 self._alpn_select_callback_args = None
1382
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001383 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001384
1385 if socket is None:
1386 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001387 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001388 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001389 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390
Alex Gaynora829e902016-06-04 18:16:01 -07001391 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1392 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001393
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001394 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001395 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001396 self._into_ssl = None
1397 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001398 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001399 set_result = _lib.SSL_set_fd(
1400 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001401 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001402
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001403 def __getattr__(self, name):
1404 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001405 Look up attributes on the wrapped socket object if they are not found
1406 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001407 """
kjav0b66fa12015-09-02 11:51:26 +01001408 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001409 raise AttributeError("'%s' object has no attribute '%s'" % (
1410 self.__class__.__name__, name
1411 ))
kjav0b66fa12015-09-02 11:51:26 +01001412 else:
1413 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001414
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001415 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001416 if self._context._verify_helper is not None:
1417 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001418 if self._context._npn_advertise_helper is not None:
1419 self._context._npn_advertise_helper.raise_if_problem()
1420 if self._context._npn_select_helper is not None:
1421 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001422 if self._context._alpn_select_helper is not None:
1423 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001424 if self._context._ocsp_helper is not None:
1425 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001426
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001427 error = _lib.SSL_get_error(ssl, result)
1428 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001429 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001430 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001431 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001432 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001434 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001435 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001436 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001437 elif error == _lib.SSL_ERROR_SYSCALL:
1438 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001439 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001440 if platform == "win32":
1441 errno = _ffi.getwinerror()[0]
1442 else:
1443 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001444
1445 if errno != 0:
1446 raise SysCallError(errno, errorcode.get(errno))
1447 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001448 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001449 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001450 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001452 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001453 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001454 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001455
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001456 def get_context(self):
1457 """
1458 Get session context
1459 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001460 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001461
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001462 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463 """
1464 Switch this connection to a new session context
1465
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 :param context: A :py:class:`Context` instance giving the new session
1467 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001468 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001469 if not isinstance(context, Context):
1470 raise TypeError("context must be a Context instance")
1471
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001472 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001473 self._context = context
1474
Cory Benfielde6f35882016-03-29 11:21:04 +01001475 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001476 def get_servername(self):
1477 """
1478 Retrieve the servername extension value if provided in the client hello
1479 message, or None if there wasn't one.
1480
1481 :return: A byte string giving the server name or :py:data:`None`.
1482 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001483 name = _lib.SSL_get_servername(
1484 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1485 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001486 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001487 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001488
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001489 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001490
Cory Benfielde6f35882016-03-29 11:21:04 +01001491 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001492 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001493 """
1494 Set the value of the servername extension to send in the client hello.
1495
1496 :param name: A byte string giving the name.
1497 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001498 if not isinstance(name, bytes):
1499 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001500 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001501 raise TypeError("name must not contain NUL byte")
1502
1503 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001504 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001505
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001506 def pending(self):
1507 """
1508 Get the number of bytes that can be safely read from the connection
1509
1510 :return: The number of bytes available in the receive buffer.
1511 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001512 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001514 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001515 """
1516 Send data on the connection. NOTE: If you get one of the WantRead,
1517 WantWrite or WantX509Lookup exceptions on this, you have to call the
1518 method again with the SAME buffer.
1519
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001520 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521 :param flags: (optional) Included for compatibility with the socket
1522 API, the value is ignored
1523 :return: The number of bytes written
1524 """
Abraham Martine82326c2015-02-04 10:18:10 +00001525 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001526 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001527
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001528 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001529 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001530 if isinstance(buf, _buffer):
1531 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001532 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001533 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001534 if len(buf) > 2147483647:
1535 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001536
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001537 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001539 return result
1540 write = send
1541
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001543 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001544 Send "all" data on the connection. This calls send() repeatedly until
1545 all data is sent. If an error occurs, it's impossible to tell how much
1546 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001547
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001548 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001549 :param flags: (optional) Included for compatibility with the socket
1550 API, the value is ignored
1551 :return: The number of bytes written
1552 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001553 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001554
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001555 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001556 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001557 if isinstance(buf, _buffer):
1558 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001559 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001560 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001561
1562 left_to_send = len(buf)
1563 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001564 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001565
1566 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001567 # SSL_write's num arg is an int,
1568 # so we cannot send more than 2**31-1 bytes at once.
1569 result = _lib.SSL_write(
1570 self._ssl,
1571 data + total_sent,
1572 min(left_to_send, 2147483647)
1573 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001574 self._raise_ssl_error(self._ssl, result)
1575 total_sent += result
1576 left_to_send -= result
1577
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001578 def recv(self, bufsiz, flags=None):
1579 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001580 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581
1582 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001583 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1584 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585 :return: The string read from the Connection
1586 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001587 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001588 if flags is not None and flags & socket.MSG_PEEK:
1589 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1590 else:
1591 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001592 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001593 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001594 read = recv
1595
Cory Benfield62d10332014-06-15 10:03:41 +01001596 def recv_into(self, buffer, nbytes=None, flags=None):
1597 """
1598 Receive data on the connection and store the data into a buffer rather
1599 than creating a new string.
1600
1601 :param buffer: The buffer to copy into.
1602 :param nbytes: (optional) The maximum number of bytes to read into the
1603 buffer. If not present, defaults to the size of the buffer. If
1604 larger than the size of the buffer, is reduced to the size of the
1605 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001606 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1607 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001608 :return: The number of bytes read into the buffer.
1609 """
1610 if nbytes is None:
1611 nbytes = len(buffer)
1612 else:
1613 nbytes = min(nbytes, len(buffer))
1614
1615 # We need to create a temporary buffer. This is annoying, it would be
1616 # better if we could pass memoryviews straight into the SSL_read call,
1617 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001618 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001619 if flags is not None and flags & socket.MSG_PEEK:
1620 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1621 else:
1622 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001623 self._raise_ssl_error(self._ssl, result)
1624
1625 # This strange line is all to avoid a memory copy. The buffer protocol
1626 # should allow us to assign a CFFI buffer to the LHS of this line, but
1627 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1628 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1629 # memoryview type.
1630 try:
1631 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1632 except NameError:
1633 buffer[:result] = _ffi.buffer(buf, result)
1634
1635 return result
1636
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001637 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001638 if _lib.BIO_should_retry(bio):
1639 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001640 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001641 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001642 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001643 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001644 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001645 # TODO: This is untested. I think io_special means the socket
1646 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001647 raise ValueError("BIO_should_io_special")
1648 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001649 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001650 raise ValueError("unknown bio failure")
1651 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001652 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001653 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001654
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001655 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001656 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001657 When using non-socket connections this function reads the "dirty" data
1658 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001659
1660 :param bufsiz: The maximum number of bytes to read
1661 :return: The string read.
1662 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001663 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001666 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001667 raise TypeError("bufsiz must be an integer")
1668
Cory Benfielde62840e2016-11-28 12:17:08 +00001669 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001670 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671 if result <= 0:
1672 self._handle_bio_errors(self._from_ssl, result)
1673
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001674 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001675
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001676 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001677 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 When using non-socket connections this function sends "dirty" data that
1679 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001680
1681 :param buf: The string to put into the memory BIO.
1682 :return: The number of bytes written
1683 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001684 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001685
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001686 if self._into_ssl is None:
1687 raise TypeError("Connection sock was not None")
1688
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001690 if result <= 0:
1691 self._handle_bio_errors(self._into_ssl, result)
1692 return result
1693
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001694 def renegotiate(self):
1695 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001696 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001697
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001698 :return: True if the renegotiation can be started, False otherwise
1699 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001700 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001701 if not self.renegotiate_pending():
1702 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1703 return True
1704 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001705
1706 def do_handshake(self):
1707 """
1708 Perform an SSL handshake (usually called after renegotiate() or one of
1709 set_*_state()). This can raise the same exceptions as send and recv.
1710
1711 :return: None.
1712 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001713 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001714 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001715
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001716 def renegotiate_pending(self):
1717 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001718 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001719 a renegotiation is finished.
1720
1721 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001722 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001723 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001724 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725
1726 def total_renegotiations(self):
1727 """
1728 Find out the total number of renegotiations.
1729
1730 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001731 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001733 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001734
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001735 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001736 """
1737 Connect to remote host and set up client-side SSL
1738
1739 :param addr: A remote address
1740 :return: What the socket's connect method returns
1741 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001742 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001743 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001744
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001745 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001746 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001747 Connect to remote host and set up client-side SSL. Note that if the
1748 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001749
1750 :param addr: A remove address
1751 :return: What the socket's connect_ex method returns
1752 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001753 connect_ex = self._socket.connect_ex
1754 self.set_connect_state()
1755 return connect_ex(addr)
1756
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001757 def accept(self):
1758 """
1759 Accept incoming connection and set up SSL on it
1760
1761 :return: A (conn,addr) pair where conn is a Connection and addr is an
1762 address
1763 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001764 client, addr = self._socket.accept()
1765 conn = Connection(self._context, client)
1766 conn.set_accept_state()
1767 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001768
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001769 def bio_shutdown(self):
1770 """
1771 When using non-socket connections this function signals end of
1772 data on the input for this connection.
1773
1774 :return: None
1775 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001776 if self._from_ssl is None:
1777 raise TypeError("Connection sock was not None")
1778
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001779 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001780
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001781 def shutdown(self):
1782 """
1783 Send closure alert
1784
1785 :return: True if the shutdown completed successfully (i.e. both sides
1786 have sent closure alerts), false otherwise (i.e. you have to
1787 wait for a ZeroReturnError on a recv() method call
1788 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001789 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001790 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001791 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001792 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001793 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001794 else:
1795 return False
1796
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001797 def get_cipher_list(self):
1798 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001799 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001800
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001801 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001802 """
1803 ciphers = []
1804 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001805 result = _lib.SSL_get_cipher_list(self._ssl, i)
1806 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001807 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001808 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809 return ciphers
1810
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001811 def get_client_ca_list(self):
1812 """
1813 Get CAs whose certificates are suggested for client authentication.
1814
Alex Gaynor62da94d2015-09-05 14:37:34 -04001815 :return: If this is a server connection, a list of X509Names
1816 representing the acceptable CAs as set by
1817 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1818 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1819 connection, the list of such X509Names sent by the server, or an
1820 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001821 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001822 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1823 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001824 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001825 return []
1826
1827 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001828 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1829 name = _lib.sk_X509_NAME_value(ca_names, i)
1830 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001831 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001832
1833 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001834 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001835 result.append(pyname)
1836 return result
1837
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001838 def makefile(self):
1839 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001840 The makefile() method is not implemented, since there is no dup
1841 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001842
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001843 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001844 """
Alex Gaynor83284952015-09-05 10:43:30 -04001845 raise NotImplementedError(
1846 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001847
1848 def get_app_data(self):
1849 """
1850 Get application data
1851
1852 :return: The application data
1853 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001854 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001855
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001856 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001857 """
1858 Set application data
1859
1860 :param data - The application data
1861 :return: None
1862 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001863 self._app_data = data
1864
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001865 def get_shutdown(self):
1866 """
1867 Get shutdown state
1868
Alex Gaynor62da94d2015-09-05 14:37:34 -04001869 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1870 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001871 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001872 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001873
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001874 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001875 """
1876 Set shutdown state
1877
1878 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1879 :return: None
1880 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001881 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001882 raise TypeError("state must be an integer")
1883
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001884 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001885
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001886 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001887 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001888 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001889
1890 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001891 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001892 """
kjavc704a2e2015-09-07 12:12:27 +01001893 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001894
1895 def server_random(self):
1896 """
1897 Get a copy of the server hello nonce.
1898
1899 :return: A string representing the state
1900 """
Alex Gaynor93603062016-06-01 20:13:09 -07001901 session = _lib.SSL_get_session(self._ssl)
1902 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001903 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001904 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1905 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001906 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001907 _lib.SSL_get_server_random(self._ssl, outp, length)
1908 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001909
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001910 def client_random(self):
1911 """
1912 Get a copy of the client hello nonce.
1913
1914 :return: A string representing the state
1915 """
Alex Gaynor93603062016-06-01 20:13:09 -07001916 session = _lib.SSL_get_session(self._ssl)
1917 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001918 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001919
1920 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1921 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001922 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001923 _lib.SSL_get_client_random(self._ssl, outp, length)
1924 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001925
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001926 def master_key(self):
1927 """
1928 Get a copy of the master key.
1929
1930 :return: A string representing the state
1931 """
Alex Gaynor93603062016-06-01 20:13:09 -07001932 session = _lib.SSL_get_session(self._ssl)
1933 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001934 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001935
1936 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1937 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001938 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001939 _lib.SSL_SESSION_get_master_key(session, outp, length)
1940 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001941
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001942 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001943 """
1944 See shutdown(2)
1945
1946 :return: What the socket's shutdown() method returns
1947 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948 return self._socket.shutdown(*args, **kwargs)
1949
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001950 def get_peer_certificate(self):
1951 """
1952 Retrieve the other side's certificate (if any)
1953
1954 :return: The peer's certificate
1955 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001956 cert = _lib.SSL_get_peer_certificate(self._ssl)
1957 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001958 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001959 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001960 return pycert
1961 return None
1962
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001963 def get_peer_cert_chain(self):
1964 """
1965 Retrieve the other side's certificate (if any)
1966
1967 :return: A list of X509 instances giving the peer's certificate chain,
1968 or None if it does not have one.
1969 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001970 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1971 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001972 return None
1973
1974 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001975 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001976 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001977 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001978 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001979 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001980 result.append(pycert)
1981 return result
1982
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001983 def want_read(self):
1984 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001985 Checks if more data has to be read from the transport layer to complete
1986 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001987
1988 :return: True iff more data has to be read
1989 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001990 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001991
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001992 def want_write(self):
1993 """
1994 Checks if there is data to write to the transport layer to complete an
1995 operation.
1996
1997 :return: True iff there is data to write
1998 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001999 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002000
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002001 def set_accept_state(self):
2002 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002003 Set the connection to work in server mode. The handshake will be
2004 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002005
2006 :return: None
2007 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002008 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002009
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002010 def set_connect_state(self):
2011 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002012 Set the connection to work in client mode. The handshake will be
2013 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002014
2015 :return: None
2016 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002017 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002018
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002019 def get_session(self):
2020 """
2021 Returns the Session currently used.
2022
Alex Gaynor62da94d2015-09-05 14:37:34 -04002023 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
2024 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002026 session = _lib.SSL_get1_session(self._ssl)
2027 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002028 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002029
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002030 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002031 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002032 return pysession
2033
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002034 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035 """
2036 Set the session to be used when the TLS/SSL connection is established.
2037
2038 :param session: A Session instance representing the session to use.
2039 :returns: None
2040 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002041 if not isinstance(session, Session):
2042 raise TypeError("session must be a Session instance")
2043
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002044 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002045 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002046 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002047
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002048 def _get_finished_message(self, function):
2049 """
2050 Helper to implement :py:meth:`get_finished` and
2051 :py:meth:`get_peer_finished`.
2052
2053 :param function: Either :py:data:`SSL_get_finished`: or
2054 :py:data:`SSL_get_peer_finished`.
2055
2056 :return: :py:data:`None` if the desired message has not yet been
2057 received, otherwise the contents of the message.
2058 :rtype: :py:class:`bytes` or :py:class:`NoneType`
2059 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002060 # The OpenSSL documentation says nothing about what might happen if the
2061 # count argument given is zero. Specifically, it doesn't say whether
2062 # the output buffer may be NULL in that case or not. Inspection of the
2063 # implementation reveals that it calls memcpy() unconditionally.
2064 # Section 7.1.4, paragraph 1 of the C standard suggests that
2065 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2066 # alone desirable) behavior (though it probably does on just about
2067 # every implementation...)
2068 #
2069 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2070 # one might expect) for the initial call so as to be safe against this
2071 # potentially undefined behavior.
2072 empty = _ffi.new("char[]", 0)
2073 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002074 if size == 0:
2075 # No Finished message so far.
2076 return None
2077
Cory Benfielde62840e2016-11-28 12:17:08 +00002078 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002079 function(self._ssl, buf, size)
2080 return _ffi.buffer(buf, size)[:]
2081
Fedor Brunner5747b932014-03-05 14:22:34 +01002082 def get_finished(self):
2083 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002084 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002085
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002086 :return: The contents of the message or :py:obj:`None` if the TLS
2087 handshake has not yet completed.
2088 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002089 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002090 return self._get_finished_message(_lib.SSL_get_finished)
2091
Fedor Brunner5747b932014-03-05 14:22:34 +01002092 def get_peer_finished(self):
2093 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002094 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002095
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002096 :return: The contents of the message or :py:obj:`None` if the TLS
2097 handshake has not yet completed.
2098 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002099 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002100 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002101
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002102 def get_cipher_name(self):
2103 """
2104 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002105
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002106 :returns: The name of the currently used cipher or :py:obj:`None`
2107 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002108 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002109 """
2110 cipher = _lib.SSL_get_current_cipher(self._ssl)
2111 if cipher == _ffi.NULL:
2112 return None
2113 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002114 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2115 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002116
2117 def get_cipher_bits(self):
2118 """
2119 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002120
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002121 :returns: The number of secret bits of the currently used cipher
2122 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002123 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002124 """
2125 cipher = _lib.SSL_get_current_cipher(self._ssl)
2126 if cipher == _ffi.NULL:
2127 return None
2128 else:
2129 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2130
2131 def get_cipher_version(self):
2132 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002133 Obtain the protocol version of the currently used cipher.
2134
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002135 :returns: The protocol name of the currently used cipher
2136 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002137 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002138 """
2139 cipher = _lib.SSL_get_current_cipher(self._ssl)
2140 if cipher == _ffi.NULL:
2141 return None
2142 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002143 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002144 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002145
Jim Shaverabff1882015-05-27 09:15:55 -04002146 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002147 """
2148 Obtain the protocol version of the current connection.
2149
2150 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002151 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002152 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002153 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002154 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002155 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002156 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002157
Jim Shaver208438c2015-05-28 09:52:38 -04002158 def get_protocol_version(self):
2159 """
2160 Obtain the protocol version of the current connection.
2161
2162 :returns: The TLS version of the current connection, for example
2163 the value for TLS 1 would be 0x769.
2164 :rtype: :py:class:`int`
2165 """
2166 version = _lib.SSL_version(self._ssl)
2167 return version
2168
Cory Benfield10b277f2015-04-13 17:12:42 -04002169 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002170 def get_next_proto_negotiated(self):
2171 """
2172 Get the protocol that was negotiated by NPN.
2173 """
2174 data = _ffi.new("unsigned char **")
2175 data_len = _ffi.new("unsigned int *")
2176
2177 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2178
Cory Benfieldcd010f62014-05-15 19:00:27 +01002179 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002180
Cory Benfield7907e332015-04-13 17:18:25 -04002181 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002182 def set_alpn_protos(self, protos):
2183 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002184 Specify the client's ALPN protocol list.
2185
2186 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002187
2188 :param protos: A list of the protocols to be offered to the server.
2189 This list should be a Python list of bytestrings representing the
2190 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2191 """
2192 # Take the list of protocols and join them together, prefixing them
2193 # with their lengths.
2194 protostr = b''.join(
2195 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2196 )
2197
2198 # Build a C string from the list. We don't need to save this off
2199 # because OpenSSL immediately copies the data out.
2200 input_str = _ffi.new("unsigned char[]", protostr)
Alex Gaynord61c46a2017-06-29 22:51:33 -07002201 _lib.SSL_set_alpn_protos(self._ssl, input_str, len(protostr))
Cory Benfield12eae892014-06-07 15:42:56 +01002202
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002203 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002204 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002205 """
2206 Get the protocol that was negotiated by ALPN.
2207 """
Cory Benfield12eae892014-06-07 15:42:56 +01002208 data = _ffi.new("unsigned char **")
2209 data_len = _ffi.new("unsigned int *")
2210
2211 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2212
Cory Benfielde8e9c382015-04-11 17:33:48 -04002213 if not data_len:
2214 return b''
2215
Cory Benfield12eae892014-06-07 15:42:56 +01002216 return _ffi.buffer(data[0], data_len[0])[:]
2217
Cory Benfield496652a2017-01-24 11:42:56 +00002218 def request_ocsp(self):
2219 """
2220 Called to request that the server sends stapled OCSP data, if
2221 available. If this is not called on the client side then the server
2222 will not send OCSP data. Should be used in conjunction with
2223 :meth:`Context.set_ocsp_client_callback`.
2224 """
2225 rc = _lib.SSL_set_tlsext_status_type(
2226 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2227 )
2228 _openssl_assert(rc == 1)
2229
Cory Benfield12eae892014-06-07 15:42:56 +01002230
Alex Gaynor10d30832017-06-29 15:31:39 -07002231ConnectionType = deprecated(
2232 Connection, __name__,
2233 "ConnectionType has been deprecated, use Connection instead",
2234 DeprecationWarning
2235)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002236
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002237# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2238# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002239_lib.SSL_library_init()