blob: b17d25b9dd1aad48cb1df8df981698287168c000 [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 Calderone1aba4162013-03-05 18:50:00 -0800655 # SSL_CTX_set_app_data(self->ctx, self);
656 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
657 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
658 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500659 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800660
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661 def load_verify_locations(self, cafile, capath=None):
662 """
663 Let SSL know where we can find trusted certificates for the certificate
664 chain
665
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400666 :param cafile: In which file we can find the certificates (``bytes`` or
667 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800668 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400669 (``bytes`` or ``unicode``).
670
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800671 :return: None
672 """
673 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500674 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400675 else:
676 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800677
678 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500679 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400680 else:
681 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682
Alex Gaynor62da94d2015-09-05 14:37:34 -0400683 load_result = _lib.SSL_CTX_load_verify_locations(
684 self._context, cafile, capath
685 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800686 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500687 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800688
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800689 def _wrap_callback(self, callback):
690 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800691 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800692 return callback(size, verify, self._passphrase_userdata)
693 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800694 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800695
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696 def set_passwd_cb(self, callback, userdata=None):
697 """
698 Set the passphrase callback
699
700 :param callback: The Python callback to use
701 :param userdata: (optional) A Python object which will be given as
702 argument to the callback
703 :return: None
704 """
705 if not callable(callback):
706 raise TypeError("callback must be callable")
707
708 self._passphrase_helper = self._wrap_callback(callback)
709 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500710 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800711 self._context, self._passphrase_callback)
712 self._passphrase_userdata = userdata
713
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800714 def set_default_verify_paths(self):
715 """
716 Use the platform-specific CA certificate locations
717
718 :return: None
719 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500720 # SSL_CTX_set_default_verify_paths will attempt to load certs from
721 # both a cafile and capath that are set at compile time. However,
722 # it will first check environment variables and, if present, load
723 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500724 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400725 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500726 # After attempting to set default_verify_paths we need to know whether
727 # to go down the fallback path.
728 # First we'll check to see if any env vars have been set. If so,
729 # we won't try to do anything else because the user has set the path
730 # themselves.
731 dir_env_var = _ffi.string(
732 _lib.X509_get_default_cert_dir_env()
733 ).decode("ascii")
734 file_env_var = _ffi.string(
735 _lib.X509_get_default_cert_file_env()
736 ).decode("ascii")
737 if not self._check_env_vars_set(dir_env_var, file_env_var):
738 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
739 default_file = _ffi.string(_lib.X509_get_default_cert_file())
740 # Now we check to see if the default_dir and default_file are set
741 # to the exact values we use in our manylinux1 builds. If they are
742 # then we know to load the fallbacks
743 if (
744 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
745 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
746 ):
747 # This is manylinux1, let's load our fallback paths
748 self._fallback_default_verify_paths(
749 _CERTIFICATE_FILE_LOCATIONS,
750 _CERTIFICATE_PATH_LOCATIONS
751 )
752
753 def _check_env_vars_set(self, dir_env_var, file_env_var):
754 """
755 Check to see if the default cert dir/file environment vars are present.
756
757 :return: bool
758 """
759 return (
760 os.environ.get(file_env_var) is not None or
761 os.environ.get(dir_env_var) is not None
762 )
763
764 def _fallback_default_verify_paths(self, file_path, dir_path):
765 """
766 Default verify paths are based on the compiled version of OpenSSL.
767 However, when pyca/cryptography is compiled as a manylinux1 wheel
768 that compiled location can potentially be wrong. So, like Go, we
769 will try a predefined set of paths and attempt to load roots
770 from there.
771
772 :return: None
773 """
774 for cafile in file_path:
775 if os.path.isfile(cafile):
776 self.load_verify_locations(cafile)
777 break
778
779 for capath in dir_path:
780 if os.path.isdir(capath):
781 self.load_verify_locations(None, capath)
782 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800783
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800784 def use_certificate_chain_file(self, certfile):
785 """
786 Load a certificate chain from a file
787
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400788 :param certfile: The name of the certificate chain file (``bytes`` or
789 ``unicode``).
790
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800791 :return: None
792 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400793 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800794
Alex Gaynor62da94d2015-09-05 14:37:34 -0400795 result = _lib.SSL_CTX_use_certificate_chain_file(
796 self._context, certfile
797 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800798 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500799 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800800
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800801 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800802 """
803 Load a certificate from a file
804
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400805 :param certfile: The name of the certificate file (``bytes`` or
806 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800807 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400808
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800809 :return: None
810 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400811 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500812 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800813 raise TypeError("filetype must be an integer")
814
Alex Gaynor62da94d2015-09-05 14:37:34 -0400815 use_result = _lib.SSL_CTX_use_certificate_file(
816 self._context, certfile, filetype
817 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800818 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500819 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800820
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800821 def use_certificate(self, cert):
822 """
823 Load a certificate from a X509 object
824
825 :param cert: The X509 object
826 :return: None
827 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800828 if not isinstance(cert, X509):
829 raise TypeError("cert must be an X509 instance")
830
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500831 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800832 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500833 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800834
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800835 def add_extra_chain_cert(self, certobj):
836 """
837 Add certificate to chain
838
839 :param certobj: The X509 certificate object to add to the chain
840 :return: None
841 """
842 if not isinstance(certobj, X509):
843 raise TypeError("certobj must be an X509 instance")
844
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500845 copy = _lib.X509_dup(certobj._x509)
846 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800847 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500848 # TODO: This is untested.
849 _lib.X509_free(copy)
850 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800851
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800852 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500853 if self._passphrase_helper is not None:
854 self._passphrase_helper.raise_if_problem(Error)
855
856 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800857
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400858 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800859 """
860 Load a private key from a file
861
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400862 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800863 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400864
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800865 :return: None
866 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400867 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800868
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400869 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800870 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500871 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800872 raise TypeError("filetype must be an integer")
873
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500874 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800875 self._context, keyfile, filetype)
876 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800877 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800878
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800879 def use_privatekey(self, pkey):
880 """
881 Load a private key from a PKey object
882
883 :param pkey: The PKey object
884 :return: None
885 """
886 if not isinstance(pkey, PKey):
887 raise TypeError("pkey must be a PKey instance")
888
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500889 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800890 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800891 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800892
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800893 def check_privatekey(self):
894 """
895 Check that the private key and certificate match up
896
897 :return: None (raises an exception if something's wrong)
898 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500899 if not _lib.SSL_CTX_check_private_key(self._context):
900 _raise_current_error()
901
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800902 def load_client_ca(self, cafile):
903 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100904 Load the trusted certificates that will be sent to the client. Does
905 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400906 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100908 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800909 :return: None
910 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100911 ca_list = _lib.SSL_load_client_CA_file(
912 _text_to_bytes_and_warn("cafile", cafile)
913 )
914 _openssl_assert(ca_list != _ffi.NULL)
915 # SSL_CTX_set_client_CA_list doesn't return anything.
916 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800917
918 def set_session_id(self, buf):
919 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100920 Set the session id to *buf* within which a session can be reused for
921 this Context object. This is needed when doing session resumption,
922 because there is no way for a stored session to know which Context
923 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800924
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100925 :param bytes buf: The session id.
926
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800927 :returns: None
928 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100929 buf = _text_to_bytes_and_warn("buf", buf)
930 _openssl_assert(
931 _lib.SSL_CTX_set_session_id_context(
932 self._context,
933 buf,
934 len(buf),
935 ) == 1
936 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800937
938 def set_session_cache_mode(self, mode):
939 """
940 Enable/disable session caching and specify the mode used.
941
942 :param mode: One or more of the SESS_CACHE_* flags (combine using
943 bitwise or)
944 :returns: The previously set caching mode.
945 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500946 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800947 raise TypeError("mode must be an integer")
948
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500949 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800950
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951 def get_session_cache_mode(self):
952 """
953 :returns: The currently used cache mode.
954 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500955 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800956
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800957 def set_verify(self, mode, callback):
958 """
959 Set the verify mode and verify callback
960
961 :param mode: The verify mode, this is either VERIFY_NONE or
962 VERIFY_PEER combined with possible other flags
963 :param callback: The Python callback to use
964 :return: None
965
966 See SSL_CTX_set_verify(3SSL) for further details.
967 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500968 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800969 raise TypeError("mode must be an integer")
970
971 if not callable(callback):
972 raise TypeError("callback must be callable")
973
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400974 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800975 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500976 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800977
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978 def set_verify_depth(self, depth):
979 """
980 Set the verify depth
981
982 :param depth: An integer specifying the verify depth
983 :return: None
984 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500985 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800986 raise TypeError("depth must be an integer")
987
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800989
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990 def get_verify_mode(self):
991 """
992 Get the verify mode
993
994 :return: The verify mode
995 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500996 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800997
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800998 def get_verify_depth(self):
999 """
1000 Get the verify depth
1001
1002 :return: The verify depth
1003 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001005
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006 def load_tmp_dh(self, dhfile):
1007 """
1008 Load parameters for Ephemeral Diffie-Hellman
1009
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001010 :param dhfile: The file to load EDH parameters from (``bytes`` or
1011 ``unicode``).
1012
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001013 :return: None
1014 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001015 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001016
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001017 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001018 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001019 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001020 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001021
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001022 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1023 dh = _ffi.gc(dh, _lib.DH_free)
1024 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001025
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001026 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001027 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001028 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001029
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001030 :param curve: A curve object to use as returned by either
1031 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
1032 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001033
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001034 :return: None
1035 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001036 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001037
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001038 def set_cipher_list(self, cipher_list):
1039 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001040 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001041
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001042 See the OpenSSL manual for more information (e.g.
1043 :manpage:`ciphers(1)`).
1044
1045 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001046 :return: None
1047 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001048 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001049
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001050 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001051 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001052
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001053 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001054 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001055 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001056
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001057 def set_client_ca_list(self, certificate_authorities):
1058 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001059 Set the list of preferred client certificate signers for this server
1060 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001061
Alex Gaynor62da94d2015-09-05 14:37:34 -04001062 This list of certificate authorities will be sent to the client when
1063 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001064
1065 :param certificate_authorities: a sequence of X509Names.
1066 :return: None
1067 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001068 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001069 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001070
1071 try:
1072 for ca_name in certificate_authorities:
1073 if not isinstance(ca_name, X509Name):
1074 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001075 "client CAs must be X509Name objects, not %s "
1076 "objects" % (
1077 type(ca_name).__name__,
1078 )
1079 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001080 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001081 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001083 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001084 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001085 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001086 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001088 raise
1089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001091
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001092 def add_client_ca(self, certificate_authority):
1093 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001094 Add the CA certificate to the list of preferred signers for this
1095 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001096
1097 The list of certificate authorities will be sent to the client when the
1098 server requests a client certificate.
1099
1100 :param certificate_authority: certificate authority's X509 certificate.
1101 :return: None
1102 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001103 if not isinstance(certificate_authority, X509):
1104 raise TypeError("certificate_authority must be an X509 instance")
1105
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001106 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001107 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001108 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001109
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001110 def set_timeout(self, timeout):
1111 """
1112 Set session timeout
1113
1114 :param timeout: The timeout in seconds
1115 :return: The previous session timeout
1116 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001117 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001118 raise TypeError("timeout must be an integer")
1119
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001120 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001121
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122 def get_timeout(self):
1123 """
1124 Get the session timeout
1125
1126 :return: The session timeout
1127 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001128 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001129
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001130 def set_info_callback(self, callback):
1131 """
1132 Set the info callback
1133
1134 :param callback: The Python callback to use
1135 :return: None
1136 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001137 @wraps(callback)
1138 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001139 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001140 self._info_callback = _ffi.callback(
1141 "void (*)(const SSL *, int, int)", wrapper)
1142 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001143
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001144 def get_app_data(self):
1145 """
1146 Get the application data (supplied via set_app_data())
1147
1148 :return: The application data
1149 """
1150 return self._app_data
1151
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001152 def set_app_data(self, data):
1153 """
1154 Set the application data (will be returned from get_app_data())
1155
1156 :param data: Any Python object
1157 :return: None
1158 """
1159 self._app_data = data
1160
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001161 def get_cert_store(self):
1162 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001163 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001164
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001165 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001166 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 store = _lib.SSL_CTX_get_cert_store(self._context)
1168 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001169 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170 return None
1171
1172 pystore = X509Store.__new__(X509Store)
1173 pystore._store = store
1174 return pystore
1175
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001176 def set_options(self, options):
1177 """
1178 Add options. Options set before are not cleared!
1179
1180 :param options: The options to add.
1181 :return: The new option bitmask.
1182 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001183 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001184 raise TypeError("options must be an integer")
1185
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001186 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001187
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001188 def set_mode(self, mode):
1189 """
1190 Add modes via bitmask. Modes set before are not cleared!
1191
1192 :param mode: The mode to add.
1193 :return: The new mode bitmask.
1194 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001195 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001196 raise TypeError("mode must be an integer")
1197
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001198 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001199
Cory Benfielde6f35882016-03-29 11:21:04 +01001200 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001201 def set_tlsext_servername_callback(self, callback):
1202 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001203 Specify a callback function to be called when clients specify a server
1204 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001205
1206 :param callback: The callback function. It will be invoked with one
1207 argument, the Connection instance.
1208 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001209 @wraps(callback)
1210 def wrapper(ssl, alert, arg):
1211 callback(Connection._reverse_mapping[ssl])
1212 return 0
1213
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001214 self._tlsext_servername_callback = _ffi.callback(
1215 "int (*)(const SSL *, int *, void *)", wrapper)
1216 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001217 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001218
Cory Benfield10b277f2015-04-13 17:12:42 -04001219 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001220 def set_npn_advertise_callback(self, callback):
1221 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001222 Specify a callback function that will be called when offering `Next
1223 Protocol Negotiation
1224 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001225
1226 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001227 argument, the Connection instance. It should return a list of
1228 bytestrings representing the advertised protocols, like
1229 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001230 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001231 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1232 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001233 _lib.SSL_CTX_set_next_protos_advertised_cb(
1234 self._context, self._npn_advertise_callback, _ffi.NULL)
1235
Cory Benfield10b277f2015-04-13 17:12:42 -04001236 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001237 def set_npn_select_callback(self, callback):
1238 """
1239 Specify a callback function that will be called when a server offers
1240 Next Protocol Negotiation options.
1241
1242 :param callback: The callback function. It will be invoked with two
1243 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001244 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1245 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001246 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001247 self._npn_select_helper = _NpnSelectHelper(callback)
1248 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001249 _lib.SSL_CTX_set_next_proto_select_cb(
1250 self._context, self._npn_select_callback, _ffi.NULL)
1251
Cory Benfield7907e332015-04-13 17:18:25 -04001252 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001253 def set_alpn_protos(self, protos):
1254 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001255 Specify the clients ALPN protocol list.
1256
1257 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001258
1259 :param protos: A list of the protocols to be offered to the server.
1260 This list should be a Python list of bytestrings representing the
1261 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1262 """
1263 # Take the list of protocols and join them together, prefixing them
1264 # with their lengths.
1265 protostr = b''.join(
1266 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1267 )
1268
1269 # Build a C string from the list. We don't need to save this off
1270 # because OpenSSL immediately copies the data out.
1271 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001272 input_str_len = _ffi.cast("unsigned", len(protostr))
1273 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001274
Cory Benfield7907e332015-04-13 17:18:25 -04001275 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001276 def set_alpn_select_callback(self, callback):
1277 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001278 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001279
1280 :param callback: The callback function. It will be invoked with two
1281 arguments: the Connection, and a list of offered protocols as
1282 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001283 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001284 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001285 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001286 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001287 _lib.SSL_CTX_set_alpn_select_cb(
1288 self._context, self._alpn_select_callback, _ffi.NULL)
1289
Cory Benfield496652a2017-01-24 11:42:56 +00001290 def _set_ocsp_callback(self, helper, data):
1291 """
1292 This internal helper does the common work for
1293 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1294 almost all of it.
1295 """
1296 self._ocsp_helper = helper
1297 self._ocsp_callback = helper.callback
1298 if data is None:
1299 self._ocsp_data = _ffi.NULL
1300 else:
1301 self._ocsp_data = _ffi.new_handle(data)
1302
1303 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1304 self._context, self._ocsp_callback
1305 )
1306 _openssl_assert(rc == 1)
1307 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1308 _openssl_assert(rc == 1)
1309
1310 def set_ocsp_server_callback(self, callback, data=None):
1311 """
1312 Set a callback to provide OCSP data to be stapled to the TLS handshake
1313 on the server side.
1314
1315 :param callback: The callback function. It will be invoked with two
1316 arguments: the Connection, and the optional arbitrary data you have
1317 provided. The callback must return a bytestring that contains the
1318 OCSP data to staple to the handshake. If no OCSP data is available
1319 for this connection, return the empty bytestring.
1320 :param data: Some opaque data that will be passed into the callback
1321 function when called. This can be used to avoid needing to do
1322 complex data lookups or to keep track of what context is being
1323 used. This parameter is optional.
1324 """
1325 helper = _OCSPServerCallbackHelper(callback)
1326 self._set_ocsp_callback(helper, data)
1327
1328 def set_ocsp_client_callback(self, callback, data=None):
1329 """
1330 Set a callback to validate OCSP data stapled to the TLS handshake on
1331 the client side.
1332
1333 :param callback: The callback function. It will be invoked with three
1334 arguments: the Connection, a bytestring containing the stapled OCSP
1335 assertion, and the optional arbitrary data you have provided. The
1336 callback must return a boolean that indicates the result of
1337 validating the OCSP data: ``True`` if the OCSP data is valid and
1338 the certificate can be trusted, or ``False`` if either the OCSP
1339 data is invalid or the certificate has been revoked.
1340 :param data: Some opaque data that will be passed into the callback
1341 function when called. This can be used to avoid needing to do
1342 complex data lookups or to keep track of what context is being
1343 used. This parameter is optional.
1344 """
1345 helper = _OCSPClientCallbackHelper(callback)
1346 self._set_ocsp_callback(helper, data)
1347
Alex Chanc6077062016-11-18 13:53:39 +00001348
Alex Gaynor10d30832017-06-29 15:31:39 -07001349ContextType = deprecated(
1350 Context, __name__,
1351 "ContextType has been deprecated, use Context instead", DeprecationWarning
1352)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001353
1354
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001355class Connection(object):
1356 """
1357 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001358 _reverse_mapping = WeakValueDictionary()
1359
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001360 def __init__(self, context, socket=None):
1361 """
1362 Create a new Connection object, using the given OpenSSL.SSL.Context
1363 instance and socket.
1364
1365 :param context: An SSL Context to use for this connection
1366 :param socket: The socket to use for transport layer
1367 """
1368 if not isinstance(context, Context):
1369 raise TypeError("context must be a Context instance")
1370
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001371 ssl = _lib.SSL_new(context._context)
1372 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001373 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001374 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001375
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001376 # References to strings used for Next Protocol Negotiation. OpenSSL's
1377 # header files suggest that these might get copied at some point, but
1378 # doesn't specify when, so we store them here to make sure they don't
1379 # get freed before OpenSSL uses them.
1380 self._npn_advertise_callback_args = None
1381 self._npn_select_callback_args = None
1382
Cory Benfield12eae892014-06-07 15:42:56 +01001383 # References to strings used for Application Layer Protocol
1384 # Negotiation. These strings get copied at some point but it's well
1385 # after the callback returns, so we have to hang them somewhere to
1386 # avoid them getting freed.
1387 self._alpn_select_callback_args = None
1388
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001389 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001390
1391 if socket is None:
1392 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001393 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001394 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001395 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001396
Alex Gaynora829e902016-06-04 18:16:01 -07001397 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1398 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001399
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001400 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001401 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001402 self._into_ssl = None
1403 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001404 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001405 set_result = _lib.SSL_set_fd(
1406 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001407 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001408
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001409 def __getattr__(self, name):
1410 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001411 Look up attributes on the wrapped socket object if they are not found
1412 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001413 """
kjav0b66fa12015-09-02 11:51:26 +01001414 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001415 raise AttributeError("'%s' object has no attribute '%s'" % (
1416 self.__class__.__name__, name
1417 ))
kjav0b66fa12015-09-02 11:51:26 +01001418 else:
1419 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001420
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001421 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001422 if self._context._verify_helper is not None:
1423 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001424 if self._context._npn_advertise_helper is not None:
1425 self._context._npn_advertise_helper.raise_if_problem()
1426 if self._context._npn_select_helper is not None:
1427 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001428 if self._context._alpn_select_helper is not None:
1429 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001430 if self._context._ocsp_helper is not None:
1431 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001432
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001433 error = _lib.SSL_get_error(ssl, result)
1434 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001435 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001436 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001437 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001438 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001439 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001440 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001441 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001442 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001443 elif error == _lib.SSL_ERROR_SYSCALL:
1444 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001445 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001446 if platform == "win32":
1447 errno = _ffi.getwinerror()[0]
1448 else:
1449 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001450
1451 if errno != 0:
1452 raise SysCallError(errno, errorcode.get(errno))
1453 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001454 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001455 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001456 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001457 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001458 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001459 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001460 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001461
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001462 def get_context(self):
1463 """
1464 Get session context
1465 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001467
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001468 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469 """
1470 Switch this connection to a new session context
1471
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001472 :param context: A :py:class:`Context` instance giving the new session
1473 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001474 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001475 if not isinstance(context, Context):
1476 raise TypeError("context must be a Context instance")
1477
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001478 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001479 self._context = context
1480
Cory Benfielde6f35882016-03-29 11:21:04 +01001481 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001482 def get_servername(self):
1483 """
1484 Retrieve the servername extension value if provided in the client hello
1485 message, or None if there wasn't one.
1486
1487 :return: A byte string giving the server name or :py:data:`None`.
1488 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001489 name = _lib.SSL_get_servername(
1490 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1491 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001492 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001493 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001494
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001495 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001496
Cory Benfielde6f35882016-03-29 11:21:04 +01001497 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001498 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001499 """
1500 Set the value of the servername extension to send in the client hello.
1501
1502 :param name: A byte string giving the name.
1503 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001504 if not isinstance(name, bytes):
1505 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001506 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001507 raise TypeError("name must not contain NUL byte")
1508
1509 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001510 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001511
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001512 def pending(self):
1513 """
1514 Get the number of bytes that can be safely read from the connection
1515
1516 :return: The number of bytes available in the receive buffer.
1517 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001518 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001519
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001520 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001521 """
1522 Send data on the connection. NOTE: If you get one of the WantRead,
1523 WantWrite or WantX509Lookup exceptions on this, you have to call the
1524 method again with the SAME buffer.
1525
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001526 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001527 :param flags: (optional) Included for compatibility with the socket
1528 API, the value is ignored
1529 :return: The number of bytes written
1530 """
Abraham Martine82326c2015-02-04 10:18:10 +00001531 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001532 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001533
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001534 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001535 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001536 if isinstance(buf, _buffer):
1537 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001538 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001539 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001540 if len(buf) > 2147483647:
1541 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001543 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001544 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001545 return result
1546 write = send
1547
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001548 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001549 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001550 Send "all" data on the connection. This calls send() repeatedly until
1551 all data is sent. If an error occurs, it's impossible to tell how much
1552 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001553
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001554 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001555 :param flags: (optional) Included for compatibility with the socket
1556 API, the value is ignored
1557 :return: The number of bytes written
1558 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001559 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001560
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001561 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001562 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001563 if isinstance(buf, _buffer):
1564 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001565 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001566 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567
1568 left_to_send = len(buf)
1569 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001570 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001571
1572 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001573 # SSL_write's num arg is an int,
1574 # so we cannot send more than 2**31-1 bytes at once.
1575 result = _lib.SSL_write(
1576 self._ssl,
1577 data + total_sent,
1578 min(left_to_send, 2147483647)
1579 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001580 self._raise_ssl_error(self._ssl, result)
1581 total_sent += result
1582 left_to_send -= result
1583
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001584 def recv(self, bufsiz, flags=None):
1585 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001586 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001587
1588 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001589 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1590 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001591 :return: The string read from the Connection
1592 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001593 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001594 if flags is not None and flags & socket.MSG_PEEK:
1595 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1596 else:
1597 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001598 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001599 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001600 read = recv
1601
Cory Benfield62d10332014-06-15 10:03:41 +01001602 def recv_into(self, buffer, nbytes=None, flags=None):
1603 """
1604 Receive data on the connection and store the data into a buffer rather
1605 than creating a new string.
1606
1607 :param buffer: The buffer to copy into.
1608 :param nbytes: (optional) The maximum number of bytes to read into the
1609 buffer. If not present, defaults to the size of the buffer. If
1610 larger than the size of the buffer, is reduced to the size of the
1611 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001612 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1613 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001614 :return: The number of bytes read into the buffer.
1615 """
1616 if nbytes is None:
1617 nbytes = len(buffer)
1618 else:
1619 nbytes = min(nbytes, len(buffer))
1620
1621 # We need to create a temporary buffer. This is annoying, it would be
1622 # better if we could pass memoryviews straight into the SSL_read call,
1623 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001624 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001625 if flags is not None and flags & socket.MSG_PEEK:
1626 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1627 else:
1628 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001629 self._raise_ssl_error(self._ssl, result)
1630
1631 # This strange line is all to avoid a memory copy. The buffer protocol
1632 # should allow us to assign a CFFI buffer to the LHS of this line, but
1633 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1634 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1635 # memoryview type.
1636 try:
1637 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1638 except NameError:
1639 buffer[:result] = _ffi.buffer(buf, result)
1640
1641 return result
1642
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001643 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001644 if _lib.BIO_should_retry(bio):
1645 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001646 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001647 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001648 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001649 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001650 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001651 # TODO: This is untested. I think io_special means the socket
1652 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001653 raise ValueError("BIO_should_io_special")
1654 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001655 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001656 raise ValueError("unknown bio failure")
1657 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001658 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001659 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001660
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001661 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001662 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001663 When using non-socket connections this function reads the "dirty" data
1664 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001665
1666 :param bufsiz: The maximum number of bytes to read
1667 :return: The string read.
1668 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001669 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001670 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001671
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001672 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001673 raise TypeError("bufsiz must be an integer")
1674
Cory Benfielde62840e2016-11-28 12:17:08 +00001675 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001676 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001677 if result <= 0:
1678 self._handle_bio_errors(self._from_ssl, result)
1679
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001680 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001681
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001682 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001683 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001684 When using non-socket connections this function sends "dirty" data that
1685 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001686
1687 :param buf: The string to put into the memory BIO.
1688 :return: The number of bytes written
1689 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001690 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001691
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001692 if self._into_ssl is None:
1693 raise TypeError("Connection sock was not None")
1694
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001695 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001696 if result <= 0:
1697 self._handle_bio_errors(self._into_ssl, result)
1698 return result
1699
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001700 def renegotiate(self):
1701 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001702 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001703
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001704 :return: True if the renegotiation can be started, False otherwise
1705 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001706 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001707 if not self.renegotiate_pending():
1708 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1709 return True
1710 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001711
1712 def do_handshake(self):
1713 """
1714 Perform an SSL handshake (usually called after renegotiate() or one of
1715 set_*_state()). This can raise the same exceptions as send and recv.
1716
1717 :return: None.
1718 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001719 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001721
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001722 def renegotiate_pending(self):
1723 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001724 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001725 a renegotiation is finished.
1726
1727 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001728 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001729 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001730 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001731
1732 def total_renegotiations(self):
1733 """
1734 Find out the total number of renegotiations.
1735
1736 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001737 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001738 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001740
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001741 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001742 """
1743 Connect to remote host and set up client-side SSL
1744
1745 :param addr: A remote address
1746 :return: What the socket's connect method returns
1747 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001749 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001750
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001751 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001752 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001753 Connect to remote host and set up client-side SSL. Note that if the
1754 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001755
1756 :param addr: A remove address
1757 :return: What the socket's connect_ex method returns
1758 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001759 connect_ex = self._socket.connect_ex
1760 self.set_connect_state()
1761 return connect_ex(addr)
1762
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001763 def accept(self):
1764 """
1765 Accept incoming connection and set up SSL on it
1766
1767 :return: A (conn,addr) pair where conn is a Connection and addr is an
1768 address
1769 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001770 client, addr = self._socket.accept()
1771 conn = Connection(self._context, client)
1772 conn.set_accept_state()
1773 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001774
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001775 def bio_shutdown(self):
1776 """
1777 When using non-socket connections this function signals end of
1778 data on the input for this connection.
1779
1780 :return: None
1781 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001782 if self._from_ssl is None:
1783 raise TypeError("Connection sock was not None")
1784
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001785 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001786
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001787 def shutdown(self):
1788 """
1789 Send closure alert
1790
1791 :return: True if the shutdown completed successfully (i.e. both sides
1792 have sent closure alerts), false otherwise (i.e. you have to
1793 wait for a ZeroReturnError on a recv() method call
1794 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001795 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001796 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001797 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001798 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001799 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001800 else:
1801 return False
1802
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001803 def get_cipher_list(self):
1804 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001805 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001806
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001807 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001808 """
1809 ciphers = []
1810 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001811 result = _lib.SSL_get_cipher_list(self._ssl, i)
1812 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001813 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001814 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001815 return ciphers
1816
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001817 def get_client_ca_list(self):
1818 """
1819 Get CAs whose certificates are suggested for client authentication.
1820
Alex Gaynor62da94d2015-09-05 14:37:34 -04001821 :return: If this is a server connection, a list of X509Names
1822 representing the acceptable CAs as set by
1823 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1824 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1825 connection, the list of such X509Names sent by the server, or an
1826 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001827 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001828 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1829 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001830 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001831 return []
1832
1833 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001834 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1835 name = _lib.sk_X509_NAME_value(ca_names, i)
1836 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001837 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001838
1839 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001840 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001841 result.append(pyname)
1842 return result
1843
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001844 def makefile(self):
1845 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001846 The makefile() method is not implemented, since there is no dup
1847 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001848
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001849 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001850 """
Alex Gaynor83284952015-09-05 10:43:30 -04001851 raise NotImplementedError(
1852 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001853
1854 def get_app_data(self):
1855 """
1856 Get application data
1857
1858 :return: The application data
1859 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001860 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001861
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001862 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001863 """
1864 Set application data
1865
1866 :param data - The application data
1867 :return: None
1868 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001869 self._app_data = data
1870
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001871 def get_shutdown(self):
1872 """
1873 Get shutdown state
1874
Alex Gaynor62da94d2015-09-05 14:37:34 -04001875 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1876 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001877 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001878 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001879
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001880 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001881 """
1882 Set shutdown state
1883
1884 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1885 :return: None
1886 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001887 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001888 raise TypeError("state must be an integer")
1889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001890 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001891
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001892 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001893 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001894 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001895
1896 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001897 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001898 """
kjavc704a2e2015-09-07 12:12:27 +01001899 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001900
1901 def server_random(self):
1902 """
1903 Get a copy of the server hello nonce.
1904
1905 :return: A string representing the state
1906 """
Alex Gaynor93603062016-06-01 20:13:09 -07001907 session = _lib.SSL_get_session(self._ssl)
1908 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001909 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001910 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1911 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001912 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001913 _lib.SSL_get_server_random(self._ssl, outp, length)
1914 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001915
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001916 def client_random(self):
1917 """
1918 Get a copy of the client hello nonce.
1919
1920 :return: A string representing the state
1921 """
Alex Gaynor93603062016-06-01 20:13:09 -07001922 session = _lib.SSL_get_session(self._ssl)
1923 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001924 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001925
1926 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1927 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001928 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001929 _lib.SSL_get_client_random(self._ssl, outp, length)
1930 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001931
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001932 def master_key(self):
1933 """
1934 Get a copy of the master key.
1935
1936 :return: A string representing the state
1937 """
Alex Gaynor93603062016-06-01 20:13:09 -07001938 session = _lib.SSL_get_session(self._ssl)
1939 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001940 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001941
1942 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1943 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001944 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001945 _lib.SSL_SESSION_get_master_key(session, outp, length)
1946 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001947
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001948 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001949 """
1950 See shutdown(2)
1951
1952 :return: What the socket's shutdown() method returns
1953 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001954 return self._socket.shutdown(*args, **kwargs)
1955
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001956 def get_peer_certificate(self):
1957 """
1958 Retrieve the other side's certificate (if any)
1959
1960 :return: The peer's certificate
1961 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001962 cert = _lib.SSL_get_peer_certificate(self._ssl)
1963 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001964 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001965 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001966 return pycert
1967 return None
1968
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001969 def get_peer_cert_chain(self):
1970 """
1971 Retrieve the other side's certificate (if any)
1972
1973 :return: A list of X509 instances giving the peer's certificate chain,
1974 or None if it does not have one.
1975 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001976 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1977 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001978 return None
1979
1980 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001981 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001982 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001983 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001984 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001985 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001986 result.append(pycert)
1987 return result
1988
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001989 def want_read(self):
1990 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001991 Checks if more data has to be read from the transport layer to complete
1992 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001993
1994 :return: True iff more data has to be read
1995 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001996 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001997
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001998 def want_write(self):
1999 """
2000 Checks if there is data to write to the transport layer to complete an
2001 operation.
2002
2003 :return: True iff there is data to write
2004 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002005 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002006
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002007 def set_accept_state(self):
2008 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002009 Set the connection to work in server mode. The handshake will be
2010 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002011
2012 :return: None
2013 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002014 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002015
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016 def set_connect_state(self):
2017 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002018 Set the connection to work in client mode. The handshake will be
2019 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002020
2021 :return: None
2022 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002023 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002024
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025 def get_session(self):
2026 """
2027 Returns the Session currently used.
2028
Alex Gaynor62da94d2015-09-05 14:37:34 -04002029 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
2030 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002031 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002032 session = _lib.SSL_get1_session(self._ssl)
2033 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002034 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002035
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002036 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002037 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002038 return pysession
2039
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002040 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002041 """
2042 Set the session to be used when the TLS/SSL connection is established.
2043
2044 :param session: A Session instance representing the session to use.
2045 :returns: None
2046 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002047 if not isinstance(session, Session):
2048 raise TypeError("session must be a Session instance")
2049
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002050 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002051 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002052 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002053
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002054 def _get_finished_message(self, function):
2055 """
2056 Helper to implement :py:meth:`get_finished` and
2057 :py:meth:`get_peer_finished`.
2058
2059 :param function: Either :py:data:`SSL_get_finished`: or
2060 :py:data:`SSL_get_peer_finished`.
2061
2062 :return: :py:data:`None` if the desired message has not yet been
2063 received, otherwise the contents of the message.
2064 :rtype: :py:class:`bytes` or :py:class:`NoneType`
2065 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002066 # The OpenSSL documentation says nothing about what might happen if the
2067 # count argument given is zero. Specifically, it doesn't say whether
2068 # the output buffer may be NULL in that case or not. Inspection of the
2069 # implementation reveals that it calls memcpy() unconditionally.
2070 # Section 7.1.4, paragraph 1 of the C standard suggests that
2071 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2072 # alone desirable) behavior (though it probably does on just about
2073 # every implementation...)
2074 #
2075 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2076 # one might expect) for the initial call so as to be safe against this
2077 # potentially undefined behavior.
2078 empty = _ffi.new("char[]", 0)
2079 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002080 if size == 0:
2081 # No Finished message so far.
2082 return None
2083
Cory Benfielde62840e2016-11-28 12:17:08 +00002084 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002085 function(self._ssl, buf, size)
2086 return _ffi.buffer(buf, size)[:]
2087
Fedor Brunner5747b932014-03-05 14:22:34 +01002088 def get_finished(self):
2089 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002090 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002091
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002092 :return: The contents of the message or :py:obj:`None` if the TLS
2093 handshake has not yet completed.
2094 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002095 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002096 return self._get_finished_message(_lib.SSL_get_finished)
2097
Fedor Brunner5747b932014-03-05 14:22:34 +01002098 def get_peer_finished(self):
2099 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002100 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002101
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002102 :return: The contents of the message or :py:obj:`None` if the TLS
2103 handshake has not yet completed.
2104 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002105 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002106 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002107
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002108 def get_cipher_name(self):
2109 """
2110 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002111
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002112 :returns: The name of the currently used cipher or :py:obj:`None`
2113 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002114 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002115 """
2116 cipher = _lib.SSL_get_current_cipher(self._ssl)
2117 if cipher == _ffi.NULL:
2118 return None
2119 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002120 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2121 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002122
2123 def get_cipher_bits(self):
2124 """
2125 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002126
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002127 :returns: The number of secret bits of the currently used cipher
2128 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002129 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002130 """
2131 cipher = _lib.SSL_get_current_cipher(self._ssl)
2132 if cipher == _ffi.NULL:
2133 return None
2134 else:
2135 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2136
2137 def get_cipher_version(self):
2138 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002139 Obtain the protocol version of the currently used cipher.
2140
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002141 :returns: The protocol name of the currently used cipher
2142 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002143 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002144 """
2145 cipher = _lib.SSL_get_current_cipher(self._ssl)
2146 if cipher == _ffi.NULL:
2147 return None
2148 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002149 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002150 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002151
Jim Shaverabff1882015-05-27 09:15:55 -04002152 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002153 """
2154 Obtain the protocol version of the current connection.
2155
2156 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002157 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002158 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002159 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002160 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002161 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002162 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002163
Jim Shaver208438c2015-05-28 09:52:38 -04002164 def get_protocol_version(self):
2165 """
2166 Obtain the protocol version of the current connection.
2167
2168 :returns: The TLS version of the current connection, for example
2169 the value for TLS 1 would be 0x769.
2170 :rtype: :py:class:`int`
2171 """
2172 version = _lib.SSL_version(self._ssl)
2173 return version
2174
Cory Benfield10b277f2015-04-13 17:12:42 -04002175 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002176 def get_next_proto_negotiated(self):
2177 """
2178 Get the protocol that was negotiated by NPN.
2179 """
2180 data = _ffi.new("unsigned char **")
2181 data_len = _ffi.new("unsigned int *")
2182
2183 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2184
Cory Benfieldcd010f62014-05-15 19:00:27 +01002185 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002186
Cory Benfield7907e332015-04-13 17:18:25 -04002187 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002188 def set_alpn_protos(self, protos):
2189 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002190 Specify the client's ALPN protocol list.
2191
2192 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002193
2194 :param protos: A list of the protocols to be offered to the server.
2195 This list should be a Python list of bytestrings representing the
2196 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2197 """
2198 # Take the list of protocols and join them together, prefixing them
2199 # with their lengths.
2200 protostr = b''.join(
2201 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2202 )
2203
2204 # Build a C string from the list. We don't need to save this off
2205 # because OpenSSL immediately copies the data out.
2206 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04002207 input_str_len = _ffi.cast("unsigned", len(protostr))
2208 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01002209
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002210 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002211 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002212 """
2213 Get the protocol that was negotiated by ALPN.
2214 """
Cory Benfield12eae892014-06-07 15:42:56 +01002215 data = _ffi.new("unsigned char **")
2216 data_len = _ffi.new("unsigned int *")
2217
2218 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2219
Cory Benfielde8e9c382015-04-11 17:33:48 -04002220 if not data_len:
2221 return b''
2222
Cory Benfield12eae892014-06-07 15:42:56 +01002223 return _ffi.buffer(data[0], data_len[0])[:]
2224
Cory Benfield496652a2017-01-24 11:42:56 +00002225 def request_ocsp(self):
2226 """
2227 Called to request that the server sends stapled OCSP data, if
2228 available. If this is not called on the client side then the server
2229 will not send OCSP data. Should be used in conjunction with
2230 :meth:`Context.set_ocsp_client_callback`.
2231 """
2232 rc = _lib.SSL_set_tlsext_status_type(
2233 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2234 )
2235 _openssl_assert(rc == 1)
2236
Cory Benfield12eae892014-06-07 15:42:56 +01002237
Alex Gaynor10d30832017-06-29 15:31:39 -07002238ConnectionType = deprecated(
2239 Connection, __name__,
2240 "ConnectionType has been deprecated, use Connection instead",
2241 DeprecationWarning
2242)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002243
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002244# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2245# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002246_lib.SSL_library_init()