blob: b571a5e11255287b05658f587d6c01d8cd15fe4b [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
Cory Benfield63759dc2015-04-12 08:57:03 -040011from six import binary_type as _binary_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -080012from six import integer_types as integer_types
Cory Benfieldcd010f62014-05-15 19:00:27 +010013from six import int2byte, 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
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050062
63OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
64OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080065
Alex Gaynorbf012872016-06-04 13:18:39 -070066MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080067
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050068OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
Akihiro Yamazakie64d80c2015-09-06 00:16:57 +090069OP_SINGLE_ECDH_USE = _lib.SSL_OP_SINGLE_ECDH_USE
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050070OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
71OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
72OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040073OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = (
74 _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
75)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050076OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
77OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040078OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050079OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
80OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
81OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
82OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
83OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
84OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
85OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
86OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
87OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
Alex Gaynor62da94d2015-09-05 14:37:34 -040088OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = (
89 _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
90)
Alex Gaynorbf012872016-06-04 13:18:39 -070091OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080092
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050093OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
94OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
Alex Gaynor5bb2bd12016-07-03 10:48:32 -040095OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080096
Alex Gaynorc4889812015-09-04 08:43:17 -040097OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080098
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050099VERIFY_PEER = _lib.SSL_VERIFY_PEER
100VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
101VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
102VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -0800103
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500104SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
105SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
106SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
107SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
108SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
109SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
110SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
111SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800112
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500113SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
114SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
115SSL_ST_MASK = _lib.SSL_ST_MASK
Alex Gaynor5af32d02016-09-24 01:52:21 -0400116if _lib.Cryptography_HAS_SSL_ST:
117 SSL_ST_INIT = _lib.SSL_ST_INIT
118 SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
119 SSL_ST_OK = _lib.SSL_ST_OK
120 SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800121
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500122SSL_CB_LOOP = _lib.SSL_CB_LOOP
123SSL_CB_EXIT = _lib.SSL_CB_EXIT
124SSL_CB_READ = _lib.SSL_CB_READ
125SSL_CB_WRITE = _lib.SSL_CB_WRITE
126SSL_CB_ALERT = _lib.SSL_CB_ALERT
127SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
128SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
129SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
130SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
131SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
132SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
133SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
134SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800135
Paul Kehrer55fb3412017-06-29 18:44:08 -0500136# Taken from https://golang.org/src/crypto/x509/root_linux.go
137_CERTIFICATE_FILE_LOCATIONS = [
138 "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
139 "/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
140 "/etc/ssl/ca-bundle.pem", # OpenSUSE
141 "/etc/pki/tls/cacert.pem", # OpenELEC
142 "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
143]
144
145_CERTIFICATE_PATH_LOCATIONS = [
146 "/etc/ssl/certs", # SLES10/SLES11
147]
148
149_CRYPTOGRAPHY_MANYLINUX1_CA_DIR = "/opt/pyca/cryptography/openssl/certs"
150_CRYPTOGRAPHY_MANYLINUX1_CA_FILE = "/opt/pyca/cryptography/openssl/cert.pem"
151
Alex Gaynor83284952015-09-05 10:43:30 -0400152
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500153class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500154 """
155 An error occurred in an `OpenSSL.SSL` API.
156 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500157
158
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500159_raise_current_error = partial(_exception_from_error_queue, Error)
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100160_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500161
162
163class WantReadError(Error):
164 pass
165
166
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500167class WantWriteError(Error):
168 pass
169
170
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500171class WantX509LookupError(Error):
172 pass
173
174
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500175class ZeroReturnError(Error):
176 pass
177
178
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500179class SysCallError(Error):
180 pass
181
182
Cory Benfield0ea76e72015-03-22 09:05:28 +0000183class _CallbackExceptionHelper(object):
184 """
185 A base class for wrapper classes that allow for intelligent exception
186 handling in OpenSSL callbacks.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500187
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400188 :ivar list _problems: Any exceptions that occurred while executing in a
189 context where they could not be raised in the normal way. Typically
190 this is because OpenSSL has called into some Python code and requires a
191 return value. The exceptions are saved to be raised later when it is
192 possible to do so.
Cory Benfield0ea76e72015-03-22 09:05:28 +0000193 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400194
Jean-Paul Calderone09540d72015-03-22 19:37:20 -0400195 def __init__(self):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800196 self._problems = []
197
Cory Benfield0ea76e72015-03-22 09:05:28 +0000198 def raise_if_problem(self):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400199 """
200 Raise an exception from the OpenSSL error queue or that was previously
201 captured whe running a callback.
202 """
Cory Benfield0ea76e72015-03-22 09:05:28 +0000203 if self._problems:
204 try:
205 _raise_current_error()
206 except Error:
207 pass
208 raise self._problems.pop(0)
209
210
211class _VerifyHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400212 """
213 Wrap a callback such that it can be used as a certificate verification
214 callback.
215 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400216
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800217 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400218 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800219
220 @wraps(callback)
221 def wrapper(ok, store_ctx):
222 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500223 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
224 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
225 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800226
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400227 index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
228 ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
229 connection = Connection._reverse_mapping[ssl]
230
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800231 try:
Alex Gaynor62da94d2015-09-05 14:37:34 -0400232 result = callback(
233 connection, cert, error_number, error_depth, ok
234 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800235 except Exception as e:
236 self._problems.append(e)
237 return 0
238 else:
239 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500240 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800241 return 1
242 else:
243 return 0
244
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500245 self.callback = _ffi.callback(
246 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800247
248
Cory Benfield0ea76e72015-03-22 09:05:28 +0000249class _NpnAdvertiseHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400250 """
251 Wrap a callback such that it can be used as an NPN advertisement callback.
252 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400253
Cory Benfield0ea76e72015-03-22 09:05:28 +0000254 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400255 _CallbackExceptionHelper.__init__(self)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800256
Cory Benfield0ea76e72015-03-22 09:05:28 +0000257 @wraps(callback)
258 def wrapper(ssl, out, outlen, arg):
259 try:
260 conn = Connection._reverse_mapping[ssl]
261 protos = callback(conn)
262
263 # Join the protocols into a Python bytestring, length-prefixing
264 # each element.
265 protostr = b''.join(
266 chain.from_iterable((int2byte(len(p)), p) for p in protos)
267 )
268
269 # Save our callback arguments on the connection object. This is
270 # done to make sure that they don't get freed before OpenSSL
271 # uses them. Then, return them appropriately in the output
272 # parameters.
273 conn._npn_advertise_callback_args = [
274 _ffi.new("unsigned int *", len(protostr)),
275 _ffi.new("unsigned char[]", protostr),
276 ]
277 outlen[0] = conn._npn_advertise_callback_args[0][0]
278 out[0] = conn._npn_advertise_callback_args[1]
279 return 0
280 except Exception as e:
281 self._problems.append(e)
282 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
283
284 self.callback = _ffi.callback(
285 "int (*)(SSL *, const unsigned char **, unsigned int *, void *)",
286 wrapper
287 )
288
289
290class _NpnSelectHelper(_CallbackExceptionHelper):
Jean-Paul Calderone1b172982015-03-22 19:37:11 -0400291 """
292 Wrap a callback such that it can be used as an NPN selection callback.
293 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400294
Cory Benfield0ea76e72015-03-22 09:05:28 +0000295 def __init__(self, callback):
Jean-Paul Calderone837f4032015-03-22 17:38:28 -0400296 _CallbackExceptionHelper.__init__(self)
Cory Benfield0ea76e72015-03-22 09:05:28 +0000297
298 @wraps(callback)
299 def wrapper(ssl, out, outlen, in_, inlen, arg):
300 try:
301 conn = Connection._reverse_mapping[ssl]
302
303 # The string passed to us is actually made up of multiple
304 # length-prefixed bytestrings. We need to split that into a
305 # list.
306 instr = _ffi.buffer(in_, inlen)[:]
307 protolist = []
308 while instr:
309 l = indexbytes(instr, 0)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400310 proto = instr[1:l + 1]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000311 protolist.append(proto)
Alex Gaynorca87ff62015-09-04 23:31:03 -0400312 instr = instr[l + 1:]
Cory Benfield0ea76e72015-03-22 09:05:28 +0000313
314 # Call the callback
315 outstr = callback(conn, protolist)
316
317 # Save our callback arguments on the connection object. This is
318 # done to make sure that they don't get freed before OpenSSL
319 # uses them. Then, return them appropriately in the output
320 # parameters.
321 conn._npn_select_callback_args = [
322 _ffi.new("unsigned char *", len(outstr)),
323 _ffi.new("unsigned char[]", outstr),
324 ]
325 outlen[0] = conn._npn_select_callback_args[0][0]
326 out[0] = conn._npn_select_callback_args[1]
327 return 0
328 except Exception as e:
329 self._problems.append(e)
330 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
331
332 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400333 ("int (*)(SSL *, unsigned char **, unsigned char *, "
334 "const unsigned char *, unsigned int, void *)"),
Cory Benfield0ea76e72015-03-22 09:05:28 +0000335 wrapper
336 )
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800337
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800338
Cory Benfield9da5ffb2015-04-13 17:20:14 -0400339class _ALPNSelectHelper(_CallbackExceptionHelper):
Cory Benfieldf1177e72015-04-12 09:11:49 -0400340 """
341 Wrap a callback such that it can be used as an ALPN selection callback.
342 """
Alex Gaynor62da94d2015-09-05 14:37:34 -0400343
Cory Benfieldf1177e72015-04-12 09:11:49 -0400344 def __init__(self, callback):
345 _CallbackExceptionHelper.__init__(self)
346
347 @wraps(callback)
348 def wrapper(ssl, out, outlen, in_, inlen, arg):
349 try:
350 conn = Connection._reverse_mapping[ssl]
351
352 # The string passed to us is made up of multiple
353 # length-prefixed bytestrings. We need to split that into a
354 # list.
355 instr = _ffi.buffer(in_, inlen)[:]
356 protolist = []
357 while instr:
Cory Benfield93134db2015-04-13 17:22:13 -0400358 encoded_len = indexbytes(instr, 0)
359 proto = instr[1:encoded_len + 1]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400360 protolist.append(proto)
Cory Benfield93134db2015-04-13 17:22:13 -0400361 instr = instr[encoded_len + 1:]
Cory Benfieldf1177e72015-04-12 09:11:49 -0400362
363 # Call the callback
364 outstr = callback(conn, protolist)
365
366 if not isinstance(outstr, _binary_type):
367 raise TypeError("ALPN callback must return a bytestring.")
368
369 # Save our callback arguments on the connection object to make
370 # sure that they don't get freed before OpenSSL can use them.
371 # Then, return them in the appropriate output parameters.
372 conn._alpn_select_callback_args = [
373 _ffi.new("unsigned char *", len(outstr)),
374 _ffi.new("unsigned char[]", outstr),
375 ]
376 outlen[0] = conn._alpn_select_callback_args[0][0]
377 out[0] = conn._alpn_select_callback_args[1]
378 return 0
379 except Exception as e:
380 self._problems.append(e)
381 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
382
383 self.callback = _ffi.callback(
Alex Gaynor62da94d2015-09-05 14:37:34 -0400384 ("int (*)(SSL *, unsigned char **, unsigned char *, "
385 "const unsigned char *, unsigned int, void *)"),
Cory Benfieldf1177e72015-04-12 09:11:49 -0400386 wrapper
387 )
388
389
Cory Benfield496652a2017-01-24 11:42:56 +0000390class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
391 """
392 Wrap a callback such that it can be used as an OCSP callback for the server
393 side.
394
395 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
396 ways. For servers, that callback is expected to retrieve some OCSP data and
397 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
398 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
399 is expected to check the OCSP data, and returns a negative value on error,
400 0 if the response is not acceptable, or positive if it is. These are
401 mutually exclusive return code behaviours, and they mean that we need two
402 helpers so that we always return an appropriate error code if the user's
403 code throws an exception.
404
405 Given that we have to have two helpers anyway, these helpers are a bit more
406 helpery than most: specifically, they hide a few more of the OpenSSL
407 functions so that the user has an easier time writing these callbacks.
408
409 This helper implements the server side.
410 """
411
412 def __init__(self, callback):
413 _CallbackExceptionHelper.__init__(self)
414
415 @wraps(callback)
416 def wrapper(ssl, cdata):
417 try:
418 conn = Connection._reverse_mapping[ssl]
419
420 # Extract the data if any was provided.
421 if cdata != _ffi.NULL:
422 data = _ffi.from_handle(cdata)
423 else:
424 data = None
425
426 # Call the callback.
427 ocsp_data = callback(conn, data)
428
429 if not isinstance(ocsp_data, _binary_type):
430 raise TypeError("OCSP callback must return a bytestring.")
431
432 # If the OCSP data was provided, we will pass it to OpenSSL.
433 # However, we have an early exit here: if no OCSP data was
434 # provided we will just exit out and tell OpenSSL that there
435 # is nothing to do.
436 if not ocsp_data:
437 return 3 # SSL_TLSEXT_ERR_NOACK
438
439 # Pass the data to OpenSSL. Insanely, OpenSSL doesn't make a
440 # private copy of this data, so we need to keep it alive, but
441 # it *does* want to free it itself if it gets replaced. This
442 # somewhat bonkers behaviour means we need to use
443 # OPENSSL_malloc directly, which is a pain in the butt to work
444 # with. It's ok for us to "leak" the memory here because
445 # OpenSSL now owns it and will free it.
446 ocsp_data_length = len(ocsp_data)
447 data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
448 _ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
449
450 _lib.SSL_set_tlsext_status_ocsp_resp(
451 ssl, data_ptr, ocsp_data_length
452 )
453
454 return 0
455 except Exception as e:
456 self._problems.append(e)
457 return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
458
459 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
460
461
462class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
463 """
464 Wrap a callback such that it can be used as an OCSP callback for the client
465 side.
466
467 Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
468 ways. For servers, that callback is expected to retrieve some OCSP data and
469 hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
470 SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
471 is expected to check the OCSP data, and returns a negative value on error,
472 0 if the response is not acceptable, or positive if it is. These are
473 mutually exclusive return code behaviours, and they mean that we need two
474 helpers so that we always return an appropriate error code if the user's
475 code throws an exception.
476
477 Given that we have to have two helpers anyway, these helpers are a bit more
478 helpery than most: specifically, they hide a few more of the OpenSSL
479 functions so that the user has an easier time writing these callbacks.
480
481 This helper implements the client side.
482 """
483
484 def __init__(self, callback):
485 _CallbackExceptionHelper.__init__(self)
486
487 @wraps(callback)
488 def wrapper(ssl, cdata):
489 try:
490 conn = Connection._reverse_mapping[ssl]
491
492 # Extract the data if any was provided.
493 if cdata != _ffi.NULL:
494 data = _ffi.from_handle(cdata)
495 else:
496 data = None
497
498 # Get the OCSP data.
499 ocsp_ptr = _ffi.new("unsigned char **")
500 ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
501 if ocsp_len < 0:
502 # No OCSP data.
503 ocsp_data = b''
504 else:
505 # Copy the OCSP data, then pass it to the callback.
506 ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
507
508 valid = callback(conn, ocsp_data, data)
509
510 # Return 1 on success or 0 on error.
511 return int(bool(valid))
512
513 except Exception as e:
514 self._problems.append(e)
515 # Return negative value if an exception is hit.
516 return -1
517
518 self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
519
520
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800521def _asFileDescriptor(obj):
522 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800523 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800524 meth = getattr(obj, "fileno", None)
525 if meth is not None:
526 obj = meth()
527
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800528 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800529 fd = obj
530
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800531 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800532 raise TypeError("argument must be an int, or have a fileno() method.")
533 elif fd < 0:
534 raise ValueError(
535 "file descriptor cannot be a negative integer (%i)" % (fd,))
536
537 return fd
538
539
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800540def SSLeay_version(type):
541 """
542 Return a string describing the version of OpenSSL in use.
543
544 :param type: One of the SSLEAY_ constants defined in this module.
545 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500546 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800547
548
Cory Benfieldef404df2016-03-29 15:32:48 +0100549def _make_requires(flag, error):
Cory Benfielda876cef2015-04-13 17:29:12 -0400550 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100551 Builds a decorator that ensures that functions that rely on OpenSSL
552 functions that are not present in this build raise NotImplementedError,
553 rather than AttributeError coming out of cryptography.
554
555 :param flag: A cryptography flag that guards the functions, e.g.
556 ``Cryptography_HAS_NEXTPROTONEG``.
557 :param error: The string to be used in the exception if the flag is false.
Cory Benfielda876cef2015-04-13 17:29:12 -0400558 """
Cory Benfieldef404df2016-03-29 15:32:48 +0100559 def _requires_decorator(func):
560 if not flag:
561 @wraps(func)
562 def explode(*args, **kwargs):
563 raise NotImplementedError(error)
564 return explode
565 else:
566 return func
Cory Benfield10b277f2015-04-13 17:12:42 -0400567
Cory Benfieldef404df2016-03-29 15:32:48 +0100568 return _requires_decorator
Cory Benfield10b277f2015-04-13 17:12:42 -0400569
570
Cory Benfieldef404df2016-03-29 15:32:48 +0100571_requires_npn = _make_requires(
572 _lib.Cryptography_HAS_NEXTPROTONEG, "NPN not available"
573)
Cory Benfield7907e332015-04-13 17:18:25 -0400574
575
Cory Benfieldef404df2016-03-29 15:32:48 +0100576_requires_alpn = _make_requires(
577 _lib.Cryptography_HAS_ALPN, "ALPN not available"
578)
Cory Benfielde6f35882016-03-29 11:21:04 +0100579
Cory Benfielde6f35882016-03-29 11:21:04 +0100580
Cory Benfieldef404df2016-03-29 15:32:48 +0100581_requires_sni = _make_requires(
582 _lib.Cryptography_HAS_TLSEXT_HOSTNAME, "SNI not available"
583)
Cory Benfielde6f35882016-03-29 11:21:04 +0100584
585
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800586class Session(object):
587 pass
588
589
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800590class Context(object):
591 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +0100592 :class:`OpenSSL.SSL.Context` instances define the parameters for setting
Alex Gaynor62da94d2015-09-05 14:37:34 -0400593 up new SSL connections.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800594 """
595 _methods = {
Andrew Dunhamec84a0a2014-02-24 12:41:37 -0800596 SSLv2_METHOD: "SSLv2_method",
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500597 SSLv3_METHOD: "SSLv3_method",
598 SSLv23_METHOD: "SSLv23_method",
599 TLSv1_METHOD: "TLSv1_method",
600 TLSv1_1_METHOD: "TLSv1_1_method",
601 TLSv1_2_METHOD: "TLSv1_2_method",
Alex Gaynorc4889812015-09-04 08:43:17 -0400602 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500603 _methods = dict(
604 (identifier, getattr(_lib, name))
605 for (identifier, name) in _methods.items()
606 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800607
608 def __init__(self, method):
609 """
610 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
611 TLSv1_METHOD.
612 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500613 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800614 raise TypeError("method must be an integer")
615
616 try:
617 method_func = self._methods[method]
618 except KeyError:
619 raise ValueError("No such protocol")
620
621 method_obj = method_func()
Alex Gaynora829e902016-06-04 18:16:01 -0700622 _openssl_assert(method_obj != _ffi.NULL)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800623
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500624 context = _lib.SSL_CTX_new(method_obj)
Alex Gaynora829e902016-06-04 18:16:01 -0700625 _openssl_assert(context != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500626 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800627
Paul Kehrer6c6bf862016-12-19 06:03:48 -0600628 # If SSL_CTX_set_ecdh_auto is available then set it so the ECDH curve
629 # will be auto-selected. This function was added in 1.0.2 and made a
630 # noop in 1.1.0+ (where it is set automatically).
631 try:
632 res = _lib.SSL_CTX_set_ecdh_auto(context, 1)
633 _openssl_assert(res == 1)
634 except AttributeError:
635 pass
636
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800637 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800638 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800639 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800640 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800641 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800642 self._verify_callback = None
643 self._info_callback = None
644 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800645 self._app_data = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000646 self._npn_advertise_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100647 self._npn_advertise_callback = None
Cory Benfield0ea76e72015-03-22 09:05:28 +0000648 self._npn_select_helper = None
Cory Benfield84a121e2014-03-31 20:30:25 +0100649 self._npn_select_callback = None
Cory Benfieldf1177e72015-04-12 09:11:49 -0400650 self._alpn_select_helper = None
Cory Benfield12eae892014-06-07 15:42:56 +0100651 self._alpn_select_callback = None
Cory Benfield496652a2017-01-24 11:42:56 +0000652 self._ocsp_helper = None
653 self._ocsp_callback = None
654 self._ocsp_data = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800655
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800656 # SSL_CTX_set_app_data(self->ctx, self);
657 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
658 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
659 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500660 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800662 def load_verify_locations(self, cafile, capath=None):
663 """
664 Let SSL know where we can find trusted certificates for the certificate
665 chain
666
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400667 :param cafile: In which file we can find the certificates (``bytes`` or
668 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800669 :param capath: In which directory we can find the certificates
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400670 (``bytes`` or ``unicode``).
671
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800672 :return: None
673 """
674 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500675 cafile = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400676 else:
677 cafile = _path_string(cafile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800678
679 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500680 capath = _ffi.NULL
Jean-Paul Calderone55f9e882015-04-12 09:31:03 -0400681 else:
682 capath = _path_string(capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800683
Alex Gaynor62da94d2015-09-05 14:37:34 -0400684 load_result = _lib.SSL_CTX_load_verify_locations(
685 self._context, cafile, capath
686 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800687 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500688 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800689
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690 def _wrap_callback(self, callback):
691 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800692 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800693 return callback(size, verify, self._passphrase_userdata)
694 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800695 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800696
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800697 def set_passwd_cb(self, callback, userdata=None):
698 """
699 Set the passphrase callback
700
701 :param callback: The Python callback to use
702 :param userdata: (optional) A Python object which will be given as
703 argument to the callback
704 :return: None
705 """
706 if not callable(callback):
707 raise TypeError("callback must be callable")
708
709 self._passphrase_helper = self._wrap_callback(callback)
710 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500711 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712 self._context, self._passphrase_callback)
713 self._passphrase_userdata = userdata
714
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800715 def set_default_verify_paths(self):
716 """
717 Use the platform-specific CA certificate locations
718
719 :return: None
720 """
Paul Kehrer55fb3412017-06-29 18:44:08 -0500721 # SSL_CTX_set_default_verify_paths will attempt to load certs from
722 # both a cafile and capath that are set at compile time. However,
723 # it will first check environment variables and, if present, load
724 # those paths instead
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500725 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Alex Gaynor09f19f52016-07-03 09:54:09 -0400726 _openssl_assert(set_result == 1)
Paul Kehrer55fb3412017-06-29 18:44:08 -0500727 # After attempting to set default_verify_paths we need to know whether
728 # to go down the fallback path.
729 # First we'll check to see if any env vars have been set. If so,
730 # we won't try to do anything else because the user has set the path
731 # themselves.
732 dir_env_var = _ffi.string(
733 _lib.X509_get_default_cert_dir_env()
734 ).decode("ascii")
735 file_env_var = _ffi.string(
736 _lib.X509_get_default_cert_file_env()
737 ).decode("ascii")
738 if not self._check_env_vars_set(dir_env_var, file_env_var):
739 default_dir = _ffi.string(_lib.X509_get_default_cert_dir())
740 default_file = _ffi.string(_lib.X509_get_default_cert_file())
741 # Now we check to see if the default_dir and default_file are set
742 # to the exact values we use in our manylinux1 builds. If they are
743 # then we know to load the fallbacks
744 if (
745 default_dir == _CRYPTOGRAPHY_MANYLINUX1_CA_DIR and
746 default_file == _CRYPTOGRAPHY_MANYLINUX1_CA_FILE
747 ):
748 # This is manylinux1, let's load our fallback paths
749 self._fallback_default_verify_paths(
750 _CERTIFICATE_FILE_LOCATIONS,
751 _CERTIFICATE_PATH_LOCATIONS
752 )
753
754 def _check_env_vars_set(self, dir_env_var, file_env_var):
755 """
756 Check to see if the default cert dir/file environment vars are present.
757
758 :return: bool
759 """
760 return (
761 os.environ.get(file_env_var) is not None or
762 os.environ.get(dir_env_var) is not None
763 )
764
765 def _fallback_default_verify_paths(self, file_path, dir_path):
766 """
767 Default verify paths are based on the compiled version of OpenSSL.
768 However, when pyca/cryptography is compiled as a manylinux1 wheel
769 that compiled location can potentially be wrong. So, like Go, we
770 will try a predefined set of paths and attempt to load roots
771 from there.
772
773 :return: None
774 """
775 for cafile in file_path:
776 if os.path.isfile(cafile):
777 self.load_verify_locations(cafile)
778 break
779
780 for capath in dir_path:
781 if os.path.isdir(capath):
782 self.load_verify_locations(None, capath)
783 break
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800784
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800785 def use_certificate_chain_file(self, certfile):
786 """
787 Load a certificate chain from a file
788
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400789 :param certfile: The name of the certificate chain file (``bytes`` or
790 ``unicode``).
791
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800792 :return: None
793 """
Jean-Paul Calderoneaac43a32015-04-12 09:51:21 -0400794 certfile = _path_string(certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800795
Alex Gaynor62da94d2015-09-05 14:37:34 -0400796 result = _lib.SSL_CTX_use_certificate_chain_file(
797 self._context, certfile
798 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800799 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500800 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800801
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800802 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800803 """
804 Load a certificate from a file
805
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400806 :param certfile: The name of the certificate file (``bytes`` or
807 ``unicode``).
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800808 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400809
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800810 :return: None
811 """
Jean-Paul Calderoned57a7b62015-04-12 09:57:36 -0400812 certfile = _path_string(certfile)
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500813 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800814 raise TypeError("filetype must be an integer")
815
Alex Gaynor62da94d2015-09-05 14:37:34 -0400816 use_result = _lib.SSL_CTX_use_certificate_file(
817 self._context, certfile, filetype
818 )
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800819 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500820 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800821
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800822 def use_certificate(self, cert):
823 """
824 Load a certificate from a X509 object
825
826 :param cert: The X509 object
827 :return: None
828 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800829 if not isinstance(cert, X509):
830 raise TypeError("cert must be an X509 instance")
831
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500832 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800833 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500834 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800835
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800836 def add_extra_chain_cert(self, certobj):
837 """
838 Add certificate to chain
839
840 :param certobj: The X509 certificate object to add to the chain
841 :return: None
842 """
843 if not isinstance(certobj, X509):
844 raise TypeError("certobj must be an X509 instance")
845
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500846 copy = _lib.X509_dup(certobj._x509)
847 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800848 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500849 # TODO: This is untested.
850 _lib.X509_free(copy)
851 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800852
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800853 def _raise_passphrase_exception(self):
Greg Bowser36eb2de2017-01-24 11:38:55 -0500854 if self._passphrase_helper is not None:
855 self._passphrase_helper.raise_if_problem(Error)
856
857 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800858
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400859 def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800860 """
861 Load a private key from a file
862
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400863 :param keyfile: The name of the key file (``bytes`` or ``unicode``)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800864 :param filetype: (optional) The encoding of the file, default is PEM
Jean-Paul Calderoneb6f8a792015-04-13 10:10:06 -0400865
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800866 :return: None
867 """
Jean-Paul Calderone69a4e5b2015-04-12 10:04:28 -0400868 keyfile = _path_string(keyfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800869
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -0400870 if filetype is _UNSPECIFIED:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800871 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500872 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873 raise TypeError("filetype must be an integer")
874
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500875 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800876 self._context, keyfile, filetype)
877 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800878 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800879
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800880 def use_privatekey(self, pkey):
881 """
882 Load a private key from a PKey object
883
884 :param pkey: The PKey object
885 :return: None
886 """
887 if not isinstance(pkey, PKey):
888 raise TypeError("pkey must be a PKey instance")
889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500890 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800891 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800892 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800893
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800894 def check_privatekey(self):
895 """
896 Check that the private key and certificate match up
897
898 :return: None (raises an exception if something's wrong)
899 """
Jean-Paul Calderonea0344922014-12-11 14:02:31 -0500900 if not _lib.SSL_CTX_check_private_key(self._context):
901 _raise_current_error()
902
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800903 def load_client_ca(self, cafile):
904 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100905 Load the trusted certificates that will be sent to the client. Does
906 not actually imply any of the certificates are trusted; that must be
Alex Gaynor62da94d2015-09-05 14:37:34 -0400907 configured separately.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100909 :param bytes cafile: The path to a certificates file in PEM format.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800910 :return: None
911 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100912 ca_list = _lib.SSL_load_client_CA_file(
913 _text_to_bytes_and_warn("cafile", cafile)
914 )
915 _openssl_assert(ca_list != _ffi.NULL)
916 # SSL_CTX_set_client_CA_list doesn't return anything.
917 _lib.SSL_CTX_set_client_CA_list(self._context, ca_list)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800918
919 def set_session_id(self, buf):
920 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100921 Set the session id to *buf* within which a session can be reused for
922 this Context object. This is needed when doing session resumption,
923 because there is no way for a stored session to know which Context
924 object it is associated with.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800925
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100926 :param bytes buf: The session id.
927
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800928 :returns: None
929 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +0100930 buf = _text_to_bytes_and_warn("buf", buf)
931 _openssl_assert(
932 _lib.SSL_CTX_set_session_id_context(
933 self._context,
934 buf,
935 len(buf),
936 ) == 1
937 )
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800938
939 def set_session_cache_mode(self, mode):
940 """
941 Enable/disable session caching and specify the mode used.
942
943 :param mode: One or more of the SESS_CACHE_* flags (combine using
944 bitwise or)
945 :returns: The previously set caching mode.
946 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500947 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800948 raise TypeError("mode must be an integer")
949
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500950 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800952 def get_session_cache_mode(self):
953 """
954 :returns: The currently used cache mode.
955 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500956 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800957
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800958 def set_verify(self, mode, callback):
959 """
960 Set the verify mode and verify callback
961
962 :param mode: The verify mode, this is either VERIFY_NONE or
963 VERIFY_PEER combined with possible other flags
964 :param callback: The Python callback to use
965 :return: None
966
967 See SSL_CTX_set_verify(3SSL) for further details.
968 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500969 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800970 raise TypeError("mode must be an integer")
971
972 if not callable(callback):
973 raise TypeError("callback must be callable")
974
Jean-Paul Calderone6a8cd112014-04-02 21:09:08 -0400975 self._verify_helper = _VerifyHelper(callback)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800976 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500977 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800978
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800979 def set_verify_depth(self, depth):
980 """
981 Set the verify depth
982
983 :param depth: An integer specifying the verify depth
984 :return: None
985 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500986 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800987 raise TypeError("depth must be an integer")
988
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500989 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800990
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800991 def get_verify_mode(self):
992 """
993 Get the verify mode
994
995 :return: The verify mode
996 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500997 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800998
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800999 def get_verify_depth(self):
1000 """
1001 Get the verify depth
1002
1003 :return: The verify depth
1004 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001005 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001006
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001007 def load_tmp_dh(self, dhfile):
1008 """
1009 Load parameters for Ephemeral Diffie-Hellman
1010
Jean-Paul Calderone4e0c43f2015-04-13 10:15:17 -04001011 :param dhfile: The file to load EDH parameters from (``bytes`` or
1012 ``unicode``).
1013
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001014 :return: None
1015 """
Jean-Paul Calderone9e1c1dd2015-04-12 10:13:13 -04001016 dhfile = _path_string(dhfile)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001017
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001018 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001019 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001020 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001021 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001022
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001023 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
1024 dh = _ffi.gc(dh, _lib.DH_free)
1025 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001026
Jean-Paul Calderone3e4e3352014-04-19 09:28:28 -04001027 def set_tmp_ecdh(self, curve):
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001028 """
Andy Lutomirski76a61332014-03-12 15:02:56 -07001029 Select a curve to use for ECDHE key exchange.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001030
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001031 :param curve: A curve object to use as returned by either
1032 :py:meth:`OpenSSL.crypto.get_elliptic_curve` or
1033 :py:meth:`OpenSSL.crypto.get_elliptic_curves`.
Andy Lutomirskif05a2732014-03-13 17:22:25 -07001034
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001035 :return: None
1036 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -04001037 _lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY())
Alex Gaynor7b8d57a2014-01-17 12:08:54 -06001038
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001039 def set_cipher_list(self, cipher_list):
1040 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001041 Set the list of ciphers to be used in this context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001042
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001043 See the OpenSSL manual for more information (e.g.
1044 :manpage:`ciphers(1)`).
1045
1046 :param bytes cipher_list: An OpenSSL cipher string.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001047 :return: None
1048 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001049 cipher_list = _text_to_bytes_and_warn("cipher_list", cipher_list)
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05001050
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001051 if not isinstance(cipher_list, bytes):
Hynek Schlawacka7a63af2016-03-11 12:05:26 +01001052 raise TypeError("cipher_list must be a byte string.")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001053
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001054 _openssl_assert(
Hynek Schlawack22a4b662016-03-11 14:59:39 +01001055 _lib.SSL_CTX_set_cipher_list(self._context, cipher_list) == 1
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001056 )
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001057
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001058 def set_client_ca_list(self, certificate_authorities):
1059 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001060 Set the list of preferred client certificate signers for this server
1061 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001062
Alex Gaynor62da94d2015-09-05 14:37:34 -04001063 This list of certificate authorities will be sent to the client when
1064 the server requests a client certificate.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001065
1066 :param certificate_authorities: a sequence of X509Names.
1067 :return: None
1068 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001069 name_stack = _lib.sk_X509_NAME_new_null()
Alex Gaynora829e902016-06-04 18:16:01 -07001070 _openssl_assert(name_stack != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001071
1072 try:
1073 for ca_name in certificate_authorities:
1074 if not isinstance(ca_name, X509Name):
1075 raise TypeError(
Alex Gaynor62da94d2015-09-05 14:37:34 -04001076 "client CAs must be X509Name objects, not %s "
1077 "objects" % (
1078 type(ca_name).__name__,
1079 )
1080 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 copy = _lib.X509_NAME_dup(ca_name._name)
Alex Gaynora829e902016-06-04 18:16:01 -07001082 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001083 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001084 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001086 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001087 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001089 raise
1090
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001091 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001092
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001093 def add_client_ca(self, certificate_authority):
1094 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001095 Add the CA certificate to the list of preferred signers for this
1096 context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001097
1098 The list of certificate authorities will be sent to the client when the
1099 server requests a client certificate.
1100
1101 :param certificate_authority: certificate authority's X509 certificate.
1102 :return: None
1103 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001104 if not isinstance(certificate_authority, X509):
1105 raise TypeError("certificate_authority must be an X509 instance")
1106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001108 self._context, certificate_authority._x509)
Alex Gaynor09f19f52016-07-03 09:54:09 -04001109 _openssl_assert(add_result == 1)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001110
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001111 def set_timeout(self, timeout):
1112 """
1113 Set session timeout
1114
1115 :param timeout: The timeout in seconds
1116 :return: The previous session timeout
1117 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001118 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001119 raise TypeError("timeout must be an integer")
1120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001121 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001122
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001123 def get_timeout(self):
1124 """
1125 Get the session timeout
1126
1127 :return: The session timeout
1128 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001129 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001130
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001131 def set_info_callback(self, callback):
1132 """
1133 Set the info callback
1134
1135 :param callback: The Python callback to use
1136 :return: None
1137 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001138 @wraps(callback)
1139 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -05001140 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 self._info_callback = _ffi.callback(
1142 "void (*)(const SSL *, int, int)", wrapper)
1143 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001144
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001145 def get_app_data(self):
1146 """
1147 Get the application data (supplied via set_app_data())
1148
1149 :return: The application data
1150 """
1151 return self._app_data
1152
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001153 def set_app_data(self, data):
1154 """
1155 Set the application data (will be returned from get_app_data())
1156
1157 :param data: Any Python object
1158 :return: None
1159 """
1160 self._app_data = data
1161
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001162 def get_cert_store(self):
1163 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001164 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001165
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001166 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001167 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 store = _lib.SSL_CTX_get_cert_store(self._context)
1169 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001170 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001171 return None
1172
1173 pystore = X509Store.__new__(X509Store)
1174 pystore._store = store
1175 return pystore
1176
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001177 def set_options(self, options):
1178 """
1179 Add options. Options set before are not cleared!
1180
1181 :param options: The options to add.
1182 :return: The new option bitmask.
1183 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001184 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001185 raise TypeError("options must be an integer")
1186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001187 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001188
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001189 def set_mode(self, mode):
1190 """
1191 Add modes via bitmask. Modes set before are not cleared!
1192
1193 :param mode: The mode to add.
1194 :return: The new mode bitmask.
1195 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001196 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001197 raise TypeError("mode must be an integer")
1198
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001199 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001200
Cory Benfielde6f35882016-03-29 11:21:04 +01001201 @_requires_sni
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001202 def set_tlsext_servername_callback(self, callback):
1203 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001204 Specify a callback function to be called when clients specify a server
1205 name.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001206
1207 :param callback: The callback function. It will be invoked with one
1208 argument, the Connection instance.
1209 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001210 @wraps(callback)
1211 def wrapper(ssl, alert, arg):
1212 callback(Connection._reverse_mapping[ssl])
1213 return 0
1214
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001215 self._tlsext_servername_callback = _ffi.callback(
1216 "int (*)(const SSL *, int *, void *)", wrapper)
1217 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001218 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08001219
Cory Benfield10b277f2015-04-13 17:12:42 -04001220 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001221 def set_npn_advertise_callback(self, callback):
1222 """
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001223 Specify a callback function that will be called when offering `Next
1224 Protocol Negotiation
1225 <https://technotes.googlecode.com/git/nextprotoneg.html>`_ as a server.
Cory Benfield84a121e2014-03-31 20:30:25 +01001226
1227 :param callback: The callback function. It will be invoked with one
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001228 argument, the Connection instance. It should return a list of
1229 bytestrings representing the advertised protocols, like
1230 ``[b'http/1.1', b'spdy/2']``.
Cory Benfield84a121e2014-03-31 20:30:25 +01001231 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001232 self._npn_advertise_helper = _NpnAdvertiseHelper(callback)
1233 self._npn_advertise_callback = self._npn_advertise_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001234 _lib.SSL_CTX_set_next_protos_advertised_cb(
1235 self._context, self._npn_advertise_callback, _ffi.NULL)
1236
Cory Benfield10b277f2015-04-13 17:12:42 -04001237 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01001238 def set_npn_select_callback(self, callback):
1239 """
1240 Specify a callback function that will be called when a server offers
1241 Next Protocol Negotiation options.
1242
1243 :param callback: The callback function. It will be invoked with two
1244 arguments: the Connection, and a list of offered protocols as
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001245 bytestrings, e.g. ``[b'http/1.1', b'spdy/2']``. It should return
1246 one of those bytestrings, the chosen protocol.
Cory Benfield84a121e2014-03-31 20:30:25 +01001247 """
Cory Benfield0ea76e72015-03-22 09:05:28 +00001248 self._npn_select_helper = _NpnSelectHelper(callback)
1249 self._npn_select_callback = self._npn_select_helper.callback
Cory Benfield84a121e2014-03-31 20:30:25 +01001250 _lib.SSL_CTX_set_next_proto_select_cb(
1251 self._context, self._npn_select_callback, _ffi.NULL)
1252
Cory Benfield7907e332015-04-13 17:18:25 -04001253 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001254 def set_alpn_protos(self, protos):
1255 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001256 Specify the clients ALPN protocol list.
1257
1258 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01001259
1260 :param protos: A list of the protocols to be offered to the server.
1261 This list should be a Python list of bytestrings representing the
1262 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
1263 """
1264 # Take the list of protocols and join them together, prefixing them
1265 # with their lengths.
1266 protostr = b''.join(
1267 chain.from_iterable((int2byte(len(p)), p) for p in protos)
1268 )
1269
1270 # Build a C string from the list. We don't need to save this off
1271 # because OpenSSL immediately copies the data out.
1272 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfielde871af52015-04-11 17:57:50 -04001273 input_str_len = _ffi.cast("unsigned", len(protostr))
1274 _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01001275
Cory Benfield7907e332015-04-13 17:18:25 -04001276 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01001277 def set_alpn_select_callback(self, callback):
1278 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04001279 Set the callback to handle ALPN protocol choice.
Cory Benfield12eae892014-06-07 15:42:56 +01001280
1281 :param callback: The callback function. It will be invoked with two
1282 arguments: the Connection, and a list of offered protocols as
1283 bytestrings, e.g ``[b'http/1.1', b'spdy/2']``. It should return
Cory Benfielde8e9c382015-04-11 17:33:48 -04001284 one of those bytestrings, the chosen protocol.
Cory Benfield12eae892014-06-07 15:42:56 +01001285 """
Cory Benfield9da5ffb2015-04-13 17:20:14 -04001286 self._alpn_select_helper = _ALPNSelectHelper(callback)
Cory Benfieldf1177e72015-04-12 09:11:49 -04001287 self._alpn_select_callback = self._alpn_select_helper.callback
Cory Benfield12eae892014-06-07 15:42:56 +01001288 _lib.SSL_CTX_set_alpn_select_cb(
1289 self._context, self._alpn_select_callback, _ffi.NULL)
1290
Cory Benfield496652a2017-01-24 11:42:56 +00001291 def _set_ocsp_callback(self, helper, data):
1292 """
1293 This internal helper does the common work for
1294 ``set_ocsp_server_callback`` and ``set_ocsp_client_callback``, which is
1295 almost all of it.
1296 """
1297 self._ocsp_helper = helper
1298 self._ocsp_callback = helper.callback
1299 if data is None:
1300 self._ocsp_data = _ffi.NULL
1301 else:
1302 self._ocsp_data = _ffi.new_handle(data)
1303
1304 rc = _lib.SSL_CTX_set_tlsext_status_cb(
1305 self._context, self._ocsp_callback
1306 )
1307 _openssl_assert(rc == 1)
1308 rc = _lib.SSL_CTX_set_tlsext_status_arg(self._context, self._ocsp_data)
1309 _openssl_assert(rc == 1)
1310
1311 def set_ocsp_server_callback(self, callback, data=None):
1312 """
1313 Set a callback to provide OCSP data to be stapled to the TLS handshake
1314 on the server side.
1315
1316 :param callback: The callback function. It will be invoked with two
1317 arguments: the Connection, and the optional arbitrary data you have
1318 provided. The callback must return a bytestring that contains the
1319 OCSP data to staple to the handshake. If no OCSP data is available
1320 for this connection, return the empty bytestring.
1321 :param data: Some opaque data that will be passed into the callback
1322 function when called. This can be used to avoid needing to do
1323 complex data lookups or to keep track of what context is being
1324 used. This parameter is optional.
1325 """
1326 helper = _OCSPServerCallbackHelper(callback)
1327 self._set_ocsp_callback(helper, data)
1328
1329 def set_ocsp_client_callback(self, callback, data=None):
1330 """
1331 Set a callback to validate OCSP data stapled to the TLS handshake on
1332 the client side.
1333
1334 :param callback: The callback function. It will be invoked with three
1335 arguments: the Connection, a bytestring containing the stapled OCSP
1336 assertion, and the optional arbitrary data you have provided. The
1337 callback must return a boolean that indicates the result of
1338 validating the OCSP data: ``True`` if the OCSP data is valid and
1339 the certificate can be trusted, or ``False`` if either the OCSP
1340 data is invalid or the certificate has been revoked.
1341 :param data: Some opaque data that will be passed into the callback
1342 function when called. This can be used to avoid needing to do
1343 complex data lookups or to keep track of what context is being
1344 used. This parameter is optional.
1345 """
1346 helper = _OCSPClientCallbackHelper(callback)
1347 self._set_ocsp_callback(helper, data)
1348
Alex Chanc6077062016-11-18 13:53:39 +00001349
Alex Gaynor10d30832017-06-29 15:31:39 -07001350ContextType = deprecated(
1351 Context, __name__,
1352 "ContextType has been deprecated, use Context instead", DeprecationWarning
1353)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001354
1355
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001356class Connection(object):
1357 """
1358 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001359 _reverse_mapping = WeakValueDictionary()
1360
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001361 def __init__(self, context, socket=None):
1362 """
1363 Create a new Connection object, using the given OpenSSL.SSL.Context
1364 instance and socket.
1365
1366 :param context: An SSL Context to use for this connection
1367 :param socket: The socket to use for transport layer
1368 """
1369 if not isinstance(context, Context):
1370 raise TypeError("context must be a Context instance")
1371
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001372 ssl = _lib.SSL_new(context._context)
1373 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001374 self._context = context
Todd Chapman4f73e4f2015-08-27 11:26:43 -04001375 self._app_data = None
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001376
Cory Benfieldbe3e7b82014-05-10 09:48:55 +01001377 # References to strings used for Next Protocol Negotiation. OpenSSL's
1378 # header files suggest that these might get copied at some point, but
1379 # doesn't specify when, so we store them here to make sure they don't
1380 # get freed before OpenSSL uses them.
1381 self._npn_advertise_callback_args = None
1382 self._npn_select_callback_args = None
1383
Cory Benfield12eae892014-06-07 15:42:56 +01001384 # References to strings used for Application Layer Protocol
1385 # Negotiation. These strings get copied at some point but it's well
1386 # after the callback returns, so we have to hang them somewhere to
1387 # avoid them getting freed.
1388 self._alpn_select_callback_args = None
1389
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001391
1392 if socket is None:
1393 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001394 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001395 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynora829e902016-06-04 18:16:01 -07001396 _openssl_assert(self._into_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001397
Alex Gaynora829e902016-06-04 18:16:01 -07001398 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
1399 _openssl_assert(self._from_ssl != _ffi.NULL)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001400
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001402 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001403 self._into_ssl = None
1404 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001405 self._socket = socket
Alex Gaynor62da94d2015-09-05 14:37:34 -04001406 set_result = _lib.SSL_set_fd(
1407 self._ssl, _asFileDescriptor(self._socket))
Alex Gaynor09f19f52016-07-03 09:54:09 -04001408 _openssl_assert(set_result == 1)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001409
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001410 def __getattr__(self, name):
1411 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001412 Look up attributes on the wrapped socket object if they are not found
1413 on the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001414 """
kjav0b66fa12015-09-02 11:51:26 +01001415 if self._socket is None:
Alex Gaynor62da94d2015-09-05 14:37:34 -04001416 raise AttributeError("'%s' object has no attribute '%s'" % (
1417 self.__class__.__name__, name
1418 ))
kjav0b66fa12015-09-02 11:51:26 +01001419 else:
1420 return getattr(self._socket, name)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001421
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001422 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001423 if self._context._verify_helper is not None:
1424 self._context._verify_helper.raise_if_problem()
Cory Benfield0ea76e72015-03-22 09:05:28 +00001425 if self._context._npn_advertise_helper is not None:
1426 self._context._npn_advertise_helper.raise_if_problem()
1427 if self._context._npn_select_helper is not None:
1428 self._context._npn_select_helper.raise_if_problem()
Cory Benfieldf1177e72015-04-12 09:11:49 -04001429 if self._context._alpn_select_helper is not None:
1430 self._context._alpn_select_helper.raise_if_problem()
Cory Benfield496652a2017-01-24 11:42:56 +00001431 if self._context._ocsp_helper is not None:
1432 self._context._ocsp_helper.raise_if_problem()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001433
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001434 error = _lib.SSL_get_error(ssl, result)
1435 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001436 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001437 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001438 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001439 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001440 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001441 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001442 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001443 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001444 elif error == _lib.SSL_ERROR_SYSCALL:
1445 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001446 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001447 if platform == "win32":
1448 errno = _ffi.getwinerror()[0]
1449 else:
1450 errno = _ffi.errno
Alex Gaynor5af32d02016-09-24 01:52:21 -04001451
1452 if errno != 0:
1453 raise SysCallError(errno, errorcode.get(errno))
1454 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001455 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001456 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001457 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001458 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001459 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001460 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001461 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001462
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001463 def get_context(self):
1464 """
1465 Get session context
1466 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001468
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001469 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001470 """
1471 Switch this connection to a new session context
1472
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001473 :param context: A :py:class:`Context` instance giving the new session
1474 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001475 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001476 if not isinstance(context, Context):
1477 raise TypeError("context must be a Context instance")
1478
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001479 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001480 self._context = context
1481
Cory Benfielde6f35882016-03-29 11:21:04 +01001482 @_requires_sni
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001483 def get_servername(self):
1484 """
1485 Retrieve the servername extension value if provided in the client hello
1486 message, or None if there wasn't one.
1487
1488 :return: A byte string giving the server name or :py:data:`None`.
1489 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001490 name = _lib.SSL_get_servername(
1491 self._ssl, _lib.TLSEXT_NAMETYPE_host_name
1492 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001493 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001494 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001495
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001496 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001497
Cory Benfielde6f35882016-03-29 11:21:04 +01001498 @_requires_sni
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001499 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001500 """
1501 Set the value of the servername extension to send in the client hello.
1502
1503 :param name: A byte string giving the name.
1504 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001505 if not isinstance(name, bytes):
1506 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001507 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001508 raise TypeError("name must not contain NUL byte")
1509
1510 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001511 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001512
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001513 def pending(self):
1514 """
1515 Get the number of bytes that can be safely read from the connection
1516
1517 :return: The number of bytes available in the receive buffer.
1518 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001519 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001520
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001521 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001522 """
1523 Send data on the connection. NOTE: If you get one of the WantRead,
1524 WantWrite or WantX509Lookup exceptions on this, you have to call the
1525 method again with the SAME buffer.
1526
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001527 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001528 :param flags: (optional) Included for compatibility with the socket
1529 API, the value is ignored
1530 :return: The number of bytes written
1531 """
Abraham Martine82326c2015-02-04 10:18:10 +00001532 # Backward compatibility
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001533 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001534
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001535 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001536 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001537 if isinstance(buf, _buffer):
1538 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001539 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001540 raise TypeError("data must be a memoryview, buffer or byte string")
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001541 if len(buf) > 2147483647:
1542 raise ValueError("Cannot send more than 2**31-1 bytes at once.")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001543
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001544 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001545 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001546 return result
1547 write = send
1548
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001549 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001550 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551 Send "all" data on the connection. This calls send() repeatedly until
1552 all data is sent. If an error occurs, it's impossible to tell how much
1553 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001554
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001555 :param buf: The string, buffer or memoryview to send
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001556 :param flags: (optional) Included for compatibility with the socket
1557 API, the value is ignored
1558 :return: The number of bytes written
1559 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001560 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001561
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001562 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001563 buf = buf.tobytes()
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001564 if isinstance(buf, _buffer):
1565 buf = str(buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 if not isinstance(buf, bytes):
Markus Unterwaditzer8e41d022014-04-19 12:27:11 +02001567 raise TypeError("buf must be a memoryview, buffer or byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001568
1569 left_to_send = len(buf)
1570 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001571 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001572
1573 while left_to_send:
Maximilian Hils868dc3c2017-02-10 14:56:55 +01001574 # SSL_write's num arg is an int,
1575 # so we cannot send more than 2**31-1 bytes at once.
1576 result = _lib.SSL_write(
1577 self._ssl,
1578 data + total_sent,
1579 min(left_to_send, 2147483647)
1580 )
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001581 self._raise_ssl_error(self._ssl, result)
1582 total_sent += result
1583 left_to_send -= result
1584
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001585 def recv(self, bufsiz, flags=None):
1586 """
Alex Gaynor67fc8c92016-05-27 08:27:19 -04001587 Receive data on the connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001588
1589 :param bufsiz: The maximum number of bytes to read
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001590 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1591 all other flags are ignored.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001592 :return: The string read from the Connection
1593 """
Cory Benfielde62840e2016-11-28 12:17:08 +00001594 buf = _no_zero_allocator("char[]", bufsiz)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001595 if flags is not None and flags & socket.MSG_PEEK:
1596 result = _lib.SSL_peek(self._ssl, buf, bufsiz)
1597 else:
1598 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001599 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001600 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001601 read = recv
1602
Cory Benfield62d10332014-06-15 10:03:41 +01001603 def recv_into(self, buffer, nbytes=None, flags=None):
1604 """
1605 Receive data on the connection and store the data into a buffer rather
1606 than creating a new string.
1607
1608 :param buffer: The buffer to copy into.
1609 :param nbytes: (optional) The maximum number of bytes to read into the
1610 buffer. If not present, defaults to the size of the buffer. If
1611 larger than the size of the buffer, is reduced to the size of the
1612 buffer.
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001613 :param flags: (optional) The only supported flag is ``MSG_PEEK``,
1614 all other flags are ignored.
Cory Benfield62d10332014-06-15 10:03:41 +01001615 :return: The number of bytes read into the buffer.
1616 """
1617 if nbytes is None:
1618 nbytes = len(buffer)
1619 else:
1620 nbytes = min(nbytes, len(buffer))
1621
1622 # We need to create a temporary buffer. This is annoying, it would be
1623 # better if we could pass memoryviews straight into the SSL_read call,
1624 # but right now we can't. Revisit this if CFFI gets that ability.
Cory Benfielde62840e2016-11-28 12:17:08 +00001625 buf = _no_zero_allocator("char[]", nbytes)
Maximilian Hils1d95dea2015-08-17 19:27:20 +02001626 if flags is not None and flags & socket.MSG_PEEK:
1627 result = _lib.SSL_peek(self._ssl, buf, nbytes)
1628 else:
1629 result = _lib.SSL_read(self._ssl, buf, nbytes)
Cory Benfield62d10332014-06-15 10:03:41 +01001630 self._raise_ssl_error(self._ssl, result)
1631
1632 # This strange line is all to avoid a memory copy. The buffer protocol
1633 # should allow us to assign a CFFI buffer to the LHS of this line, but
1634 # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
1635 # wrap it in a memoryview, except on Python 2.6 which doesn't have a
1636 # memoryview type.
1637 try:
1638 buffer[:result] = memoryview(_ffi.buffer(buf, result))
1639 except NameError:
1640 buffer[:result] = _ffi.buffer(buf, result)
1641
1642 return result
1643
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001644 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001645 if _lib.BIO_should_retry(bio):
1646 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001647 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001648 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001649 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001650 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001652 # TODO: This is untested. I think io_special means the socket
1653 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001654 raise ValueError("BIO_should_io_special")
1655 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001656 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001657 raise ValueError("unknown bio failure")
1658 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001659 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001660 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001661
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001662 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001663 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001664 When using non-socket connections this function reads the "dirty" data
1665 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001666
1667 :param bufsiz: The maximum number of bytes to read
1668 :return: The string read.
1669 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001670 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001671 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001672
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001673 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674 raise TypeError("bufsiz must be an integer")
1675
Cory Benfielde62840e2016-11-28 12:17:08 +00001676 buf = _no_zero_allocator("char[]", bufsiz)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001677 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001678 if result <= 0:
1679 self._handle_bio_errors(self._from_ssl, result)
1680
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001681 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001682
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001683 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001684 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001685 When using non-socket connections this function sends "dirty" data that
1686 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001687
1688 :param buf: The string to put into the memory BIO.
1689 :return: The number of bytes written
1690 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04001691 buf = _text_to_bytes_and_warn("buf", buf)
Abraham Martine82326c2015-02-04 10:18:10 +00001692
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001693 if self._into_ssl is None:
1694 raise TypeError("Connection sock was not None")
1695
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001696 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001697 if result <= 0:
1698 self._handle_bio_errors(self._into_ssl, result)
1699 return result
1700
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001701 def renegotiate(self):
1702 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001703 Renegotiate the session.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001704
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001705 :return: True if the renegotiation can be started, False otherwise
1706 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001707 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001708 if not self.renegotiate_pending():
1709 _openssl_assert(_lib.SSL_renegotiate(self._ssl) == 1)
1710 return True
1711 return False
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001712
1713 def do_handshake(self):
1714 """
1715 Perform an SSL handshake (usually called after renegotiate() or one of
1716 set_*_state()). This can raise the same exceptions as send and recv.
1717
1718 :return: None.
1719 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001720 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001721 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001722
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001723 def renegotiate_pending(self):
1724 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001725 Check if there's a renegotiation in progress, it will return False once
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001726 a renegotiation is finished.
1727
1728 :return: Whether there's a renegotiation in progress
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001729 :rtype: bool
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001730 """
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001731 return _lib.SSL_renegotiate_pending(self._ssl) == 1
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001732
1733 def total_renegotiations(self):
1734 """
1735 Find out the total number of renegotiations.
1736
1737 :return: The number of renegotiations.
Hynek Schlawackb1f3ca82016-02-13 09:10:04 +01001738 :rtype: int
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001739 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001740 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001741
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001743 """
1744 Connect to remote host and set up client-side SSL
1745
1746 :param addr: A remote address
1747 :return: What the socket's connect method returns
1748 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001749 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001750 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001751
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001752 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001753 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001754 Connect to remote host and set up client-side SSL. Note that if the
1755 socket's connect_ex method doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001756
1757 :param addr: A remove address
1758 :return: What the socket's connect_ex method returns
1759 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001760 connect_ex = self._socket.connect_ex
1761 self.set_connect_state()
1762 return connect_ex(addr)
1763
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001764 def accept(self):
1765 """
1766 Accept incoming connection and set up SSL on it
1767
1768 :return: A (conn,addr) pair where conn is a Connection and addr is an
1769 address
1770 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001771 client, addr = self._socket.accept()
1772 conn = Connection(self._context, client)
1773 conn.set_accept_state()
1774 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001775
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001776 def bio_shutdown(self):
1777 """
1778 When using non-socket connections this function signals end of
1779 data on the input for this connection.
1780
1781 :return: None
1782 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001783 if self._from_ssl is None:
1784 raise TypeError("Connection sock was not None")
1785
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001786 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001787
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001788 def shutdown(self):
1789 """
1790 Send closure alert
1791
1792 :return: True if the shutdown completed successfully (i.e. both sides
1793 have sent closure alerts), false otherwise (i.e. you have to
1794 wait for a ZeroReturnError on a recv() method call
1795 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001796 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001797 if result < 0:
Paul Aurichbff1d1a2015-01-08 08:36:53 -08001798 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001799 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001800 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001801 else:
1802 return False
1803
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001804 def get_cipher_list(self):
1805 """
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001806 Retrieve the list of ciphers used by the Connection object.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001807
Hynek Schlawackf90e3682016-03-11 11:21:13 +01001808 :return: A list of native cipher strings.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001809 """
1810 ciphers = []
1811 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001812 result = _lib.SSL_get_cipher_list(self._ssl, i)
1813 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001814 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001815 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001816 return ciphers
1817
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001818 def get_client_ca_list(self):
1819 """
1820 Get CAs whose certificates are suggested for client authentication.
1821
Alex Gaynor62da94d2015-09-05 14:37:34 -04001822 :return: If this is a server connection, a list of X509Names
1823 representing the acceptable CAs as set by
1824 :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1825 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client
1826 connection, the list of such X509Names sent by the server, or an
1827 empty list if that has not yet happened.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001828 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001829 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1830 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001831 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001832 return []
1833
1834 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001835 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1836 name = _lib.sk_X509_NAME_value(ca_names, i)
1837 copy = _lib.X509_NAME_dup(name)
Alex Gaynora829e902016-06-04 18:16:01 -07001838 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001839
1840 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001841 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001842 result.append(pyname)
1843 return result
1844
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001845 def makefile(self):
1846 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001847 The makefile() method is not implemented, since there is no dup
1848 semantics for SSL connections
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001849
Jean-Paul Calderone6749ec22014-04-17 16:30:21 -04001850 :raise: NotImplementedError
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001851 """
Alex Gaynor83284952015-09-05 10:43:30 -04001852 raise NotImplementedError(
1853 "Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001854
1855 def get_app_data(self):
1856 """
1857 Get application data
1858
1859 :return: The application data
1860 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001861 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001862
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001863 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001864 """
1865 Set application data
1866
1867 :param data - The application data
1868 :return: None
1869 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001870 self._app_data = data
1871
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001872 def get_shutdown(self):
1873 """
1874 Get shutdown state
1875
Alex Gaynor62da94d2015-09-05 14:37:34 -04001876 :return: The shutdown state, a bitvector of SENT_SHUTDOWN,
1877 RECEIVED_SHUTDOWN.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001878 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001879 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001880
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001881 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001882 """
1883 Set shutdown state
1884
1885 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1886 :return: None
1887 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001888 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001889 raise TypeError("state must be an integer")
1890
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001891 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001892
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001893 def get_state_string(self):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001894 """
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001895 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001896
1897 :return: A string representing the state
Hynek Schlawackea94f2b2016-03-13 16:17:53 +01001898 :rtype: bytes
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001899 """
kjavc704a2e2015-09-07 12:12:27 +01001900 return _ffi.string(_lib.SSL_state_string_long(self._ssl))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001901
1902 def server_random(self):
1903 """
1904 Get a copy of the server hello nonce.
1905
1906 :return: A string representing the state
1907 """
Alex Gaynor93603062016-06-01 20:13:09 -07001908 session = _lib.SSL_get_session(self._ssl)
1909 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001910 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001911 length = _lib.SSL_get_server_random(self._ssl, _ffi.NULL, 0)
1912 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001913 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001914 _lib.SSL_get_server_random(self._ssl, outp, length)
1915 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001916
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001917 def client_random(self):
1918 """
1919 Get a copy of the client hello nonce.
1920
1921 :return: A string representing the state
1922 """
Alex Gaynor93603062016-06-01 20:13:09 -07001923 session = _lib.SSL_get_session(self._ssl)
1924 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001925 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001926
1927 length = _lib.SSL_get_client_random(self._ssl, _ffi.NULL, 0)
1928 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001929 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001930 _lib.SSL_get_client_random(self._ssl, outp, length)
1931 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001932
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001933 def master_key(self):
1934 """
1935 Get a copy of the master key.
1936
1937 :return: A string representing the state
1938 """
Alex Gaynor93603062016-06-01 20:13:09 -07001939 session = _lib.SSL_get_session(self._ssl)
1940 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001941 return None
Alex Gaynor93603062016-06-01 20:13:09 -07001942
1943 length = _lib.SSL_SESSION_get_master_key(session, _ffi.NULL, 0)
1944 assert length > 0
Cory Benfielde62840e2016-11-28 12:17:08 +00001945 outp = _no_zero_allocator("unsigned char[]", length)
Alex Gaynor93603062016-06-01 20:13:09 -07001946 _lib.SSL_SESSION_get_master_key(session, outp, length)
1947 return _ffi.buffer(outp, length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001948
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001949 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001950 """
1951 See shutdown(2)
1952
1953 :return: What the socket's shutdown() method returns
1954 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001955 return self._socket.shutdown(*args, **kwargs)
1956
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001957 def get_peer_certificate(self):
1958 """
1959 Retrieve the other side's certificate (if any)
1960
1961 :return: The peer's certificate
1962 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001963 cert = _lib.SSL_get_peer_certificate(self._ssl)
1964 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001965 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001966 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001967 return pycert
1968 return None
1969
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001970 def get_peer_cert_chain(self):
1971 """
1972 Retrieve the other side's certificate (if any)
1973
1974 :return: A list of X509 instances giving the peer's certificate chain,
1975 or None if it does not have one.
1976 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001977 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1978 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001979 return None
1980
1981 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001982 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001983 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001984 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001985 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001986 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001987 result.append(pycert)
1988 return result
1989
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001990 def want_read(self):
1991 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04001992 Checks if more data has to be read from the transport layer to complete
1993 an operation.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001994
1995 :return: True iff more data has to be read
1996 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001997 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001998
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001999 def want_write(self):
2000 """
2001 Checks if there is data to write to the transport layer to complete an
2002 operation.
2003
2004 :return: True iff there is data to write
2005 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002006 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002007
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002008 def set_accept_state(self):
2009 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002010 Set the connection to work in server mode. The handshake will be
2011 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002012
2013 :return: None
2014 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002015 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002016
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002017 def set_connect_state(self):
2018 """
Alex Gaynor62da94d2015-09-05 14:37:34 -04002019 Set the connection to work in client mode. The handshake will be
2020 handled automatically by read/write.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002021
2022 :return: None
2023 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002024 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002025
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002026 def get_session(self):
2027 """
2028 Returns the Session currently used.
2029
Alex Gaynor62da94d2015-09-05 14:37:34 -04002030 @return: An instance of :py:class:`OpenSSL.SSL.Session` or
2031 :py:obj:`None` if no session exists.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002032 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002033 session = _lib.SSL_get1_session(self._ssl)
2034 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002035 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002036
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002037 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002038 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002039 return pysession
2040
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002041 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002042 """
2043 Set the session to be used when the TLS/SSL connection is established.
2044
2045 :param session: A Session instance representing the session to use.
2046 :returns: None
2047 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002048 if not isinstance(session, Session):
2049 raise TypeError("session must be a Session instance")
2050
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002051 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08002052 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002053 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08002054
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002055 def _get_finished_message(self, function):
2056 """
2057 Helper to implement :py:meth:`get_finished` and
2058 :py:meth:`get_peer_finished`.
2059
2060 :param function: Either :py:data:`SSL_get_finished`: or
2061 :py:data:`SSL_get_peer_finished`.
2062
2063 :return: :py:data:`None` if the desired message has not yet been
2064 received, otherwise the contents of the message.
2065 :rtype: :py:class:`bytes` or :py:class:`NoneType`
2066 """
Jean-Paul Calderone01af9042014-03-30 11:40:42 -04002067 # The OpenSSL documentation says nothing about what might happen if the
2068 # count argument given is zero. Specifically, it doesn't say whether
2069 # the output buffer may be NULL in that case or not. Inspection of the
2070 # implementation reveals that it calls memcpy() unconditionally.
2071 # Section 7.1.4, paragraph 1 of the C standard suggests that
2072 # memcpy(NULL, source, 0) is not guaranteed to produce defined (let
2073 # alone desirable) behavior (though it probably does on just about
2074 # every implementation...)
2075 #
2076 # Allocate a tiny buffer to pass in (instead of just passing NULL as
2077 # one might expect) for the initial call so as to be safe against this
2078 # potentially undefined behavior.
2079 empty = _ffi.new("char[]", 0)
2080 size = function(self._ssl, empty, 0)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002081 if size == 0:
2082 # No Finished message so far.
2083 return None
2084
Cory Benfielde62840e2016-11-28 12:17:08 +00002085 buf = _no_zero_allocator("char[]", size)
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002086 function(self._ssl, buf, size)
2087 return _ffi.buffer(buf, size)[:]
2088
Fedor Brunner5747b932014-03-05 14:22:34 +01002089 def get_finished(self):
2090 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002091 Obtain the latest `handshake finished` message sent to the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002092
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002093 :return: The contents of the message or :py:obj:`None` if the TLS
2094 handshake has not yet completed.
2095 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002096 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002097 return self._get_finished_message(_lib.SSL_get_finished)
2098
Fedor Brunner5747b932014-03-05 14:22:34 +01002099 def get_peer_finished(self):
2100 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002101 Obtain the latest `handshake finished` message received from the peer.
Fedor Brunner5747b932014-03-05 14:22:34 +01002102
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002103 :return: The contents of the message or :py:obj:`None` if the TLS
2104 handshake has not yet completed.
2105 :rtype: :py:class:`bytes` or :py:class:`NoneType`
Fedor Brunner5747b932014-03-05 14:22:34 +01002106 """
Jean-Paul Calderoneac209562014-03-30 11:26:32 -04002107 return self._get_finished_message(_lib.SSL_get_peer_finished)
Fedor Brunner5747b932014-03-05 14:22:34 +01002108
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002109 def get_cipher_name(self):
2110 """
2111 Obtain the name of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002112
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002113 :returns: The name of the currently used cipher or :py:obj:`None`
2114 if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002115 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002116 """
2117 cipher = _lib.SSL_get_current_cipher(self._ssl)
2118 if cipher == _ffi.NULL:
2119 return None
2120 else:
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002121 name = _ffi.string(_lib.SSL_CIPHER_get_name(cipher))
2122 return name.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002123
2124 def get_cipher_bits(self):
2125 """
2126 Obtain the number of secret bits of the currently used cipher.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002127
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002128 :returns: The number of secret bits of the currently used cipher
2129 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002130 :rtype: :py:class:`int` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002131 """
2132 cipher = _lib.SSL_get_current_cipher(self._ssl)
2133 if cipher == _ffi.NULL:
2134 return None
2135 else:
2136 return _lib.SSL_CIPHER_get_bits(cipher, _ffi.NULL)
2137
2138 def get_cipher_version(self):
2139 """
Jean-Paul Calderone9e3ccd42014-03-29 18:13:36 -04002140 Obtain the protocol version of the currently used cipher.
2141
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002142 :returns: The protocol name of the currently used cipher
2143 or :py:obj:`None` if no connection has been established.
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002144 :rtype: :py:class:`unicode` or :py:class:`NoneType`
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002145 """
2146 cipher = _lib.SSL_get_current_cipher(self._ssl)
2147 if cipher == _ffi.NULL:
2148 return None
2149 else:
Alex Gaynorc4889812015-09-04 08:43:17 -04002150 version = _ffi.string(_lib.SSL_CIPHER_get_version(cipher))
Jean-Paul Calderone7f0ded42014-03-30 10:34:17 -04002151 return version.decode("utf-8")
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002152
Jim Shaverabff1882015-05-27 09:15:55 -04002153 def get_protocol_version_name(self):
Jim Shaverba65e662015-04-26 12:23:40 -04002154 """
2155 Obtain the protocol version of the current connection.
2156
2157 :returns: The TLS version of the current connection, for example
Jim Shaver58d25732015-05-28 11:52:32 -04002158 the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
Jim Shaverb5b6b0e2015-05-28 16:47:36 -04002159 for connections that were not successfully established.
Jim Shaver58d25732015-05-28 11:52:32 -04002160 :rtype: :py:class:`unicode`
Jim Shaverba65e662015-04-26 12:23:40 -04002161 """
Jim Shaverd1c896e2015-05-27 17:50:21 -04002162 version = _ffi.string(_lib.SSL_get_version(self._ssl))
Jim Shaver58d25732015-05-28 11:52:32 -04002163 return version.decode("utf-8")
Jim Shaverb2967922015-04-26 23:58:52 -04002164
Jim Shaver208438c2015-05-28 09:52:38 -04002165 def get_protocol_version(self):
2166 """
2167 Obtain the protocol version of the current connection.
2168
2169 :returns: The TLS version of the current connection, for example
2170 the value for TLS 1 would be 0x769.
2171 :rtype: :py:class:`int`
2172 """
2173 version = _lib.SSL_version(self._ssl)
2174 return version
2175
Cory Benfield10b277f2015-04-13 17:12:42 -04002176 @_requires_npn
Cory Benfield84a121e2014-03-31 20:30:25 +01002177 def get_next_proto_negotiated(self):
2178 """
2179 Get the protocol that was negotiated by NPN.
2180 """
2181 data = _ffi.new("unsigned char **")
2182 data_len = _ffi.new("unsigned int *")
2183
2184 _lib.SSL_get0_next_proto_negotiated(self._ssl, data, data_len)
2185
Cory Benfieldcd010f62014-05-15 19:00:27 +01002186 return _ffi.buffer(data[0], data_len[0])[:]
Fedor Brunnerd95014a2014-03-03 17:34:41 +01002187
Cory Benfield7907e332015-04-13 17:18:25 -04002188 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002189 def set_alpn_protos(self, protos):
2190 """
Cory Benfielde8e9c382015-04-11 17:33:48 -04002191 Specify the client's ALPN protocol list.
2192
2193 These protocols are offered to the server during protocol negotiation.
Cory Benfield12eae892014-06-07 15:42:56 +01002194
2195 :param protos: A list of the protocols to be offered to the server.
2196 This list should be a Python list of bytestrings representing the
2197 protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
2198 """
2199 # Take the list of protocols and join them together, prefixing them
2200 # with their lengths.
2201 protostr = b''.join(
2202 chain.from_iterable((int2byte(len(p)), p) for p in protos)
2203 )
2204
2205 # Build a C string from the list. We don't need to save this off
2206 # because OpenSSL immediately copies the data out.
2207 input_str = _ffi.new("unsigned char[]", protostr)
Cory Benfield9c1979a2015-04-12 08:51:52 -04002208 input_str_len = _ffi.cast("unsigned", len(protostr))
2209 _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len)
Cory Benfield12eae892014-06-07 15:42:56 +01002210
Maximilian Hils66ded6a2015-08-26 06:02:03 +02002211 @_requires_alpn
Cory Benfield12eae892014-06-07 15:42:56 +01002212 def get_alpn_proto_negotiated(self):
Cory Benfield222f30e2015-04-13 18:10:21 -04002213 """
2214 Get the protocol that was negotiated by ALPN.
2215 """
Cory Benfield12eae892014-06-07 15:42:56 +01002216 data = _ffi.new("unsigned char **")
2217 data_len = _ffi.new("unsigned int *")
2218
2219 _lib.SSL_get0_alpn_selected(self._ssl, data, data_len)
2220
Cory Benfielde8e9c382015-04-11 17:33:48 -04002221 if not data_len:
2222 return b''
2223
Cory Benfield12eae892014-06-07 15:42:56 +01002224 return _ffi.buffer(data[0], data_len[0])[:]
2225
Cory Benfield496652a2017-01-24 11:42:56 +00002226 def request_ocsp(self):
2227 """
2228 Called to request that the server sends stapled OCSP data, if
2229 available. If this is not called on the client side then the server
2230 will not send OCSP data. Should be used in conjunction with
2231 :meth:`Context.set_ocsp_client_callback`.
2232 """
2233 rc = _lib.SSL_set_tlsext_status_type(
2234 self._ssl, _lib.TLSEXT_STATUSTYPE_ocsp
2235 )
2236 _openssl_assert(rc == 1)
2237
Cory Benfield12eae892014-06-07 15:42:56 +01002238
Alex Gaynor10d30832017-06-29 15:31:39 -07002239ConnectionType = deprecated(
2240 Connection, __name__,
2241 "ConnectionType has been deprecated, use Connection instead",
2242 DeprecationWarning
2243)
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002244
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002245# This is similar to the initialization calls at the end of OpenSSL/crypto.py
2246# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002247_lib.SSL_library_init()