aboutsummaryrefslogtreecommitdiff
path: root/library
diff options
context:
space:
mode:
Diffstat (limited to 'library')
-rw-r--r--library/CMakeLists.txt7
-rw-r--r--library/Makefile35
-rw-r--r--library/bignum.c374
-rw-r--r--library/bignum_core.c9
-rw-r--r--library/bignum_core.h8
-rw-r--r--library/cmac.c46
-rw-r--r--library/ecdh.c9
-rw-r--r--library/ecp.c34
-rw-r--r--library/gcm.c9
-rw-r--r--library/pk.c341
-rw-r--r--library/pk_ecc.c255
-rw-r--r--library/pk_internal.h56
-rw-r--r--library/pk_wrap.c37
-rw-r--r--library/pkparse.c314
-rw-r--r--library/pkwrite.c2
-rw-r--r--library/pkwrite.h9
-rw-r--r--library/psa_crypto.c1728
-rw-r--r--library/psa_crypto_aead.c8
-rw-r--r--library/psa_crypto_cipher.c10
-rw-r--r--library/psa_crypto_core.h127
-rw-r--r--library/psa_crypto_ecp.c51
-rw-r--r--library/psa_crypto_ffdh.c6
-rw-r--r--library/psa_crypto_invasive.h15
-rw-r--r--library/psa_crypto_random_impl.h129
-rw-r--r--library/psa_crypto_rsa.c22
-rw-r--r--library/psa_crypto_slot_management.c28
-rw-r--r--library/psa_crypto_storage.c8
-rw-r--r--library/psa_crypto_storage.h13
-rw-r--r--library/psa_util.c29
-rw-r--r--library/psa_util_internal.h4
-rw-r--r--library/rsa.c2
-rw-r--r--library/sha3.c117
-rw-r--r--library/ssl_client.c18
-rw-r--r--library/ssl_debug_helpers.h5
-rw-r--r--library/ssl_misc.h92
-rw-r--r--library/ssl_msg.c119
-rw-r--r--library/ssl_ticket.c2
-rw-r--r--library/ssl_tls.c1525
-rw-r--r--library/ssl_tls12_server.c8
-rw-r--r--library/ssl_tls13_client.c140
-rw-r--r--library/ssl_tls13_generic.c56
-rw-r--r--library/ssl_tls13_server.c684
-rw-r--r--library/threading.c6
-rw-r--r--library/x509_crt.c8
44 files changed, 3920 insertions, 2585 deletions
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index eda377e..37a9724 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -56,6 +56,7 @@ set(src_crypto
padlock.c
pem.c
pk.c
+ pk_ecc.c
pk_wrap.c
pkcs12.c
pkcs5.c
@@ -299,7 +300,7 @@ endif(USE_STATIC_MBEDTLS_LIBRARY)
if(USE_SHARED_MBEDTLS_LIBRARY)
set(CMAKE_LIBRARY_PATH ${CMAKE_CURRENT_BINARY_DIR})
add_library(${mbedcrypto_target} SHARED ${src_crypto})
- set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 3.5.2 SOVERSION 15)
+ set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 3.6.0 SOVERSION 16)
target_link_libraries(${mbedcrypto_target} PUBLIC ${libs})
if(TARGET ${everest_target})
@@ -311,11 +312,11 @@ if(USE_SHARED_MBEDTLS_LIBRARY)
endif()
add_library(${mbedx509_target} SHARED ${src_x509})
- set_target_properties(${mbedx509_target} PROPERTIES VERSION 3.5.2 SOVERSION 6)
+ set_target_properties(${mbedx509_target} PROPERTIES VERSION 3.6.0 SOVERSION 7)
target_link_libraries(${mbedx509_target} PUBLIC ${libs} ${mbedcrypto_target})
add_library(${mbedtls_target} SHARED ${src_tls})
- set_target_properties(${mbedtls_target} PROPERTIES VERSION 3.5.2 SOVERSION 20)
+ set_target_properties(${mbedtls_target} PROPERTIES VERSION 3.6.0 SOVERSION 21)
target_link_libraries(${mbedtls_target} PUBLIC ${libs} ${mbedx509_target})
endif(USE_SHARED_MBEDTLS_LIBRARY)
diff --git a/library/Makefile b/library/Makefile
index d11a98d..388fcea 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -1,3 +1,26 @@
+ifndef MBEDTLS_PATH
+MBEDTLS_PATH := ..
+endif
+
+GENERATED_FILES := \
+ error.c version_features.c \
+ ssl_debug_helpers_generated.c \
+ psa_crypto_driver_wrappers.h \
+ psa_crypto_driver_wrappers_no_static.c
+
+ifneq ($(GENERATED_FILES),$(wildcard $(GENERATED_FILES)))
+ ifeq (,$(wildcard $(MBEDTLS_PATH)/framework/exported.make))
+ # Use the define keyword to get a multi-line message.
+ # GNU make appends ". Stop.", so tweak the ending of our message accordingly.
+ define error_message
+$(MBEDTLS_PATH)/framework/exported.make not found.
+Run `git submodule update --init` to fetch the submodule contents.
+This is a fatal error
+ endef
+ $(error $(error_message))
+ endif
+ include $(MBEDTLS_PATH)/framework/exported.make
+endif
# Also see "include/mbedtls/mbedtls_config.h"
@@ -51,9 +74,9 @@ LOCAL_CFLAGS += -fPIC -fpic
endif
endif
-SOEXT_TLS?=so.20
-SOEXT_X509?=so.6
-SOEXT_CRYPTO?=so.15
+SOEXT_TLS?=so.21
+SOEXT_X509?=so.7
+SOEXT_CRYPTO?=so.16
# Set AR_DASH= (empty string) to use an ar implementation that does not accept
# the - prefix for command line options (e.g. llvm-ar)
@@ -125,6 +148,7 @@ OBJS_CRYPTO= \
padlock.o \
pem.o \
pk.o \
+ pk_ecc.o \
pk_wrap.o \
pkcs12.o \
pkcs5.o \
@@ -314,11 +338,6 @@ libmbedcrypto.dll: $(OBJS_CRYPTO)
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
.PHONY: generated_files
-GENERATED_FILES = \
- error.c version_features.c \
- ssl_debug_helpers_generated.c \
- psa_crypto_driver_wrappers.h \
- psa_crypto_driver_wrappers_no_static.c
generated_files: $(GENERATED_FILES)
# See root Makefile
diff --git a/library/bignum.c b/library/bignum.c
index d3d72ab..c45fd5b 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -37,6 +37,19 @@
#include "mbedtls/platform.h"
+
+
+/*
+ * Conditionally select an MPI sign in constant time.
+ * (MPI sign is the field s in mbedtls_mpi. It is unsigned short and only 1 and -1 are valid
+ * values.)
+ */
+static inline signed short mbedtls_ct_mpi_sign_if(mbedtls_ct_condition_t cond,
+ signed short sign1, signed short sign2)
+{
+ return (signed short) mbedtls_ct_uint_if(cond, sign1 + 1, sign2 + 1) - 1;
+}
+
/*
* Compare signed values in constant time
*/
@@ -112,7 +125,7 @@ int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
{
mbedtls_ct_condition_t do_assign = mbedtls_ct_bool(assign);
- X->s = (int) mbedtls_ct_uint_if(do_assign, Y->s, X->s);
+ X->s = mbedtls_ct_mpi_sign_if(do_assign, Y->s, X->s);
mbedtls_mpi_core_cond_assign(X->p, Y->p, Y->n, do_assign);
@@ -149,8 +162,8 @@ int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
s = X->s;
- X->s = (int) mbedtls_ct_uint_if(do_swap, Y->s, X->s);
- Y->s = (int) mbedtls_ct_uint_if(do_swap, s, Y->s);
+ X->s = mbedtls_ct_mpi_sign_if(do_swap, Y->s, X->s);
+ Y->s = mbedtls_ct_mpi_sign_if(do_swap, s, Y->s);
mbedtls_mpi_core_cond_swap(X->p, Y->p, X->n, do_swap);
@@ -288,8 +301,7 @@ static int mbedtls_mpi_resize_clear(mbedtls_mpi *X, size_t limbs)
* This function is not constant-time. Leading zeros in Y may be removed.
*
* Ensure that X does not shrink. This is not guaranteed by the public API,
- * but some code in the bignum module relies on this property, for example
- * in mbedtls_mpi_exp_mod().
+ * but some code in the bignum module might still rely on this property.
*/
int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y)
{
@@ -1598,98 +1610,11 @@ int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_s
return 0;
}
-static void mpi_montg_init(mbedtls_mpi_uint *mm, const mbedtls_mpi *N)
-{
- *mm = mbedtls_mpi_core_montmul_init(N->p);
-}
-
-/** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
- *
- * \param[in,out] A One of the numbers to multiply.
- * It must have at least as many limbs as N
- * (A->n >= N->n), and any limbs beyond n are ignored.
- * On successful completion, A contains the result of
- * the multiplication A * B * R^-1 mod N where
- * R = (2^ciL)^n.
- * \param[in] B One of the numbers to multiply.
- * It must be nonzero and must not have more limbs than N
- * (B->n <= N->n).
- * \param[in] N The modulus. \p N must be odd.
- * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
- * This is -N^-1 mod 2^ciL.
- * \param[in,out] T A bignum for temporary storage.
- * It must be at least twice the limb size of N plus 1
- * (T->n >= 2 * N->n + 1).
- * Its initial content is unused and
- * its final content is indeterminate.
- * It does not get reallocated.
- */
-static void mpi_montmul(mbedtls_mpi *A, const mbedtls_mpi *B,
- const mbedtls_mpi *N, mbedtls_mpi_uint mm,
- mbedtls_mpi *T)
-{
- mbedtls_mpi_core_montmul(A->p, A->p, B->p, B->n, N->p, N->n, mm, T->p);
-}
-
-/*
- * Montgomery reduction: A = A * R^-1 mod N
- *
- * See mpi_montmul() regarding constraints and guarantees on the parameters.
- */
-static void mpi_montred(mbedtls_mpi *A, const mbedtls_mpi *N,
- mbedtls_mpi_uint mm, mbedtls_mpi *T)
-{
- mbedtls_mpi_uint z = 1;
- mbedtls_mpi U;
- U.n = 1;
- U.s = 1;
- U.p = &z;
-
- mpi_montmul(A, &U, N, mm, T);
-}
-
-/**
- * Select an MPI from a table without leaking the index.
- *
- * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
- * reads the entire table in order to avoid leaking the value of idx to an
- * attacker able to observe memory access patterns.
- *
- * \param[out] R Where to write the selected MPI.
- * \param[in] T The table to read from.
- * \param[in] T_size The number of elements in the table.
- * \param[in] idx The index of the element to select;
- * this must satisfy 0 <= idx < T_size.
- *
- * \return \c 0 on success, or a negative error code.
- */
-static int mpi_select(mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx)
-{
- int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
-
- for (size_t i = 0; i < T_size; i++) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(R, &T[i],
- (unsigned char) mbedtls_ct_uint_eq(i, idx)));
- }
-cleanup:
- return ret;
-}
-
-/*
- * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
- */
int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
const mbedtls_mpi *E, const mbedtls_mpi *N,
mbedtls_mpi *prec_RR)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
- size_t window_bitsize;
- size_t i, j, nblimbs;
- size_t bufsize, nbits;
- size_t exponent_bits_in_window = 0;
- mbedtls_mpi_uint ei, mm, state;
- mbedtls_mpi RR, T, W[(size_t) 1 << MBEDTLS_MPI_WINDOW_SIZE], WW, Apos;
- int neg;
if (mbedtls_mpi_cmp_int(N, 0) <= 0 || (N->p[0] & 1) == 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
@@ -1705,261 +1630,88 @@ int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
}
/*
- * Init temps and window size
+ * Ensure that the exponent that we are passing to the core is not NULL.
*/
- mpi_montg_init(&mm, N);
- mbedtls_mpi_init(&RR); mbedtls_mpi_init(&T);
- mbedtls_mpi_init(&Apos);
- mbedtls_mpi_init(&WW);
- memset(W, 0, sizeof(W));
-
- i = mbedtls_mpi_bitlen(E);
-
- window_bitsize = (i > 671) ? 6 : (i > 239) ? 5 :
- (i > 79) ? 4 : (i > 23) ? 3 : 1;
-
-#if (MBEDTLS_MPI_WINDOW_SIZE < 6)
- if (window_bitsize > MBEDTLS_MPI_WINDOW_SIZE) {
- window_bitsize = MBEDTLS_MPI_WINDOW_SIZE;
+ if (E->n == 0) {
+ ret = mbedtls_mpi_lset(X, 1);
+ return ret;
}
-#endif
-
- const size_t w_table_used_size = (size_t) 1 << window_bitsize;
/*
- * This function is not constant-trace: its memory accesses depend on the
- * exponent value. To defend against timing attacks, callers (such as RSA
- * and DHM) should use exponent blinding. However this is not enough if the
- * adversary can find the exponent in a single trace, so this function
- * takes extra precautions against adversaries who can observe memory
- * access patterns.
- *
- * This function performs a series of multiplications by table elements and
- * squarings, and we want the prevent the adversary from finding out which
- * table element was used, and from distinguishing between multiplications
- * and squarings. Firstly, when multiplying by an element of the window
- * W[i], we do a constant-trace table lookup to obfuscate i. This leaves
- * squarings as having a different memory access patterns from other
- * multiplications. So secondly, we put the accumulator in the table as
- * well, and also do a constant-trace table lookup to multiply by the
- * accumulator which is W[x_index].
- *
- * This way, all multiplications take the form of a lookup-and-multiply.
- * The number of lookup-and-multiply operations inside each iteration of
- * the main loop still depends on the bits of the exponent, but since the
- * other operations in the loop don't have an easily recognizable memory
- * trace, an adversary is unlikely to be able to observe the exact
- * patterns.
- *
- * An adversary may still be able to recover the exponent if they can
- * observe both memory accesses and branches. However, branch prediction
- * exploitation typically requires many traces of execution over the same
- * data, which is defeated by randomized blinding.
- */
- const size_t x_index = 0;
- mbedtls_mpi_init(&W[x_index]);
-
- j = N->n + 1;
- /* All W[i] including the accumulator must have at least N->n limbs for
- * the mpi_montmul() and mpi_montred() calls later. Here we ensure that
- * W[1] and the accumulator W[x_index] are large enough. later we'll grow
- * other W[i] to the same length. They must not be shrunk midway through
- * this function!
+ * Allocate working memory for mbedtls_mpi_core_exp_mod()
*/
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[x_index], j));
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[1], j));
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&T, j * 2));
-
- /*
- * Compensate for negative A (and correct at the end)
- */
- neg = (A->s == -1);
- if (neg) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Apos, A));
- Apos.s = 1;
- A = &Apos;
+ size_t T_limbs = mbedtls_mpi_core_exp_mod_working_limbs(N->n, E->n);
+ mbedtls_mpi_uint *T = (mbedtls_mpi_uint *) mbedtls_calloc(T_limbs, sizeof(mbedtls_mpi_uint));
+ if (T == NULL) {
+ return MBEDTLS_ERR_MPI_ALLOC_FAILED;
}
+ mbedtls_mpi RR;
+ mbedtls_mpi_init(&RR);
+
/*
* If 1st call, pre-compute R^2 mod N
*/
if (prec_RR == NULL || prec_RR->p == NULL) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&RR, 1));
- MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&RR, N->n * 2 * biL));
- MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&RR, &RR, N));
+ MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
if (prec_RR != NULL) {
- memcpy(prec_RR, &RR, sizeof(mbedtls_mpi));
+ *prec_RR = RR;
}
} else {
- memcpy(&RR, prec_RR, sizeof(mbedtls_mpi));
+ MBEDTLS_MPI_CHK(mbedtls_mpi_grow(prec_RR, N->n));
+ RR = *prec_RR;
}
/*
- * W[1] = A * R^2 * R^-1 mod N = A * R mod N
+ * To preserve constness we need to make a copy of A. Using X for this to
+ * save memory.
*/
- if (mbedtls_mpi_cmp_mpi(A, N) >= 0) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&W[1], A, N));
- /* This should be a no-op because W[1] is already that large before
- * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
- * in mpi_montmul() below, so let's make sure. */
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[1], N->n + 1));
- } else {
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[1], A));
- }
-
- /* Note that this is safe because W[1] always has at least N->n limbs
- * (it grew above and was preserved by mbedtls_mpi_copy()). */
- mpi_montmul(&W[1], &RR, N, mm, &T);
+ MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
/*
- * W[x_index] = R^2 * R^-1 mod N = R mod N
+ * Compensate for negative A (and correct at the end).
*/
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[x_index], &RR));
- mpi_montred(&W[x_index], N, mm, &T);
-
-
- if (window_bitsize > 1) {
- /*
- * W[i] = W[1] ^ i
- *
- * The first bit of the sliding window is always 1 and therefore we
- * only need to store the second half of the table.
- *
- * (There are two special elements in the table: W[0] for the
- * accumulator/result and W[1] for A in Montgomery form. Both of these
- * are already set at this point.)
- */
- j = w_table_used_size / 2;
-
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[j], N->n + 1));
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[j], &W[1]));
-
- for (i = 0; i < window_bitsize - 1; i++) {
- mpi_montmul(&W[j], &W[j], N, mm, &T);
- }
-
- /*
- * W[i] = W[i - 1] * W[1]
- */
- for (i = j + 1; i < w_table_used_size; i++) {
- MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[i], N->n + 1));
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[i], &W[i - 1]));
-
- mpi_montmul(&W[i], &W[1], N, mm, &T);
- }
- }
-
- nblimbs = E->n;
- bufsize = 0;
- nbits = 0;
- state = 0;
-
- while (1) {
- if (bufsize == 0) {
- if (nblimbs == 0) {
- break;
- }
-
- nblimbs--;
-
- bufsize = sizeof(mbedtls_mpi_uint) << 3;
- }
-
- bufsize--;
-
- ei = (E->p[nblimbs] >> bufsize) & 1;
-
- /*
- * skip leading 0s
- */
- if (ei == 0 && state == 0) {
- continue;
- }
-
- if (ei == 0 && state == 1) {
- /*
- * out of window, square W[x_index]
- */
- MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, x_index));
- mpi_montmul(&W[x_index], &WW, N, mm, &T);
- continue;
- }
-
- /*
- * add ei to current window
- */
- state = 2;
-
- nbits++;
- exponent_bits_in_window |= (ei << (window_bitsize - nbits));
-
- if (nbits == window_bitsize) {
- /*
- * W[x_index] = W[x_index]^window_bitsize R^-1 mod N
- */
- for (i = 0; i < window_bitsize; i++) {
- MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size,
- x_index));
- mpi_montmul(&W[x_index], &WW, N, mm, &T);
- }
-
- /*
- * W[x_index] = W[x_index] * W[exponent_bits_in_window] R^-1 mod N
- */
- MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size,
- exponent_bits_in_window));
- mpi_montmul(&W[x_index], &WW, N, mm, &T);
-
- state--;
- nbits = 0;
- exponent_bits_in_window = 0;
- }
- }
+ X->s = 1;
/*
- * process the remaining bits
+ * Make sure that X is in a form that is safe for consumption by
+ * the core functions.
+ *
+ * - The core functions will not touch the limbs of X above N->n. The
+ * result will be correct if those limbs are 0, which the mod call
+ * ensures.
+ * - Also, X must have at least as many limbs as N for the calls to the
+ * core functions.
*/
- for (i = 0; i < nbits; i++) {
- MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, x_index));
- mpi_montmul(&W[x_index], &WW, N, mm, &T);
-
- exponent_bits_in_window <<= 1;
-
- if ((exponent_bits_in_window & ((size_t) 1 << window_bitsize)) != 0) {
- MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, 1));
- mpi_montmul(&W[x_index], &WW, N, mm, &T);
- }
+ if (mbedtls_mpi_cmp_mpi(X, N) >= 0) {
+ MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(X, X, N));
}
+ MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, N->n));
/*
- * W[x_index] = A^E * R * R^-1 mod N = A^E mod N
+ * Convert to and from Montgomery around mbedtls_mpi_core_exp_mod().
*/
- mpi_montred(&W[x_index], N, mm, &T);
-
- if (neg && E->n != 0 && (E->p[0] & 1) != 0) {
- W[x_index].s = -1;
- MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&W[x_index], N, &W[x_index]));
+ {
+ mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
+ mbedtls_mpi_core_to_mont_rep(X->p, X->p, N->p, N->n, mm, RR.p, T);
+ mbedtls_mpi_core_exp_mod(X->p, X->p, N->p, N->n, E->p, E->n, RR.p, T);
+ mbedtls_mpi_core_from_mont_rep(X->p, X->p, N->p, N->n, mm, T);
}
/*
- * Load the result in the output variable.
+ * Correct for negative A.
*/
- MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &W[x_index]));
-
-cleanup:
+ if (A->s == -1 && (E->p[0] & 1) != 0) {
+ mbedtls_ct_condition_t is_x_non_zero = mbedtls_mpi_core_check_zero_ct(X->p, X->n);
+ X->s = mbedtls_ct_mpi_sign_if(is_x_non_zero, -1, 1);
- /* The first bit of the sliding window is always 1 and therefore the first
- * half of the table was unused. */
- for (i = w_table_used_size/2; i < w_table_used_size; i++) {
- mbedtls_mpi_free(&W[i]);
+ MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, N, X));
}
- mbedtls_mpi_free(&W[x_index]);
- mbedtls_mpi_free(&W[1]);
- mbedtls_mpi_free(&T);
- mbedtls_mpi_free(&Apos);
- mbedtls_mpi_free(&WW);
+cleanup:
+
+ mbedtls_mpi_zeroize_and_free(T, T_limbs);
if (prec_RR == NULL || prec_RR->p == NULL) {
mbedtls_mpi_free(&RR);
diff --git a/library/bignum_core.c b/library/bignum_core.c
index dfed60d..1a3e0b9 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -856,16 +856,17 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,
return c;
}
-mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
- size_t limbs)
+mbedtls_ct_condition_t mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
+ size_t limbs)
{
+ volatile const mbedtls_mpi_uint *force_read_A = A;
mbedtls_mpi_uint bits = 0;
for (size_t i = 0; i < limbs; i++) {
- bits |= A[i];
+ bits |= force_read_A[i];
}
- return bits;
+ return mbedtls_ct_bool(bits);
}
void mbedtls_mpi_core_to_mont_rep(mbedtls_mpi_uint *X,
diff --git a/library/bignum_core.h b/library/bignum_core.h
index b56be0a..92c8d47 100644
--- a/library/bignum_core.h
+++ b/library/bignum_core.h
@@ -662,11 +662,11 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,
* \param[in] A The MPI to test.
* \param limbs Number of limbs in \p A.
*
- * \return 0 if `A == 0`
- * non-0 (may be any value) if `A != 0`.
+ * \return MBEDTLS_CT_FALSE if `A == 0`
+ * MBEDTLS_CT_TRUE if `A != 0`.
*/
-mbedtls_mpi_uint mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
- size_t limbs);
+mbedtls_ct_condition_t mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
+ size_t limbs);
/**
* \brief Returns the number of limbs of working memory required for
diff --git a/library/cmac.c b/library/cmac.c
index f40cae2..eda10d0 100644
--- a/library/cmac.c
+++ b/library/cmac.c
@@ -34,6 +34,7 @@
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include "mbedtls/platform.h"
+#include "constant_time_internal.h"
#include <string.h>
@@ -56,39 +57,33 @@ static int cmac_multiply_by_u(unsigned char *output,
size_t blocksize)
{
const unsigned char R_128 = 0x87;
- const unsigned char R_64 = 0x1B;
- unsigned char R_n, mask;
- unsigned char overflow = 0x00;
+ unsigned char R_n;
+ uint32_t overflow = 0x00;
int i;
if (blocksize == MBEDTLS_AES_BLOCK_SIZE) {
R_n = R_128;
- } else if (blocksize == MBEDTLS_DES3_BLOCK_SIZE) {
+ }
+#if defined(MBEDTLS_DES_C)
+ else if (blocksize == MBEDTLS_DES3_BLOCK_SIZE) {
+ const unsigned char R_64 = 0x1B;
R_n = R_64;
- } else {
+ }
+#endif
+ else {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
- for (i = (int) blocksize - 1; i >= 0; i--) {
- output[i] = input[i] << 1 | overflow;
- overflow = input[i] >> 7;
+ for (i = (int) blocksize - 4; i >= 0; i -= 4) {
+ uint32_t i32 = MBEDTLS_GET_UINT32_BE(&input[i], 0);
+ uint32_t new_overflow = i32 >> 31;
+ i32 = (i32 << 1) | overflow;
+ MBEDTLS_PUT_UINT32_BE(i32, &output[i], 0);
+ overflow = new_overflow;
}
- /* mask = ( input[0] >> 7 ) ? 0xff : 0x00
- * using bit operations to avoid branches */
-
- /* MSVC has a warning about unary minus on unsigned, but this is
- * well-defined and precisely what we want to do here */
-#if defined(_MSC_VER)
-#pragma warning( push )
-#pragma warning( disable : 4146 )
-#endif
- mask = -(input[0] >> 7);
-#if defined(_MSC_VER)
-#pragma warning( pop )
-#endif
-
- output[blocksize - 1] ^= R_n & mask;
+ R_n = (unsigned char) mbedtls_ct_uint_if_else_0(mbedtls_ct_bool(input[0] >> 7), R_n);
+ output[blocksize - 1] ^= R_n;
return 0;
}
@@ -217,6 +212,10 @@ int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,
block_size = mbedtls_cipher_info_get_block_size(ctx->cipher_info);
state = ctx->cmac_ctx->state;
+ /* Without the MBEDTLS_ASSUME below, gcc -O3 will generate a warning of the form
+ * error: writing 16 bytes into a region of size 0 [-Werror=stringop-overflow=] */
+ MBEDTLS_ASSUME(block_size <= MBEDTLS_CMAC_MAX_BLOCK_SIZE);
+
/* Is there data still to process from the last call, that's greater in
* size than a block? */
if (cmac_ctx->unprocessed_len > 0 &&
@@ -284,6 +283,7 @@ int mbedtls_cipher_cmac_finish(mbedtls_cipher_context_t *ctx,
cmac_ctx = ctx->cmac_ctx;
block_size = mbedtls_cipher_info_get_block_size(ctx->cipher_info);
+ MBEDTLS_ASSUME(block_size <= MBEDTLS_CMAC_MAX_BLOCK_SIZE); // silence GCC warning
state = cmac_ctx->state;
mbedtls_platform_zeroize(K1, sizeof(K1));
diff --git a/library/ecdh.c b/library/ecdh.c
index 52b1617..b276c6a 100644
--- a/library/ecdh.c
+++ b/library/ecdh.c
@@ -144,6 +144,15 @@ static void ecdh_init_internal(mbedtls_ecdh_context_mbed *ctx)
#endif
}
+mbedtls_ecp_group_id mbedtls_ecdh_get_grp_id(mbedtls_ecdh_context *ctx)
+{
+#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
+ return ctx->MBEDTLS_PRIVATE(grp).id;
+#else
+ return ctx->MBEDTLS_PRIVATE(grp_id);
+#endif
+}
+
/*
* Initialize context
*/
diff --git a/library/ecp.c b/library/ecp.c
index 66b3dc1..427059b 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -3302,6 +3302,7 @@ cleanup:
/*
* Write a private key.
*/
+#if !defined MBEDTLS_DEPRECATED_REMOVED
int mbedtls_ecp_write_key(mbedtls_ecp_keypair *key,
unsigned char *buf, size_t buflen)
{
@@ -3332,6 +3333,39 @@ cleanup:
return ret;
}
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+int mbedtls_ecp_write_key_ext(const mbedtls_ecp_keypair *key,
+ size_t *olen, unsigned char *buf, size_t buflen)
+{
+ size_t len = (key->grp.nbits + 7) / 8;
+ if (len > buflen) {
+ /* For robustness, ensure *olen <= buflen even on error. */
+ *olen = 0;
+ return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
+ }
+ *olen = len;
+
+ /* Private key not set */
+ if (key->d.n == 0) {
+ return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
+ }
+
+#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
+ if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
+ return mbedtls_mpi_write_binary_le(&key->d, buf, len);
+ }
+#endif
+
+#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
+ if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
+ return mbedtls_mpi_write_binary(&key->d, buf, len);
+ }
+#endif
+
+ /* Private key set but no recognized curve type? This shouldn't happen. */
+ return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+}
/*
* Write a public key.
diff --git a/library/gcm.c b/library/gcm.c
index 90c1d1d..5dfac23 100644
--- a/library/gcm.c
+++ b/library/gcm.c
@@ -412,8 +412,17 @@ int mbedtls_gcm_starts(mbedtls_gcm_context *ctx,
while (iv_len > 0) {
use_len = (iv_len < 16) ? iv_len : 16;
+#if defined(MBEDTLS_COMPILER_IS_GCC) && (MBEDTLS_GCC_VERSION >= 70110)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic warning "-Wstringop-overflow=0"
+#endif
+
mbedtls_xor(ctx->y, ctx->y, p, use_len);
+#if defined(MBEDTLS_COMPILER_IS_GCC) && (MBEDTLS_GCC_VERSION >= 70110)
+#pragma GCC diagnostic pop
+#endif
+
gcm_mult(ctx, ctx->y, ctx->y);
iv_len -= use_len;
diff --git a/library/pk.c b/library/pk.c
index 1ded487..097777f 100644
--- a/library/pk.c
+++ b/library/pk.c
@@ -35,6 +35,10 @@
#include <limits.h>
#include <stdint.h>
+#define PSA_EXPORT_KEY_PAIR_OR_PUBLIC_MAX_SIZE \
+ (PSA_EXPORT_KEY_PAIR_MAX_SIZE > PSA_EXPORT_PUBLIC_KEY_MAX_SIZE) ? \
+ PSA_EXPORT_KEY_PAIR_MAX_SIZE : PSA_EXPORT_PUBLIC_KEY_MAX_SIZE
+
/*
* Initialise a mbedtls_pk_context
*/
@@ -320,14 +324,14 @@ int mbedtls_pk_can_do_ext(const mbedtls_pk_context *ctx, psa_algorithm_t alg,
}
psa_algorithm_t key_alg = psa_get_key_algorithm(&attributes);
- /* Key's enrollment is available only when MBEDTLS_PSA_CRYPTO_CLIENT is
- * defined, i.e. when the Mbed TLS implementation of PSA Crypto is being used.
+ /* Key's enrollment is available only when an Mbed TLS implementation of PSA
+ * Crypto is being used, i.e. when MBEDTLS_PSA_CRYPTO_C is defined.
* Even though we don't officially support using other implementations of PSA
- * Crypto with TLS and X.509 (yet), we're still trying to simplify the life of
- * people who would like to try it before it's officially supported. */
-#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
+ * Crypto with TLS and X.509 (yet), we try to keep vendor's customizations
+ * separated. */
+#if defined(MBEDTLS_PSA_CRYPTO_C)
psa_algorithm_t key_alg2 = psa_get_key_enrollment_algorithm(&attributes);
-#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
+#endif /* MBEDTLS_PSA_CRYPTO_C */
key_usage = psa_get_key_usage_flags(&attributes);
psa_reset_key_attributes(&attributes);
@@ -345,11 +349,11 @@ int mbedtls_pk_can_do_ext(const mbedtls_pk_context *ctx, psa_algorithm_t alg,
if (alg == key_alg) {
return 1;
}
-#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
+#if defined(MBEDTLS_PSA_CRYPTO_C)
if (alg == key_alg2) {
return 1;
}
-#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
+#endif /* MBEDTLS_PSA_CRYPTO_C */
/*
* If key_alg [or key_alg2] is a hash-and-sign with a wildcard for the hash,
@@ -357,26 +361,25 @@ int mbedtls_pk_can_do_ext(const mbedtls_pk_context *ctx, psa_algorithm_t alg,
* then alg is compliant with this key alg
*/
if (PSA_ALG_IS_SIGN_HASH(alg)) {
-
if (PSA_ALG_IS_SIGN_HASH(key_alg) &&
PSA_ALG_SIGN_GET_HASH(key_alg) == PSA_ALG_ANY_HASH &&
(alg & ~PSA_ALG_HASH_MASK) == (key_alg & ~PSA_ALG_HASH_MASK)) {
return 1;
}
-#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
+#if defined(MBEDTLS_PSA_CRYPTO_C)
if (PSA_ALG_IS_SIGN_HASH(key_alg2) &&
PSA_ALG_SIGN_GET_HASH(key_alg2) == PSA_ALG_ANY_HASH &&
(alg & ~PSA_ALG_HASH_MASK) == (key_alg2 & ~PSA_ALG_HASH_MASK)) {
return 1;
}
-#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
+#endif /* MBEDTLS_PSA_CRYPTO_C */
}
return 0;
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
-#if defined(MBEDTLS_PSA_CRYPTO_C)
+#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
#if defined(MBEDTLS_RSA_C)
static psa_algorithm_t psa_algorithm_for_rsa(const mbedtls_rsa_context *rsa,
int want_crypt)
@@ -573,7 +576,14 @@ int mbedtls_pk_get_psa_attributes(const mbedtls_pk_context *pk,
}
psa_set_key_usage_flags(attributes, more_usage);
+ /* Key's enrollment is available only when an Mbed TLS implementation of PSA
+ * Crypto is being used, i.e. when MBEDTLS_PSA_CRYPTO_C is defined.
+ * Even though we don't officially support using other implementations of PSA
+ * Crypto with TLS and X.509 (yet), we try to keep vendor's customizations
+ * separated. */
+#if defined(MBEDTLS_PSA_CRYPTO_C)
psa_set_key_enrollment_algorithm(attributes, PSA_ALG_NONE);
+#endif
return 0;
}
@@ -675,10 +685,7 @@ static int import_pair_into_psa(const mbedtls_pk_context *pk,
#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
psa_ecc_family_t from_family = pk->ec_family;
#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
- /* We're only reading the key, but mbedtls_ecp_write_key()
- * is missing a const annotation on its key parameter, so
- * we need the non-const accessor here. */
- mbedtls_ecp_keypair *ec = mbedtls_pk_ec_rw(*pk);
+ const mbedtls_ecp_keypair *ec = mbedtls_pk_ec_ro(*pk);
size_t from_bits = 0;
psa_ecc_family_t from_family = mbedtls_ecc_group_to_psa(ec->grp.id,
&from_bits);
@@ -704,12 +711,9 @@ static int import_pair_into_psa(const mbedtls_pk_context *pk,
return MBEDTLS_ERR_PK_TYPE_MISMATCH;
}
unsigned char key_buffer[PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
- /* Make sure to pass the exact key length to
- * mbedtls_ecp_write_key(), because it writes Montgomery keys
- * at the start of the buffer but Weierstrass keys at the
- * end of the buffer. */
- size_t key_length = PSA_BITS_TO_BYTES(ec->grp.nbits);
- int ret = mbedtls_ecp_write_key(ec, key_buffer, key_length);
+ size_t key_length = 0;
+ int ret = mbedtls_ecp_write_key_ext(ec, &key_length,
+ key_buffer, sizeof(key_buffer));
if (ret < 0) {
return ret;
}
@@ -856,7 +860,136 @@ int mbedtls_pk_import_into_psa(const mbedtls_pk_context *pk,
return import_pair_into_psa(pk, attributes, key_id);
}
}
-#endif /* MBEDTLS_PSA_CRYPTO_C */
+
+static int copy_from_psa(mbedtls_svc_key_id_t key_id,
+ mbedtls_pk_context *pk,
+ int public_only)
+{
+ psa_status_t status;
+ psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
+ psa_key_type_t key_type;
+ psa_algorithm_t alg_type;
+ size_t key_bits;
+ /* Use a buffer size large enough to contain either a key pair or public key. */
+ unsigned char exp_key[PSA_EXPORT_KEY_PAIR_OR_PUBLIC_MAX_SIZE];
+ size_t exp_key_len;
+ int ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+
+ if (pk == NULL) {
+ return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+ }
+
+ status = psa_get_key_attributes(key_id, &key_attr);
+ if (status != PSA_SUCCESS) {
+ return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+ }
+
+ if (public_only) {
+ status = psa_export_public_key(key_id, exp_key, sizeof(exp_key), &exp_key_len);
+ } else {
+ status = psa_export_key(key_id, exp_key, sizeof(exp_key), &exp_key_len);
+ }
+ if (status != PSA_SUCCESS) {
+ ret = PSA_PK_TO_MBEDTLS_ERR(status);
+ goto exit;
+ }
+
+ key_type = psa_get_key_type(&key_attr);
+ if (public_only) {
+ key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(key_type);
+ }
+ key_bits = psa_get_key_bits(&key_attr);
+ alg_type = psa_get_key_algorithm(&key_attr);
+
+#if defined(MBEDTLS_RSA_C)
+ if ((key_type == PSA_KEY_TYPE_RSA_KEY_PAIR) ||
+ (key_type == PSA_KEY_TYPE_RSA_PUBLIC_KEY)) {
+
+ ret = mbedtls_pk_setup(pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));
+ if (ret != 0) {
+ goto exit;
+ }
+
+ if (key_type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
+ ret = mbedtls_rsa_parse_key(mbedtls_pk_rsa(*pk), exp_key, exp_key_len);
+ } else {
+ ret = mbedtls_rsa_parse_pubkey(mbedtls_pk_rsa(*pk), exp_key, exp_key_len);
+ }
+ if (ret != 0) {
+ goto exit;
+ }
+
+ mbedtls_md_type_t md_type = MBEDTLS_MD_NONE;
+ if (PSA_ALG_GET_HASH(alg_type) != PSA_ALG_ANY_HASH) {
+ md_type = mbedtls_md_type_from_psa_alg(alg_type);
+ }
+
+ if (PSA_ALG_IS_RSA_OAEP(alg_type) || PSA_ALG_IS_RSA_PSS(alg_type)) {
+ ret = mbedtls_rsa_set_padding(mbedtls_pk_rsa(*pk), MBEDTLS_RSA_PKCS_V21, md_type);
+ } else if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg_type) ||
+ alg_type == PSA_ALG_RSA_PKCS1V15_CRYPT) {
+ ret = mbedtls_rsa_set_padding(mbedtls_pk_rsa(*pk), MBEDTLS_RSA_PKCS_V15, md_type);
+ }
+ if (ret != 0) {
+ goto exit;
+ }
+ } else
+#endif /* MBEDTLS_RSA_C */
+#if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
+ if (PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) ||
+ PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(key_type)) {
+ mbedtls_ecp_group_id grp_id;
+
+ ret = mbedtls_pk_setup(pk, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY));
+ if (ret != 0) {
+ goto exit;
+ }
+
+ grp_id = mbedtls_ecc_group_from_psa(PSA_KEY_TYPE_ECC_GET_FAMILY(key_type), key_bits);
+ ret = mbedtls_pk_ecc_set_group(pk, grp_id);
+ if (ret != 0) {
+ goto exit;
+ }
+
+ if (PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type)) {
+ ret = mbedtls_pk_ecc_set_key(pk, exp_key, exp_key_len);
+ if (ret != 0) {
+ goto exit;
+ }
+ ret = mbedtls_pk_ecc_set_pubkey_from_prv(pk, exp_key, exp_key_len,
+ mbedtls_psa_get_random,
+ MBEDTLS_PSA_RANDOM_STATE);
+ } else {
+ ret = mbedtls_pk_ecc_set_pubkey(pk, exp_key, exp_key_len);
+ }
+ if (ret != 0) {
+ goto exit;
+ }
+ } else
+#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
+ {
+ return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+ }
+
+exit:
+ psa_reset_key_attributes(&key_attr);
+ mbedtls_platform_zeroize(exp_key, sizeof(exp_key));
+
+ return ret;
+}
+
+int mbedtls_pk_copy_from_psa(mbedtls_svc_key_id_t key_id,
+ mbedtls_pk_context *pk)
+{
+ return copy_from_psa(key_id, pk, 0);
+}
+
+int mbedtls_pk_copy_public_from_psa(mbedtls_svc_key_id_t key_id,
+ mbedtls_pk_context *pk)
+{
+ return copy_from_psa(key_id, pk, 1);
+}
+#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
/*
* Helper for mbedtls_pk_sign and mbedtls_pk_verify
@@ -993,6 +1126,12 @@ int mbedtls_pk_verify_ext(mbedtls_pk_type_t type, const void *options,
return mbedtls_pk_verify(ctx, md_alg, hash, hash_len, sig, sig_len);
}
+ /* Ensure the PK context is of the right type otherwise mbedtls_pk_rsa()
+ * below would return a NULL pointer. */
+ if (mbedtls_pk_get_type(ctx) != MBEDTLS_PK_RSA) {
+ return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
+ }
+
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21)
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_pk_rsassa_pss_options *pss_opts;
@@ -1023,7 +1162,7 @@ int mbedtls_pk_verify_ext(mbedtls_pk_type_t type, const void *options,
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t psa_sig_alg = PSA_ALG_RSA_PSS_ANY_SALT(psa_md_alg);
p = buf + sizeof(buf);
- key_len = mbedtls_pk_write_pubkey(&p, buf, ctx);
+ key_len = mbedtls_rsa_write_pubkey(mbedtls_pk_rsa(*ctx), buf, &p);
if (key_len < 0) {
return key_len;
@@ -1188,9 +1327,41 @@ int mbedtls_pk_sign_ext(mbedtls_pk_type_t pk_type,
}
if (mbedtls_pk_get_type(ctx) == MBEDTLS_PK_OPAQUE) {
+ psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
+ psa_algorithm_t psa_alg, sign_alg;
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+ psa_algorithm_t psa_enrollment_alg;
+#endif /* MBEDTLS_PSA_CRYPTO_C */
psa_status_t status;
- status = psa_sign_hash(ctx->priv_id, PSA_ALG_RSA_PSS(psa_md_alg),
+ status = psa_get_key_attributes(ctx->priv_id, &key_attr);
+ if (status != PSA_SUCCESS) {
+ return PSA_PK_RSA_TO_MBEDTLS_ERR(status);
+ }
+ psa_alg = psa_get_key_algorithm(&key_attr);
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+ psa_enrollment_alg = psa_get_key_enrollment_algorithm(&key_attr);
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+ psa_reset_key_attributes(&key_attr);
+
+ /* Since we're PK type is MBEDTLS_PK_RSASSA_PSS at least one between
+ * alg and enrollment alg should be of type RSA_PSS. */
+ if (PSA_ALG_IS_RSA_PSS(psa_alg)) {
+ sign_alg = psa_alg;
+ }
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+ else if (PSA_ALG_IS_RSA_PSS(psa_enrollment_alg)) {
+ sign_alg = psa_enrollment_alg;
+ }
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+ else {
+ /* The opaque key has no RSA PSS algorithm associated. */
+ return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+ }
+ /* Adjust the hashing algorithm. */
+ sign_alg = (sign_alg & ~PSA_ALG_HASH_MASK) | PSA_ALG_GET_HASH(psa_md_alg);
+
+ status = psa_sign_hash(ctx->priv_id, sign_alg,
hash, hash_len,
sig, sig_size, sig_len);
return PSA_PK_RSA_TO_MBEDTLS_ERR(status);
@@ -1357,124 +1528,4 @@ mbedtls_pk_type_t mbedtls_pk_get_type(const mbedtls_pk_context *ctx)
return ctx->pk_info->type;
}
-#if defined(MBEDTLS_USE_PSA_CRYPTO)
-/*
- * Load the key to a PSA key slot,
- * then turn the PK context into a wrapper for that key slot.
- *
- * Currently only works for EC & RSA private keys.
- */
-int mbedtls_pk_wrap_as_opaque(mbedtls_pk_context *pk,
- mbedtls_svc_key_id_t *key,
- psa_algorithm_t alg,
- psa_key_usage_t usage,
- psa_algorithm_t alg2)
-{
-#if !defined(MBEDTLS_PK_HAVE_ECC_KEYS) && !defined(MBEDTLS_RSA_C)
- ((void) pk);
- ((void) key);
- ((void) alg);
- ((void) usage);
- ((void) alg2);
-#else /* !MBEDTLS_PK_HAVE_ECC_KEYS && !MBEDTLS_RSA_C */
-#if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
- if (mbedtls_pk_get_type(pk) == MBEDTLS_PK_ECKEY) {
- size_t d_len;
- psa_ecc_family_t curve_id;
- psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
- psa_key_type_t key_type;
- size_t bits;
- psa_status_t status;
-
- /* export the private key material in the format PSA wants */
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
- unsigned char d[MBEDTLS_PSA_MAX_EC_KEY_PAIR_LENGTH];
- status = psa_export_key(pk->priv_id, d, sizeof(d), &d_len);
- if (status != PSA_SUCCESS) {
- return psa_pk_status_to_mbedtls(status);
- }
-
- curve_id = pk->ec_family;
- bits = pk->ec_bits;
-#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
- unsigned char d[MBEDTLS_ECP_MAX_BYTES];
- mbedtls_ecp_keypair *ec = mbedtls_pk_ec_rw(*pk);
- int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
-
- d_len = PSA_BITS_TO_BYTES(ec->grp.nbits);
- if ((ret = mbedtls_ecp_write_key(ec, d, d_len)) != 0) {
- return ret;
- }
-
- curve_id = mbedtls_ecc_group_to_psa(ec->grp.id, &bits);
-#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
- key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(curve_id);
-
- /* prepare the key attributes */
- psa_set_key_type(&attributes, key_type);
- psa_set_key_bits(&attributes, bits);
- psa_set_key_usage_flags(&attributes, usage);
- psa_set_key_algorithm(&attributes, alg);
- if (alg2 != PSA_ALG_NONE) {
- psa_set_key_enrollment_algorithm(&attributes, alg2);
- }
-
- /* import private key into PSA */
- status = psa_import_key(&attributes, d, d_len, key);
- mbedtls_platform_zeroize(d, sizeof(d));
- if (status != PSA_SUCCESS) {
- return PSA_PK_TO_MBEDTLS_ERR(status);
- }
-
- /* make PK context wrap the key slot */
- mbedtls_pk_free(pk);
- mbedtls_pk_init(pk);
-
- return mbedtls_pk_setup_opaque(pk, *key);
- } else
-#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
-#if defined(MBEDTLS_RSA_C)
- if (mbedtls_pk_get_type(pk) == MBEDTLS_PK_RSA) {
- unsigned char buf[MBEDTLS_PK_RSA_PRV_DER_MAX_BYTES];
- psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
- int key_len;
- psa_status_t status;
-
- /* export the private key material in the format PSA wants */
- key_len = mbedtls_pk_write_key_der(pk, buf, sizeof(buf));
- if (key_len <= 0) {
- return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
- }
-
- /* prepare the key attributes */
- psa_set_key_type(&attributes, PSA_KEY_TYPE_RSA_KEY_PAIR);
- psa_set_key_bits(&attributes, mbedtls_pk_get_bitlen(pk));
- psa_set_key_usage_flags(&attributes, usage);
- psa_set_key_algorithm(&attributes, alg);
- if (alg2 != PSA_ALG_NONE) {
- psa_set_key_enrollment_algorithm(&attributes, alg2);
- }
-
- /* import private key into PSA */
- status = psa_import_key(&attributes,
- buf + sizeof(buf) - key_len,
- key_len, key);
-
- mbedtls_platform_zeroize(buf, sizeof(buf));
-
- if (status != PSA_SUCCESS) {
- return PSA_PK_TO_MBEDTLS_ERR(status);
- }
-
- /* make PK context wrap the key slot */
- mbedtls_pk_free(pk);
- mbedtls_pk_init(pk);
-
- return mbedtls_pk_setup_opaque(pk, *key);
- } else
-#endif /* MBEDTLS_RSA_C */
-#endif /* !MBEDTLS_PK_HAVE_ECC_KEYS && !MBEDTLS_RSA_C */
- return MBEDTLS_ERR_PK_TYPE_MISMATCH;
-}
-#endif /* MBEDTLS_USE_PSA_CRYPTO */
#endif /* MBEDTLS_PK_C */
diff --git a/library/pk_ecc.c b/library/pk_ecc.c
new file mode 100644
index 0000000..86218ff
--- /dev/null
+++ b/library/pk_ecc.c
@@ -0,0 +1,255 @@
+/*
+ * ECC setters for PK.
+ *
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#include "common.h"
+
+#include "mbedtls/pk.h"
+#include "mbedtls/error.h"
+#include "mbedtls/ecp.h"
+#include "pk_internal.h"
+
+#if defined(MBEDTLS_PK_C) && defined(MBEDTLS_PK_HAVE_ECC_KEYS)
+
+int mbedtls_pk_ecc_set_group(mbedtls_pk_context *pk, mbedtls_ecp_group_id grp_id)
+{
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+ size_t ec_bits;
+ psa_ecc_family_t ec_family = mbedtls_ecc_group_to_psa(grp_id, &ec_bits);
+
+ /* group may already be initialized; if so, make sure IDs match */
+ if ((pk->ec_family != 0 && pk->ec_family != ec_family) ||
+ (pk->ec_bits != 0 && pk->ec_bits != ec_bits)) {
+ return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
+ }
+
+ /* set group */
+ pk->ec_family = ec_family;
+ pk->ec_bits = ec_bits;
+
+ return 0;
+#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
+ mbedtls_ecp_keypair *ecp = mbedtls_pk_ec_rw(*pk);
+
+ /* grp may already be initialized; if so, make sure IDs match */
+ if (mbedtls_pk_ec_ro(*pk)->grp.id != MBEDTLS_ECP_DP_NONE &&
+ mbedtls_pk_ec_ro(*pk)->grp.id != grp_id) {
+ return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
+ }
+
+ /* set group */
+ return mbedtls_ecp_group_load(&(ecp->grp), grp_id);
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
+}
+
+int mbedtls_pk_ecc_set_key(mbedtls_pk_context *pk, unsigned char *key, size_t key_len)
+{
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+ psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+ psa_key_usage_t flags;
+ psa_status_t status;
+
+ psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(pk->ec_family));
+ if (pk->ec_family == PSA_ECC_FAMILY_MONTGOMERY) {
+ /* Do not set algorithm here because Montgomery keys cannot do ECDSA and
+ * the PK module cannot do ECDH. When the key will be used in TLS for
+ * ECDH, it will be exported and then re-imported with proper flags
+ * and algorithm. */
+ flags = PSA_KEY_USAGE_EXPORT;
+ } else {
+ psa_set_key_algorithm(&attributes,
+ MBEDTLS_PK_PSA_ALG_ECDSA_MAYBE_DET(PSA_ALG_ANY_HASH));
+ flags = PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_SIGN_MESSAGE |
+ PSA_KEY_USAGE_EXPORT;
+ }
+ psa_set_key_usage_flags(&attributes, flags);
+
+ status = psa_import_key(&attributes, key, key_len, &pk->priv_id);
+ return psa_pk_status_to_mbedtls(status);
+
+#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
+
+ mbedtls_ecp_keypair *eck = mbedtls_pk_ec_rw(*pk);
+ int ret = mbedtls_ecp_read_key(eck->grp.id, eck, key, key_len);
+ if (ret != 0) {
+ return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
+ }
+ return 0;
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
+}
+
+int mbedtls_pk_ecc_set_pubkey_from_prv(mbedtls_pk_context *pk,
+ const unsigned char *prv, size_t prv_len,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
+{
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+
+ (void) f_rng;
+ (void) p_rng;
+ (void) prv;
+ (void) prv_len;
+ psa_status_t status;
+
+ status = psa_export_public_key(pk->priv_id, pk->pub_raw, sizeof(pk->pub_raw),
+ &pk->pub_raw_len);
+ return psa_pk_status_to_mbedtls(status);
+
+#elif defined(MBEDTLS_USE_PSA_CRYPTO) /* && !MBEDTLS_PK_USE_PSA_EC_DATA */
+
+ (void) f_rng;
+ (void) p_rng;
+ psa_status_t status;
+
+ mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
+ size_t curve_bits;
+ psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(eck->grp.id, &curve_bits);
+
+ /* Import private key into PSA, from serialized input */
+ mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+ psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
+ psa_set_key_type(&key_attr, PSA_KEY_TYPE_ECC_KEY_PAIR(curve));
+ psa_set_key_usage_flags(&key_attr, PSA_KEY_USAGE_EXPORT);
+ status = psa_import_key(&key_attr, prv, prv_len, &key_id);
+ if (status != PSA_SUCCESS) {
+ return psa_pk_status_to_mbedtls(status);
+ }
+
+ /* Export public key from PSA */
+ unsigned char pub[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
+ size_t pub_len;
+ status = psa_export_public_key(key_id, pub, sizeof(pub), &pub_len);
+ psa_status_t destruction_status = psa_destroy_key(key_id);
+ if (status != PSA_SUCCESS) {
+ return psa_pk_status_to_mbedtls(status);
+ } else if (destruction_status != PSA_SUCCESS) {
+ return psa_pk_status_to_mbedtls(destruction_status);
+ }
+
+ /* Load serialized public key into ecp_keypair structure */
+ return mbedtls_ecp_point_read_binary(&eck->grp, &eck->Q, pub, pub_len);
+
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+
+ (void) prv;
+ (void) prv_len;
+
+ mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
+ return mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G, f_rng, p_rng);
+
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+}
+
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+/*
+ * Set the public key: fallback using ECP_LIGHT in the USE_PSA_EC_DATA case.
+ *
+ * Normally, when MBEDTLS_PK_USE_PSA_EC_DATA is enabled, we only use PSA
+ * functions to handle keys. However, currently psa_import_key() does not
+ * support compressed points. In case that support was explicitly requested,
+ * this fallback uses ECP functions to get the job done. This is the reason
+ * why MBEDTLS_PK_PARSE_EC_COMPRESSED auto-enables MBEDTLS_ECP_LIGHT.
+ *
+ * [in/out] pk: in: must have the group set, see mbedtls_pk_ecc_set_group().
+ * out: will have the public key set.
+ * [in] pub, pub_len: the public key as an ECPoint,
+ * in any format supported by ECP.
+ *
+ * Return:
+ * - 0 on success;
+ * - MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the format is potentially valid
+ * but not supported;
+ * - another error code otherwise.
+ */
+static int pk_ecc_set_pubkey_psa_ecp_fallback(mbedtls_pk_context *pk,
+ const unsigned char *pub,
+ size_t pub_len)
+{
+#if !defined(MBEDTLS_PK_PARSE_EC_COMPRESSED)
+ (void) pk;
+ (void) pub;
+ (void) pub_len;
+ return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
+#else /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
+ mbedtls_ecp_keypair ecp_key;
+ mbedtls_ecp_group_id ecp_group_id;
+ int ret;
+
+ ecp_group_id = mbedtls_ecc_group_from_psa(pk->ec_family, pk->ec_bits);
+
+ mbedtls_ecp_keypair_init(&ecp_key);
+ ret = mbedtls_ecp_group_load(&(ecp_key.grp), ecp_group_id);
+ if (ret != 0) {
+ goto exit;
+ }
+ ret = mbedtls_ecp_point_read_binary(&(ecp_key.grp), &ecp_key.Q,
+ pub, pub_len);
+ if (ret != 0) {
+ goto exit;
+ }
+ ret = mbedtls_ecp_point_write_binary(&(ecp_key.grp), &ecp_key.Q,
+ MBEDTLS_ECP_PF_UNCOMPRESSED,
+ &pk->pub_raw_len, pk->pub_raw,
+ sizeof(pk->pub_raw));
+
+exit:
+ mbedtls_ecp_keypair_free(&ecp_key);
+ return ret;
+#endif /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
+}
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
+
+int mbedtls_pk_ecc_set_pubkey(mbedtls_pk_context *pk, const unsigned char *pub, size_t pub_len)
+{
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+
+ /* Load the key */
+ if (!PSA_ECC_FAMILY_IS_WEIERSTRASS(pk->ec_family) || *pub == 0x04) {
+ /* Format directly supported by PSA:
+ * - non-Weierstrass curves that only have one format;
+ * - uncompressed format for Weierstrass curves. */
+ if (pub_len > sizeof(pk->pub_raw)) {
+ return MBEDTLS_ERR_PK_BUFFER_TOO_SMALL;
+ }
+ memcpy(pk->pub_raw, pub, pub_len);
+ pk->pub_raw_len = pub_len;
+ } else {
+ /* Other format, try the fallback */
+ int ret = pk_ecc_set_pubkey_psa_ecp_fallback(pk, pub, pub_len);
+ if (ret != 0) {
+ return ret;
+ }
+ }
+
+ /* Validate the key by trying to import it */
+ mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
+ psa_key_attributes_t key_attrs = PSA_KEY_ATTRIBUTES_INIT;
+
+ psa_set_key_usage_flags(&key_attrs, 0);
+ psa_set_key_type(&key_attrs, PSA_KEY_TYPE_ECC_PUBLIC_KEY(pk->ec_family));
+ psa_set_key_bits(&key_attrs, pk->ec_bits);
+
+ if ((psa_import_key(&key_attrs, pk->pub_raw, pk->pub_raw_len,
+ &key_id) != PSA_SUCCESS) ||
+ (psa_destroy_key(key_id) != PSA_SUCCESS)) {
+ return MBEDTLS_ERR_PK_INVALID_PUBKEY;
+ }
+
+ return 0;
+
+#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
+
+ int ret;
+ mbedtls_ecp_keypair *ec_key = (mbedtls_ecp_keypair *) pk->pk_ctx;
+ ret = mbedtls_ecp_point_read_binary(&ec_key->grp, &ec_key->Q, pub, pub_len);
+ if (ret != 0) {
+ return ret;
+ }
+ return mbedtls_ecp_check_pubkey(&ec_key->grp, &ec_key->Q);
+
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
+}
+
+#endif /* MBEDTLS_PK_C && MBEDTLS_PK_HAVE_ECC_KEYS */
diff --git a/library/pk_internal.h b/library/pk_internal.h
index f5924ad..e86a3a0 100644
--- a/library/pk_internal.h
+++ b/library/pk_internal.h
@@ -127,6 +127,62 @@ static inline int mbedtls_pk_is_rfc8410(const mbedtls_pk_context *pk)
return MBEDTLS_PK_IS_RFC8410_GROUP_ID(id);
}
+
+/*
+ * Set the group used by this key.
+ *
+ * [in/out] pk: in: must have been pk_setup() to an ECC type
+ * out: will have group (curve) information set
+ * [in] grp_in: a supported group ID (not NONE)
+ */
+int mbedtls_pk_ecc_set_group(mbedtls_pk_context *pk, mbedtls_ecp_group_id grp_id);
+
+/*
+ * Set the private key material
+ *
+ * [in/out] pk: in: must have the group set already, see mbedtls_pk_ecc_set_group().
+ * out: will have the private key set.
+ * [in] key, key_len: the raw private key (no ASN.1 wrapping).
+ */
+int mbedtls_pk_ecc_set_key(mbedtls_pk_context *pk, unsigned char *key, size_t key_len);
+
+/*
+ * Set the public key.
+ *
+ * [in/out] pk: in: must have its group set, see mbedtls_pk_ecc_set_group().
+ * out: will have the public key set.
+ * [in] pub, pub_len: the raw public key (an ECPoint).
+ *
+ * Return:
+ * - 0 on success;
+ * - MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the format is potentially valid
+ * but not supported;
+ * - another error code otherwise.
+ */
+int mbedtls_pk_ecc_set_pubkey(mbedtls_pk_context *pk, const unsigned char *pub, size_t pub_len);
+
+/*
+ * Derive a public key from its private counterpart.
+ * Computationally intensive, only use when public key is not available.
+ *
+ * [in/out] pk: in: must have the private key set, see mbedtls_pk_ecc_set_key().
+ * out: will have the public key set.
+ * [in] prv, prv_len: the raw private key (see note below).
+ * [in] f_rng, p_rng: RNG function and context.
+ *
+ * Note: the private key information is always available from pk,
+ * however for convenience the serialized version is also passed,
+ * as it's available at each calling site, and useful in some configs
+ * (as otherwise we would have to re-serialize it from the pk context).
+ *
+ * There are three implementations of this function:
+ * 1. MBEDTLS_PK_USE_PSA_EC_DATA,
+ * 2. MBEDTLS_USE_PSA_CRYPTO but not MBEDTLS_PK_USE_PSA_EC_DATA,
+ * 3. not MBEDTLS_USE_PSA_CRYPTO.
+ */
+int mbedtls_pk_ecc_set_pubkey_from_prv(mbedtls_pk_context *pk,
+ const unsigned char *prv, size_t prv_len,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
/* Helper for (deterministic) ECDSA */
diff --git a/library/pk_wrap.c b/library/pk_wrap.c
index 846175e..19196b5 100644
--- a/library/pk_wrap.c
+++ b/library/pk_wrap.c
@@ -368,7 +368,7 @@ static int rsa_encrypt_wrap(mbedtls_pk_context *pk,
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
- psa_algorithm_t psa_md_alg;
+ psa_algorithm_t psa_md_alg, psa_encrypt_alg;
psa_status_t status;
int key_len;
unsigned char buf[MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES];
@@ -389,10 +389,11 @@ static int rsa_encrypt_wrap(mbedtls_pk_context *pk,
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
if (mbedtls_rsa_get_padding_mode(rsa) == MBEDTLS_RSA_PKCS_V21) {
psa_md_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) mbedtls_rsa_get_md_alg(rsa));
- psa_set_key_algorithm(&attributes, PSA_ALG_RSA_OAEP(psa_md_alg));
+ psa_encrypt_alg = PSA_ALG_RSA_OAEP(psa_md_alg);
} else {
- psa_set_key_algorithm(&attributes, PSA_ALG_RSA_PKCS1V15_CRYPT);
+ psa_encrypt_alg = PSA_ALG_RSA_PKCS1V15_CRYPT;
}
+ psa_set_key_algorithm(&attributes, psa_encrypt_alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_RSA_PUBLIC_KEY);
status = psa_import_key(&attributes,
@@ -403,7 +404,7 @@ static int rsa_encrypt_wrap(mbedtls_pk_context *pk,
goto cleanup;
}
- status = psa_asymmetric_encrypt(key_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
+ status = psa_asymmetric_encrypt(key_id, psa_encrypt_alg,
input, ilen,
NULL, 0,
output, osize, olen);
@@ -1468,16 +1469,29 @@ static int rsa_opaque_decrypt(mbedtls_pk_context *pk,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
+ psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+ psa_algorithm_t alg;
+ psa_key_type_t type;
psa_status_t status;
/* PSA has its own RNG */
(void) f_rng;
(void) p_rng;
- status = psa_asymmetric_decrypt(pk->priv_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
- input, ilen,
- NULL, 0,
- output, osize, olen);
+ status = psa_get_key_attributes(pk->priv_id, &attributes);
+ if (status != PSA_SUCCESS) {
+ return PSA_PK_TO_MBEDTLS_ERR(status);
+ }
+
+ type = psa_get_key_type(&attributes);
+ alg = psa_get_key_algorithm(&attributes);
+ psa_reset_key_attributes(&attributes);
+
+ if (!PSA_KEY_TYPE_IS_RSA(type)) {
+ return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
+ }
+
+ status = psa_asymmetric_decrypt(pk->priv_id, alg, input, ilen, NULL, 0, output, osize, olen);
if (status != PSA_SUCCESS) {
return PSA_PK_RSA_TO_MBEDTLS_ERR(status);
}
@@ -1507,17 +1521,16 @@ static int rsa_opaque_sign_wrap(mbedtls_pk_context *pk, mbedtls_md_type_t md_alg
}
type = psa_get_key_type(&attributes);
+ alg = psa_get_key_algorithm(&attributes);
psa_reset_key_attributes(&attributes);
if (PSA_KEY_TYPE_IS_RSA(type)) {
- alg = PSA_ALG_RSA_PKCS1V15_SIGN(mbedtls_md_psa_alg_from_type(md_alg));
+ alg = (alg & ~PSA_ALG_HASH_MASK) | mbedtls_md_psa_alg_from_type(md_alg);
} else {
return MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE;
}
- /* make the signature */
- status = psa_sign_hash(pk->priv_id, alg, hash, hash_len,
- sig, sig_size, sig_len);
+ status = psa_sign_hash(pk->priv_id, alg, hash, hash_len, sig, sig_size, sig_len);
if (status != PSA_SUCCESS) {
if (PSA_KEY_TYPE_IS_RSA(type)) {
return PSA_PK_RSA_TO_MBEDTLS_ERR(status);
diff --git a/library/pkparse.c b/library/pkparse.c
index 5a3d3b2..4f6ee13 100644
--- a/library/pkparse.c
+++ b/library/pkparse.c
@@ -46,302 +46,6 @@
/***********************************************************************
*
- * ECC setters
- *
- * 1. This is an abstraction layer around MBEDTLS_PK_USE_PSA_EC_DATA:
- * this macro will not appear outside this section.
- * 2. All inputs are raw: no metadata, no ASN.1 until the next section.
- *
- **********************************************************************/
-
-/*
- * Set the group used by this key.
- *
- * [in/out] pk: in: must have been pk_setup() to an ECC type
- * out: will have group (curve) information set
- * [in] grp_in: a supported group ID (not NONE)
- */
-static int pk_ecc_set_group(mbedtls_pk_context *pk, mbedtls_ecp_group_id grp_id)
-{
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
- size_t ec_bits;
- psa_ecc_family_t ec_family = mbedtls_ecc_group_to_psa(grp_id, &ec_bits);
-
- /* group may already be initialized; if so, make sure IDs match */
- if ((pk->ec_family != 0 && pk->ec_family != ec_family) ||
- (pk->ec_bits != 0 && pk->ec_bits != ec_bits)) {
- return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
- }
-
- /* set group */
- pk->ec_family = ec_family;
- pk->ec_bits = ec_bits;
-
- return 0;
-#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
- mbedtls_ecp_keypair *ecp = mbedtls_pk_ec_rw(*pk);
-
- /* grp may already be initialized; if so, make sure IDs match */
- if (mbedtls_pk_ec_ro(*pk)->grp.id != MBEDTLS_ECP_DP_NONE &&
- mbedtls_pk_ec_ro(*pk)->grp.id != grp_id) {
- return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
- }
-
- /* set group */
- return mbedtls_ecp_group_load(&(ecp->grp), grp_id);
-#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
-}
-
-/*
- * Set the private key material
- *
- * [in/out] pk: in: must have the group set already, see pk_ecc_set_group().
- * out: will have the private key set.
- * [in] key, key_len: the raw private key (no ASN.1 wrapping).
- */
-static int pk_ecc_set_key(mbedtls_pk_context *pk,
- unsigned char *key, size_t key_len)
-{
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
- psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
- psa_key_usage_t flags;
- psa_status_t status;
-
- psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(pk->ec_family));
- if (pk->ec_family == PSA_ECC_FAMILY_MONTGOMERY) {
- /* Do not set algorithm here because Montgomery keys cannot do ECDSA and
- * the PK module cannot do ECDH. When the key will be used in TLS for
- * ECDH, it will be exported and then re-imported with proper flags
- * and algorithm. */
- flags = PSA_KEY_USAGE_EXPORT;
- } else {
- psa_set_key_algorithm(&attributes,
- MBEDTLS_PK_PSA_ALG_ECDSA_MAYBE_DET(PSA_ALG_ANY_HASH));
- flags = PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_SIGN_MESSAGE |
- PSA_KEY_USAGE_EXPORT;
- }
- psa_set_key_usage_flags(&attributes, flags);
-
- status = psa_import_key(&attributes, key, key_len, &pk->priv_id);
- return psa_pk_status_to_mbedtls(status);
-
-#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
-
- mbedtls_ecp_keypair *eck = mbedtls_pk_ec_rw(*pk);
- int ret = mbedtls_ecp_read_key(eck->grp.id, eck, key, key_len);
- if (ret != 0) {
- return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret);
- }
- return 0;
-#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
-}
-
-/*
- * Derive a public key from its private counterpart.
- * Computationally intensive, only use when public key is not available.
- *
- * [in/out] pk: in: must have the private key set, see pk_ecc_set_key().
- * out: will have the public key set.
- * [in] prv, prv_len: the raw private key (see note below).
- * [in] f_rng, p_rng: RNG function and context.
- *
- * Note: the private key information is always available from pk,
- * however for convenience the serialized version is also passed,
- * as it's available at each calling site, and useful in some configs
- * (as otherwise we would have to re-serialize it from the pk context).
- *
- * There are three implementations of this function:
- * 1. MBEDTLS_PK_USE_PSA_EC_DATA,
- * 2. MBEDTLS_USE_PSA_CRYPTO but not MBEDTLS_PK_USE_PSA_EC_DATA,
- * 3. not MBEDTLS_USE_PSA_CRYPTO.
- */
-static int pk_ecc_set_pubkey_from_prv(mbedtls_pk_context *pk,
- const unsigned char *prv, size_t prv_len,
- int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
-{
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
-
- (void) f_rng;
- (void) p_rng;
- (void) prv;
- (void) prv_len;
- psa_status_t status;
-
- status = psa_export_public_key(pk->priv_id, pk->pub_raw, sizeof(pk->pub_raw),
- &pk->pub_raw_len);
- return psa_pk_status_to_mbedtls(status);
-
-#elif defined(MBEDTLS_USE_PSA_CRYPTO) /* && !MBEDTLS_PK_USE_PSA_EC_DATA */
-
- (void) f_rng;
- (void) p_rng;
- psa_status_t status;
-
- mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
- size_t curve_bits;
- psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(eck->grp.id, &curve_bits);
-
- /* Import private key into PSA, from serialized input */
- mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
- psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
- psa_set_key_type(&key_attr, PSA_KEY_TYPE_ECC_KEY_PAIR(curve));
- psa_set_key_usage_flags(&key_attr, PSA_KEY_USAGE_EXPORT);
- status = psa_import_key(&key_attr, prv, prv_len, &key_id);
- if (status != PSA_SUCCESS) {
- return psa_pk_status_to_mbedtls(status);
- }
-
- /* Export public key from PSA */
- unsigned char pub[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
- size_t pub_len;
- status = psa_export_public_key(key_id, pub, sizeof(pub), &pub_len);
- psa_status_t destruction_status = psa_destroy_key(key_id);
- if (status != PSA_SUCCESS) {
- return psa_pk_status_to_mbedtls(status);
- } else if (destruction_status != PSA_SUCCESS) {
- return psa_pk_status_to_mbedtls(destruction_status);
- }
-
- /* Load serialized public key into ecp_keypair structure */
- return mbedtls_ecp_point_read_binary(&eck->grp, &eck->Q, pub, pub_len);
-
-#else /* MBEDTLS_USE_PSA_CRYPTO */
-
- (void) prv;
- (void) prv_len;
-
- mbedtls_ecp_keypair *eck = (mbedtls_ecp_keypair *) pk->pk_ctx;
- return mbedtls_ecp_mul(&eck->grp, &eck->Q, &eck->d, &eck->grp.G, f_rng, p_rng);
-
-#endif /* MBEDTLS_USE_PSA_CRYPTO */
-}
-
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
-/*
- * Set the public key: fallback using ECP_LIGHT in the USE_PSA_EC_DATA case.
- *
- * Normally, when MBEDTLS_PK_USE_PSA_EC_DATA is enabled, we only use PSA
- * functions to handle keys. However, currently psa_import_key() does not
- * support compressed points. In case that support was explicitly requested,
- * this fallback uses ECP functions to get the job done. This is the reason
- * why MBEDTLS_PK_PARSE_EC_COMPRESSED auto-enables MBEDTLS_ECP_LIGHT.
- *
- * [in/out] pk: in: must have the group set, see pk_ecc_set_group().
- * out: will have the public key set.
- * [in] pub, pub_len: the public key as an ECPoint,
- * in any format supported by ECP.
- *
- * Return:
- * - 0 on success;
- * - MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the format is potentially valid
- * but not supported;
- * - another error code otherwise.
- */
-static int pk_ecc_set_pubkey_psa_ecp_fallback(mbedtls_pk_context *pk,
- const unsigned char *pub,
- size_t pub_len)
-{
-#if !defined(MBEDTLS_PK_PARSE_EC_COMPRESSED)
- (void) pk;
- (void) pub;
- (void) pub_len;
- return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
-#else /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
- mbedtls_ecp_keypair ecp_key;
- mbedtls_ecp_group_id ecp_group_id;
- int ret;
-
- ecp_group_id = mbedtls_ecc_group_from_psa(pk->ec_family, pk->ec_bits);
-
- mbedtls_ecp_keypair_init(&ecp_key);
- ret = mbedtls_ecp_group_load(&(ecp_key.grp), ecp_group_id);
- if (ret != 0) {
- goto exit;
- }
- ret = mbedtls_ecp_point_read_binary(&(ecp_key.grp), &ecp_key.Q,
- pub, pub_len);
- if (ret != 0) {
- goto exit;
- }
- ret = mbedtls_ecp_point_write_binary(&(ecp_key.grp), &ecp_key.Q,
- MBEDTLS_ECP_PF_UNCOMPRESSED,
- &pk->pub_raw_len, pk->pub_raw,
- sizeof(pk->pub_raw));
-
-exit:
- mbedtls_ecp_keypair_free(&ecp_key);
- return ret;
-#endif /* MBEDTLS_PK_PARSE_EC_COMPRESSED */
-}
-#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
-
-/*
- * Set the public key.
- *
- * [in/out] pk: in: must have its group set, see pk_ecc_set_group().
- * out: will have the public key set.
- * [in] pub, pub_len: the raw public key (an ECPoint).
- *
- * Return:
- * - 0 on success;
- * - MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the format is potentially valid
- * but not supported;
- * - another error code otherwise.
- */
-static int pk_ecc_set_pubkey(mbedtls_pk_context *pk,
- const unsigned char *pub, size_t pub_len)
-{
-#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
-
- /* Load the key */
- if (!PSA_ECC_FAMILY_IS_WEIERSTRASS(pk->ec_family) || *pub == 0x04) {
- /* Format directly supported by PSA:
- * - non-Weierstrass curves that only have one format;
- * - uncompressed format for Weierstrass curves. */
- if (pub_len > sizeof(pk->pub_raw)) {
- return MBEDTLS_ERR_PK_BUFFER_TOO_SMALL;
- }
- memcpy(pk->pub_raw, pub, pub_len);
- pk->pub_raw_len = pub_len;
- } else {
- /* Other format, try the fallback */
- int ret = pk_ecc_set_pubkey_psa_ecp_fallback(pk, pub, pub_len);
- if (ret != 0) {
- return ret;
- }
- }
-
- /* Validate the key by trying to import it */
- mbedtls_svc_key_id_t key_id = MBEDTLS_SVC_KEY_ID_INIT;
- psa_key_attributes_t key_attrs = PSA_KEY_ATTRIBUTES_INIT;
-
- psa_set_key_usage_flags(&key_attrs, 0);
- psa_set_key_type(&key_attrs, PSA_KEY_TYPE_ECC_PUBLIC_KEY(pk->ec_family));
- psa_set_key_bits(&key_attrs, pk->ec_bits);
-
- if ((psa_import_key(&key_attrs, pk->pub_raw, pk->pub_raw_len,
- &key_id) != PSA_SUCCESS) ||
- (psa_destroy_key(key_id) != PSA_SUCCESS)) {
- return MBEDTLS_ERR_PK_INVALID_PUBKEY;
- }
-
- return 0;
-
-#else /* MBEDTLS_PK_USE_PSA_EC_DATA */
-
- int ret;
- mbedtls_ecp_keypair *ec_key = (mbedtls_ecp_keypair *) pk->pk_ctx;
- ret = mbedtls_ecp_point_read_binary(&ec_key->grp, &ec_key->Q, pub, pub_len);
- if (ret != 0) {
- return ret;
- }
- return mbedtls_ecp_check_pubkey(&ec_key->grp, &ec_key->Q);
-
-#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
-}
-
-/***********************************************************************
- *
* Low-level ECC parsing: optional support for SpecifiedECDomain
*
* There are two functions here that are used by the rest of the code:
@@ -698,7 +402,7 @@ static int pk_use_ecparams(const mbedtls_asn1_buf *params, mbedtls_pk_context *p
}
}
- return pk_ecc_set_group(pk, grp_id);
+ return mbedtls_pk_ecc_set_group(pk, grp_id);
}
#if defined(MBEDTLS_PK_HAVE_RFC8410_CURVES)
@@ -714,7 +418,7 @@ static int pk_use_ecparams_rfc8410(const mbedtls_asn1_buf *params,
return MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
}
- return pk_ecc_set_group(pk, grp_id);
+ return mbedtls_pk_ecc_set_group(pk, grp_id);
}
/*
@@ -740,7 +444,7 @@ static int pk_parse_key_rfc8410_der(mbedtls_pk_context *pk,
/*
* Load the private key
*/
- ret = pk_ecc_set_key(pk, key, len);
+ ret = mbedtls_pk_ecc_set_key(pk, key, len);
if (ret != 0) {
return ret;
}
@@ -748,7 +452,7 @@ static int pk_parse_key_rfc8410_der(mbedtls_pk_context *pk,
/* pk_parse_key_pkcs8_unencrypted_der() only supports version 1 PKCS8 keys,
* which never contain a public key. As such, derive the public key
* unconditionally. */
- if ((ret = pk_ecc_set_pubkey_from_prv(pk, key, len, f_rng, p_rng)) != 0) {
+ if ((ret = mbedtls_pk_ecc_set_pubkey_from_prv(pk, key, len, f_rng, p_rng)) != 0) {
return ret;
}
@@ -874,7 +578,7 @@ int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
ret = pk_use_ecparams(&alg_params, pk);
}
if (ret == 0) {
- ret = pk_ecc_set_pubkey(pk, *p, (size_t) (end - *p));
+ ret = mbedtls_pk_ecc_set_pubkey(pk, *p, (size_t) (end - *p));
*p += end - *p;
}
} else
@@ -966,7 +670,7 @@ static int pk_parse_key_sec1_der(mbedtls_pk_context *pk,
/*
* Load the private key
*/
- ret = pk_ecc_set_key(pk, d, d_len);
+ ret = mbedtls_pk_ecc_set_key(pk, d, d_len);
if (ret != 0) {
return ret;
}
@@ -990,11 +694,11 @@ static int pk_parse_key_sec1_der(mbedtls_pk_context *pk,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
}
- if ((ret = pk_ecc_set_pubkey(pk, p, (size_t) (end2 - p))) == 0) {
+ if ((ret = mbedtls_pk_ecc_set_pubkey(pk, p, (size_t) (end2 - p))) == 0) {
pubkey_done = 1;
} else {
/*
- * The only acceptable failure mode of pk_ecc_set_pubkey() above
+ * The only acceptable failure mode of mbedtls_pk_ecc_set_pubkey() above
* is if the point format is not recognized.
*/
if (ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) {
@@ -1007,7 +711,7 @@ static int pk_parse_key_sec1_der(mbedtls_pk_context *pk,
}
if (!pubkey_done) {
- if ((ret = pk_ecc_set_pubkey_from_prv(pk, d, d_len, f_rng, p_rng)) != 0) {
+ if ((ret = mbedtls_pk_ecc_set_pubkey_from_prv(pk, d, d_len, f_rng, p_rng)) != 0) {
return ret;
}
}
diff --git a/library/pkwrite.c b/library/pkwrite.c
index b9ddcf1..5e009c5 100644
--- a/library/pkwrite.c
+++ b/library/pkwrite.c
@@ -202,7 +202,7 @@ static int pk_write_ec_private(unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec = mbedtls_pk_ec_rw(*pk);
byte_length = (ec->grp.pbits + 7) / 8;
- ret = mbedtls_ecp_write_key(ec, tmp, byte_length);
+ ret = mbedtls_ecp_write_key_ext(ec, &byte_length, tmp, sizeof(tmp));
if (ret != 0) {
goto exit;
}
diff --git a/library/pkwrite.h b/library/pkwrite.h
index 544ab2f..01dc3d2 100644
--- a/library/pkwrite.h
+++ b/library/pkwrite.h
@@ -109,4 +109,13 @@
#define MBEDTLS_PK_ECP_PRV_DER_MAX_BYTES 0
#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
+
+/* Define the maximum available public key DER length based on the supported
+ * key types (EC and/or RSA). */
+#if (MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES > MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES)
+#define MBEDTLS_PK_WRITE_PUBKEY_MAX_SIZE MBEDTLS_PK_RSA_PUB_DER_MAX_BYTES
+#else
+#define MBEDTLS_PK_WRITE_PUBKEY_MAX_SIZE MBEDTLS_PK_ECP_PUB_DER_MAX_BYTES
+#endif
+
#endif /* MBEDTLS_PK_WRITE_H */
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index ca01e76..969c695 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -71,6 +71,7 @@
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"
#include "mbedtls/psa_util.h"
+#include "mbedtls/threading.h"
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) || \
@@ -92,35 +93,205 @@ static int key_type_is_raw_bytes(psa_key_type_t type)
#define RNG_INITIALIZED 1
#define RNG_SEEDED 2
+/* IDs for PSA crypto subsystems. Starts at 1 to catch potential uninitialized
+ * variables as arguments. */
+typedef enum {
+ PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS = 1,
+ PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS,
+ PSA_CRYPTO_SUBSYSTEM_RNG,
+ PSA_CRYPTO_SUBSYSTEM_TRANSACTION,
+} mbedtls_psa_crypto_subsystem;
+
+/* Initialization flags for global_data::initialized */
+#define PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED 0x01
+#define PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED 0x02
+#define PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED 0x04
+
+#define PSA_CRYPTO_SUBSYSTEM_ALL_INITIALISED ( \
+ PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED | \
+ PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED | \
+ PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED)
+
typedef struct {
uint8_t initialized;
uint8_t rng_state;
- uint8_t drivers_initialized;
mbedtls_psa_random_context_t rng;
} psa_global_data_t;
static psa_global_data_t global_data;
-#if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
-mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
- &global_data.rng.drbg;
-#endif
+static uint8_t psa_get_initialized(void)
+{
+ uint8_t initialized;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ initialized = global_data.rng_state == RNG_SEEDED;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ initialized =
+ (initialized && (global_data.initialized == PSA_CRYPTO_SUBSYSTEM_ALL_INITIALISED));
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ return initialized;
+}
+
+static uint8_t psa_get_drivers_initialized(void)
+{
+ uint8_t initialized;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ initialized = (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED) != 0;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ return initialized;
+}
#define GUARD_MODULE_INITIALIZED \
- if (global_data.initialized == 0) \
+ if (psa_get_initialized() == 0) \
return PSA_ERROR_BAD_STATE;
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+
+/* Declare a local copy of an input buffer and a variable that will be used
+ * to store a pointer to the start of the buffer.
+ *
+ * Note: This macro must be called before any operations which may jump to
+ * the exit label, so that the local input copy object is safe to be freed.
+ *
+ * Assumptions:
+ * - input is the name of a pointer to the buffer to be copied
+ * - The name LOCAL_INPUT_COPY_OF_input is unused in the current scope
+ * - input_copy_name is a name that is unused in the current scope
+ */
+#define LOCAL_INPUT_DECLARE(input, input_copy_name) \
+ psa_crypto_local_input_t LOCAL_INPUT_COPY_OF_##input = PSA_CRYPTO_LOCAL_INPUT_INIT; \
+ const uint8_t *input_copy_name = NULL;
+
+/* Allocate a copy of the buffer input and set the pointer input_copy to
+ * point to the start of the copy.
+ *
+ * Assumptions:
+ * - psa_status_t status exists
+ * - An exit label is declared
+ * - input is the name of a pointer to the buffer to be copied
+ * - LOCAL_INPUT_DECLARE(input, input_copy) has previously been called
+ */
+#define LOCAL_INPUT_ALLOC(input, length, input_copy) \
+ status = psa_crypto_local_input_alloc(input, length, \
+ &LOCAL_INPUT_COPY_OF_##input); \
+ if (status != PSA_SUCCESS) { \
+ goto exit; \
+ } \
+ input_copy = LOCAL_INPUT_COPY_OF_##input.buffer;
+
+/* Free the local input copy allocated previously by LOCAL_INPUT_ALLOC()
+ *
+ * Assumptions:
+ * - input_copy is the name of the input copy pointer set by LOCAL_INPUT_ALLOC()
+ * - input is the name of the original buffer that was copied
+ */
+#define LOCAL_INPUT_FREE(input, input_copy) \
+ input_copy = NULL; \
+ psa_crypto_local_input_free(&LOCAL_INPUT_COPY_OF_##input);
+
+/* Declare a local copy of an output buffer and a variable that will be used
+ * to store a pointer to the start of the buffer.
+ *
+ * Note: This macro must be called before any operations which may jump to
+ * the exit label, so that the local output copy object is safe to be freed.
+ *
+ * Assumptions:
+ * - output is the name of a pointer to the buffer to be copied
+ * - The name LOCAL_OUTPUT_COPY_OF_output is unused in the current scope
+ * - output_copy_name is a name that is unused in the current scope
+ */
+#define LOCAL_OUTPUT_DECLARE(output, output_copy_name) \
+ psa_crypto_local_output_t LOCAL_OUTPUT_COPY_OF_##output = PSA_CRYPTO_LOCAL_OUTPUT_INIT; \
+ uint8_t *output_copy_name = NULL;
+
+/* Allocate a copy of the buffer output and set the pointer output_copy to
+ * point to the start of the copy.
+ *
+ * Assumptions:
+ * - psa_status_t status exists
+ * - An exit label is declared
+ * - output is the name of a pointer to the buffer to be copied
+ * - LOCAL_OUTPUT_DECLARE(output, output_copy) has previously been called
+ */
+#define LOCAL_OUTPUT_ALLOC(output, length, output_copy) \
+ status = psa_crypto_local_output_alloc(output, length, \
+ &LOCAL_OUTPUT_COPY_OF_##output); \
+ if (status != PSA_SUCCESS) { \
+ goto exit; \
+ } \
+ output_copy = LOCAL_OUTPUT_COPY_OF_##output.buffer;
+
+/* Free the local output copy allocated previously by LOCAL_OUTPUT_ALLOC()
+ * after first copying back its contents to the original buffer.
+ *
+ * Assumptions:
+ * - psa_status_t status exists
+ * - output_copy is the name of the output copy pointer set by LOCAL_OUTPUT_ALLOC()
+ * - output is the name of the original buffer that was copied
+ */
+#define LOCAL_OUTPUT_FREE(output, output_copy) \
+ output_copy = NULL; \
+ do { \
+ psa_status_t local_output_status; \
+ local_output_status = psa_crypto_local_output_free(&LOCAL_OUTPUT_COPY_OF_##output); \
+ if (local_output_status != PSA_SUCCESS) { \
+ /* Since this error case is an internal error, it's more serious than \
+ * any existing error code and so it's fine to overwrite the existing \
+ * status. */ \
+ status = local_output_status; \
+ } \
+ } while (0)
+#else /* !MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS */
+#define LOCAL_INPUT_DECLARE(input, input_copy_name) \
+ const uint8_t *input_copy_name = NULL;
+#define LOCAL_INPUT_ALLOC(input, length, input_copy) \
+ input_copy = input;
+#define LOCAL_INPUT_FREE(input, input_copy) \
+ input_copy = NULL;
+#define LOCAL_OUTPUT_DECLARE(output, output_copy_name) \
+ uint8_t *output_copy_name = NULL;
+#define LOCAL_OUTPUT_ALLOC(output, length, output_copy) \
+ output_copy = output;
+#define LOCAL_OUTPUT_FREE(output, output_copy) \
+ output_copy = NULL;
+#endif /* !MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS */
+
+
int psa_can_do_hash(psa_algorithm_t hash_alg)
{
(void) hash_alg;
- return global_data.drivers_initialized;
+ return psa_get_drivers_initialized();
}
int psa_can_do_cipher(psa_key_type_t key_type, psa_algorithm_t cipher_alg)
{
(void) key_type;
(void) cipher_alg;
- return global_data.drivers_initialized;
+ return psa_get_drivers_initialized();
}
@@ -568,7 +739,7 @@ psa_status_t psa_import_key_into_slot(
size_t *key_buffer_length, size_t *bits)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
- psa_key_type_t type = attributes->core.type;
+ psa_key_type_t type = attributes->type;
/* zero-length keys are never supported. */
if (data_length == 0) {
@@ -578,7 +749,7 @@ psa_status_t psa_import_key_into_slot(
if (key_type_is_raw_bytes(type)) {
*bits = PSA_BYTES_TO_BITS(data_length);
- status = psa_validate_unstructured_key_bit_size(attributes->core.type,
+ status = psa_validate_unstructured_key_bit_size(attributes->type,
*bits);
if (status != PSA_SUCCESS) {
return status;
@@ -1106,6 +1277,17 @@ psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key)
* fully destroyed. */
PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(
&mbedtls_threading_key_slot_mutex));
+
+ if (slot->state == PSA_SLOT_PENDING_DELETION) {
+ /* Another thread has destroyed the key between us locking the slot
+ * and us gaining the mutex. Unregister from the slot,
+ * and report that the key does not exist. */
+ status = psa_unregister_read(slot);
+
+ PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
+ &mbedtls_threading_key_slot_mutex));
+ return (status == PSA_SUCCESS) ? PSA_ERROR_INVALID_HANDLE : status;
+ }
#endif
/* Set the key slot containing the key description's state to
* PENDING_DELETION. This stops new operations from registering
@@ -1115,10 +1297,10 @@ psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key)
* If the key is persistent, we can now delete the copy of the key
* from memory. If the key is opaque, we require the driver to
* deal with the deletion. */
- status = psa_key_slot_state_transition(slot, PSA_SLOT_FULL,
- PSA_SLOT_PENDING_DELETION);
+ overall_status = psa_key_slot_state_transition(slot, PSA_SLOT_FULL,
+ PSA_SLOT_PENDING_DELETION);
- if (status != PSA_SUCCESS) {
+ if (overall_status != PSA_SUCCESS) {
goto exit;
}
@@ -1226,9 +1408,7 @@ psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
return status;
}
- attributes->core = slot->attr;
- attributes->core.flags &= (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
- MBEDTLS_PSA_KA_MASK_DUAL_USE);
+ *attributes = slot->attr;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if (psa_get_se_driver_entry(slot->attr.lifetime) != NULL) {
@@ -1245,7 +1425,7 @@ psa_status_t psa_get_key_slot_number(
const psa_key_attributes_t *attributes,
psa_key_slot_number_t *slot_number)
{
- if (attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER) {
+ if (attributes->has_slot_number) {
*slot_number = attributes->slot_number;
return PSA_SUCCESS;
} else {
@@ -1275,7 +1455,7 @@ psa_status_t psa_export_key_internal(
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length)
{
- psa_key_type_t type = attributes->core.type;
+ psa_key_type_t type = attributes->type;
if (key_type_is_raw_bytes(type) ||
PSA_KEY_TYPE_IS_RSA(type) ||
@@ -1293,13 +1473,14 @@ psa_status_t psa_export_key_internal(
}
psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
- uint8_t *data,
+ uint8_t *data_external,
size_t data_size,
size_t *data_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
+ LOCAL_OUTPUT_DECLARE(data_external, data);
/* Reject a zero-length output buffer now, since this can never be a
* valid key representation. This way we know that data must be a valid
@@ -1324,15 +1505,18 @@ psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
return status;
}
- psa_key_attributes_t attributes = {
- .core = slot->attr
- };
- status = psa_driver_wrapper_export_key(&attributes,
+ LOCAL_OUTPUT_ALLOC(data_external, data_size, data);
+
+ status = psa_driver_wrapper_export_key(&slot->attr,
slot->key.data, slot->key.bytes,
data, data_size, data_length);
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_OUTPUT_FREE(data_external, data);
return (status == PSA_SUCCESS) ? unlock_status : status;
}
@@ -1344,7 +1528,7 @@ psa_status_t psa_export_public_key_internal(
size_t data_size,
size_t *data_length)
{
- psa_key_type_t type = attributes->core.type;
+ psa_key_type_t type = attributes->type;
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type) &&
(PSA_KEY_TYPE_IS_RSA(type) || PSA_KEY_TYPE_IS_ECC(type) ||
@@ -1404,14 +1588,15 @@ psa_status_t psa_export_public_key_internal(
}
psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
- uint8_t *data,
+ uint8_t *data_external,
size_t data_size,
size_t *data_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
- psa_key_attributes_t attributes;
+
+ LOCAL_OUTPUT_DECLARE(data_external, data);
/* Reject a zero-length output buffer now, since this can never be a
* valid key representation. This way we know that data must be a valid
@@ -1432,34 +1617,24 @@ psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
return status;
}
+ LOCAL_OUTPUT_ALLOC(data_external, data_size, data);
+
if (!PSA_KEY_TYPE_IS_ASYMMETRIC(slot->attr.type)) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
status = psa_driver_wrapper_export_public_key(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
data, data_size, data_length);
exit:
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_OUTPUT_FREE(data_external, data);
return (status == PSA_SUCCESS) ? unlock_status : status;
}
-MBEDTLS_STATIC_ASSERT(
- (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
- "One or more key attribute flag is listed as both external-only and dual-use")
-MBEDTLS_STATIC_ASSERT(
- (PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
- "One or more key attribute flag is listed as both internal-only and dual-use")
-MBEDTLS_STATIC_ASSERT(
- (PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY) == 0,
- "One or more key attribute flag is listed as both internal-only and external-only")
-
/** Validate that a key policy is internally well-formed.
*
* This function only rejects invalid policies. It does not validate the
@@ -1525,7 +1700,7 @@ static psa_status_t psa_validate_key_attributes(
}
}
- status = psa_validate_key_policy(&attributes->core.policy);
+ status = psa_validate_key_policy(&attributes->policy);
if (status != PSA_SUCCESS) {
return status;
}
@@ -1538,12 +1713,6 @@ static psa_status_t psa_validate_key_attributes(
return PSA_ERROR_NOT_SUPPORTED;
}
- /* Reject invalid flags. These should not be reachable through the API. */
- if (attributes->core.flags & ~(MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
- MBEDTLS_PSA_KA_MASK_DUAL_USE)) {
- return PSA_ERROR_INVALID_ARGUMENT;
- }
-
return PSA_SUCCESS;
}
@@ -1617,7 +1786,7 @@ static psa_status_t psa_start_key_creation(
* volatile key identifier associated to the slot returned to contain its
* definition. */
- slot->attr = attributes->core;
+ slot->attr = *attributes;
if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
#if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
slot->attr.id = volatile_key_id;
@@ -1626,13 +1795,6 @@ static psa_status_t psa_start_key_creation(
#endif
}
- /* Erase external-only flags from the internal copy. To access
- * external-only flags, query `attributes`. Thanks to the check
- * in psa_validate_key_attributes(), this leaves the dual-use
- * flags and any internal flag that psa_reserve_free_key_slot()
- * may have set. */
- slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
-
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* For a key in a secure element, we need to do three things
* when creating or registering a persistent key:
@@ -1659,7 +1821,7 @@ static psa_status_t psa_start_key_creation(
return status;
}
- if (!PSA_KEY_LIFETIME_IS_VOLATILE(attributes->core.lifetime)) {
+ if (!PSA_KEY_LIFETIME_IS_VOLATILE(attributes->lifetime)) {
psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_CREATE_KEY);
psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
psa_crypto_transaction.key.slot = slot_number;
@@ -1859,14 +2021,14 @@ static psa_status_t psa_validate_optional_attributes(
const psa_key_slot_t *slot,
const psa_key_attributes_t *attributes)
{
- if (attributes->core.type != 0) {
- if (attributes->core.type != slot->attr.type) {
+ if (attributes->type != 0) {
+ if (attributes->type != slot->attr.type) {
return PSA_ERROR_INVALID_ARGUMENT;
}
}
- if (attributes->core.bits != 0) {
- if (attributes->core.bits != slot->attr.bits) {
+ if (attributes->bits != 0) {
+ if (attributes->bits != slot->attr.bits) {
return PSA_ERROR_INVALID_ARGUMENT;
}
}
@@ -1875,11 +2037,12 @@ static psa_status_t psa_validate_optional_attributes(
}
psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
- const uint8_t *data,
+ const uint8_t *data_external,
size_t data_length,
mbedtls_svc_key_id_t *key)
{
psa_status_t status;
+ LOCAL_INPUT_DECLARE(data_external, data);
psa_key_slot_t *slot = NULL;
psa_se_drv_table_entry_t *driver = NULL;
size_t bits;
@@ -1899,6 +2062,8 @@ psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
return PSA_ERROR_NOT_SUPPORTED;
}
+ LOCAL_INPUT_ALLOC(data_external, data_length, data);
+
status = psa_start_key_creation(PSA_KEY_CREATION_IMPORT, attributes,
&slot, &driver);
if (status != PSA_SUCCESS) {
@@ -1910,7 +2075,7 @@ psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
* with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
* buffer to hold the imported key material. */
if (slot->key.data == NULL) {
- if (psa_key_lifetime_is_external(attributes->core.lifetime)) {
+ if (psa_key_lifetime_is_external(attributes->lifetime)) {
status = psa_driver_wrapper_get_key_buffer_size_from_key_data(
attributes, data, data_length, &storage_size);
if (status != PSA_SUCCESS) {
@@ -1953,6 +2118,7 @@ psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
status = psa_finish_key_creation(slot, driver, key);
exit:
+ LOCAL_INPUT_FREE(data_external, data);
if (status != PSA_SUCCESS) {
psa_fail_key_creation(slot, driver);
}
@@ -2030,12 +2196,12 @@ psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
* equal to the ones of the source key. So it is safe to inherit
* them from the source key now."
* */
- actual_attributes.core.bits = source_slot->attr.bits;
- actual_attributes.core.type = source_slot->attr.type;
+ actual_attributes.bits = source_slot->attr.bits;
+ actual_attributes.type = source_slot->attr.type;
status = psa_restrict_key_policy(source_slot->attr.type,
- &actual_attributes.core.policy,
+ &actual_attributes.policy,
&source_slot->attr.policy);
if (status != PSA_SUCCESS) {
goto exit;
@@ -2064,7 +2230,7 @@ psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
* - For opaque keys this translates to an invocation of the drivers'
* copy_key entry point through the dispatch layer.
* */
- if (psa_key_lifetime_is_external(actual_attributes.core.lifetime)) {
+ if (psa_key_lifetime_is_external(actual_attributes.lifetime)) {
status = psa_driver_wrapper_get_key_buffer_size(&actual_attributes,
&storage_size);
if (status != PSA_SUCCESS) {
@@ -2154,10 +2320,11 @@ exit:
}
psa_status_t psa_hash_update(psa_hash_operation_t *operation,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
@@ -2170,6 +2337,7 @@ psa_status_t psa_hash_update(psa_hash_operation_t *operation,
return PSA_SUCCESS;
}
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
status = psa_driver_wrapper_hash_update(operation, input, input_length);
exit:
@@ -2177,32 +2345,57 @@ exit:
psa_hash_abort(operation);
}
+ LOCAL_INPUT_FREE(input_external, input);
return status;
}
-psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
- uint8_t *hash,
- size_t hash_size,
- size_t *hash_length)
+static psa_status_t psa_hash_finish_internal(psa_hash_operation_t *operation,
+ uint8_t *hash,
+ size_t hash_size,
+ size_t *hash_length)
{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+
*hash_length = 0;
if (operation->id == 0) {
return PSA_ERROR_BAD_STATE;
}
- psa_status_t status = psa_driver_wrapper_hash_finish(
+ status = psa_driver_wrapper_hash_finish(
operation, hash, hash_size, hash_length);
psa_hash_abort(operation);
+
+ return status;
+}
+
+psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
+ uint8_t *hash_external,
+ size_t hash_size,
+ size_t *hash_length)
+{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_OUTPUT_DECLARE(hash_external, hash);
+
+ LOCAL_OUTPUT_ALLOC(hash_external, hash_size, hash);
+ status = psa_hash_finish_internal(operation, hash, hash_size, hash_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_OUTPUT_FREE(hash_external, hash);
return status;
}
psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
- const uint8_t *hash,
+ const uint8_t *hash_external,
size_t hash_length)
{
uint8_t actual_hash[PSA_HASH_MAX_SIZE];
size_t actual_hash_length;
- psa_status_t status = psa_hash_finish(
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(hash_external, hash);
+
+ status = psa_hash_finish_internal(
operation,
actual_hash, sizeof(actual_hash),
&actual_hash_length);
@@ -2216,6 +2409,7 @@ psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
goto exit;
}
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
status = PSA_ERROR_INVALID_SIGNATURE;
}
@@ -2225,36 +2419,55 @@ exit:
if (status != PSA_SUCCESS) {
psa_hash_abort(operation);
}
-
+ LOCAL_INPUT_FREE(hash_external, hash);
return status;
}
psa_status_t psa_hash_compute(psa_algorithm_t alg,
- const uint8_t *input, size_t input_length,
- uint8_t *hash, size_t hash_size,
+ const uint8_t *input_external, size_t input_length,
+ uint8_t *hash_external, size_t hash_size,
size_t *hash_length)
{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(hash_external, hash);
+
*hash_length = 0;
if (!PSA_ALG_IS_HASH(alg)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
- return psa_driver_wrapper_hash_compute(alg, input, input_length,
- hash, hash_size, hash_length);
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(hash_external, hash_size, hash);
+ status = psa_driver_wrapper_hash_compute(alg, input, input_length,
+ hash, hash_size, hash_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(hash_external, hash);
+ return status;
}
psa_status_t psa_hash_compare(psa_algorithm_t alg,
- const uint8_t *input, size_t input_length,
- const uint8_t *hash, size_t hash_length)
+ const uint8_t *input_external, size_t input_length,
+ const uint8_t *hash_external, size_t hash_length)
{
uint8_t actual_hash[PSA_HASH_MAX_SIZE];
size_t actual_hash_length;
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_DECLARE(hash_external, hash);
if (!PSA_ALG_IS_HASH(alg)) {
- return PSA_ERROR_INVALID_ARGUMENT;
+ status = PSA_ERROR_INVALID_ARGUMENT;
+ return status;
}
- psa_status_t status = psa_driver_wrapper_hash_compute(
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ status = psa_driver_wrapper_hash_compute(
alg, input, input_length,
actual_hash, sizeof(actual_hash),
&actual_hash_length);
@@ -2265,12 +2478,18 @@ psa_status_t psa_hash_compare(psa_algorithm_t alg,
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
+
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
status = PSA_ERROR_INVALID_SIGNATURE;
}
exit:
mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
+
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_INPUT_FREE(hash_external, hash);
+
return status;
}
@@ -2372,7 +2591,6 @@ static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
- psa_key_attributes_t attributes;
/* A context must be freshly initialized before it can be set up. */
if (operation->id != 0) {
@@ -2389,11 +2607,7 @@ static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
- status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
+ status = psa_mac_finalize_alg_and_key_validation(alg, &slot->attr,
&operation->mac_size);
if (status != PSA_SUCCESS) {
goto exit;
@@ -2403,13 +2617,13 @@ static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
/* Dispatch the MAC setup call with validated input */
if (is_sign) {
status = psa_driver_wrapper_mac_sign_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
} else {
status = psa_driver_wrapper_mac_verify_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
@@ -2440,35 +2654,48 @@ psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
}
psa_status_t psa_mac_update(psa_mac_operation_t *operation,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length)
{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+
if (operation->id == 0) {
- return PSA_ERROR_BAD_STATE;
+ status = PSA_ERROR_BAD_STATE;
+ return status;
}
/* Don't require hash implementations to behave correctly on a
* zero-length input, which may have an invalid pointer. */
if (input_length == 0) {
- return PSA_SUCCESS;
+ status = PSA_SUCCESS;
+ return status;
}
- psa_status_t status = psa_driver_wrapper_mac_update(operation,
- input, input_length);
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ status = psa_driver_wrapper_mac_update(operation, input, input_length);
+
if (status != PSA_SUCCESS) {
psa_mac_abort(operation);
}
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(input_external, input);
+
return status;
}
psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
- uint8_t *mac,
+ uint8_t *mac_external,
size_t mac_size,
size_t *mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_OUTPUT_DECLARE(mac_external, mac);
+ LOCAL_OUTPUT_ALLOC(mac_external, mac_size, mac);
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
@@ -2492,6 +2719,7 @@ psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
goto exit;
}
+
status = psa_driver_wrapper_mac_sign_finish(operation,
mac, operation->mac_size,
mac_length);
@@ -2508,19 +2736,23 @@ exit:
operation->mac_size = 0;
}
- psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
+ if (mac != NULL) {
+ psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
+ }
abort_status = psa_mac_abort(operation);
+ LOCAL_OUTPUT_FREE(mac_external, mac);
return status == PSA_SUCCESS ? abort_status : status;
}
psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
- const uint8_t *mac,
+ const uint8_t *mac_external,
size_t mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(mac_external, mac);
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
@@ -2537,11 +2769,13 @@ psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
goto exit;
}
+ LOCAL_INPUT_ALLOC(mac_external, mac_length, mac);
status = psa_driver_wrapper_mac_verify_finish(operation,
mac, mac_length);
exit:
abort_status = psa_mac_abort(operation);
+ LOCAL_INPUT_FREE(mac_external, mac);
return status == PSA_SUCCESS ? abort_status : status;
}
@@ -2559,7 +2793,6 @@ static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
uint8_t operation_mac_size = 0;
- psa_key_attributes_t attributes;
status = psa_get_and_lock_key_slot_with_policy(
key,
@@ -2570,11 +2803,7 @@ static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
- status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
+ status = psa_mac_finalize_alg_and_key_validation(alg, &slot->attr,
&operation_mac_size);
if (status != PSA_SUCCESS) {
goto exit;
@@ -2586,7 +2815,7 @@ static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
}
status = psa_driver_wrapper_mac_compute(
- &attributes,
+ &slot->attr,
slot->key.data, slot->key.bytes,
alg,
input, input_length,
@@ -2613,28 +2842,45 @@ exit:
psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *mac,
+ uint8_t *mac_external,
size_t mac_size,
size_t *mac_length)
{
- return psa_mac_compute_internal(key, alg,
- input, input_length,
- mac, mac_size, mac_length, 1);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(mac_external, mac);
+
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(mac_external, mac_size, mac);
+ status = psa_mac_compute_internal(key, alg,
+ input, input_length,
+ mac, mac_size, mac_length, 1);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(mac_external, mac);
+
+ return status;
}
psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- const uint8_t *mac,
+ const uint8_t *mac_external,
size_t mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
uint8_t actual_mac[PSA_MAC_MAX_SIZE];
size_t actual_mac_length;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_DECLARE(mac_external, mac);
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
status = psa_mac_compute_internal(key, alg,
input, input_length,
actual_mac, sizeof(actual_mac),
@@ -2647,6 +2893,8 @@ psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
+
+ LOCAL_INPUT_ALLOC(mac_external, mac_length, mac);
if (mbedtls_ct_memcmp(mac, actual_mac, actual_mac_length) != 0) {
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
@@ -2654,6 +2902,8 @@ psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
exit:
mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_INPUT_FREE(mac_external, mac);
return status;
}
@@ -2696,7 +2946,6 @@ static psa_status_t psa_sign_internal(mbedtls_svc_key_id_t key,
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
- psa_key_attributes_t attributes;
*signature_length = 0;
@@ -2728,19 +2977,15 @@ static psa_status_t psa_sign_internal(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
if (input_is_message) {
status = psa_driver_wrapper_sign_message(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_size, signature_length);
} else {
status = psa_driver_wrapper_sign_hash(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_size, signature_length);
}
@@ -2782,18 +3027,14 @@ static psa_status_t psa_verify_internal(mbedtls_svc_key_id_t key,
return status;
}
- psa_key_attributes_t attributes = {
- .core = slot->attr
- };
-
if (input_is_message) {
status = psa_driver_wrapper_verify_message(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_length);
} else {
status = psa_driver_wrapper_verify_hash(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_length);
}
@@ -2841,15 +3082,27 @@ psa_status_t psa_sign_message_builtin(
psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *signature,
+ uint8_t *signature_external,
size_t signature_size,
size_t *signature_length)
{
- return psa_sign_internal(
- key, 1, alg, input, input_length,
- signature, signature_size, signature_length);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(signature_external, signature);
+
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
+ status = psa_sign_internal(key, 1, alg, input, input_length, signature,
+ signature_size, signature_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(signature_external, signature);
+ return status;
}
psa_status_t psa_verify_message_builtin(
@@ -2888,14 +3141,27 @@ psa_status_t psa_verify_message_builtin(
psa_status_t psa_verify_message(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- const uint8_t *signature,
+ const uint8_t *signature_external,
size_t signature_length)
{
- return psa_verify_internal(
- key, 1, alg, input, input_length,
- signature, signature_length);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_DECLARE(signature_external, signature);
+
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
+ status = psa_verify_internal(key, 1, alg, input, input_length, signature,
+ signature_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_INPUT_FREE(signature_external, signature);
+
+ return status;
}
psa_status_t psa_sign_hash_builtin(
@@ -2904,7 +3170,7 @@ psa_status_t psa_sign_hash_builtin(
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
uint8_t *signature, size_t signature_size, size_t *signature_length)
{
- if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
+ if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
PSA_ALG_IS_RSA_PSS(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
@@ -2919,7 +3185,7 @@ psa_status_t psa_sign_hash_builtin(
} else {
return PSA_ERROR_INVALID_ARGUMENT;
}
- } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
+ } else if (PSA_KEY_TYPE_IS_ECC(attributes->type)) {
if (PSA_ALG_IS_ECDSA(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
@@ -2948,15 +3214,28 @@ psa_status_t psa_sign_hash_builtin(
psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *hash,
+ const uint8_t *hash_external,
size_t hash_length,
- uint8_t *signature,
+ uint8_t *signature_external,
size_t signature_size,
size_t *signature_length)
{
- return psa_sign_internal(
- key, 0, alg, hash, hash_length,
- signature, signature_size, signature_length);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(hash_external, hash);
+ LOCAL_OUTPUT_DECLARE(signature_external, signature);
+
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
+ LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
+ status = psa_sign_internal(key, 0, alg, hash, hash_length, signature,
+ signature_size, signature_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(hash_external, hash);
+ LOCAL_OUTPUT_FREE(signature_external, signature);
+
+ return status;
}
psa_status_t psa_verify_hash_builtin(
@@ -2965,7 +3244,7 @@ psa_status_t psa_verify_hash_builtin(
psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
const uint8_t *signature, size_t signature_length)
{
- if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
+ if (PSA_KEY_TYPE_IS_RSA(attributes->type)) {
if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
PSA_ALG_IS_RSA_PSS(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
@@ -2980,7 +3259,7 @@ psa_status_t psa_verify_hash_builtin(
} else {
return PSA_ERROR_INVALID_ARGUMENT;
}
- } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
+ } else if (PSA_KEY_TYPE_IS_ECC(attributes->type)) {
if (PSA_ALG_IS_ECDSA(alg)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
@@ -3008,30 +3287,46 @@ psa_status_t psa_verify_hash_builtin(
psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *hash,
+ const uint8_t *hash_external,
size_t hash_length,
- const uint8_t *signature,
+ const uint8_t *signature_external,
size_t signature_length)
{
- return psa_verify_internal(
- key, 0, alg, hash, hash_length,
- signature, signature_length);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(hash_external, hash);
+ LOCAL_INPUT_DECLARE(signature_external, signature);
+
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
+ LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
+ status = psa_verify_internal(key, 0, alg, hash, hash_length, signature,
+ signature_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(hash_external, hash);
+ LOCAL_INPUT_FREE(signature_external, signature);
+
+ return status;
}
psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- const uint8_t *salt,
+ const uint8_t *salt_external,
size_t salt_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
- psa_key_attributes_t attributes;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_DECLARE(salt_external, salt);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
(void) input;
(void) input_length;
@@ -3056,34 +3351,41 @@ psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
status = psa_driver_wrapper_asymmetric_encrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length, salt, salt_length,
output, output_size, output_length);
exit:
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_INPUT_FREE(salt_external, salt);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return (status == PSA_SUCCESS) ? unlock_status : status;
}
psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- const uint8_t *salt,
+ const uint8_t *salt_external,
size_t salt_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
- psa_key_attributes_t attributes;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_DECLARE(salt_external, salt);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
(void) input;
(void) input_length;
@@ -3107,18 +3409,22 @@ psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
status = psa_driver_wrapper_asymmetric_decrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length, salt, salt_length,
output, output_size, output_length);
exit:
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_INPUT_FREE(salt_external, salt);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return (status == PSA_SUCCESS) ? unlock_status : status;
}
@@ -3176,12 +3482,13 @@ static psa_status_t psa_sign_hash_abort_internal(
psa_status_t psa_sign_hash_start(
psa_sign_hash_interruptible_operation_t *operation,
mbedtls_svc_key_id_t key, psa_algorithm_t alg,
- const uint8_t *hash, size_t hash_length)
+ const uint8_t *hash_external, size_t hash_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
- psa_key_attributes_t attributes;
+
+ LOCAL_INPUT_DECLARE(hash_external, hash);
/* Check that start has not been previously called, or operation has not
* previously errored. */
@@ -3208,14 +3515,12 @@ psa_status_t psa_sign_hash_start(
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
/* Ensure ops count gets reset, in case of operation re-use. */
operation->num_ops = 0;
- status = psa_driver_wrapper_sign_hash_start(operation, &attributes,
+ status = psa_driver_wrapper_sign_hash_start(operation, &slot->attr,
slot->key.data,
slot->key.bytes, alg,
hash, hash_length);
@@ -3232,17 +3537,21 @@ exit:
operation->error_occurred = 1;
}
+ LOCAL_INPUT_FREE(hash_external, hash);
+
return (status == PSA_SUCCESS) ? unlock_status : status;
}
psa_status_t psa_sign_hash_complete(
psa_sign_hash_interruptible_operation_t *operation,
- uint8_t *signature, size_t signature_size,
+ uint8_t *signature_external, size_t signature_size,
size_t *signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_OUTPUT_DECLARE(signature_external, signature);
+
*signature_length = 0;
/* Check that start has been called first, and that operation has not
@@ -3259,6 +3568,8 @@ psa_status_t psa_sign_hash_complete(
goto exit;
}
+ LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
+
status = psa_driver_wrapper_sign_hash_complete(operation, signature,
signature_size,
signature_length);
@@ -3268,8 +3579,10 @@ psa_status_t psa_sign_hash_complete(
exit:
- psa_wipe_tag_output_buffer(signature, status, signature_size,
- *signature_length);
+ if (signature != NULL) {
+ psa_wipe_tag_output_buffer(signature, status, signature_size,
+ *signature_length);
+ }
if (status != PSA_OPERATION_INCOMPLETE) {
if (status != PSA_SUCCESS) {
@@ -3279,6 +3592,8 @@ exit:
psa_sign_hash_abort_internal(operation);
}
+ LOCAL_OUTPUT_FREE(signature_external, signature);
+
return status;
}
@@ -3325,13 +3640,16 @@ static psa_status_t psa_verify_hash_abort_internal(
psa_status_t psa_verify_hash_start(
psa_verify_hash_interruptible_operation_t *operation,
mbedtls_svc_key_id_t key, psa_algorithm_t alg,
- const uint8_t *hash, size_t hash_length,
- const uint8_t *signature, size_t signature_length)
+ const uint8_t *hash_external, size_t hash_length,
+ const uint8_t *signature_external, size_t signature_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
+ LOCAL_INPUT_DECLARE(hash_external, hash);
+ LOCAL_INPUT_DECLARE(signature_external, signature);
+
/* Check that start has not been previously called, or operation has not
* previously errored. */
if (operation->id != 0 || operation->error_occurred) {
@@ -3353,18 +3671,20 @@ psa_status_t psa_verify_hash_start(
return status;
}
- psa_key_attributes_t attributes = {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
+ LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
/* Ensure ops count gets reset, in case of operation re-use. */
operation->num_ops = 0;
- status = psa_driver_wrapper_verify_hash_start(operation, &attributes,
+ status = psa_driver_wrapper_verify_hash_start(operation, &slot->attr,
slot->key.data,
slot->key.bytes,
alg, hash, hash_length,
signature, signature_length);
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
if (status != PSA_SUCCESS) {
operation->error_occurred = 1;
@@ -3377,6 +3697,9 @@ psa_status_t psa_verify_hash_start(
operation->error_occurred = 1;
}
+ LOCAL_INPUT_FREE(hash_external, hash);
+ LOCAL_INPUT_FREE(signature_external, signature);
+
return (status == PSA_SUCCESS) ? unlock_status : status;
}
@@ -3495,7 +3818,7 @@ psa_status_t mbedtls_psa_sign_hash_start(
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t required_hash_length;
- if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
+ if (!PSA_KEY_TYPE_IS_ECC(attributes->type)) {
return PSA_ERROR_NOT_SUPPORTED;
}
@@ -3512,8 +3835,8 @@ psa_status_t mbedtls_psa_sign_hash_start(
/* Ensure num_ops is zero'ed in case of context re-use. */
operation->num_ops = 0;
- status = mbedtls_psa_ecp_load_representation(attributes->core.type,
- attributes->core.bits,
+ status = mbedtls_psa_ecp_load_representation(attributes->type,
+ attributes->bits,
key_buffer,
key_buffer_size,
&operation->ctx);
@@ -3711,7 +4034,7 @@ psa_status_t mbedtls_psa_verify_hash_start(
size_t coordinate_bytes = 0;
size_t required_hash_length = 0;
- if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
+ if (!PSA_KEY_TYPE_IS_ECC(attributes->type)) {
return PSA_ERROR_NOT_SUPPORTED;
}
@@ -3730,8 +4053,8 @@ psa_status_t mbedtls_psa_verify_hash_start(
/* Ensure num_ops is zero'ed in case of context re-use. */
operation->num_ops = 0;
- status = mbedtls_psa_ecp_load_representation(attributes->core.type,
- attributes->core.bits,
+ status = mbedtls_psa_ecp_load_representation(attributes->type,
+ attributes->bits,
key_buffer,
key_buffer_size,
&operation->ctx);
@@ -3874,6 +4197,52 @@ psa_status_t mbedtls_psa_verify_hash_abort(
* defined( MBEDTLS_ECP_RESTARTABLE ) */
}
+static psa_status_t psa_generate_random_internal(uint8_t *output,
+ size_t output_size)
+{
+ GUARD_MODULE_INITIALIZED;
+
+#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
+
+ psa_status_t status;
+ size_t output_length = 0;
+ status = mbedtls_psa_external_get_random(&global_data.rng,
+ output, output_size,
+ &output_length);
+ if (status != PSA_SUCCESS) {
+ return status;
+ }
+ /* Breaking up a request into smaller chunks is currently not supported
+ * for the external RNG interface. */
+ if (output_length != output_size) {
+ return PSA_ERROR_INSUFFICIENT_ENTROPY;
+ }
+ return PSA_SUCCESS;
+
+#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+
+ while (output_size > 0) {
+ int ret = MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
+ size_t request_size =
+ (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
+ MBEDTLS_PSA_RANDOM_MAX_REQUEST :
+ output_size);
+#if defined(MBEDTLS_CTR_DRBG_C)
+ ret = mbedtls_ctr_drbg_random(&global_data.rng.drbg, output, request_size);
+#elif defined(MBEDTLS_HMAC_DRBG_C)
+ ret = mbedtls_hmac_drbg_random(&global_data.rng.drbg, output, request_size);
+#endif /* !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C */
+ if (ret != 0) {
+ return mbedtls_to_psa_error(ret);
+ }
+ output_size -= request_size;
+ output += request_size;
+ }
+ return PSA_SUCCESS;
+#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+}
+
+
/****************************************************************/
/* Symmetric cryptography */
/****************************************************************/
@@ -3889,7 +4258,6 @@ static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
PSA_KEY_USAGE_ENCRYPT :
PSA_KEY_USAGE_DECRYPT);
- psa_key_attributes_t attributes;
/* A context must be freshly initialized before it can be set up. */
if (operation->id != 0) {
@@ -3919,20 +4287,16 @@ static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
}
operation->default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
/* Try doing the operation through a driver before using software fallback. */
if (cipher_operation == MBEDTLS_ENCRYPT) {
status = psa_driver_wrapper_cipher_encrypt_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
} else {
status = psa_driver_wrapper_cipher_decrypt_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
@@ -3963,14 +4327,15 @@ psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
}
psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
- uint8_t *iv,
+ uint8_t *iv_external,
size_t iv_size,
size_t *iv_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
- uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
size_t default_iv_length = 0;
+ LOCAL_OUTPUT_DECLARE(iv_external, iv);
+
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
goto exit;
@@ -3992,33 +4357,40 @@ psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
goto exit;
}
- status = psa_generate_random(local_iv, default_iv_length);
+ LOCAL_OUTPUT_ALLOC(iv_external, default_iv_length, iv);
+
+ status = psa_generate_random_internal(iv, default_iv_length);
if (status != PSA_SUCCESS) {
goto exit;
}
status = psa_driver_wrapper_cipher_set_iv(operation,
- local_iv, default_iv_length);
+ iv, default_iv_length);
exit:
if (status == PSA_SUCCESS) {
- memcpy(iv, local_iv, default_iv_length);
*iv_length = default_iv_length;
operation->iv_set = 1;
} else {
*iv_length = 0;
psa_cipher_abort(operation);
+ if (iv != NULL) {
+ mbedtls_platform_zeroize(iv, default_iv_length);
+ }
}
+ LOCAL_OUTPUT_FREE(iv_external, iv);
return status;
}
psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
- const uint8_t *iv,
+ const uint8_t *iv_external,
size_t iv_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(iv_external, iv);
+
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
goto exit;
@@ -4034,6 +4406,8 @@ psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
goto exit;
}
+ LOCAL_INPUT_ALLOC(iv_external, iv_length, iv);
+
status = psa_driver_wrapper_cipher_set_iv(operation,
iv,
iv_length);
@@ -4044,18 +4418,24 @@ exit:
} else {
psa_cipher_abort(operation);
}
+
+ LOCAL_INPUT_FREE(iv_external, iv);
+
return status;
}
psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
goto exit;
@@ -4066,6 +4446,9 @@ psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
goto exit;
}
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
status = psa_driver_wrapper_cipher_update(operation,
input,
input_length,
@@ -4078,16 +4461,21 @@ exit:
psa_cipher_abort(operation);
}
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return status;
}
psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_GENERIC_ERROR;
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
goto exit;
@@ -4098,6 +4486,8 @@ psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
goto exit;
}
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
status = psa_driver_wrapper_cipher_finish(operation,
output,
output_size,
@@ -4105,13 +4495,15 @@ psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
exit:
if (status == PSA_SUCCESS) {
- return psa_cipher_abort(operation);
+ status = psa_cipher_abort(operation);
} else {
*output_length = 0;
(void) psa_cipher_abort(operation);
-
- return status;
}
+
+ LOCAL_OUTPUT_FREE(output_external, output);
+
+ return status;
}
psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
@@ -4134,9 +4526,9 @@ psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
@@ -4145,7 +4537,9 @@ psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
psa_key_slot_t *slot = NULL;
uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
size_t default_iv_length = 0;
- psa_key_attributes_t attributes;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
if (!PSA_ALG_IS_CIPHER(alg)) {
status = PSA_ERROR_INVALID_ARGUMENT;
@@ -4159,10 +4553,6 @@ psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
status = PSA_ERROR_GENERIC_ERROR;
@@ -4175,14 +4565,17 @@ psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
goto exit;
}
- status = psa_generate_random(local_iv, default_iv_length);
+ status = psa_generate_random_internal(local_iv, default_iv_length);
if (status != PSA_SUCCESS) {
goto exit;
}
}
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
status = psa_driver_wrapper_cipher_encrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, local_iv, default_iv_length, input, input_length,
psa_crypto_buffer_offset(output, default_iv_length),
output_size - default_iv_length, output_length);
@@ -4202,21 +4595,26 @@ exit:
*output_length = 0;
}
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return status;
}
psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
- psa_key_attributes_t attributes;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
if (!PSA_ALG_IS_CIPHER(alg)) {
status = PSA_ERROR_INVALID_ARGUMENT;
@@ -4230,10 +4628,6 @@ psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
if (alg == PSA_ALG_CCM_STAR_NO_TAG &&
input_length < PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type)) {
status = PSA_ERROR_INVALID_ARGUMENT;
@@ -4243,8 +4637,11 @@ psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
goto exit;
}
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
status = psa_driver_wrapper_cipher_decrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg, input, input_length,
output, output_size, output_length);
@@ -4258,6 +4655,9 @@ exit:
*output_length = 0;
}
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return status;
}
@@ -4327,19 +4727,24 @@ static psa_status_t psa_aead_check_algorithm(psa_algorithm_t alg)
psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *nonce,
+ const uint8_t *nonce_external,
size_t nonce_length,
- const uint8_t *additional_data,
+ const uint8_t *additional_data_external,
size_t additional_data_length,
- const uint8_t *plaintext,
+ const uint8_t *plaintext_external,
size_t plaintext_length,
- uint8_t *ciphertext,
+ uint8_t *ciphertext_external,
size_t ciphertext_size,
size_t *ciphertext_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
+ LOCAL_INPUT_DECLARE(nonce_external, nonce);
+ LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
+ LOCAL_INPUT_DECLARE(plaintext_external, plaintext);
+ LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
+
*ciphertext_length = 0;
status = psa_aead_check_algorithm(alg);
@@ -4353,9 +4758,10 @@ psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
return status;
}
- psa_key_attributes_t attributes = {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
+ LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length, additional_data);
+ LOCAL_INPUT_ALLOC(plaintext_external, plaintext_length, plaintext);
+ LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
status = psa_aead_check_nonce_length(alg, nonce_length);
if (status != PSA_SUCCESS) {
@@ -4363,7 +4769,7 @@ psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
}
status = psa_driver_wrapper_aead_encrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg,
nonce, nonce_length,
additional_data, additional_data_length,
@@ -4375,6 +4781,11 @@ psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
}
exit:
+ LOCAL_INPUT_FREE(nonce_external, nonce);
+ LOCAL_INPUT_FREE(additional_data_external, additional_data);
+ LOCAL_INPUT_FREE(plaintext_external, plaintext);
+ LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
+
psa_unregister_read_under_mutex(slot);
return status;
@@ -4382,19 +4793,24 @@ exit:
psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
- const uint8_t *nonce,
+ const uint8_t *nonce_external,
size_t nonce_length,
- const uint8_t *additional_data,
+ const uint8_t *additional_data_external,
size_t additional_data_length,
- const uint8_t *ciphertext,
+ const uint8_t *ciphertext_external,
size_t ciphertext_length,
- uint8_t *plaintext,
+ uint8_t *plaintext_external,
size_t plaintext_size,
size_t *plaintext_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
+ LOCAL_INPUT_DECLARE(nonce_external, nonce);
+ LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
+ LOCAL_INPUT_DECLARE(ciphertext_external, ciphertext);
+ LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
+
*plaintext_length = 0;
status = psa_aead_check_algorithm(alg);
@@ -4408,9 +4824,11 @@ psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
return status;
}
- psa_key_attributes_t attributes = {
- .core = slot->attr
- };
+ LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
+ LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length,
+ additional_data);
+ LOCAL_INPUT_ALLOC(ciphertext_external, ciphertext_length, ciphertext);
+ LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
status = psa_aead_check_nonce_length(alg, nonce_length);
if (status != PSA_SUCCESS) {
@@ -4418,7 +4836,7 @@ psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
}
status = psa_driver_wrapper_aead_decrypt(
- &attributes, slot->key.data, slot->key.bytes,
+ &slot->attr, slot->key.data, slot->key.bytes,
alg,
nonce, nonce_length,
additional_data, additional_data_length,
@@ -4430,6 +4848,11 @@ psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
}
exit:
+ LOCAL_INPUT_FREE(nonce_external, nonce);
+ LOCAL_INPUT_FREE(additional_data_external, additional_data);
+ LOCAL_INPUT_FREE(ciphertext_external, ciphertext);
+ LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
+
psa_unregister_read_under_mutex(slot);
return status;
@@ -4484,7 +4907,6 @@ static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
psa_key_usage_t key_usage = 0;
- psa_key_attributes_t attributes;
status = psa_aead_check_algorithm(alg);
if (status != PSA_SUCCESS) {
@@ -4514,23 +4936,19 @@ static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
if ((status = psa_validate_tag_length(alg)) != PSA_SUCCESS) {
goto exit;
}
if (is_encrypt) {
status = psa_driver_wrapper_aead_encrypt_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
} else {
status = psa_driver_wrapper_aead_decrypt_setup(operation,
- &attributes,
+ &slot->attr,
slot->key.data,
slot->key.bytes,
alg);
@@ -4539,7 +4957,7 @@ static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
goto exit;
}
- operation->key_type = psa_get_key_type(&attributes);
+ operation->key_type = psa_get_key_type(&slot->attr);
exit:
unlock_status = psa_unregister_read_under_mutex(slot);
@@ -4571,9 +4989,44 @@ psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
return psa_aead_setup(operation, 0, key, alg);
}
+static psa_status_t psa_aead_set_nonce_internal(psa_aead_operation_t *operation,
+ const uint8_t *nonce,
+ size_t nonce_length)
+{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+
+ if (operation->id == 0) {
+ status = PSA_ERROR_BAD_STATE;
+ goto exit;
+ }
+
+ if (operation->nonce_set) {
+ status = PSA_ERROR_BAD_STATE;
+ goto exit;
+ }
+
+ status = psa_aead_check_nonce_length(operation->alg, nonce_length);
+ if (status != PSA_SUCCESS) {
+ status = PSA_ERROR_INVALID_ARGUMENT;
+ goto exit;
+ }
+
+ status = psa_driver_wrapper_aead_set_nonce(operation, nonce,
+ nonce_length);
+
+exit:
+ if (status == PSA_SUCCESS) {
+ operation->nonce_set = 1;
+ } else {
+ psa_aead_abort(operation);
+ }
+
+ return status;
+}
+
/* Generate a random nonce / IV for multipart AEAD operation */
psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
- uint8_t *nonce,
+ uint8_t *nonce_external,
size_t nonce_size,
size_t *nonce_length)
{
@@ -4581,6 +5034,9 @@ psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
uint8_t local_nonce[PSA_AEAD_NONCE_MAX_SIZE];
size_t required_nonce_size = 0;
+ LOCAL_OUTPUT_DECLARE(nonce_external, nonce);
+ LOCAL_OUTPUT_ALLOC(nonce_external, nonce_size, nonce);
+
*nonce_length = 0;
if (operation->id == 0) {
@@ -4609,12 +5065,13 @@ psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
goto exit;
}
- status = psa_generate_random(local_nonce, required_nonce_size);
+ status = psa_generate_random_internal(local_nonce, required_nonce_size);
if (status != PSA_SUCCESS) {
goto exit;
}
- status = psa_aead_set_nonce(operation, local_nonce, required_nonce_size);
+ status = psa_aead_set_nonce_internal(operation, local_nonce,
+ required_nonce_size);
exit:
if (status == PSA_SUCCESS) {
@@ -4624,42 +5081,30 @@ exit:
psa_aead_abort(operation);
}
+ LOCAL_OUTPUT_FREE(nonce_external, nonce);
+
return status;
}
/* Set the nonce for a multipart authenticated encryption or decryption
operation.*/
psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
- const uint8_t *nonce,
+ const uint8_t *nonce_external,
size_t nonce_length)
{
- psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
-
- if (operation->id == 0) {
- status = PSA_ERROR_BAD_STATE;
- goto exit;
- }
-
- if (operation->nonce_set) {
- status = PSA_ERROR_BAD_STATE;
- goto exit;
- }
+ psa_status_t status;
- status = psa_aead_check_nonce_length(operation->alg, nonce_length);
- if (status != PSA_SUCCESS) {
- status = PSA_ERROR_INVALID_ARGUMENT;
- goto exit;
- }
+ LOCAL_INPUT_DECLARE(nonce_external, nonce);
+ LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
- status = psa_driver_wrapper_aead_set_nonce(operation, nonce,
- nonce_length);
+ status = psa_aead_set_nonce_internal(operation, nonce, nonce_length);
+/* Exit label is only needed for buffer copying, prevent unused warnings. */
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
exit:
- if (status == PSA_SUCCESS) {
- operation->nonce_set = 1;
- } else {
- psa_aead_abort(operation);
- }
+#endif
+
+ LOCAL_INPUT_FREE(nonce_external, nonce);
return status;
}
@@ -4731,11 +5176,14 @@ exit:
/* Pass additional data to an active multipart AEAD operation. */
psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+
if (operation->id == 0) {
status = PSA_ERROR_BAD_STATE;
goto exit;
@@ -4771,20 +5219,29 @@ exit:
psa_aead_abort(operation);
}
+ LOCAL_INPUT_FREE(input_external, input);
+
return status;
}
/* Encrypt or decrypt a message fragment in an active multipart AEAD
operation.*/
psa_status_t psa_aead_update(psa_aead_operation_t *operation,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+
+ LOCAL_INPUT_DECLARE(input_external, input);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
*output_length = 0;
if (operation->id == 0) {
@@ -4831,6 +5288,9 @@ exit:
psa_aead_abort(operation);
}
+ LOCAL_INPUT_FREE(input_external, input);
+ LOCAL_OUTPUT_FREE(output_external, output);
+
return status;
}
@@ -4850,15 +5310,21 @@ static psa_status_t psa_aead_final_checks(const psa_aead_operation_t *operation)
/* Finish encrypting a message in a multipart AEAD operation. */
psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
- uint8_t *ciphertext,
+ uint8_t *ciphertext_external,
size_t ciphertext_size,
size_t *ciphertext_length,
- uint8_t *tag,
+ uint8_t *tag_external,
size_t tag_size,
size_t *tag_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
+ LOCAL_OUTPUT_DECLARE(tag_external, tag);
+
+ LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
+ LOCAL_OUTPUT_ALLOC(tag_external, tag_size, tag);
+
*ciphertext_length = 0;
*tag_length = tag_size;
@@ -4889,20 +5355,29 @@ exit:
psa_aead_abort(operation);
+ LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
+ LOCAL_OUTPUT_FREE(tag_external, tag);
+
return status;
}
/* Finish authenticating and decrypting a message in a multipart AEAD
operation.*/
psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
- uint8_t *plaintext,
+ uint8_t *plaintext_external,
size_t plaintext_size,
size_t *plaintext_length,
- const uint8_t *tag,
+ const uint8_t *tag_external,
size_t tag_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
+ LOCAL_INPUT_DECLARE(tag_external, tag);
+
+ LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
+ LOCAL_INPUT_ALLOC(tag_external, tag_length, tag);
+
*plaintext_length = 0;
status = psa_aead_final_checks(operation);
@@ -4923,6 +5398,9 @@ psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
exit:
psa_aead_abort(operation);
+ LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
+ LOCAL_INPUT_FREE(tag_external, tag);
+
return status;
}
@@ -5529,10 +6007,12 @@ static psa_status_t psa_key_derivation_pbkdf2_read(
psa_status_t psa_key_derivation_output_bytes(
psa_key_derivation_operation_t *operation,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_length)
{
psa_status_t status;
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+
psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
if (operation->alg == 0) {
@@ -5540,13 +6020,6 @@ psa_status_t psa_key_derivation_output_bytes(
return PSA_ERROR_BAD_STATE;
}
- if (output_length > operation->capacity) {
- operation->capacity = 0;
- /* Go through the error path to wipe all confidential data now
- * that the operation object is useless. */
- status = PSA_ERROR_INSUFFICIENT_DATA;
- goto exit;
- }
if (output_length == 0 && operation->capacity == 0) {
/* Edge case: this is a finished operation, and 0 bytes
* were requested. The right error in this case could
@@ -5556,6 +6029,16 @@ psa_status_t psa_key_derivation_output_bytes(
* output_length > 0. */
return PSA_ERROR_INSUFFICIENT_DATA;
}
+
+ LOCAL_OUTPUT_ALLOC(output_external, output_length, output);
+ if (output_length > operation->capacity) {
+ operation->capacity = 0;
+ /* Go through the error path to wipe all confidential data now
+ * that the operation object is useless. */
+ status = PSA_ERROR_INSUFFICIENT_DATA;
+ goto exit;
+ }
+
operation->capacity -= output_length;
#if defined(BUILTIN_ALG_ANY_HKDF)
@@ -5589,7 +6072,10 @@ psa_status_t psa_key_derivation_output_bytes(
{
(void) kdf_alg;
- return PSA_ERROR_BAD_STATE;
+ status = PSA_ERROR_BAD_STATE;
+ LOCAL_OUTPUT_FREE(output_external, output);
+
+ return status;
}
exit:
@@ -5601,8 +6087,12 @@ exit:
psa_algorithm_t alg = operation->alg;
psa_key_derivation_abort(operation);
operation->alg = alg;
- memset(output, '!', output_length);
+ if (output != NULL) {
+ memset(output, '!', output_length);
+ }
}
+
+ LOCAL_OUTPUT_FREE(output_external, output);
return status;
}
@@ -5842,7 +6332,6 @@ static psa_status_t psa_generate_derived_key_internal(
size_t bytes = PSA_BITS_TO_BYTES(bits);
size_t storage_size = bytes;
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
- psa_key_attributes_t attributes;
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
return PSA_ERROR_INVALID_ARGUMENT;
@@ -5891,12 +6380,9 @@ static psa_status_t psa_generate_derived_key_internal(
}
slot->attr.bits = (psa_key_bits_t) bits;
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
- if (psa_key_lifetime_is_external(attributes.core.lifetime)) {
- status = psa_driver_wrapper_get_key_buffer_size(&attributes,
+ if (psa_key_lifetime_is_external(slot->attr.lifetime)) {
+ status = psa_driver_wrapper_get_key_buffer_size(&slot->attr,
&storage_size);
if (status != PSA_SUCCESS) {
goto exit;
@@ -5907,7 +6393,7 @@ static psa_status_t psa_generate_derived_key_internal(
goto exit;
}
- status = psa_driver_wrapper_import_key(&attributes,
+ status = psa_driver_wrapper_import_key(&slot->attr,
data, bytes,
slot->key.data,
slot->key.bytes,
@@ -5978,7 +6464,7 @@ psa_status_t psa_key_derivation_output_key_ext(
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
if (status == PSA_SUCCESS) {
status = psa_generate_derived_key_internal(slot,
- attributes->core.bits,
+ attributes->bits,
operation);
}
if (status == PSA_SUCCESS) {
@@ -6665,12 +7151,12 @@ static psa_status_t psa_pbkdf2_hmac_set_password(psa_algorithm_t hash_alg,
{
psa_status_t status = PSA_SUCCESS;
if (input_len > PSA_HASH_BLOCK_LENGTH(hash_alg)) {
- status = psa_hash_compute(hash_alg, input, input_len, output,
- PSA_HMAC_MAX_HASH_BLOCK_SIZE, output_len);
- } else {
+ return psa_hash_compute(hash_alg, input, input_len, output,
+ PSA_HMAC_MAX_HASH_BLOCK_SIZE, output_len);
+ } else if (input_len > 0) {
memcpy(output, input, input_len);
- *output_len = PSA_HASH_BLOCK_LENGTH(hash_alg);
}
+ *output_len = PSA_HASH_BLOCK_LENGTH(hash_alg);
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
@@ -6904,12 +7390,22 @@ static psa_status_t psa_key_derivation_input_integer_internal(
psa_status_t psa_key_derivation_input_bytes(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
- const uint8_t *data,
+ const uint8_t *data_external,
size_t data_length)
{
- return psa_key_derivation_input_internal(operation, step,
- PSA_KEY_TYPE_NONE,
- data, data_length);
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(data_external, data);
+
+ LOCAL_INPUT_ALLOC(data_external, data_length, data);
+
+ status = psa_key_derivation_input_internal(operation, step,
+ PSA_KEY_TYPE_NONE,
+ data, data_length);
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_INPUT_FREE(data_external, data);
+ return status;
}
psa_status_t psa_key_derivation_input_integer(
@@ -7023,11 +7519,7 @@ static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
return PSA_ERROR_NOT_SUPPORTED;
}
- psa_key_attributes_t attributes = {
- .core = private_key->attr
- };
-
- return psa_driver_wrapper_key_agreement(&attributes,
+ return psa_driver_wrapper_key_agreement(&private_key->attr,
private_key->key.data,
private_key->key.bytes, alg,
peer_key, peer_key_length,
@@ -7046,7 +7538,7 @@ static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *o
size_t peer_key_length)
{
psa_status_t status;
- uint8_t shared_secret[PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE];
+ uint8_t shared_secret[PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE] = { 0 };
size_t shared_secret_length = 0;
psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
@@ -7077,12 +7569,13 @@ exit:
psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
mbedtls_svc_key_id_t private_key,
- const uint8_t *peer_key,
+ const uint8_t *peer_key_external,
size_t peer_key_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
+ LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
if (!PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
return PSA_ERROR_INVALID_ARGUMENT;
@@ -7092,9 +7585,15 @@ psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *op
if (status != PSA_SUCCESS) {
return status;
}
+
+ LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
status = psa_key_agreement_internal(operation, step,
slot,
peer_key, peer_key_length);
+
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
if (status != PSA_SUCCESS) {
psa_key_derivation_abort(operation);
} else {
@@ -7106,15 +7605,16 @@ psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *op
}
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_INPUT_FREE(peer_key_external, peer_key);
return (status == PSA_SUCCESS) ? unlock_status : status;
}
psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
mbedtls_svc_key_id_t private_key,
- const uint8_t *peer_key,
+ const uint8_t *peer_key_external,
size_t peer_key_length,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
@@ -7122,6 +7622,9 @@ psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
size_t expected_length;
+ LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
if (!PSA_ALG_IS_KEY_AGREEMENT(alg)) {
status = PSA_ERROR_INVALID_ARGUMENT;
@@ -7148,13 +7651,16 @@ psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
goto exit;
}
+ LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
status = psa_key_agreement_raw_internal(alg, slot,
peer_key, peer_key_length,
output, output_size,
output_length);
exit:
- if (status != PSA_SUCCESS) {
+ /* Check for successful allocation of output,
+ * with an unsuccessful status. */
+ if (output != NULL && status != PSA_SUCCESS) {
/* If an error happens and is not handled properly, the output
* may be used as a key to protect sensitive data. Arrange for such
* a key to be random, which is likely to result in decryption or
@@ -7162,17 +7668,23 @@ exit:
* some constant data such as zeros, which would result in the data
* being protected with a reproducible, easily knowable key.
*/
- psa_generate_random(output, output_size);
+ psa_generate_random_internal(output, output_size);
*output_length = output_size;
}
+ if (output == NULL) {
+ /* output allocation failed. */
+ *output_length = 0;
+ }
+
unlock_status = psa_unregister_read_under_mutex(slot);
+ LOCAL_INPUT_FREE(peer_key_external, peer_key);
+ LOCAL_OUTPUT_FREE(output_external, output);
return (status == PSA_SUCCESS) ? unlock_status : status;
}
-
/****************************************************************/
/* Random generation */
/****************************************************************/
@@ -7182,6 +7694,9 @@ exit:
#endif
/** Initialize the PSA random generator.
+ *
+ * Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
+ * this function if mutexes are enabled.
*/
static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
{
@@ -7209,18 +7724,21 @@ static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
MBEDTLS_ENTROPY_SOURCE_STRONG);
#endif
- mbedtls_psa_drbg_init(MBEDTLS_PSA_RANDOM_STATE);
+ mbedtls_psa_drbg_init(&rng->drbg);
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
/** Deinitialize the PSA random generator.
+ *
+ * Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
+ * this function if mutexes are enabled.
*/
static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng)
{
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
memset(rng, 0, sizeof(*rng));
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
- mbedtls_psa_drbg_free(MBEDTLS_PSA_RANDOM_STATE);
+ mbedtls_psa_drbg_free(&rng->drbg);
rng->entropy_free(&rng->entropy);
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
@@ -7235,90 +7753,34 @@ static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng)
return PSA_SUCCESS;
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
const unsigned char drbg_seed[] = "PSA";
- int ret = mbedtls_psa_drbg_seed(&rng->entropy,
+ int ret = mbedtls_psa_drbg_seed(&rng->drbg, &rng->entropy,
drbg_seed, sizeof(drbg_seed) - 1);
return mbedtls_to_psa_error(ret);
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
-psa_status_t psa_generate_random(uint8_t *output,
+psa_status_t psa_generate_random(uint8_t *output_external,
size_t output_size)
{
- GUARD_MODULE_INITIALIZED;
-
-#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
-
- size_t output_length = 0;
- psa_status_t status = mbedtls_psa_external_get_random(&global_data.rng,
- output, output_size,
- &output_length);
- if (status != PSA_SUCCESS) {
- return status;
- }
- /* Breaking up a request into smaller chunks is currently not supported
- * for the external RNG interface. */
- if (output_length != output_size) {
- return PSA_ERROR_INSUFFICIENT_ENTROPY;
- }
- return PSA_SUCCESS;
+ psa_status_t status;
-#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+ LOCAL_OUTPUT_DECLARE(output_external, output);
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
- while (output_size > 0) {
- size_t request_size =
- (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
- MBEDTLS_PSA_RANDOM_MAX_REQUEST :
- output_size);
- int ret = mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE,
- output, request_size);
- if (ret != 0) {
- return mbedtls_to_psa_error(ret);
- }
- output_size -= request_size;
- output += request_size;
- }
- return PSA_SUCCESS;
-#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
-}
+ status = psa_generate_random_internal(output, output_size);
-/* Wrapper function allowing the classic API to use the PSA RNG.
- *
- * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
- * `psa_generate_random(...)`. The state parameter is ignored since the
- * PSA API doesn't support passing an explicit state.
- *
- * In the non-external case, psa_generate_random() calls an
- * `mbedtls_xxx_drbg_random` function which has exactly the same signature
- * and semantics as mbedtls_psa_get_random(). As an optimization,
- * instead of doing this back-and-forth between the PSA API and the
- * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
- * as a constant function pointer to `mbedtls_xxx_drbg_random`.
- */
-#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
-int mbedtls_psa_get_random(void *p_rng,
- unsigned char *output,
- size_t output_size)
-{
- /* This function takes a pointer to the RNG state because that's what
- * classic mbedtls functions using an RNG expect. The PSA RNG manages
- * its own state internally and doesn't let the caller access that state.
- * So we just ignore the state parameter, and in practice we'll pass
- * NULL. */
- (void) p_rng;
- psa_status_t status = psa_generate_random(output, output_size);
- if (status == PSA_SUCCESS) {
- return 0;
- } else {
- return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
- }
+#if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
+exit:
+#endif
+ LOCAL_OUTPUT_FREE(output_external, output);
+ return status;
}
-#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
size_t seed_size)
{
- if (global_data.initialized) {
+ if (psa_get_initialized()) {
return PSA_ERROR_NOT_PERMITTED;
}
@@ -7400,14 +7862,14 @@ psa_status_t psa_generate_key_internal(
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
- psa_key_type_t type = attributes->core.type;
+ psa_key_type_t type = attributes->type;
/* Only used for RSA */
(void) params;
(void) params_data_length;
if (key_type_is_raw_bytes(type)) {
- status = psa_generate_random(key_buffer, key_buffer_size);
+ status = psa_generate_random_internal(key_buffer, key_buffer_size);
if (status != PSA_SUCCESS) {
return status;
}
@@ -7473,12 +7935,12 @@ psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
}
/* Reject any attempt to create a public key. */
- if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->core.type)) {
+ if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->type)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
- if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
+ if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
if (params->flags != 0) {
return PSA_ERROR_INVALID_ARGUMENT;
}
@@ -7499,17 +7961,17 @@ psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
* with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
* buffer to hold the generated key material. */
if (slot->key.data == NULL) {
- if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->core.lifetime) ==
+ if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->lifetime) ==
PSA_KEY_LOCATION_LOCAL_STORAGE) {
status = psa_validate_key_type_and_size_for_key_generation(
- attributes->core.type, attributes->core.bits);
+ attributes->type, attributes->bits);
if (status != PSA_SUCCESS) {
goto exit;
}
key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
- attributes->core.type,
- attributes->core.bits);
+ attributes->type,
+ attributes->bits);
} else {
status = psa_driver_wrapper_get_key_buffer_size(
attributes, &key_buffer_size);
@@ -7560,28 +8022,77 @@ psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
void (* entropy_init)(mbedtls_entropy_context *ctx),
void (* entropy_free)(mbedtls_entropy_context *ctx))
{
+ psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
if (global_data.rng_state != RNG_NOT_INITIALIZED) {
- return PSA_ERROR_BAD_STATE;
+ status = PSA_ERROR_BAD_STATE;
+ } else {
+ global_data.rng.entropy_init = entropy_init;
+ global_data.rng.entropy_free = entropy_free;
+ status = PSA_SUCCESS;
}
- global_data.rng.entropy_init = entropy_init;
- global_data.rng.entropy_free = entropy_free;
- return PSA_SUCCESS;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ return status;
}
#endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
void mbedtls_psa_crypto_free(void)
{
- psa_wipe_all_key_slots();
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ /* Nothing to do to free transaction. */
+ if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED) {
+ global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
+ }
+
+ if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED) {
+ psa_wipe_all_key_slots();
+ global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
+ }
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
if (global_data.rng_state != RNG_NOT_INITIALIZED) {
mbedtls_psa_random_free(&global_data.rng);
}
- /* Wipe all remaining data, including configuration.
- * In particular, this sets all state indicator to the value
- * indicating "uninitialized". */
- mbedtls_platform_zeroize(&global_data, sizeof(global_data));
+ global_data.rng_state = RNG_NOT_INITIALIZED;
+ mbedtls_platform_zeroize(&global_data.rng, sizeof(global_data.rng));
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
/* Terminate drivers */
- psa_driver_wrapper_free();
+ if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED) {
+ psa_driver_wrapper_free();
+ global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
+ }
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
}
#if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
@@ -7609,57 +8120,171 @@ static psa_status_t psa_crypto_recover_transaction(
}
#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
+static psa_status_t mbedtls_psa_crypto_init_subsystem(mbedtls_psa_crypto_subsystem subsystem)
+{
+ psa_status_t status = PSA_SUCCESS;
+ uint8_t driver_wrappers_initialized = 0;
+
+ switch (subsystem) {
+ case PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS:
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED)) {
+ /* Init drivers */
+ status = psa_driver_wrapper_init();
+
+ /* Drivers need shutdown regardless of startup errors. */
+ global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
+
+
+ }
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
+ &mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ break;
+
+ case PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS:
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED)) {
+ status = psa_initialize_key_slots();
+
+ /* Need to wipe keys even if initialization fails. */
+ global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
+
+ }
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
+ &mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ break;
+
+ case PSA_CRYPTO_SUBSYSTEM_RNG:
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ driver_wrappers_initialized =
+ (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED);
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
+ &mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ /* Need to use separate mutex here, as initialisation can require
+ * testing of init flags, which requires locking the global data
+ * mutex. */
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ /* Initialize and seed the random generator. */
+ if (global_data.rng_state == RNG_NOT_INITIALIZED && driver_wrappers_initialized) {
+ mbedtls_psa_random_init(&global_data.rng);
+ global_data.rng_state = RNG_INITIALIZED;
+
+ status = mbedtls_psa_random_seed(&global_data.rng);
+ if (status == PSA_SUCCESS) {
+ global_data.rng_state = RNG_SEEDED;
+ }
+ }
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
+ &mbedtls_threading_psa_rngdata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ break;
+
+ case PSA_CRYPTO_SUBSYSTEM_TRANSACTION:
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED)) {
+#if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
+ status = psa_crypto_load_transaction();
+ if (status == PSA_SUCCESS) {
+ status = psa_crypto_recover_transaction(&psa_crypto_transaction);
+ if (status == PSA_SUCCESS) {
+ global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
+ }
+ status = psa_crypto_stop_transaction();
+ } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
+ /* There's no transaction to complete. It's all good. */
+ global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
+ status = PSA_SUCCESS;
+ }
+#else /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
+ global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
+ status = PSA_SUCCESS;
+#endif /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
+ }
+
+#if defined(MBEDTLS_THREADING_C)
+ PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
+ &mbedtls_threading_psa_globaldata_mutex));
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ break;
+
+ default:
+ status = PSA_ERROR_CORRUPTION_DETECTED;
+ }
+
+ /* Exit label only required when using threading macros. */
+#if defined(MBEDTLS_THREADING_C)
+exit:
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ return status;
+}
+
psa_status_t psa_crypto_init(void)
{
psa_status_t status;
- /* Double initialization is explicitly allowed. */
- if (global_data.initialized != 0) {
+ /* Double initialization is explicitly allowed. Early out if everything is
+ * done. */
+ if (psa_get_initialized()) {
return PSA_SUCCESS;
}
- /* Init drivers */
- status = psa_driver_wrapper_init();
+ status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS);
if (status != PSA_SUCCESS) {
goto exit;
}
- global_data.drivers_initialized = 1;
- status = psa_initialize_key_slots();
+ status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS);
if (status != PSA_SUCCESS) {
goto exit;
}
- /* Initialize and seed the random generator. */
- mbedtls_psa_random_init(&global_data.rng);
- global_data.rng_state = RNG_INITIALIZED;
- status = mbedtls_psa_random_seed(&global_data.rng);
+ status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_RNG);
if (status != PSA_SUCCESS) {
goto exit;
}
- global_data.rng_state = RNG_SEEDED;
-#if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
- status = psa_crypto_load_transaction();
- if (status == PSA_SUCCESS) {
- status = psa_crypto_recover_transaction(&psa_crypto_transaction);
- if (status != PSA_SUCCESS) {
- goto exit;
- }
- status = psa_crypto_stop_transaction();
- } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
- /* There's no transaction to complete. It's all good. */
- status = PSA_SUCCESS;
- }
-#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
-
- /* All done. */
- global_data.initialized = 1;
+ status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_TRANSACTION);
exit:
+
if (status != PSA_SUCCESS) {
mbedtls_psa_crypto_free();
}
+
return status;
}
@@ -7823,7 +8448,6 @@ psa_status_t psa_pake_set_password_key(
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
- psa_key_attributes_t attributes;
psa_key_type_t type;
if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
@@ -7838,11 +8462,7 @@ psa_status_t psa_pake_set_password_key(
goto exit;
}
- attributes = (psa_key_attributes_t) {
- .core = slot->attr
- };
-
- type = psa_get_key_type(&attributes);
+ type = psa_get_key_type(&slot->attr);
if (type != PSA_KEY_TYPE_PASSWORD &&
type != PSA_KEY_TYPE_PASSWORD_HASH) {
@@ -7858,7 +8478,8 @@ psa_status_t psa_pake_set_password_key(
memcpy(operation->data.inputs.password, slot->key.data, slot->key.bytes);
operation->data.inputs.password_len = slot->key.bytes;
- operation->data.inputs.attributes = attributes;
+ operation->data.inputs.attributes = slot->attr;
+
exit:
if (status != PSA_SUCCESS) {
psa_pake_abort(operation);
@@ -7869,10 +8490,11 @@ exit:
psa_status_t psa_pake_set_user(
psa_pake_operation_t *operation,
- const uint8_t *user_id,
+ const uint8_t *user_id_external,
size_t user_id_len)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(user_id_external, user_id);
if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
status = PSA_ERROR_BAD_STATE;
@@ -7895,21 +8517,28 @@ psa_status_t psa_pake_set_user(
goto exit;
}
+ LOCAL_INPUT_ALLOC(user_id_external, user_id_len, user_id);
+
memcpy(operation->data.inputs.user, user_id, user_id_len);
operation->data.inputs.user_len = user_id_len;
- return PSA_SUCCESS;
+ status = PSA_SUCCESS;
+
exit:
- psa_pake_abort(operation);
+ LOCAL_INPUT_FREE(user_id_external, user_id);
+ if (status != PSA_SUCCESS) {
+ psa_pake_abort(operation);
+ }
return status;
}
psa_status_t psa_pake_set_peer(
psa_pake_operation_t *operation,
- const uint8_t *peer_id,
+ const uint8_t *peer_id_external,
size_t peer_id_len)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
+ LOCAL_INPUT_DECLARE(peer_id_external, peer_id);
if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
status = PSA_ERROR_BAD_STATE;
@@ -7932,12 +8561,18 @@ psa_status_t psa_pake_set_peer(
goto exit;
}
+ LOCAL_INPUT_ALLOC(peer_id_external, peer_id_len, peer_id);
+
memcpy(operation->data.inputs.peer, peer_id, peer_id_len);
operation->data.inputs.peer_len = peer_id_len;
- return PSA_SUCCESS;
+ status = PSA_SUCCESS;
+
exit:
- psa_pake_abort(operation);
+ LOCAL_INPUT_FREE(peer_id_external, peer_id);
+ if (status != PSA_SUCCESS) {
+ psa_pake_abort(operation);
+ }
return status;
}
@@ -8123,12 +8758,13 @@ static psa_status_t psa_jpake_epilogue(
psa_status_t psa_pake_output(
psa_pake_operation_t *operation,
psa_pake_step_t step,
- uint8_t *output,
+ uint8_t *output_external,
size_t output_size,
size_t *output_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
+ LOCAL_OUTPUT_DECLARE(output_external, output);
*output_length = 0;
if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
@@ -8165,6 +8801,8 @@ psa_status_t psa_pake_output(
goto exit;
}
+ LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
+
status = psa_driver_wrapper_pake_output(operation, driver_step,
output, output_size, output_length);
@@ -8186,16 +8824,18 @@ psa_status_t psa_pake_output(
goto exit;
}
- return PSA_SUCCESS;
exit:
- psa_pake_abort(operation);
+ LOCAL_OUTPUT_FREE(output_external, output);
+ if (status != PSA_SUCCESS) {
+ psa_pake_abort(operation);
+ }
return status;
}
psa_status_t psa_pake_input(
psa_pake_operation_t *operation,
psa_pake_step_t step,
- const uint8_t *input,
+ const uint8_t *input_external,
size_t input_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
@@ -8203,6 +8843,7 @@ psa_status_t psa_pake_input(
const size_t max_input_length = (size_t) PSA_PAKE_INPUT_SIZE(operation->alg,
operation->primitive,
step);
+ LOCAL_INPUT_DECLARE(input_external, input);
if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
status = psa_pake_complete_inputs(operation);
@@ -8238,6 +8879,7 @@ psa_status_t psa_pake_input(
goto exit;
}
+ LOCAL_INPUT_ALLOC(input_external, input_length, input);
status = psa_driver_wrapper_pake_input(operation, driver_step,
input, input_length);
@@ -8259,9 +8901,11 @@ psa_status_t psa_pake_input(
goto exit;
}
- return PSA_SUCCESS;
exit:
- psa_pake_abort(operation);
+ LOCAL_INPUT_FREE(input_external, input);
+ if (status != PSA_SUCCESS) {
+ psa_pake_abort(operation);
+ }
return status;
}
@@ -8341,4 +8985,182 @@ psa_status_t psa_pake_abort(
}
#endif /* PSA_WANT_ALG_SOME_PAKE */
+/* Memory copying test hooks. These are called before input copy, after input
+ * copy, before output copy and after output copy, respectively.
+ * They are used by memory-poisoning tests to temporarily unpoison buffers
+ * while they are copied. */
+#if defined(MBEDTLS_TEST_HOOKS)
+void (*psa_input_pre_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
+void (*psa_input_post_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
+void (*psa_output_pre_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
+void (*psa_output_post_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
+#endif
+
+/** Copy from an input buffer to a local copy.
+ *
+ * \param[in] input Pointer to input buffer.
+ * \param[in] input_len Length of the input buffer.
+ * \param[out] input_copy Pointer to a local copy in which to store the input data.
+ * \param[out] input_copy_len Length of the local copy buffer.
+ * \return #PSA_SUCCESS, if the buffer was successfully
+ * copied.
+ * \return #PSA_ERROR_CORRUPTION_DETECTED, if the local
+ * copy is too small to hold contents of the
+ * input buffer.
+ */
+MBEDTLS_STATIC_TESTABLE
+psa_status_t psa_crypto_copy_input(const uint8_t *input, size_t input_len,
+ uint8_t *input_copy, size_t input_copy_len)
+{
+ if (input_len > input_copy_len) {
+ return PSA_ERROR_CORRUPTION_DETECTED;
+ }
+
+#if defined(MBEDTLS_TEST_HOOKS)
+ if (psa_input_pre_copy_hook != NULL) {
+ psa_input_pre_copy_hook(input, input_len);
+ }
+#endif
+
+ if (input_len > 0) {
+ memcpy(input_copy, input, input_len);
+ }
+
+#if defined(MBEDTLS_TEST_HOOKS)
+ if (psa_input_post_copy_hook != NULL) {
+ psa_input_post_copy_hook(input, input_len);
+ }
+#endif
+
+ return PSA_SUCCESS;
+}
+
+/** Copy from a local output buffer into a user-supplied one.
+ *
+ * \param[in] output_copy Pointer to a local buffer containing the output.
+ * \param[in] output_copy_len Length of the local buffer.
+ * \param[out] output Pointer to user-supplied output buffer.
+ * \param[out] output_len Length of the user-supplied output buffer.
+ * \return #PSA_SUCCESS, if the buffer was successfully
+ * copied.
+ * \return #PSA_ERROR_BUFFER_TOO_SMALL, if the
+ * user-supplied output buffer is too small to
+ * hold the contents of the local buffer.
+ */
+MBEDTLS_STATIC_TESTABLE
+psa_status_t psa_crypto_copy_output(const uint8_t *output_copy, size_t output_copy_len,
+ uint8_t *output, size_t output_len)
+{
+ if (output_len < output_copy_len) {
+ return PSA_ERROR_BUFFER_TOO_SMALL;
+ }
+
+#if defined(MBEDTLS_TEST_HOOKS)
+ if (psa_output_pre_copy_hook != NULL) {
+ psa_output_pre_copy_hook(output, output_len);
+ }
+#endif
+
+ if (output_copy_len > 0) {
+ memcpy(output, output_copy, output_copy_len);
+ }
+
+#if defined(MBEDTLS_TEST_HOOKS)
+ if (psa_output_post_copy_hook != NULL) {
+ psa_output_post_copy_hook(output, output_len);
+ }
+#endif
+
+ return PSA_SUCCESS;
+}
+
+psa_status_t psa_crypto_local_input_alloc(const uint8_t *input, size_t input_len,
+ psa_crypto_local_input_t *local_input)
+{
+ psa_status_t status;
+
+ *local_input = PSA_CRYPTO_LOCAL_INPUT_INIT;
+
+ if (input_len == 0) {
+ return PSA_SUCCESS;
+ }
+
+ local_input->buffer = mbedtls_calloc(input_len, 1);
+ if (local_input->buffer == NULL) {
+ /* Since we dealt with the zero-length case above, we know that
+ * a NULL return value means a failure of allocation. */
+ return PSA_ERROR_INSUFFICIENT_MEMORY;
+ }
+ /* From now on, we must free local_input->buffer on error. */
+
+ local_input->length = input_len;
+
+ status = psa_crypto_copy_input(input, input_len,
+ local_input->buffer, local_input->length);
+ if (status != PSA_SUCCESS) {
+ goto error;
+ }
+
+ return PSA_SUCCESS;
+
+error:
+ mbedtls_free(local_input->buffer);
+ local_input->buffer = NULL;
+ local_input->length = 0;
+ return status;
+}
+
+void psa_crypto_local_input_free(psa_crypto_local_input_t *local_input)
+{
+ mbedtls_free(local_input->buffer);
+ local_input->buffer = NULL;
+ local_input->length = 0;
+}
+
+psa_status_t psa_crypto_local_output_alloc(uint8_t *output, size_t output_len,
+ psa_crypto_local_output_t *local_output)
+{
+ *local_output = PSA_CRYPTO_LOCAL_OUTPUT_INIT;
+
+ if (output_len == 0) {
+ return PSA_SUCCESS;
+ }
+ local_output->buffer = mbedtls_calloc(output_len, 1);
+ if (local_output->buffer == NULL) {
+ /* Since we dealt with the zero-length case above, we know that
+ * a NULL return value means a failure of allocation. */
+ return PSA_ERROR_INSUFFICIENT_MEMORY;
+ }
+ local_output->length = output_len;
+ local_output->original = output;
+
+ return PSA_SUCCESS;
+}
+
+psa_status_t psa_crypto_local_output_free(psa_crypto_local_output_t *local_output)
+{
+ psa_status_t status;
+
+ if (local_output->buffer == NULL) {
+ local_output->length = 0;
+ return PSA_SUCCESS;
+ }
+ if (local_output->original == NULL) {
+ /* We have an internal copy but nothing to copy back to. */
+ return PSA_ERROR_CORRUPTION_DETECTED;
+ }
+
+ status = psa_crypto_copy_output(local_output->buffer, local_output->length,
+ local_output->original, local_output->length);
+ if (status != PSA_SUCCESS) {
+ return status;
+ }
+
+ mbedtls_free(local_output->buffer);
+ local_output->buffer = NULL;
+ local_output->length = 0;
+
+ return PSA_SUCCESS;
+}
+
#endif /* MBEDTLS_PSA_CRYPTO_C */
diff --git a/library/psa_crypto_aead.c b/library/psa_crypto_aead.c
index 49aa961..a201985 100644
--- a/library/psa_crypto_aead.c
+++ b/library/psa_crypto_aead.c
@@ -33,10 +33,10 @@ static psa_status_t psa_aead_setup(
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_cipher_id_t cipher_id;
mbedtls_cipher_mode_t mode;
- size_t key_bits = attributes->core.bits;
+ size_t key_bits = attributes->bits;
(void) key_buffer_size;
- status = mbedtls_cipher_values_from_psa(alg, attributes->core.type,
+ status = mbedtls_cipher_values_from_psa(alg, attributes->type,
&key_bits, &mode, &cipher_id);
if (status != PSA_SUCCESS) {
return status;
@@ -49,7 +49,7 @@ static psa_status_t psa_aead_setup(
/* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
* The call to mbedtls_ccm_encrypt_and_tag or
* mbedtls_ccm_auth_decrypt will validate the tag length. */
- if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->core.type) != 16) {
+ if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->type) != 16) {
return PSA_ERROR_INVALID_ARGUMENT;
}
@@ -69,7 +69,7 @@ static psa_status_t psa_aead_setup(
/* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
* The call to mbedtls_gcm_crypt_and_tag or
* mbedtls_gcm_auth_decrypt will validate the tag length. */
- if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->core.type) != 16) {
+ if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(attributes->type) != 16) {
return PSA_ERROR_INVALID_ARGUMENT;
}
diff --git a/library/psa_crypto_cipher.c b/library/psa_crypto_cipher.c
index 3132854..881d673 100644
--- a/library/psa_crypto_cipher.c
+++ b/library/psa_crypto_cipher.c
@@ -289,14 +289,14 @@ static psa_status_t psa_cipher_setup(
int ret = 0;
size_t key_bits;
const mbedtls_cipher_info_t *cipher_info = NULL;
- psa_key_type_t key_type = attributes->core.type;
+ psa_key_type_t key_type = attributes->type;
(void) key_buffer_size;
mbedtls_cipher_init(&operation->ctx.cipher);
operation->alg = alg;
- key_bits = attributes->core.bits;
+ key_bits = attributes->bits;
cipher_info = mbedtls_cipher_info_from_psa(alg, key_type,
key_bits, NULL);
if (cipher_info == NULL) {
@@ -532,7 +532,11 @@ psa_status_t mbedtls_psa_cipher_update(
output_length);
} else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING */
- {
+ if (input_length == 0) {
+ /* There is no input, nothing to be done */
+ *output_length = 0;
+ status = PSA_SUCCESS;
+ } else {
status = mbedtls_to_psa_error(
mbedtls_cipher_update(&operation->ctx.cipher, input,
input_length, output, output_length));
diff --git a/library/psa_crypto_core.h b/library/psa_crypto_core.h
index afa8659..9462d2e 100644
--- a/library/psa_crypto_core.h
+++ b/library/psa_crypto_core.h
@@ -59,7 +59,7 @@ typedef enum {
* and metadata for one key.
*/
typedef struct {
- psa_core_key_attributes_t attr;
+ psa_key_attributes_t attr;
/*
* The current state of the key slot, as described in
@@ -159,11 +159,6 @@ typedef struct {
} while (0);
#endif
-/* A mask of key attribute flags used only internally.
- * Currently there aren't any. */
-#define PSA_KA_MASK_INTERNAL_ONLY ( \
- 0)
-
/** Test whether a key slot has any registered readers.
* If multi-threading is enabled, the caller must hold the
* global key slot mutex.
@@ -177,56 +172,6 @@ static inline int psa_key_slot_has_readers(const psa_key_slot_t *slot)
return slot->registered_readers > 0;
}
-/** Retrieve flags from psa_key_slot_t::attr::core::flags.
- *
- * \param[in] slot The key slot to query.
- * \param mask The mask of bits to extract.
- *
- * \return The key attribute flags in the given slot,
- * bitwise-anded with \p mask.
- */
-static inline uint16_t psa_key_slot_get_flags(const psa_key_slot_t *slot,
- uint16_t mask)
-{
- return slot->attr.flags & mask;
-}
-
-/** Set flags in psa_key_slot_t::attr::core::flags.
- *
- * \param[in,out] slot The key slot to modify.
- * \param mask The mask of bits to modify.
- * \param value The new value of the selected bits.
- */
-static inline void psa_key_slot_set_flags(psa_key_slot_t *slot,
- uint16_t mask,
- uint16_t value)
-{
- slot->attr.flags = ((~mask & slot->attr.flags) |
- (mask & value));
-}
-
-/** Turn on flags in psa_key_slot_t::attr::core::flags.
- *
- * \param[in,out] slot The key slot to modify.
- * \param mask The mask of bits to set.
- */
-static inline void psa_key_slot_set_bits_in_flags(psa_key_slot_t *slot,
- uint16_t mask)
-{
- slot->attr.flags |= mask;
-}
-
-/** Turn off flags in psa_key_slot_t::attr::core::flags.
- *
- * \param[in,out] slot The key slot to modify.
- * \param mask The mask of bits to clear.
- */
-static inline void psa_key_slot_clear_bits(psa_key_slot_t *slot,
- uint16_t mask)
-{
- slot->attr.flags &= ~mask;
-}
-
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/** Get the SE slot number of a key from the key slot storing its description.
*
@@ -939,4 +884,74 @@ psa_status_t mbedtls_psa_verify_hash_complete(
psa_status_t mbedtls_psa_verify_hash_abort(
mbedtls_psa_verify_hash_interruptible_operation_t *operation);
+typedef struct psa_crypto_local_input_s {
+ uint8_t *buffer;
+ size_t length;
+} psa_crypto_local_input_t;
+
+#define PSA_CRYPTO_LOCAL_INPUT_INIT ((psa_crypto_local_input_t) { NULL, 0 })
+
+/** Allocate a local copy of an input buffer and copy the contents into it.
+ *
+ * \param[in] input Pointer to input buffer.
+ * \param[in] input_len Length of the input buffer.
+ * \param[out] local_input Pointer to a psa_crypto_local_input_t struct
+ * containing a local input copy.
+ * \return #PSA_SUCCESS, if the buffer was successfully
+ * copied.
+ * \return #PSA_ERROR_INSUFFICIENT_MEMORY, if a copy of
+ * the buffer cannot be allocated.
+ */
+psa_status_t psa_crypto_local_input_alloc(const uint8_t *input, size_t input_len,
+ psa_crypto_local_input_t *local_input);
+
+/** Free a local copy of an input buffer.
+ *
+ * \param[in] local_input Pointer to a psa_crypto_local_input_t struct
+ * populated by a previous call to
+ * psa_crypto_local_input_alloc().
+ */
+void psa_crypto_local_input_free(psa_crypto_local_input_t *local_input);
+
+typedef struct psa_crypto_local_output_s {
+ uint8_t *original;
+ uint8_t *buffer;
+ size_t length;
+} psa_crypto_local_output_t;
+
+#define PSA_CRYPTO_LOCAL_OUTPUT_INIT ((psa_crypto_local_output_t) { NULL, NULL, 0 })
+
+/** Allocate a local copy of an output buffer.
+ *
+ * \note This does not copy any data from the original
+ * output buffer but only allocates a buffer
+ * whose contents will be copied back to the
+ * original in a future call to
+ * psa_crypto_local_output_free().
+ *
+ * \param[in] output Pointer to output buffer.
+ * \param[in] output_len Length of the output buffer.
+ * \param[out] local_output Pointer to a psa_crypto_local_output_t struct to
+ * populate with the local output copy.
+ * \return #PSA_SUCCESS, if the buffer was successfully
+ * copied.
+ * \return #PSA_ERROR_INSUFFICIENT_MEMORY, if a copy of
+ * the buffer cannot be allocated.
+ */
+psa_status_t psa_crypto_local_output_alloc(uint8_t *output, size_t output_len,
+ psa_crypto_local_output_t *local_output);
+
+/** Copy from a local copy of an output buffer back to the original, then
+ * free the local copy.
+ *
+ * \param[in] local_output Pointer to a psa_crypto_local_output_t struct
+ * populated by a previous call to
+ * psa_crypto_local_output_alloc().
+ * \return #PSA_SUCCESS, if the local output was
+ * successfully copied back to the original.
+ * \return #PSA_ERROR_CORRUPTION_DETECTED, if the output
+ * could not be copied back to the original.
+ */
+psa_status_t psa_crypto_local_output_free(psa_crypto_local_output_t *local_output);
+
#endif /* PSA_CRYPTO_CORE_H */
diff --git a/library/psa_crypto_ecp.c b/library/psa_crypto_ecp.c
index 7edea81..95baff6 100644
--- a/library/psa_crypto_ecp.c
+++ b/library/psa_crypto_ecp.c
@@ -216,8 +216,8 @@ psa_status_t mbedtls_psa_ecp_import_key(
mbedtls_ecp_keypair *ecp = NULL;
/* Parse input */
- status = mbedtls_psa_ecp_load_representation(attributes->core.type,
- attributes->core.bits,
+ status = mbedtls_psa_ecp_load_representation(attributes->type,
+ attributes->bits,
data,
data_length,
&ecp);
@@ -225,7 +225,7 @@ psa_status_t mbedtls_psa_ecp_import_key(
goto exit;
}
- if (PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type) ==
+ if (PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->type) ==
PSA_ECC_FAMILY_MONTGOMERY) {
*bits = ecp->grp.nbits + 1;
} else {
@@ -235,7 +235,7 @@ psa_status_t mbedtls_psa_ecp_import_key(
/* Re-export the data to PSA export format. There is currently no support
* for other input formats then the export format, so this is a 1-1
* copy operation. */
- status = mbedtls_psa_ecp_export_key(attributes->core.type,
+ status = mbedtls_psa_ecp_export_key(attributes->type,
ecp,
key_buffer,
key_buffer_size,
@@ -281,20 +281,8 @@ psa_status_t mbedtls_psa_ecp_export_key(psa_key_type_t type,
return status;
} else {
- if (data_size < PSA_BITS_TO_BYTES(ecp->grp.nbits)) {
- return PSA_ERROR_BUFFER_TOO_SMALL;
- }
-
status = mbedtls_to_psa_error(
- mbedtls_ecp_write_key(ecp,
- data,
- PSA_BITS_TO_BYTES(ecp->grp.nbits)));
- if (status == PSA_SUCCESS) {
- *data_length = PSA_BITS_TO_BYTES(ecp->grp.nbits);
- } else {
- memset(data, 0, data_size);
- }
-
+ mbedtls_ecp_write_key_ext(ecp, data_length, data, data_size));
return status;
}
}
@@ -308,7 +296,7 @@ psa_status_t mbedtls_psa_ecp_export_public_key(
mbedtls_ecp_keypair *ecp = NULL;
status = mbedtls_psa_ecp_load_representation(
- attributes->core.type, attributes->core.bits,
+ attributes->type, attributes->bits,
key_buffer, key_buffer_size, &ecp);
if (status != PSA_SUCCESS) {
return status;
@@ -316,7 +304,7 @@ psa_status_t mbedtls_psa_ecp_export_public_key(
status = mbedtls_psa_ecp_export_key(
PSA_KEY_TYPE_ECC_PUBLIC_KEY(
- PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type)),
+ PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->type)),
ecp, data, data_size, data_length);
mbedtls_ecp_keypair_free(ecp);
@@ -337,9 +325,9 @@ psa_status_t mbedtls_psa_ecp_generate_key(
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(
- attributes->core.type);
+ attributes->type);
mbedtls_ecp_group_id grp_id =
- mbedtls_ecc_group_from_psa(curve, attributes->core.bits);
+ mbedtls_ecc_group_from_psa(curve, attributes->bits);
const mbedtls_ecp_curve_info *curve_info =
mbedtls_ecp_curve_info_from_grp_id(grp_id);
@@ -359,14 +347,11 @@ psa_status_t mbedtls_psa_ecp_generate_key(
}
status = mbedtls_to_psa_error(
- mbedtls_ecp_write_key(&ecp, key_buffer, key_buffer_size));
+ mbedtls_ecp_write_key_ext(&ecp, key_buffer_length,
+ key_buffer, key_buffer_size));
mbedtls_ecp_keypair_free(&ecp);
- if (status == PSA_SUCCESS) {
- *key_buffer_length = key_buffer_size;
- }
-
return status;
}
#endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE */
@@ -389,8 +374,8 @@ psa_status_t mbedtls_psa_ecdsa_sign_hash(
size_t curve_bytes;
mbedtls_mpi r, s;
- status = mbedtls_psa_ecp_load_representation(attributes->core.type,
- attributes->core.bits,
+ status = mbedtls_psa_ecp_load_representation(attributes->type,
+ attributes->bits,
key_buffer,
key_buffer_size,
&ecp);
@@ -476,8 +461,8 @@ psa_status_t mbedtls_psa_ecdsa_verify_hash(
(void) alg;
- status = mbedtls_psa_ecp_load_representation(attributes->core.type,
- attributes->core.bits,
+ status = mbedtls_psa_ecp_load_representation(attributes->type,
+ attributes->bits,
key_buffer,
key_buffer_size,
&ecp);
@@ -541,14 +526,14 @@ psa_status_t mbedtls_psa_key_agreement_ecdh(
size_t *shared_secret_length)
{
psa_status_t status;
- if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(attributes->core.type) ||
+ if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(attributes->type) ||
!PSA_ALG_IS_ECDH(alg)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
mbedtls_ecp_keypair *ecp = NULL;
status = mbedtls_psa_ecp_load_representation(
- attributes->core.type,
- attributes->core.bits,
+ attributes->type,
+ attributes->bits,
key_buffer,
key_buffer_size,
&ecp);
diff --git a/library/psa_crypto_ffdh.c b/library/psa_crypto_ffdh.c
index 0099d5f..ae38f6d 100644
--- a/library/psa_crypto_ffdh.c
+++ b/library/psa_crypto_ffdh.c
@@ -151,7 +151,7 @@ psa_status_t mbedtls_psa_ffdh_export_public_key(
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi GX, G, X, P;
- psa_key_type_t type = attributes->core.type;
+ psa_key_type_t type = attributes->type;
if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type)) {
if (key_buffer_size > data_size) {
@@ -167,7 +167,7 @@ psa_status_t mbedtls_psa_ffdh_export_public_key(
mbedtls_mpi_init(&GX); mbedtls_mpi_init(&G);
mbedtls_mpi_init(&X); mbedtls_mpi_init(&P);
- size_t key_len = PSA_BITS_TO_BYTES(attributes->core.bits);
+ size_t key_len = PSA_BITS_TO_BYTES(attributes->bits);
status = mbedtls_psa_ffdh_set_prime_generator(key_len, &P, &G);
@@ -283,7 +283,7 @@ psa_status_t mbedtls_psa_ffdh_key_agreement(
mbedtls_mpi_init(&K);
status = mbedtls_psa_ffdh_set_prime_generator(
- PSA_BITS_TO_BYTES(attributes->core.bits), &P, &G);
+ PSA_BITS_TO_BYTES(attributes->bits), &P, &G);
if (status != PSA_SUCCESS) {
goto cleanup;
diff --git a/library/psa_crypto_invasive.h b/library/psa_crypto_invasive.h
index 8b445a1..51c90c6 100644
--- a/library/psa_crypto_invasive.h
+++ b/library/psa_crypto_invasive.h
@@ -72,6 +72,21 @@ psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
psa_status_t psa_mac_key_can_do(
psa_algorithm_t algorithm,
psa_key_type_t key_type);
+
+psa_status_t psa_crypto_copy_input(const uint8_t *input, size_t input_len,
+ uint8_t *input_copy, size_t input_copy_len);
+
+psa_status_t psa_crypto_copy_output(const uint8_t *output_copy, size_t output_copy_len,
+ uint8_t *output, size_t output_len);
+
+/*
+ * Test hooks to use for memory unpoisoning/poisoning in copy functions.
+ */
+extern void (*psa_input_pre_copy_hook)(const uint8_t *input, size_t input_len);
+extern void (*psa_input_post_copy_hook)(const uint8_t *input, size_t input_len);
+extern void (*psa_output_pre_copy_hook)(const uint8_t *output, size_t output_len);
+extern void (*psa_output_post_copy_hook)(const uint8_t *output, size_t output_len);
+
#endif /* MBEDTLS_TEST_HOOKS && MBEDTLS_PSA_CRYPTO_C */
#endif /* PSA_CRYPTO_INVASIVE_H */
diff --git a/library/psa_crypto_random_impl.h b/library/psa_crypto_random_impl.h
index 64b8949..533fb2e 100644
--- a/library/psa_crypto_random_impl.h
+++ b/library/psa_crypto_random_impl.h
@@ -1,14 +1,6 @@
/** \file psa_crypto_random_impl.h
*
* \brief PSA crypto random generator implementation abstraction.
- *
- * The definitions here need to be consistent with the declarations
- * in include/psa_util_internal.h. This file contains some redundant
- * declarations to increase the chance that a compiler will detect
- * inconsistencies if one file is changed without updating the other,
- * but not all potential inconsistencies can be enforced, so make sure
- * to check the public declarations and contracts in
- * include/psa_util_internal.h if you modify this file.
*/
/*
* Copyright The Mbed TLS Contributors
@@ -22,22 +14,12 @@
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
-#include <string.h>
-#include <mbedtls/entropy.h> // only for error codes
-#include <psa/crypto.h>
-
typedef mbedtls_psa_external_random_context_t mbedtls_psa_random_context_t;
-/* Trivial wrapper around psa_generate_random(). */
-int mbedtls_psa_get_random(void *p_rng,
- unsigned char *output,
- size_t output_size);
-
-/* The PSA RNG API doesn't need any externally maintained state. */
-#define MBEDTLS_PSA_RANDOM_STATE NULL
-
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+#include "mbedtls/entropy.h"
+
/* Choose a DRBG based on configuration and availability */
#if defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
@@ -67,11 +49,37 @@ int mbedtls_psa_get_random(void *p_rng,
#error "No hash algorithm available for HMAC_DBRG."
#endif
-#else
+#else /* !MBEDTLS_PSA_HMAC_DRBG_MD_TYPE && !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C*/
+
#error "No DRBG module available for the psa_crypto module."
+
+#endif /* !MBEDTLS_PSA_HMAC_DRBG_MD_TYPE && !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C*/
+
+#if defined(MBEDTLS_CTR_DRBG_C)
+#include "mbedtls/ctr_drbg.h"
+#elif defined(MBEDTLS_HMAC_DRBG_C)
+#include "mbedtls/hmac_drbg.h"
+#endif /* !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C */
+
+/* The maximum number of bytes that mbedtls_psa_get_random() is expected to return. */
+#if defined(MBEDTLS_CTR_DRBG_C)
+#define MBEDTLS_PSA_RANDOM_MAX_REQUEST MBEDTLS_CTR_DRBG_MAX_REQUEST
+#elif defined(MBEDTLS_HMAC_DRBG_C)
+#define MBEDTLS_PSA_RANDOM_MAX_REQUEST MBEDTLS_HMAC_DRBG_MAX_REQUEST
#endif
-#include "mbedtls/entropy.h"
+#if defined(MBEDTLS_CTR_DRBG_C)
+typedef mbedtls_ctr_drbg_context mbedtls_psa_drbg_context_t;
+#elif defined(MBEDTLS_HMAC_DRBG_C)
+typedef mbedtls_hmac_drbg_context mbedtls_psa_drbg_context_t;
+#endif /* !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C */
+
+typedef struct {
+ void (* entropy_init)(mbedtls_entropy_context *ctx);
+ void (* entropy_free)(mbedtls_entropy_context *ctx);
+ mbedtls_entropy_context entropy;
+ mbedtls_psa_drbg_context_t drbg;
+} mbedtls_psa_random_context_t;
/** Initialize the PSA DRBG.
*
@@ -99,63 +107,6 @@ static inline void mbedtls_psa_drbg_free(mbedtls_psa_drbg_context_t *p_rng)
#endif
}
-/** The type of the PSA random generator context.
- *
- * The random generator context is composed of an entropy context and
- * a DRBG context.
- */
-typedef struct {
- void (* entropy_init)(mbedtls_entropy_context *ctx);
- void (* entropy_free)(mbedtls_entropy_context *ctx);
- mbedtls_entropy_context entropy;
- mbedtls_psa_drbg_context_t drbg;
-} mbedtls_psa_random_context_t;
-
-/* Defined in include/psa_util_internal.h so that it's visible to
- * application code. The declaration here is redundant, but included
- * as a safety net to make it more likely that a future change that
- * accidentally causes the implementation to diverge from the interface
- * will be noticed. */
-/* Do not include the declaration under MSVC because it doesn't accept it
- * ("error C2370: 'mbedtls_psa_get_random' : redefinition; different storage class").
- * Observed with Visual Studio 2013. A known bug apparently:
- * https://stackoverflow.com/questions/8146541/duplicate-external-static-declarations-not-allowed-in-visual-studio
- */
-#if !defined(_MSC_VER)
-static mbedtls_f_rng_t *const mbedtls_psa_get_random;
-#endif
-
-/** The maximum number of bytes that mbedtls_psa_get_random() is expected to
- * return.
- */
-#if defined(MBEDTLS_CTR_DRBG_C)
-#define MBEDTLS_PSA_RANDOM_MAX_REQUEST MBEDTLS_CTR_DRBG_MAX_REQUEST
-#elif defined(MBEDTLS_HMAC_DRBG_C)
-#define MBEDTLS_PSA_RANDOM_MAX_REQUEST MBEDTLS_HMAC_DRBG_MAX_REQUEST
-#endif
-
-/** A pointer to the PSA DRBG state.
- *
- * This variable is only intended to be used through the macro
- * #MBEDTLS_PSA_RANDOM_STATE.
- */
-/* psa_crypto.c sets this variable to a pointer to the DRBG state in the
- * global PSA crypto state. */
-/* The type `mbedtls_psa_drbg_context_t` is defined in
- * include/psa_util_internal.h so that `mbedtls_psa_random_state` can be
- * declared there and be visible to application code. */
-extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state;
-
-/** A pointer to the PSA DRBG state.
- *
- * This macro expands to an expression that is suitable as the \c p_rng
- * parameter to pass to mbedtls_psa_get_random().
- *
- * This macro exists in all configurations where the psa_crypto module is
- * enabled. Its expansion depends on the configuration.
- */
-#define MBEDTLS_PSA_RANDOM_STATE mbedtls_psa_random_state
-
/** Seed the PSA DRBG.
*
* \param entropy An entropy context to read the seed from.
@@ -167,23 +118,15 @@ extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state;
* \return \c 0 on success.
* \return An Mbed TLS error code (\c MBEDTLS_ERR_xxx) on failure.
*/
-static inline int mbedtls_psa_drbg_seed(
- mbedtls_entropy_context *entropy,
- const unsigned char *custom, size_t len)
+static inline int mbedtls_psa_drbg_seed(mbedtls_psa_drbg_context_t *drbg_ctx,
+ mbedtls_entropy_context *entropy,
+ const unsigned char *custom, size_t len)
{
#if defined(MBEDTLS_CTR_DRBG_C)
- return mbedtls_ctr_drbg_seed(MBEDTLS_PSA_RANDOM_STATE,
- mbedtls_entropy_func,
- entropy,
- custom, len);
+ return mbedtls_ctr_drbg_seed(drbg_ctx, mbedtls_entropy_func, entropy, custom, len);
#elif defined(MBEDTLS_HMAC_DRBG_C)
- const mbedtls_md_info_t *md_info =
- mbedtls_md_info_from_type(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE);
- return mbedtls_hmac_drbg_seed(MBEDTLS_PSA_RANDOM_STATE,
- md_info,
- mbedtls_entropy_func,
- entropy,
- custom, len);
+ const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE);
+ return mbedtls_hmac_drbg_seed(drbg_ctx, md_info, mbedtls_entropy_func, entropy, custom, len);
#endif
}
diff --git a/library/psa_crypto_rsa.c b/library/psa_crypto_rsa.c
index 84a8667..2f613b3 100644
--- a/library/psa_crypto_rsa.c
+++ b/library/psa_crypto_rsa.c
@@ -116,7 +116,7 @@ psa_status_t mbedtls_psa_rsa_import_key(
mbedtls_rsa_context *rsa = NULL;
/* Parse input */
- status = mbedtls_psa_rsa_load_representation(attributes->core.type,
+ status = mbedtls_psa_rsa_load_representation(attributes->type,
data,
data_length,
&rsa);
@@ -130,7 +130,7 @@ psa_status_t mbedtls_psa_rsa_import_key(
* representation in the key slot. Export representation in case of RSA is
* the smallest representation that's allowed as input, so a straight-up
* allocation of the same size as the input buffer will be large enough. */
- status = mbedtls_psa_rsa_export_key(attributes->core.type,
+ status = mbedtls_psa_rsa_export_key(attributes->type,
rsa,
key_buffer,
key_buffer_size,
@@ -196,7 +196,7 @@ psa_status_t mbedtls_psa_rsa_export_public_key(
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation(
- attributes->core.type, key_buffer, key_buffer_size, &rsa);
+ attributes->type, key_buffer, key_buffer_size, &rsa);
if (status != PSA_SUCCESS) {
return status;
}
@@ -261,13 +261,13 @@ psa_status_t mbedtls_psa_rsa_generate_key(
ret = mbedtls_rsa_gen_key(&rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
- (unsigned int) attributes->core.bits,
+ (unsigned int) attributes->bits,
exponent);
if (ret != 0) {
return mbedtls_to_psa_error(ret);
}
- status = mbedtls_psa_rsa_export_key(attributes->core.type,
+ status = mbedtls_psa_rsa_export_key(attributes->type,
&rsa, key_buffer, key_buffer_size,
key_buffer_length);
mbedtls_rsa_free(&rsa);
@@ -325,7 +325,7 @@ psa_status_t mbedtls_psa_rsa_sign_hash(
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_type_t md_alg;
- status = mbedtls_psa_rsa_load_representation(attributes->core.type,
+ status = mbedtls_psa_rsa_load_representation(attributes->type,
key_buffer,
key_buffer_size,
&rsa);
@@ -424,7 +424,7 @@ psa_status_t mbedtls_psa_rsa_verify_hash(
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md_type_t md_alg;
- status = mbedtls_psa_rsa_load_representation(attributes->core.type,
+ status = mbedtls_psa_rsa_load_representation(attributes->type,
key_buffer,
key_buffer_size,
&rsa);
@@ -536,11 +536,11 @@ psa_status_t mbedtls_psa_asymmetric_encrypt(const psa_key_attributes_t *attribut
(void) output_size;
(void) output_length;
- if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
+ if (PSA_KEY_TYPE_IS_RSA(attributes->type)) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
mbedtls_rsa_context *rsa = NULL;
- status = mbedtls_psa_rsa_load_representation(attributes->core.type,
+ status = mbedtls_psa_rsa_load_representation(attributes->type,
key_buffer,
key_buffer_size,
&rsa);
@@ -632,11 +632,11 @@ psa_status_t mbedtls_psa_asymmetric_decrypt(const psa_key_attributes_t *attribut
*output_length = 0;
- if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
+ if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
mbedtls_rsa_context *rsa = NULL;
- status = mbedtls_psa_rsa_load_representation(attributes->core.type,
+ status = mbedtls_psa_rsa_load_representation(attributes->type,
key_buffer,
key_buffer_size,
&rsa);
diff --git a/library/psa_crypto_slot_management.c b/library/psa_crypto_slot_management.c
index b2a3c7e..b184ed0 100644
--- a/library/psa_crypto_slot_management.c
+++ b/library/psa_crypto_slot_management.c
@@ -34,6 +34,23 @@ typedef struct {
static psa_global_data_t global_data;
+static uint8_t psa_get_key_slots_initialized(void)
+{
+ uint8_t initialized;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ initialized = global_data.key_slots_initialized;
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
+#endif /* defined(MBEDTLS_THREADING_C) */
+
+ return initialized;
+}
+
int psa_is_valid_key_id(mbedtls_svc_key_id_t key, int vendor_ok)
{
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
@@ -136,7 +153,9 @@ psa_status_t psa_initialize_key_slots(void)
{
/* Nothing to do: program startup and psa_wipe_all_key_slots() both
* guarantee that the key slots are initialized to all-zero, which
- * means that all the key slots are in a valid, empty state. */
+ * means that all the key slots are in a valid, empty state. The global
+ * data mutex is already held when calling this function, so no need to
+ * lock it here, to set the flag. */
global_data.key_slots_initialized = 1;
return PSA_SUCCESS;
}
@@ -151,6 +170,7 @@ void psa_wipe_all_key_slots(void)
slot->state = PSA_SLOT_PENDING_DELETION;
(void) psa_wipe_key_slot(slot);
}
+ /* The global data mutex is already held when calling this function. */
global_data.key_slots_initialized = 0;
}
@@ -161,7 +181,7 @@ psa_status_t psa_reserve_free_key_slot(psa_key_id_t *volatile_key_id,
size_t slot_idx;
psa_key_slot_t *selected_slot, *unused_persistent_key_slot;
- if (!global_data.key_slots_initialized) {
+ if (!psa_get_key_slots_initialized()) {
status = PSA_ERROR_BAD_STATE;
goto error;
}
@@ -329,7 +349,7 @@ static psa_status_t psa_load_builtin_key_into_slot(psa_key_slot_t *slot)
/* Copy actual key length and core attributes into the slot on success */
slot->key.bytes = key_buffer_length;
- slot->attr = attributes.core;
+ slot->attr = attributes;
exit:
if (status != PSA_SUCCESS) {
psa_remove_key_data_from_memory(slot);
@@ -344,7 +364,7 @@ psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
*p_slot = NULL;
- if (!global_data.key_slots_initialized) {
+ if (!psa_get_key_slots_initialized()) {
return PSA_ERROR_BAD_STATE;
}
diff --git a/library/psa_crypto_storage.c b/library/psa_crypto_storage.c
index 13a3c8a..7d1317b 100644
--- a/library/psa_crypto_storage.c
+++ b/library/psa_crypto_storage.c
@@ -235,7 +235,7 @@ typedef struct {
void psa_format_key_data_for_storage(const uint8_t *data,
const size_t data_length,
- const psa_core_key_attributes_t *attr,
+ const psa_key_attributes_t *attr,
uint8_t *storage_data)
{
psa_persistent_key_storage_format *storage_format =
@@ -267,7 +267,7 @@ psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
- psa_core_key_attributes_t *attr)
+ psa_key_attributes_t *attr)
{
psa_status_t status;
const psa_persistent_key_storage_format *storage_format =
@@ -314,7 +314,7 @@ psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
return PSA_SUCCESS;
}
-psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
+psa_status_t psa_save_persistent_key(const psa_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length)
{
@@ -352,7 +352,7 @@ void psa_free_persistent_key_data(uint8_t *key_data, size_t key_data_length)
mbedtls_zeroize_and_free(key_data, key_data_length);
}
-psa_status_t psa_load_persistent_key(psa_core_key_attributes_t *attr,
+psa_status_t psa_load_persistent_key(psa_key_attributes_t *attr,
uint8_t **data,
size_t *data_length)
{
diff --git a/library/psa_crypto_storage.h b/library/psa_crypto_storage.h
index b6b5e15..d7f5b18 100644
--- a/library/psa_crypto_storage.h
+++ b/library/psa_crypto_storage.h
@@ -93,7 +93,7 @@ int psa_is_key_present_in_storage(const mbedtls_svc_key_id_t key);
* \retval #PSA_ERROR_DATA_INVALID \emptydescription
* \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
*/
-psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
+psa_status_t psa_save_persistent_key(const psa_key_attributes_t *attr,
const uint8_t *data,
const size_t data_length);
@@ -123,7 +123,7 @@ psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
* \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
* \retval #PSA_ERROR_DOES_NOT_EXIST \emptydescription
*/
-psa_status_t psa_load_persistent_key(psa_core_key_attributes_t *attr,
+psa_status_t psa_load_persistent_key(psa_key_attributes_t *attr,
uint8_t **data,
size_t *data_length);
@@ -163,7 +163,7 @@ void psa_free_persistent_key_data(uint8_t *key_data, size_t key_data_length);
*/
void psa_format_key_data_for_storage(const uint8_t *data,
const size_t data_length,
- const psa_core_key_attributes_t *attr,
+ const psa_key_attributes_t *attr,
uint8_t *storage_data);
/**
@@ -186,7 +186,7 @@ psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
size_t storage_data_length,
uint8_t **key_data,
size_t *key_data_length,
- psa_core_key_attributes_t *attr);
+ psa_key_attributes_t *attr);
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/** This symbol is defined if transaction support is required. */
@@ -231,8 +231,9 @@ typedef uint16_t psa_crypto_transaction_type_t;
* This type is designed to be serialized by writing the memory representation
* and reading it back on the same device.
*
- * \note The transaction mechanism is designed for a single active transaction
- * at a time. The transaction object is #psa_crypto_transaction.
+ * \note The transaction mechanism is not thread-safe. There can only be one
+ * single active transaction at a time.
+ * The transaction object is #psa_crypto_transaction.
*
* \note If an API call starts a transaction, it must complete this transaction
* before returning to the application.
diff --git a/library/psa_util.c b/library/psa_util.c
index 125b173..4ccc5b0 100644
--- a/library/psa_util.c
+++ b/library/psa_util.c
@@ -18,7 +18,7 @@
#include "psa_util_internal.h"
-#if defined(MBEDTLS_PSA_CRYPTO_C)
+#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
#include <psa/crypto.h>
@@ -46,6 +46,7 @@
#if defined(MBEDTLS_BLOCK_CIPHER_SOME_PSA)
#include <mbedtls/cipher.h>
#endif
+#include <mbedtls/entropy.h>
/* PSA_SUCCESS is kept at the top of each error table since
* it's the most common status when everything functions properly. */
@@ -338,7 +339,31 @@ mbedtls_ecp_group_id mbedtls_ecc_group_from_psa(psa_ecc_family_t family,
}
#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
-#endif /* MBEDTLS_PSA_CRYPTO_C */
+/* Wrapper function allowing the classic API to use the PSA RNG.
+ *
+ * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
+ * `psa_generate_random(...)`. The state parameter is ignored since the
+ * PSA API doesn't support passing an explicit state.
+ */
+int mbedtls_psa_get_random(void *p_rng,
+ unsigned char *output,
+ size_t output_size)
+{
+ /* This function takes a pointer to the RNG state because that's what
+ * classic mbedtls functions using an RNG expect. The PSA RNG manages
+ * its own state internally and doesn't let the caller access that state.
+ * So we just ignore the state parameter, and in practice we'll pass
+ * NULL. */
+ (void) p_rng;
+ psa_status_t status = psa_generate_random(output, output_size);
+ if (status == PSA_SUCCESS) {
+ return 0;
+ } else {
+ return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
+ }
+}
+
+#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
#if defined(MBEDTLS_PSA_UTIL_HAVE_ECDSA)
diff --git a/library/psa_util_internal.h b/library/psa_util_internal.h
index 3e62d5f..70a08a0 100644
--- a/library/psa_util_internal.h
+++ b/library/psa_util_internal.h
@@ -16,7 +16,7 @@
#include "psa/crypto.h"
-#if defined(MBEDTLS_PSA_CRYPTO_C)
+#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
/*************************************************************************
* FFDH
@@ -96,5 +96,5 @@ int psa_pk_status_to_mbedtls(psa_status_t status);
sizeof(error_list)/sizeof(error_list[0]), \
fallback_f)
-#endif /* MBEDTLS_PSA_CRYPTO_C */
+#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
#endif /* MBEDTLS_PSA_UTIL_INTERNAL_H */
diff --git a/library/rsa.c b/library/rsa.c
index 5debc69..7eb4a25 100644
--- a/library/rsa.c
+++ b/library/rsa.c
@@ -2231,7 +2231,7 @@ static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
- if (ctx->hash_id == MBEDTLS_MD_NONE) {
+ if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
}
return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
diff --git a/library/sha3.c b/library/sha3.c
index 27d495f..5738559 100644
--- a/library/sha3.c
+++ b/library/sha3.c
@@ -14,6 +14,33 @@
#if defined(MBEDTLS_SHA3_C)
+/*
+ * These macros select manually unrolled implementations of parts of the main permutation function.
+ *
+ * Unrolling has a major impact on both performance and code size. gcc performance benefits a lot
+ * from manually unrolling at higher optimisation levels.
+ *
+ * Depending on your size/perf priorities, compiler and target, it may be beneficial to adjust
+ * these; the defaults here should give sensible trade-offs for gcc and clang on aarch64 and
+ * x86-64.
+ */
+#if !defined(MBEDTLS_SHA3_THETA_UNROLL)
+ #define MBEDTLS_SHA3_THETA_UNROLL 0 //no-check-names
+#endif
+#if !defined(MBEDTLS_SHA3_CHI_UNROLL)
+ #if defined(__OPTIMIZE_SIZE__)
+ #define MBEDTLS_SHA3_CHI_UNROLL 0 //no-check-names
+ #else
+ #define MBEDTLS_SHA3_CHI_UNROLL 1 //no-check-names
+ #endif
+#endif
+#if !defined(MBEDTLS_SHA3_PI_UNROLL)
+ #define MBEDTLS_SHA3_PI_UNROLL 1 //no-check-names
+#endif
+#if !defined(MBEDTLS_SHA3_RHO_UNROLL)
+ #define MBEDTLS_SHA3_RHO_UNROLL 1 //no-check-names
+#endif
+
#include "mbedtls/sha3.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
@@ -56,18 +83,15 @@ static const uint8_t iota_r_packed[24] = {
};
#undef H
-static const uint8_t rho[24] = {
- 1, 62, 28, 27, 36, 44, 6, 55, 20,
- 3, 10, 43, 25, 39, 41, 45, 15,
- 21, 8, 18, 2, 61, 56, 14
+static const uint32_t rho[6] = {
+ 0x3f022425, 0x1c143a09, 0x2c3d3615, 0x27191713, 0x312b382e, 0x3e030832
};
-static const uint8_t pi[24] = {
- 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4,
- 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1,
+static const uint32_t pi[6] = {
+ 0x110b070a, 0x10050312, 0x04181508, 0x0d13170f, 0x0e14020c, 0x01060916
};
-#define ROT64(x, y) (((x) << (y)) | ((x) >> (64U - (y))))
+#define ROTR64(x, y) (((x) << (64U - (y))) | ((x) >> (y))) // 64-bit rotate right
#define ABSORB(ctx, idx, v) do { ctx->state[(idx) >> 3] ^= ((uint64_t) (v)) << (((idx) & 0x7) << 3); \
} while (0)
#define SQUEEZE(ctx, idx) ((uint8_t) (ctx->state[(idx) >> 3] >> (((idx) & 0x7) << 3)))
@@ -84,39 +108,97 @@ static void keccak_f1600(mbedtls_sha3_context *ctx)
uint64_t t;
/* Theta */
+#if MBEDTLS_SHA3_THETA_UNROLL == 0 //no-check-names
+ for (i = 0; i < 5; i++) {
+ lane[i] = s[i] ^ s[i + 5] ^ s[i + 10] ^ s[i + 15] ^ s[i + 20];
+ }
+ for (i = 0; i < 5; i++) {
+ t = lane[(i + 4) % 5] ^ ROTR64(lane[(i + 1) % 5], 63);
+ s[i] ^= t; s[i + 5] ^= t; s[i + 10] ^= t; s[i + 15] ^= t; s[i + 20] ^= t;
+ }
+#else
lane[0] = s[0] ^ s[5] ^ s[10] ^ s[15] ^ s[20];
lane[1] = s[1] ^ s[6] ^ s[11] ^ s[16] ^ s[21];
lane[2] = s[2] ^ s[7] ^ s[12] ^ s[17] ^ s[22];
lane[3] = s[3] ^ s[8] ^ s[13] ^ s[18] ^ s[23];
lane[4] = s[4] ^ s[9] ^ s[14] ^ s[19] ^ s[24];
- t = lane[4] ^ ROT64(lane[1], 1);
+ t = lane[4] ^ ROTR64(lane[1], 63);
s[0] ^= t; s[5] ^= t; s[10] ^= t; s[15] ^= t; s[20] ^= t;
- t = lane[0] ^ ROT64(lane[2], 1);
+ t = lane[0] ^ ROTR64(lane[2], 63);
s[1] ^= t; s[6] ^= t; s[11] ^= t; s[16] ^= t; s[21] ^= t;
- t = lane[1] ^ ROT64(lane[3], 1);
+ t = lane[1] ^ ROTR64(lane[3], 63);
s[2] ^= t; s[7] ^= t; s[12] ^= t; s[17] ^= t; s[22] ^= t;
- t = lane[2] ^ ROT64(lane[4], 1);
+ t = lane[2] ^ ROTR64(lane[4], 63);
s[3] ^= t; s[8] ^= t; s[13] ^= t; s[18] ^= t; s[23] ^= t;
- t = lane[3] ^ ROT64(lane[0], 1);
+ t = lane[3] ^ ROTR64(lane[0], 63);
s[4] ^= t; s[9] ^= t; s[14] ^= t; s[19] ^= t; s[24] ^= t;
+#endif
/* Rho */
- for (i = 1; i < 25; i++) {
- s[i] = ROT64(s[i], rho[i-1]);
+ for (i = 1; i < 25; i += 4) {
+ uint32_t r = rho[(i - 1) >> 2];
+#if MBEDTLS_SHA3_RHO_UNROLL == 0
+ for (int j = i; j < i + 4; j++) {
+ uint8_t r8 = (uint8_t) (r >> 24);
+ r <<= 8;
+ s[j] = ROTR64(s[j], r8);
+ }
+#else
+ s[i + 0] = ROTR64(s[i + 0], MBEDTLS_BYTE_3(r));
+ s[i + 1] = ROTR64(s[i + 1], MBEDTLS_BYTE_2(r));
+ s[i + 2] = ROTR64(s[i + 2], MBEDTLS_BYTE_1(r));
+ s[i + 3] = ROTR64(s[i + 3], MBEDTLS_BYTE_0(r));
+#endif
}
/* Pi */
t = s[1];
- for (i = 0; i < 24; i++) {
- SWAP(s[pi[i]], t);
+#if MBEDTLS_SHA3_PI_UNROLL == 0
+ for (i = 0; i < 24; i += 4) {
+ uint32_t p = pi[i >> 2];
+ for (unsigned j = 0; j < 4; j++) {
+ SWAP(s[p & 0xff], t);
+ p >>= 8;
+ }
}
+#else
+ uint32_t p = pi[0];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+ p = pi[1];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+ p = pi[2];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+ p = pi[3];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+ p = pi[4];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+ p = pi[5];
+ SWAP(s[MBEDTLS_BYTE_0(p)], t); SWAP(s[MBEDTLS_BYTE_1(p)], t);
+ SWAP(s[MBEDTLS_BYTE_2(p)], t); SWAP(s[MBEDTLS_BYTE_3(p)], t);
+#endif
/* Chi */
+#if MBEDTLS_SHA3_CHI_UNROLL == 0 //no-check-names
+ for (i = 0; i <= 20; i += 5) {
+ lane[0] = s[i]; lane[1] = s[i + 1]; lane[2] = s[i + 2];
+ lane[3] = s[i + 3]; lane[4] = s[i + 4];
+ s[i + 0] ^= (~lane[1]) & lane[2];
+ s[i + 1] ^= (~lane[2]) & lane[3];
+ s[i + 2] ^= (~lane[3]) & lane[4];
+ s[i + 3] ^= (~lane[4]) & lane[0];
+ s[i + 4] ^= (~lane[0]) & lane[1];
+ }
+#else
lane[0] = s[0]; lane[1] = s[1]; lane[2] = s[2]; lane[3] = s[3]; lane[4] = s[4];
s[0] ^= (~lane[1]) & lane[2];
s[1] ^= (~lane[2]) & lane[3];
@@ -151,6 +233,7 @@ static void keccak_f1600(mbedtls_sha3_context *ctx)
s[22] ^= (~lane[3]) & lane[4];
s[23] ^= (~lane[4]) & lane[0];
s[24] ^= (~lane[0]) & lane[1];
+#endif
/* Iota */
/* Decompress the round masks (see definition of rc) */
diff --git a/library/ssl_client.c b/library/ssl_client.c
index 6d988a8..345e608 100644
--- a/library/ssl_client.c
+++ b/library/ssl_client.c
@@ -765,11 +765,6 @@ static int ssl_prepare_client_hello(mbedtls_ssl_context *ssl)
MBEDTLS_SSL_SESSION_TICKETS &&
MBEDTLS_HAVE_TIME */
- if (ssl->conf->f_rng == NULL) {
- MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
- return MBEDTLS_ERR_SSL_NO_RNG;
- }
-
/* Bet on the highest configured version if we are not in a TLS 1.2
* renegotiation or session resumption.
*/
@@ -797,10 +792,15 @@ static int ssl_prepare_client_hello(mbedtls_ssl_context *ssl)
(ssl->handshake->cookie == NULL))
#endif
{
- ret = ssl_generate_random(ssl);
- if (ret != 0) {
- MBEDTLS_SSL_DEBUG_RET(1, "Random bytes generation failed", ret);
- return ret;
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ if (!ssl->handshake->hello_retry_request_flag)
+#endif
+ {
+ ret = ssl_generate_random(ssl);
+ if (ret != 0) {
+ MBEDTLS_SSL_DEBUG_RET(1, "Random bytes generation failed", ret);
+ return ret;
+ }
}
}
diff --git a/library/ssl_debug_helpers.h b/library/ssl_debug_helpers.h
index 2b0e737..4889e77 100644
--- a/library/ssl_debug_helpers.h
+++ b/library/ssl_debug_helpers.h
@@ -21,6 +21,11 @@
const char *mbedtls_ssl_states_str(mbedtls_ssl_states in);
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
+const char *mbedtls_ssl_early_data_status_str(mbedtls_ssl_early_data_status in);
+const char *mbedtls_ssl_early_data_state_str(mbedtls_ssl_early_data_state in);
+#endif
+
const char *mbedtls_ssl_protocol_version_str(mbedtls_ssl_protocol_version in);
const char *mbedtls_tls_prf_types_str(mbedtls_tls_prf_types in);
diff --git a/library/ssl_misc.h b/library/ssl_misc.h
index 942d4ad..a8807f6 100644
--- a/library/ssl_misc.h
+++ b/library/ssl_misc.h
@@ -665,21 +665,21 @@ struct mbedtls_ssl_handshake_params {
#if defined(MBEDTLS_SSL_CLI_C)
/** Minimum TLS version to be negotiated.
*
- * It is set up in the ClientHello writing preparation stage and used
- * throughout the ClientHello writing. Not relevant anymore as soon as
- * the protocol version has been negotiated thus as soon as the
- * ServerHello is received.
- * For a fresh handshake not linked to any previous handshake, it is
- * equal to the configured minimum minor version to be negotiated. When
- * renegotiating or resuming a session, it is equal to the previously
- * negotiated minor version.
+ * It is set up in the ClientHello writing preparation stage and used
+ * throughout the ClientHello writing. Not relevant anymore as soon as
+ * the protocol version has been negotiated thus as soon as the
+ * ServerHello is received.
+ * For a fresh handshake not linked to any previous handshake, it is
+ * equal to the configured minimum minor version to be negotiated. When
+ * renegotiating or resuming a session, it is equal to the previously
+ * negotiated minor version.
*
- * There is no maximum TLS version field in this handshake context.
- * From the start of the handshake, we need to define a current protocol
- * version for the record layer which we define as the maximum TLS
- * version to be negotiated. The `tls_version` field of the SSL context is
- * used to store this maximum value until it contains the actual
- * negotiated value.
+ * There is no maximum TLS version field in this handshake context.
+ * From the start of the handshake, we need to define a current protocol
+ * version for the record layer which we define as the maximum TLS
+ * version to be negotiated. The `tls_version` field of the SSL context is
+ * used to store this maximum value until it contains the actual
+ * negotiated value.
*/
mbedtls_ssl_protocol_version min_tls_version;
#endif
@@ -730,16 +730,21 @@ struct mbedtls_ssl_handshake_params {
#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
uint8_t key_exchange_mode; /*!< Selected key exchange mode */
- /** Number of HelloRetryRequest messages received/sent from/to the server. */
- uint8_t hello_retry_request_count;
+ /**
+ * Flag indicating if, in the course of the current handshake, an
+ * HelloRetryRequest message has been sent by the server or received by
+ * the client (<> 0) or not (0).
+ */
+ uint8_t hello_retry_request_flag;
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
/**
- * Number of dummy change_cipher_spec (CCS) record sent. Used to send only
- * one CCS per handshake without having to complicate the handshake state
- * transitions.
+ * Flag indicating if, in the course of the current handshake, a dummy
+ * change_cipher_spec (CCS) record has already been sent. Used to send only
+ * one CCS per handshake while not complicating the handshake state
+ * transitions for that purpose.
*/
- uint8_t ccs_count;
+ uint8_t ccs_sent;
#endif
#if defined(MBEDTLS_SSL_SRV_C)
@@ -2146,20 +2151,30 @@ int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
const unsigned char *end,
size_t *out_len);
-#if defined(MBEDTLS_SSL_CLI_C)
+int mbedtls_ssl_tls13_check_early_data_len(mbedtls_ssl_context *ssl,
+ size_t early_data_len);
+
+typedef enum {
/*
- * The client has not sent the first ClientHello yet, it is unknown if the
- * client will send an early data indication extension or not.
+ * The client has not sent the first ClientHello yet, the negotiation of early
+ * data has not started yet.
*/
-#define MBEDTLS_SSL_EARLY_DATA_STATUS_UNKNOWN 0
+ MBEDTLS_SSL_EARLY_DATA_STATE_IDLE,
+
+/*
+ * In its ClientHello, the client has not included an early data indication
+ * extension.
+ */
+ MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT,
/*
* The client has sent an early data indication extension in its first
* ClientHello, it has not received the response (ServerHello or
* HelloRetryRequest) from the server yet. The transform to protect early data
- * is not set and early data cannot be sent yet.
+ * is not set either as for middlebox compatibility a dummy CCS may have to be
+ * sent in clear. Early data cannot be sent to the server yet.
*/
-#define MBEDTLS_SSL_EARLY_DATA_STATUS_SENT 4
+ MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT,
/*
* The client has sent an early data indication extension in its first
@@ -2167,16 +2182,28 @@ int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
* HelloRetryRequest) from the server yet. The transform to protect early data
* has been set and early data can be written now.
*/
-#define MBEDTLS_SSL_EARLY_DATA_STATUS_CAN_WRITE 5
+ MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE,
+
+/*
+ * The client has indicated the use of early data and the server has accepted
+ * it.
+ */
+ MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED,
+
+/*
+ * The client has indicated the use of early data but the server has rejected
+ * it.
+ */
+ MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED,
/*
* The client has sent an early data indication extension in its first
* ClientHello, the server has accepted them and the client has received the
* server Finished message. It cannot send early data to the server anymore.
*/
-#define MBEDTLS_SSL_EARLY_DATA_STATUS_SERVER_FINISHED_RECEIVED 6
-#endif /* MBEDTLS_SSL_CLI_C */
+ MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED,
+} mbedtls_ssl_early_data_state;
#endif /* MBEDTLS_SSL_EARLY_DATA */
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
@@ -2825,6 +2852,13 @@ int mbedtls_ssl_session_set_hostname(mbedtls_ssl_session *session,
const char *hostname);
#endif
+#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA) && \
+ defined(MBEDTLS_SSL_ALPN)
+MBEDTLS_CHECK_RETURN_CRITICAL
+int mbedtls_ssl_session_set_ticket_alpn(mbedtls_ssl_session *session,
+ const char *alpn);
+#endif
+
#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
#define MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME (604800)
diff --git a/library/ssl_msg.c b/library/ssl_msg.c
index c2e64c6..b07cd96 100644
--- a/library/ssl_msg.c
+++ b/library/ssl_msg.c
@@ -4005,7 +4005,11 @@ static int ssl_prepare_record_content(mbedtls_ssl_context *ssl,
MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD)) {
MBEDTLS_SSL_DEBUG_MSG(
3, ("EarlyData: deprotect and discard app data records."));
- /* TODO: Add max_early_data_size check here, see issue 6347 */
+
+ ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
+ if (ret != 0) {
+ return ret;
+ }
ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
}
#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_SRV_C */
@@ -4129,9 +4133,15 @@ static int ssl_prepare_record_content(mbedtls_ssl_context *ssl,
*/
if (ssl->discard_early_data_record == MBEDTLS_SSL_EARLY_DATA_DISCARD) {
if (rec->type == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
+
+ ret = mbedtls_ssl_tls13_check_early_data_len(ssl, rec->data_len);
+ if (ret != 0) {
+ return ret;
+ }
+
MBEDTLS_SSL_DEBUG_MSG(
3, ("EarlyData: Ignore application message before 2nd ClientHello"));
- /* TODO: Add max_early_data_size check here, see issue 6347 */
+
return MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
} else if (rec->type == MBEDTLS_SSL_MSG_HANDSHAKE) {
ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
@@ -6058,6 +6068,111 @@ int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t
return ret;
}
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
+int mbedtls_ssl_write_early_data(mbedtls_ssl_context *ssl,
+ const unsigned char *buf, size_t len)
+{
+ int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+ const struct mbedtls_ssl_config *conf;
+ uint32_t remaining;
+
+ MBEDTLS_SSL_DEBUG_MSG(2, ("=> write early_data"));
+
+ if (ssl == NULL || (conf = ssl->conf) == NULL) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ if (conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ if ((!mbedtls_ssl_conf_is_tls13_enabled(conf)) ||
+ (conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
+ (conf->early_data_enabled != MBEDTLS_SSL_EARLY_DATA_ENABLED)) {
+ return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
+ }
+
+ if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
+ return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
+ }
+
+ /*
+ * If we are at the beginning of the handshake, the early data state being
+ * equal to MBEDTLS_SSL_EARLY_DATA_STATE_IDLE or
+ * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT advance the handshake just
+ * enough to be able to send early data if possible. That way, we can
+ * guarantee that when starting the handshake with this function we will
+ * send at least one record of early data. Note that when the state is
+ * MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT and not yet
+ * MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE, we cannot send early data
+ * as the early data outbound transform has not been set as we may have to
+ * first send a dummy CCS in clear.
+ */
+ if ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
+ (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
+ while ((ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IDLE) ||
+ (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT)) {
+ ret = mbedtls_ssl_handshake_step(ssl);
+ if (ret != 0) {
+ MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake_step", ret);
+ return ret;
+ }
+
+ ret = mbedtls_ssl_flush_output(ssl);
+ if (ret != 0) {
+ MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flush_output", ret);
+ return ret;
+ }
+ }
+ remaining = ssl->session_negotiate->max_early_data_size;
+ } else {
+ /*
+ * If we are past the point where we can send early data or we have
+ * already reached the maximum early data size, return immediatly.
+ * Otherwise, progress the handshake as much as possible to not delay
+ * it too much. If we reach a point where we can still send early data,
+ * then we will send some.
+ */
+ if ((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
+ (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED)) {
+ return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
+ }
+
+ remaining = ssl->session_negotiate->max_early_data_size -
+ ssl->total_early_data_size;
+
+ if (remaining == 0) {
+ return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
+ }
+
+ ret = mbedtls_ssl_handshake(ssl);
+ if ((ret != 0) && (ret != MBEDTLS_ERR_SSL_WANT_READ)) {
+ MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
+ return ret;
+ }
+ }
+
+ if (((ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE) &&
+ (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED))
+ || (remaining == 0)) {
+ return MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA;
+ }
+
+ if (len > remaining) {
+ len = remaining;
+ }
+
+ ret = ssl_write_real(ssl, buf, len);
+ if (ret >= 0) {
+ ssl->total_early_data_size += ret;
+ }
+
+ MBEDTLS_SSL_DEBUG_MSG(2, ("<= write early_data, ret=%d", ret));
+
+ return ret;
+}
+#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_CLI_C */
+
/*
* Notify the peer that the connection is being closed
*/
diff --git a/library/ssl_ticket.c b/library/ssl_ticket.c
index 5da3887..6a31b0b 100644
--- a/library/ssl_ticket.c
+++ b/library/ssl_ticket.c
@@ -504,7 +504,7 @@ int mbedtls_ssl_ticket_parse(void *p_ticket,
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_ms_time_t ticket_creation_time, ticket_age;
mbedtls_ms_time_t ticket_lifetime =
- (mbedtls_ms_time_t) ctx->ticket_lifetime * 1000;
+ (mbedtls_ms_time_t) key->lifetime * 1000;
ret = mbedtls_ssl_session_get_ticket_creation_time(session,
&ticket_creation_time);
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 5b0a4b9..c5e0649 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -238,6 +238,11 @@ int mbedtls_ssl_session_copy(mbedtls_ssl_session *dst,
#endif
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
+#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN) && \
+ defined(MBEDTLS_SSL_EARLY_DATA)
+ dst->ticket_alpn = NULL;
+#endif
+
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
@@ -275,6 +280,16 @@ int mbedtls_ssl_session_copy(mbedtls_ssl_session *dst,
#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN) && \
+ defined(MBEDTLS_SSL_EARLY_DATA)
+ {
+ int ret = mbedtls_ssl_session_set_ticket_alpn(dst, src->ticket_alpn);
+ if (ret != 0) {
+ return ret;
+ }
+ }
+#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN && MBEDTLS_SSL_EARLY_DATA */
+
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
if (src->ticket != NULL) {
dst->ticket = mbedtls_calloc(1, src->ticket_len);
@@ -432,10 +447,6 @@ static int ssl_calc_verify_tls_sha384(const mbedtls_ssl_context *, unsigned char
static int ssl_calc_finished_tls_sha384(mbedtls_ssl_context *, unsigned char *, int);
#endif /* MBEDTLS_MD_CAN_SHA384*/
-static size_t ssl_tls12_session_save(const mbedtls_ssl_session *session,
- unsigned char *buf,
- size_t buf_len);
-
MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls12_session_load(mbedtls_ssl_session *session,
const unsigned char *buf,
@@ -1100,11 +1111,12 @@ static int ssl_handshake_init(mbedtls_ssl_context *ssl)
#if defined(MBEDTLS_SSL_EARLY_DATA)
#if defined(MBEDTLS_SSL_CLI_C)
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_UNKNOWN;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_IDLE;
#endif
#if defined(MBEDTLS_SSL_SRV_C)
ssl->discard_early_data_record = MBEDTLS_SSL_EARLY_DATA_NO_DISCARD;
#endif
+ ssl->total_early_data_size = 0;
#endif /* MBEDTLS_SSL_EARLY_DATA */
/* Initialize structures */
@@ -1365,6 +1377,11 @@ static int ssl_conf_check(const mbedtls_ssl_context *ssl)
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+ if (ssl->conf->f_rng == NULL) {
+ MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
+ return MBEDTLS_ERR_SSL_NO_RNG;
+ }
+
/* Space for further checks */
return 0;
@@ -1549,6 +1566,7 @@ int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial)
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
+ ssl->tls_version = ssl->conf->max_tls_version;
mbedtls_ssl_session_reset_msg_layer(ssl, partial);
@@ -2448,282 +2466,6 @@ mbedtls_ssl_mode_t mbedtls_ssl_get_mode_from_ciphersuite(
#if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3)
-#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
-/* Serialization of TLS 1.3 sessions:
- *
- * struct {
- * opaque hostname<0..2^16-1>;
- * uint64 ticket_reception_time;
- * uint32 ticket_lifetime;
- * opaque ticket<1..2^16-1>;
- * } ClientOnlyData;
- *
- * struct {
- * uint32 ticket_age_add;
- * uint8 ticket_flags;
- * opaque resumption_key<0..255>;
- * uint32 max_early_data_size;
- * uint16 record_size_limit;
- * select ( endpoint ) {
- * case client: ClientOnlyData;
- * case server: uint64 ticket_creation_time;
- * };
- * } serialized_session_tls13;
- *
- */
-#if defined(MBEDTLS_SSL_SESSION_TICKETS)
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_session_save(const mbedtls_ssl_session *session,
- unsigned char *buf,
- size_t buf_len,
- size_t *olen)
-{
- unsigned char *p = buf;
-#if defined(MBEDTLS_SSL_CLI_C) && \
- defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
- size_t hostname_len = (session->hostname == NULL) ?
- 0 : strlen(session->hostname) + 1;
-#endif
- size_t needed = 4 /* ticket_age_add */
- + 1 /* ticket_flags */
- + 1; /* resumption_key length */
- *olen = 0;
-
- if (session->resumption_key_len > MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- needed += session->resumption_key_len; /* resumption_key */
-
-#if defined(MBEDTLS_SSL_EARLY_DATA)
- needed += 4; /* max_early_data_size */
-#endif
-#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
- needed += 2; /* record_size_limit */
-#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
-
-#if defined(MBEDTLS_HAVE_TIME)
- needed += 8; /* ticket_creation_time or ticket_reception_time */
-#endif
-
-#if defined(MBEDTLS_SSL_CLI_C)
- if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
-#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
- needed += 2 /* hostname_len */
- + hostname_len; /* hostname */
-#endif
-
- needed += 4 /* ticket_lifetime */
- + 2; /* ticket_len */
-
- /* Check size_t overflow */
- if (session->ticket_len > SIZE_MAX - needed) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- needed += session->ticket_len; /* ticket */
- }
-#endif /* MBEDTLS_SSL_CLI_C */
-
- *olen = needed;
- if (needed > buf_len) {
- return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
- }
-
- MBEDTLS_PUT_UINT32_BE(session->ticket_age_add, p, 0);
- p[4] = session->ticket_flags;
-
- /* save resumption_key */
- p[5] = session->resumption_key_len;
- p += 6;
- memcpy(p, session->resumption_key, session->resumption_key_len);
- p += session->resumption_key_len;
-
-#if defined(MBEDTLS_SSL_EARLY_DATA)
- MBEDTLS_PUT_UINT32_BE(session->max_early_data_size, p, 0);
- p += 4;
-#endif
-#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
- MBEDTLS_PUT_UINT16_BE(session->record_size_limit, p, 0);
- p += 2;
-#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
-
-#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
- if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
- MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_creation_time, p, 0);
- p += 8;
- }
-#endif /* MBEDTLS_HAVE_TIME */
-
-#if defined(MBEDTLS_SSL_CLI_C)
- if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
-#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
- MBEDTLS_PUT_UINT16_BE(hostname_len, p, 0);
- p += 2;
- if (hostname_len > 0) {
- /* save host name */
- memcpy(p, session->hostname, hostname_len);
- p += hostname_len;
- }
-#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
-
-#if defined(MBEDTLS_HAVE_TIME)
- MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_reception_time, p, 0);
- p += 8;
-#endif
- MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
- p += 4;
-
- MBEDTLS_PUT_UINT16_BE(session->ticket_len, p, 0);
- p += 2;
-
- if (session->ticket != NULL && session->ticket_len > 0) {
- memcpy(p, session->ticket, session->ticket_len);
- p += session->ticket_len;
- }
- }
-#endif /* MBEDTLS_SSL_CLI_C */
- return 0;
-}
-
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_session_load(mbedtls_ssl_session *session,
- const unsigned char *buf,
- size_t len)
-{
- const unsigned char *p = buf;
- const unsigned char *end = buf + len;
-
- if (end - p < 6) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_age_add = MBEDTLS_GET_UINT32_BE(p, 0);
- session->ticket_flags = p[4];
-
- /* load resumption_key */
- session->resumption_key_len = p[5];
- p += 6;
-
- if (end - p < session->resumption_key_len) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- if (sizeof(session->resumption_key) < session->resumption_key_len) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- memcpy(session->resumption_key, p, session->resumption_key_len);
- p += session->resumption_key_len;
-
-#if defined(MBEDTLS_SSL_EARLY_DATA)
- if (end - p < 4) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->max_early_data_size = MBEDTLS_GET_UINT32_BE(p, 0);
- p += 4;
-#endif
-#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
- if (end - p < 2) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->record_size_limit = MBEDTLS_GET_UINT16_BE(p, 0);
- p += 2;
-#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
-
-#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
- if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
- if (end - p < 8) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_creation_time = MBEDTLS_GET_UINT64_BE(p, 0);
- p += 8;
- }
-#endif /* MBEDTLS_HAVE_TIME */
-
-#if defined(MBEDTLS_SSL_CLI_C)
- if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
-#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
- size_t hostname_len;
- /* load host name */
- if (end - p < 2) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- hostname_len = MBEDTLS_GET_UINT16_BE(p, 0);
- p += 2;
-
- if (end - p < (long int) hostname_len) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- if (hostname_len > 0) {
- session->hostname = mbedtls_calloc(1, hostname_len);
- if (session->hostname == NULL) {
- return MBEDTLS_ERR_SSL_ALLOC_FAILED;
- }
- memcpy(session->hostname, p, hostname_len);
- p += hostname_len;
- }
-#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
-
-#if defined(MBEDTLS_HAVE_TIME)
- if (end - p < 8) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_reception_time = MBEDTLS_GET_UINT64_BE(p, 0);
- p += 8;
-#endif
- if (end - p < 4) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_lifetime = MBEDTLS_GET_UINT32_BE(p, 0);
- p += 4;
-
- if (end - p < 2) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_len = MBEDTLS_GET_UINT16_BE(p, 0);
- p += 2;
-
- if (end - p < (long int) session->ticket_len) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- if (session->ticket_len > 0) {
- session->ticket = mbedtls_calloc(1, session->ticket_len);
- if (session->ticket == NULL) {
- return MBEDTLS_ERR_SSL_ALLOC_FAILED;
- }
- memcpy(session->ticket, p, session->ticket_len);
- p += session->ticket_len;
- }
- }
-#endif /* MBEDTLS_SSL_CLI_C */
-
- return 0;
-
-}
-#else /* MBEDTLS_SSL_SESSION_TICKETS */
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_session_save(const mbedtls_ssl_session *session,
- unsigned char *buf,
- size_t buf_len,
- size_t *olen)
-{
- ((void) session);
- ((void) buf);
- ((void) buf_len);
- *olen = 0;
- return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
-}
-
-static int ssl_tls13_session_load(const mbedtls_ssl_session *session,
- unsigned char *buf,
- size_t buf_len)
-{
- ((void) session);
- ((void) buf);
- ((void) buf_len);
- return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
-}
-#endif /* !MBEDTLS_SSL_SESSION_TICKETS */
-#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
-
psa_status_t mbedtls_ssl_cipher_to_psa(mbedtls_cipher_type_t mbedtls_cipher_type,
size_t taglen,
psa_algorithm_t *alg,
@@ -3640,6 +3382,684 @@ int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
}
#endif /* MBEDTLS_SSL_CLI_C */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
+
+/* Serialization of TLS 1.2 sessions
+ *
+ * For more detail, see the description of ssl_session_save().
+ */
+static size_t ssl_tls12_session_save(const mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t buf_len)
+{
+ unsigned char *p = buf;
+ size_t used = 0;
+
+#if defined(MBEDTLS_HAVE_TIME)
+ uint64_t start;
+#endif
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ size_t cert_len;
+#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+ /*
+ * Time
+ */
+#if defined(MBEDTLS_HAVE_TIME)
+ used += 8;
+
+ if (used <= buf_len) {
+ start = (uint64_t) session->start;
+
+ MBEDTLS_PUT_UINT64_BE(start, p, 0);
+ p += 8;
+ }
+#endif /* MBEDTLS_HAVE_TIME */
+
+ /*
+ * Basic mandatory fields
+ */
+ used += 1 /* id_len */
+ + sizeof(session->id)
+ + sizeof(session->master)
+ + 4; /* verify_result */
+
+ if (used <= buf_len) {
+ *p++ = MBEDTLS_BYTE_0(session->id_len);
+ memcpy(p, session->id, 32);
+ p += 32;
+
+ memcpy(p, session->master, 48);
+ p += 48;
+
+ MBEDTLS_PUT_UINT32_BE(session->verify_result, p, 0);
+ p += 4;
+ }
+
+ /*
+ * Peer's end-entity certificate
+ */
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ if (session->peer_cert == NULL) {
+ cert_len = 0;
+ } else {
+ cert_len = session->peer_cert->raw.len;
+ }
+
+ used += 3 + cert_len;
+
+ if (used <= buf_len) {
+ *p++ = MBEDTLS_BYTE_2(cert_len);
+ *p++ = MBEDTLS_BYTE_1(cert_len);
+ *p++ = MBEDTLS_BYTE_0(cert_len);
+
+ if (session->peer_cert != NULL) {
+ memcpy(p, session->peer_cert->raw.p, cert_len);
+ p += cert_len;
+ }
+ }
+#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+ if (session->peer_cert_digest != NULL) {
+ used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
+ if (used <= buf_len) {
+ *p++ = (unsigned char) session->peer_cert_digest_type;
+ *p++ = (unsigned char) session->peer_cert_digest_len;
+ memcpy(p, session->peer_cert_digest,
+ session->peer_cert_digest_len);
+ p += session->peer_cert_digest_len;
+ }
+ } else {
+ used += 2;
+ if (used <= buf_len) {
+ *p++ = (unsigned char) MBEDTLS_MD_NONE;
+ *p++ = 0;
+ }
+ }
+#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+ /*
+ * Session ticket if any, plus associated data
+ */
+#if defined(MBEDTLS_SSL_SESSION_TICKETS)
+#if defined(MBEDTLS_SSL_CLI_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
+ used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
+
+ if (used <= buf_len) {
+ *p++ = MBEDTLS_BYTE_2(session->ticket_len);
+ *p++ = MBEDTLS_BYTE_1(session->ticket_len);
+ *p++ = MBEDTLS_BYTE_0(session->ticket_len);
+
+ if (session->ticket != NULL) {
+ memcpy(p, session->ticket, session->ticket_len);
+ p += session->ticket_len;
+ }
+
+ MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
+ p += 4;
+ }
+ }
+#endif /* MBEDTLS_SSL_CLI_C */
+#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
+ used += 8;
+
+ if (used <= buf_len) {
+ MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_creation_time, p, 0);
+ p += 8;
+ }
+ }
+#endif /* MBEDTLS_HAVE_TIME && MBEDTLS_SSL_SRV_C */
+#endif /* MBEDTLS_SSL_SESSION_TICKETS */
+
+ /*
+ * Misc extension-related info
+ */
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+ used += 1;
+
+ if (used <= buf_len) {
+ *p++ = session->mfl_code;
+ }
+#endif
+
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+ used += 1;
+
+ if (used <= buf_len) {
+ *p++ = MBEDTLS_BYTE_0(session->encrypt_then_mac);
+ }
+#endif
+
+ return used;
+}
+
+MBEDTLS_CHECK_RETURN_CRITICAL
+static int ssl_tls12_session_load(mbedtls_ssl_session *session,
+ const unsigned char *buf,
+ size_t len)
+{
+#if defined(MBEDTLS_HAVE_TIME)
+ uint64_t start;
+#endif
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ size_t cert_len;
+#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+ const unsigned char *p = buf;
+ const unsigned char * const end = buf + len;
+
+ /*
+ * Time
+ */
+#if defined(MBEDTLS_HAVE_TIME)
+ if (8 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ start = MBEDTLS_GET_UINT64_BE(p, 0);
+ p += 8;
+
+ session->start = (time_t) start;
+#endif /* MBEDTLS_HAVE_TIME */
+
+ /*
+ * Basic mandatory fields
+ */
+ if (1 + 32 + 48 + 4 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->id_len = *p++;
+ memcpy(session->id, p, 32);
+ p += 32;
+
+ memcpy(session->master, p, 48);
+ p += 48;
+
+ session->verify_result = MBEDTLS_GET_UINT32_BE(p, 0);
+ p += 4;
+
+ /* Immediately clear invalid pointer values that have been read, in case
+ * we exit early before we replaced them with valid ones. */
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ session->peer_cert = NULL;
+#else
+ session->peer_cert_digest = NULL;
+#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
+ session->ticket = NULL;
+#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
+
+ /*
+ * Peer certificate
+ */
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ /* Deserialize CRT from the end of the ticket. */
+ if (3 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ cert_len = MBEDTLS_GET_UINT24_BE(p, 0);
+ p += 3;
+
+ if (cert_len != 0) {
+ int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+
+ if (cert_len > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
+
+ if (session->peer_cert == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+
+ mbedtls_x509_crt_init(session->peer_cert);
+
+ if ((ret = mbedtls_x509_crt_parse_der(session->peer_cert,
+ p, cert_len)) != 0) {
+ mbedtls_x509_crt_free(session->peer_cert);
+ mbedtls_free(session->peer_cert);
+ session->peer_cert = NULL;
+ return ret;
+ }
+
+ p += cert_len;
+ }
+#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+ /* Deserialize CRT digest from the end of the ticket. */
+ if (2 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
+ session->peer_cert_digest_len = (size_t) *p++;
+
+ if (session->peer_cert_digest_len != 0) {
+ const mbedtls_md_info_t *md_info =
+ mbedtls_md_info_from_type(session->peer_cert_digest_type);
+ if (md_info == NULL) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ if (session->peer_cert_digest_len != mbedtls_md_get_size(md_info)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ if (session->peer_cert_digest_len > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->peer_cert_digest =
+ mbedtls_calloc(1, session->peer_cert_digest_len);
+ if (session->peer_cert_digest == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+
+ memcpy(session->peer_cert_digest, p,
+ session->peer_cert_digest_len);
+ p += session->peer_cert_digest_len;
+ }
+#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+ /*
+ * Session ticket and associated data
+ */
+#if defined(MBEDTLS_SSL_SESSION_TICKETS)
+#if defined(MBEDTLS_SSL_CLI_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
+ if (3 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->ticket_len = MBEDTLS_GET_UINT24_BE(p, 0);
+ p += 3;
+
+ if (session->ticket_len != 0) {
+ if (session->ticket_len > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->ticket = mbedtls_calloc(1, session->ticket_len);
+ if (session->ticket == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+
+ memcpy(session->ticket, p, session->ticket_len);
+ p += session->ticket_len;
+ }
+
+ if (4 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->ticket_lifetime = MBEDTLS_GET_UINT32_BE(p, 0);
+ p += 4;
+ }
+#endif /* MBEDTLS_SSL_CLI_C */
+#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
+ if (8 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_creation_time = MBEDTLS_GET_UINT64_BE(p, 0);
+ p += 8;
+ }
+#endif /* MBEDTLS_HAVE_TIME && MBEDTLS_SSL_SRV_C */
+#endif /* MBEDTLS_SSL_SESSION_TICKETS */
+
+ /*
+ * Misc extension-related info
+ */
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+ if (1 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->mfl_code = *p++;
+#endif
+
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+ if (1 > (size_t) (end - p)) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ session->encrypt_then_mac = *p++;
+#endif
+
+ /* Done, should have consumed entire buffer */
+ if (p != end) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ return 0;
+}
+
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+/* Serialization of TLS 1.3 sessions:
+ *
+ * For more detail, see the description of ssl_session_save().
+ */
+#if defined(MBEDTLS_SSL_SESSION_TICKETS)
+MBEDTLS_CHECK_RETURN_CRITICAL
+static int ssl_tls13_session_save(const mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t buf_len,
+ size_t *olen)
+{
+ unsigned char *p = buf;
+#if defined(MBEDTLS_SSL_CLI_C) && \
+ defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ size_t hostname_len = (session->hostname == NULL) ?
+ 0 : strlen(session->hostname) + 1;
+#endif
+
+#if defined(MBEDTLS_SSL_SRV_C) && \
+ defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ const size_t alpn_len = (session->ticket_alpn == NULL) ?
+ 0 : strlen(session->ticket_alpn) + 1;
+#endif
+ size_t needed = 4 /* ticket_age_add */
+ + 1 /* ticket_flags */
+ + 1; /* resumption_key length */
+
+ *olen = 0;
+
+ if (session->resumption_key_len > MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ needed += session->resumption_key_len; /* resumption_key */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+ needed += 4; /* max_early_data_size */
+#endif
+#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
+ needed += 2; /* record_size_limit */
+#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
+
+#if defined(MBEDTLS_HAVE_TIME)
+ needed += 8; /* ticket_creation_time or ticket_reception_time */
+#endif
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ needed += 2 /* alpn_len */
+ + alpn_len; /* alpn */
+#endif
+ }
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ needed += 2 /* hostname_len */
+ + hostname_len; /* hostname */
+#endif
+
+ needed += 4 /* ticket_lifetime */
+ + 2; /* ticket_len */
+
+ /* Check size_t overflow */
+ if (session->ticket_len > SIZE_MAX - needed) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ needed += session->ticket_len; /* ticket */
+ }
+#endif /* MBEDTLS_SSL_CLI_C */
+
+ *olen = needed;
+ if (needed > buf_len) {
+ return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
+ }
+
+ MBEDTLS_PUT_UINT32_BE(session->ticket_age_add, p, 0);
+ p[4] = session->ticket_flags;
+
+ /* save resumption_key */
+ p[5] = session->resumption_key_len;
+ p += 6;
+ memcpy(p, session->resumption_key, session->resumption_key_len);
+ p += session->resumption_key_len;
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+ MBEDTLS_PUT_UINT32_BE(session->max_early_data_size, p, 0);
+ p += 4;
+#endif
+#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
+ MBEDTLS_PUT_UINT16_BE(session->record_size_limit, p, 0);
+ p += 2;
+#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
+#if defined(MBEDTLS_HAVE_TIME)
+ MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_creation_time, p, 0);
+ p += 8;
+#endif /* MBEDTLS_HAVE_TIME */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ MBEDTLS_PUT_UINT16_BE(alpn_len, p, 0);
+ p += 2;
+
+ if (alpn_len > 0) {
+ /* save chosen alpn */
+ memcpy(p, session->ticket_alpn, alpn_len);
+ p += alpn_len;
+ }
+#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_ALPN */
+ }
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ MBEDTLS_PUT_UINT16_BE(hostname_len, p, 0);
+ p += 2;
+ if (hostname_len > 0) {
+ /* save host name */
+ memcpy(p, session->hostname, hostname_len);
+ p += hostname_len;
+ }
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
+
+#if defined(MBEDTLS_HAVE_TIME)
+ MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_reception_time, p, 0);
+ p += 8;
+#endif
+ MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
+ p += 4;
+
+ MBEDTLS_PUT_UINT16_BE(session->ticket_len, p, 0);
+ p += 2;
+
+ if (session->ticket != NULL && session->ticket_len > 0) {
+ memcpy(p, session->ticket, session->ticket_len);
+ p += session->ticket_len;
+ }
+ }
+#endif /* MBEDTLS_SSL_CLI_C */
+ return 0;
+}
+
+MBEDTLS_CHECK_RETURN_CRITICAL
+static int ssl_tls13_session_load(mbedtls_ssl_session *session,
+ const unsigned char *buf,
+ size_t len)
+{
+ const unsigned char *p = buf;
+ const unsigned char *end = buf + len;
+
+ if (end - p < 6) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_age_add = MBEDTLS_GET_UINT32_BE(p, 0);
+ session->ticket_flags = p[4];
+
+ /* load resumption_key */
+ session->resumption_key_len = p[5];
+ p += 6;
+
+ if (end - p < session->resumption_key_len) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ if (sizeof(session->resumption_key) < session->resumption_key_len) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ memcpy(session->resumption_key, p, session->resumption_key_len);
+ p += session->resumption_key_len;
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+ if (end - p < 4) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->max_early_data_size = MBEDTLS_GET_UINT32_BE(p, 0);
+ p += 4;
+#endif
+#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
+ if (end - p < 2) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->record_size_limit = MBEDTLS_GET_UINT16_BE(p, 0);
+ p += 2;
+#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
+#if defined(MBEDTLS_HAVE_TIME)
+ if (end - p < 8) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_creation_time = MBEDTLS_GET_UINT64_BE(p, 0);
+ p += 8;
+#endif /* MBEDTLS_HAVE_TIME */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ size_t alpn_len;
+
+ if (end - p < 2) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ alpn_len = MBEDTLS_GET_UINT16_BE(p, 0);
+ p += 2;
+
+ if (end - p < (long int) alpn_len) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ if (alpn_len > 0) {
+ int ret = mbedtls_ssl_session_set_ticket_alpn(session, (char *) p);
+ if (ret != 0) {
+ return ret;
+ }
+ p += alpn_len;
+ }
+#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_ALPN */
+ }
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+ if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ size_t hostname_len;
+ /* load host name */
+ if (end - p < 2) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ hostname_len = MBEDTLS_GET_UINT16_BE(p, 0);
+ p += 2;
+
+ if (end - p < (long int) hostname_len) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ if (hostname_len > 0) {
+ session->hostname = mbedtls_calloc(1, hostname_len);
+ if (session->hostname == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+ memcpy(session->hostname, p, hostname_len);
+ p += hostname_len;
+ }
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
+
+#if defined(MBEDTLS_HAVE_TIME)
+ if (end - p < 8) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_reception_time = MBEDTLS_GET_UINT64_BE(p, 0);
+ p += 8;
+#endif
+ if (end - p < 4) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_lifetime = MBEDTLS_GET_UINT32_BE(p, 0);
+ p += 4;
+
+ if (end - p < 2) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ session->ticket_len = MBEDTLS_GET_UINT16_BE(p, 0);
+ p += 2;
+
+ if (end - p < (long int) session->ticket_len) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ if (session->ticket_len > 0) {
+ session->ticket = mbedtls_calloc(1, session->ticket_len);
+ if (session->ticket == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+ memcpy(session->ticket, p, session->ticket_len);
+ p += session->ticket_len;
+ }
+ }
+#endif /* MBEDTLS_SSL_CLI_C */
+
+ return 0;
+
+}
+#else /* MBEDTLS_SSL_SESSION_TICKETS */
+MBEDTLS_CHECK_RETURN_CRITICAL
+static int ssl_tls13_session_save(const mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t buf_len,
+ size_t *olen)
+{
+ ((void) session);
+ ((void) buf);
+ ((void) buf_len);
+ *olen = 0;
+ return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
+}
+
+static int ssl_tls13_session_load(const mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t buf_len)
+{
+ ((void) session);
+ ((void) buf);
+ ((void) buf_len);
+ return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
+}
+#endif /* !MBEDTLS_SSL_SESSION_TICKETS */
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+
/*
* Define ticket header determining Mbed TLS version
* and structure of the ticket.
@@ -3662,6 +4082,12 @@ int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
#define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+#define SSL_SERIALIZED_SESSION_CONFIG_KEEP_PEER_CRT 1
+#else
+#define SSL_SERIALIZED_SESSION_CONFIG_KEEP_PEER_CRT 0
+#endif /* MBEDTLS_SSL_SESSION_TICKETS */
+
#if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
#define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
#else
@@ -3686,12 +4112,42 @@ int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
#define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+#define SSL_SERIALIZED_SESSION_CONFIG_SNI 1
+#else
+#define SSL_SERIALIZED_SESSION_CONFIG_SNI 0
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+#define SSL_SERIALIZED_SESSION_CONFIG_EARLY_DATA 1
+#else
+#define SSL_SERIALIZED_SESSION_CONFIG_EARLY_DATA 0
+#endif /* MBEDTLS_SSL_EARLY_DATA */
+
+#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
+#define SSL_SERIALIZED_SESSION_CONFIG_RECORD_SIZE 1
+#else
+#define SSL_SERIALIZED_SESSION_CONFIG_RECORD_SIZE 0
+#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
+
+#if defined(MBEDTLS_SSL_ALPN) && defined(MBEDTLS_SSL_SRV_C) && \
+ defined(MBEDTLS_SSL_EARLY_DATA)
+#define SSL_SERIALIZED_SESSION_CONFIG_ALPN 1
+#else
+#define SSL_SERIALIZED_SESSION_CONFIG_ALPN 0
+#endif /* MBEDTLS_SSL_ALPN */
+
#define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT 0
#define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT 1
#define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
#define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT 3
#define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT 4
#define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT 5
+#define SSL_SERIALIZED_SESSION_CONFIG_KEEP_PEER_CRT_BIT 6
+#define SSL_SERIALIZED_SESSION_CONFIG_SNI_BIT 7
+#define SSL_SERIALIZED_SESSION_CONFIG_EARLY_DATA_BIT 8
+#define SSL_SERIALIZED_SESSION_CONFIG_RECORD_SIZE_BIT 9
+#define SSL_SERIALIZED_SESSION_CONFIG_ALPN_BIT 10
#define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG \
((uint16_t) ( \
@@ -3701,7 +4157,16 @@ int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT) | \
(SSL_SERIALIZED_SESSION_CONFIG_MFL << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT) | \
(SSL_SERIALIZED_SESSION_CONFIG_ETM << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT) | \
- (SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT)))
+ (SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT) | \
+ (SSL_SERIALIZED_SESSION_CONFIG_KEEP_PEER_CRT << \
+ SSL_SERIALIZED_SESSION_CONFIG_KEEP_PEER_CRT_BIT) | \
+ (SSL_SERIALIZED_SESSION_CONFIG_SNI << SSL_SERIALIZED_SESSION_CONFIG_SNI_BIT) | \
+ (SSL_SERIALIZED_SESSION_CONFIG_EARLY_DATA << \
+ SSL_SERIALIZED_SESSION_CONFIG_EARLY_DATA_BIT) | \
+ (SSL_SERIALIZED_SESSION_CONFIG_RECORD_SIZE << \
+ SSL_SERIALIZED_SESSION_CONFIG_RECORD_SIZE_BIT) | \
+ (SSL_SERIALIZED_SESSION_CONFIG_ALPN << \
+ SSL_SERIALIZED_SESSION_CONFIG_ALPN_BIT)))
static const unsigned char ssl_serialized_session_header[] = {
MBEDTLS_VERSION_MAJOR,
@@ -3715,7 +4180,81 @@ static const unsigned char ssl_serialized_session_header[] = {
* Serialize a session in the following format:
* (in the presentation language of TLS, RFC 8446 section 3)
*
- * struct {
+ * TLS 1.2 session:
+ *
+ * struct {
+ * #if defined(MBEDTLS_SSL_SESSION_TICKETS)
+ * opaque ticket<0..2^24-1>; // length 0 means no ticket
+ * uint32 ticket_lifetime;
+ * #endif
+ * } ClientOnlyData;
+ *
+ * struct {
+ * #if defined(MBEDTLS_HAVE_TIME)
+ * uint64 start_time;
+ * #endif
+ * uint8 session_id_len; // at most 32
+ * opaque session_id[32];
+ * opaque master[48]; // fixed length in the standard
+ * uint32 verify_result;
+ * #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
+ * opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
+ * #else
+ * uint8 peer_cert_digest_type;
+ * opaque peer_cert_digest<0..2^8-1>
+ * #endif
+ * select (endpoint) {
+ * case client: ClientOnlyData;
+ * case server: uint64 ticket_creation_time;
+ * };
+ * #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+ * uint8 mfl_code; // up to 255 according to standard
+ * #endif
+ * #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+ * uint8 encrypt_then_mac; // 0 or 1
+ * #endif
+ * } serialized_session_tls12;
+ *
+ *
+ * TLS 1.3 Session:
+ *
+ * struct {
+ * #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ * opaque hostname<0..2^16-1>;
+ * #endif
+ * #if defined(MBEDTLS_HAVE_TIME)
+ * uint64 ticket_reception_time;
+ * #endif
+ * uint32 ticket_lifetime;
+ * opaque ticket<1..2^16-1>;
+ * } ClientOnlyData;
+ *
+ * struct {
+ * uint32 ticket_age_add;
+ * uint8 ticket_flags;
+ * opaque resumption_key<0..255>;
+ * #if defined(MBEDTLS_SSL_EARLY_DATA)
+ * uint32 max_early_data_size;
+ * #endif
+ * #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
+ * uint16 record_size_limit;
+ * #endif
+ * select ( endpoint ) {
+ * case client: ClientOnlyData;
+ * case server:
+ * #if defined(MBEDTLS_HAVE_TIME)
+ * uint64 ticket_creation_time;
+ * #endif
+ * #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ * opaque ticket_alpn<0..256>;
+ * #endif
+ * };
+ * } serialized_session_tls13;
+ *
+ *
+ * SSL session:
+ *
+ * struct {
*
* opaque mbedtls_version[3]; // library version: major, minor, patch
* opaque session_format[2]; // library-version specific 16-bit field
@@ -3733,6 +4272,8 @@ static const unsigned char ssl_serialized_session_header[] = {
* uint8_t minor_ver; // Protocol minor version. Possible values:
* // - TLS 1.2 (0x0303)
* // - TLS 1.3 (0x0304)
+ * uint8_t endpoint;
+ * uint16_t ciphersuite;
*
* select (serialized_session.tls_version) {
*
@@ -4395,6 +4936,11 @@ void mbedtls_ssl_session_free(mbedtls_ssl_session *session)
mbedtls_free(session->ticket);
#endif
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN) && \
+ defined(MBEDTLS_SSL_SRV_C)
+ mbedtls_free(session->ticket_alpn);
+#endif
+
mbedtls_platform_zeroize(session, sizeof(mbedtls_ssl_session));
}
@@ -4893,7 +5439,7 @@ static int ssl_context_load(mbedtls_ssl_context *ssl,
/* alpn_chosen should point to an item in the configured list */
for (cur = ssl->conf->alpn_list; *cur != NULL; cur++) {
if (strlen(*cur) == alpn_len &&
- memcmp(p, cur, alpn_len) == 0) {
+ memcmp(p, *cur, alpn_len) == 0) {
ssl->alpn_chosen = *cur;
break;
}
@@ -8948,385 +9494,6 @@ unsigned int mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
-/* Serialization of TLS 1.2 sessions:
- *
- * struct {
- * opaque ticket<0..2^24-1>; // length 0 means no ticket
- * uint32 ticket_lifetime;
- * } ClientOnlyData;
- *
- * struct {
- * uint64 start_time;
- * uint8 session_id_len; // at most 32
- * opaque session_id[32];
- * opaque master[48]; // fixed length in the standard
- * uint32 verify_result;
- * opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
- * select (endpoint) {
- * case client: ClientOnlyData;
- * case server: uint64 ticket_creation_time;
- * };
- * uint8 mfl_code; // up to 255 according to standard
- * uint8 encrypt_then_mac; // 0 or 1
- * } serialized_session_tls12;
- */
-static size_t ssl_tls12_session_save(const mbedtls_ssl_session *session,
- unsigned char *buf,
- size_t buf_len)
-{
- unsigned char *p = buf;
- size_t used = 0;
-
-#if defined(MBEDTLS_HAVE_TIME)
- uint64_t start;
-#endif
-#if defined(MBEDTLS_X509_CRT_PARSE_C)
-#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
- size_t cert_len;
-#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
-#endif /* MBEDTLS_X509_CRT_PARSE_C */
-
- /*
- * Time
- */
-#if defined(MBEDTLS_HAVE_TIME)
- used += 8;
-
- if (used <= buf_len) {
- start = (uint64_t) session->start;
-
- MBEDTLS_PUT_UINT64_BE(start, p, 0);
- p += 8;
- }
-#endif /* MBEDTLS_HAVE_TIME */
-
- /*
- * Basic mandatory fields
- */
- used += 1 /* id_len */
- + sizeof(session->id)
- + sizeof(session->master)
- + 4; /* verify_result */
-
- if (used <= buf_len) {
- *p++ = MBEDTLS_BYTE_0(session->id_len);
- memcpy(p, session->id, 32);
- p += 32;
-
- memcpy(p, session->master, 48);
- p += 48;
-
- MBEDTLS_PUT_UINT32_BE(session->verify_result, p, 0);
- p += 4;
- }
-
- /*
- * Peer's end-entity certificate
- */
-#if defined(MBEDTLS_X509_CRT_PARSE_C)
-#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
- if (session->peer_cert == NULL) {
- cert_len = 0;
- } else {
- cert_len = session->peer_cert->raw.len;
- }
-
- used += 3 + cert_len;
-
- if (used <= buf_len) {
- *p++ = MBEDTLS_BYTE_2(cert_len);
- *p++ = MBEDTLS_BYTE_1(cert_len);
- *p++ = MBEDTLS_BYTE_0(cert_len);
-
- if (session->peer_cert != NULL) {
- memcpy(p, session->peer_cert->raw.p, cert_len);
- p += cert_len;
- }
- }
-#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
- if (session->peer_cert_digest != NULL) {
- used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
- if (used <= buf_len) {
- *p++ = (unsigned char) session->peer_cert_digest_type;
- *p++ = (unsigned char) session->peer_cert_digest_len;
- memcpy(p, session->peer_cert_digest,
- session->peer_cert_digest_len);
- p += session->peer_cert_digest_len;
- }
- } else {
- used += 2;
- if (used <= buf_len) {
- *p++ = (unsigned char) MBEDTLS_MD_NONE;
- *p++ = 0;
- }
- }
-#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
-#endif /* MBEDTLS_X509_CRT_PARSE_C */
-
- /*
- * Session ticket if any, plus associated data
- */
-#if defined(MBEDTLS_SSL_SESSION_TICKETS)
-#if defined(MBEDTLS_SSL_CLI_C)
- if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
- used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
-
- if (used <= buf_len) {
- *p++ = MBEDTLS_BYTE_2(session->ticket_len);
- *p++ = MBEDTLS_BYTE_1(session->ticket_len);
- *p++ = MBEDTLS_BYTE_0(session->ticket_len);
-
- if (session->ticket != NULL) {
- memcpy(p, session->ticket, session->ticket_len);
- p += session->ticket_len;
- }
-
- MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
- p += 4;
- }
- }
-#endif /* MBEDTLS_SSL_CLI_C */
-#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
- if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
- used += 8;
-
- if (used <= buf_len) {
- MBEDTLS_PUT_UINT64_BE((uint64_t) session->ticket_creation_time, p, 0);
- p += 8;
- }
- }
-#endif /* MBEDTLS_HAVE_TIME && MBEDTLS_SSL_SRV_C */
-#endif /* MBEDTLS_SSL_SESSION_TICKETS */
-
- /*
- * Misc extension-related info
- */
-#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
- used += 1;
-
- if (used <= buf_len) {
- *p++ = session->mfl_code;
- }
-#endif
-
-#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
- used += 1;
-
- if (used <= buf_len) {
- *p++ = MBEDTLS_BYTE_0(session->encrypt_then_mac);
- }
-#endif
-
- return used;
-}
-
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls12_session_load(mbedtls_ssl_session *session,
- const unsigned char *buf,
- size_t len)
-{
-#if defined(MBEDTLS_HAVE_TIME)
- uint64_t start;
-#endif
-#if defined(MBEDTLS_X509_CRT_PARSE_C)
-#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
- size_t cert_len;
-#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
-#endif /* MBEDTLS_X509_CRT_PARSE_C */
-
- const unsigned char *p = buf;
- const unsigned char * const end = buf + len;
-
- /*
- * Time
- */
-#if defined(MBEDTLS_HAVE_TIME)
- if (8 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- start = MBEDTLS_GET_UINT64_BE(p, 0);
- p += 8;
-
- session->start = (time_t) start;
-#endif /* MBEDTLS_HAVE_TIME */
-
- /*
- * Basic mandatory fields
- */
- if (1 + 32 + 48 + 4 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->id_len = *p++;
- memcpy(session->id, p, 32);
- p += 32;
-
- memcpy(session->master, p, 48);
- p += 48;
-
- session->verify_result = MBEDTLS_GET_UINT32_BE(p, 0);
- p += 4;
-
- /* Immediately clear invalid pointer values that have been read, in case
- * we exit early before we replaced them with valid ones. */
-#if defined(MBEDTLS_X509_CRT_PARSE_C)
-#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
- session->peer_cert = NULL;
-#else
- session->peer_cert_digest = NULL;
-#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
-#endif /* MBEDTLS_X509_CRT_PARSE_C */
-#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
- session->ticket = NULL;
-#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
-
- /*
- * Peer certificate
- */
-#if defined(MBEDTLS_X509_CRT_PARSE_C)
-#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
- /* Deserialize CRT from the end of the ticket. */
- if (3 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- cert_len = MBEDTLS_GET_UINT24_BE(p, 0);
- p += 3;
-
- if (cert_len != 0) {
- int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
-
- if (cert_len > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
-
- if (session->peer_cert == NULL) {
- return MBEDTLS_ERR_SSL_ALLOC_FAILED;
- }
-
- mbedtls_x509_crt_init(session->peer_cert);
-
- if ((ret = mbedtls_x509_crt_parse_der(session->peer_cert,
- p, cert_len)) != 0) {
- mbedtls_x509_crt_free(session->peer_cert);
- mbedtls_free(session->peer_cert);
- session->peer_cert = NULL;
- return ret;
- }
-
- p += cert_len;
- }
-#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
- /* Deserialize CRT digest from the end of the ticket. */
- if (2 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
- session->peer_cert_digest_len = (size_t) *p++;
-
- if (session->peer_cert_digest_len != 0) {
- const mbedtls_md_info_t *md_info =
- mbedtls_md_info_from_type(session->peer_cert_digest_type);
- if (md_info == NULL) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- if (session->peer_cert_digest_len != mbedtls_md_get_size(md_info)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- if (session->peer_cert_digest_len > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->peer_cert_digest =
- mbedtls_calloc(1, session->peer_cert_digest_len);
- if (session->peer_cert_digest == NULL) {
- return MBEDTLS_ERR_SSL_ALLOC_FAILED;
- }
-
- memcpy(session->peer_cert_digest, p,
- session->peer_cert_digest_len);
- p += session->peer_cert_digest_len;
- }
-#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
-#endif /* MBEDTLS_X509_CRT_PARSE_C */
-
- /*
- * Session ticket and associated data
- */
-#if defined(MBEDTLS_SSL_SESSION_TICKETS)
-#if defined(MBEDTLS_SSL_CLI_C)
- if (session->endpoint == MBEDTLS_SSL_IS_CLIENT) {
- if (3 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->ticket_len = MBEDTLS_GET_UINT24_BE(p, 0);
- p += 3;
-
- if (session->ticket_len != 0) {
- if (session->ticket_len > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->ticket = mbedtls_calloc(1, session->ticket_len);
- if (session->ticket == NULL) {
- return MBEDTLS_ERR_SSL_ALLOC_FAILED;
- }
-
- memcpy(session->ticket, p, session->ticket_len);
- p += session->ticket_len;
- }
-
- if (4 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->ticket_lifetime = MBEDTLS_GET_UINT32_BE(p, 0);
- p += 4;
- }
-#endif /* MBEDTLS_SSL_CLI_C */
-#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_SRV_C)
- if (session->endpoint == MBEDTLS_SSL_IS_SERVER) {
- if (8 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
- session->ticket_creation_time = MBEDTLS_GET_UINT64_BE(p, 0);
- p += 8;
- }
-#endif /* MBEDTLS_HAVE_TIME && MBEDTLS_SSL_SRV_C */
-#endif /* MBEDTLS_SSL_SESSION_TICKETS */
-
- /*
- * Misc extension-related info
- */
-#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
- if (1 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->mfl_code = *p++;
-#endif
-
-#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
- if (1 > (size_t) (end - p)) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- session->encrypt_then_mac = *p++;
-#endif
-
- /* Done, should have consumed entire buffer */
- if (p != end) {
- return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
- }
-
- return 0;
-}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
int mbedtls_ssl_validate_ciphersuite(
@@ -9720,4 +9887,36 @@ int mbedtls_ssl_session_set_hostname(mbedtls_ssl_session *session,
MBEDTLS_SSL_SERVER_NAME_INDICATION &&
MBEDTLS_SSL_CLI_C */
+#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_EARLY_DATA) && \
+ defined(MBEDTLS_SSL_ALPN)
+int mbedtls_ssl_session_set_ticket_alpn(mbedtls_ssl_session *session,
+ const char *alpn)
+{
+ size_t alpn_len = 0;
+
+ if (alpn != NULL) {
+ alpn_len = strlen(alpn);
+
+ if (alpn_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+ }
+
+ if (session->ticket_alpn != NULL) {
+ mbedtls_zeroize_and_free(session->ticket_alpn,
+ strlen(session->ticket_alpn));
+ session->ticket_alpn = NULL;
+ }
+
+ if (alpn != NULL) {
+ session->ticket_alpn = mbedtls_calloc(alpn_len + 1, 1);
+ if (session->ticket_alpn == NULL) {
+ return MBEDTLS_ERR_SSL_ALLOC_FAILED;
+ }
+ memcpy(session->ticket_alpn, alpn, alpn_len);
+ }
+
+ return 0;
+}
+#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_ALPN */
#endif /* MBEDTLS_SSL_TLS_C */
diff --git a/library/ssl_tls12_server.c b/library/ssl_tls12_server.c
index 53a9ce2..b49a8ae 100644
--- a/library/ssl_tls12_server.c
+++ b/library/ssl_tls12_server.c
@@ -2178,11 +2178,6 @@ static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
}
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
- if (ssl->conf->f_rng == NULL) {
- MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
- return MBEDTLS_ERR_SSL_NO_RNG;
- }
-
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
@@ -2703,8 +2698,7 @@ static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
PSA_KEY_TYPE_ECC_KEY_PAIR(ssl->handshake->xxdh_psa_type));
psa_set_key_bits(&key_attributes, ssl->handshake->xxdh_psa_bits);
- key_len = PSA_BITS_TO_BYTES(key->grp.pbits);
- ret = mbedtls_ecp_write_key(key, buf, key_len);
+ ret = mbedtls_ecp_write_key_ext(key, &key_len, buf, sizeof(buf));
if (ret != 0) {
mbedtls_platform_zeroize(buf, sizeof(buf));
break;
diff --git a/library/ssl_tls13_client.c b/library/ssl_tls13_client.c
index 1e8df1b..7fcc394 100644
--- a/library/ssl_tls13_client.c
+++ b/library/ssl_tls13_client.c
@@ -1180,7 +1180,15 @@ int mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context *ssl,
#endif
#if defined(MBEDTLS_SSL_EARLY_DATA)
- if (ssl->handshake->hello_retry_request_count == 0) {
+ /* In the first ClientHello, write the early data indication extension if
+ * necessary and update the early data state.
+ * If an HRR has been received and thus we are currently writing the
+ * second ClientHello, the second ClientHello must not contain an early
+ * data extension and the early data state must stay as it is:
+ * MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT or
+ * MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED.
+ */
+ if (!ssl->handshake->hello_retry_request_flag) {
if (mbedtls_ssl_conf_tls13_is_some_psk_enabled(ssl) &&
ssl_tls13_early_data_has_valid_ticket(ssl) &&
ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_ENABLED) {
@@ -1191,9 +1199,9 @@ int mbedtls_ssl_tls13_write_client_hello_exts(mbedtls_ssl_context *ssl,
}
p += ext_len;
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_SENT;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT;
} else {
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT;
}
}
#endif /* MBEDTLS_SSL_EARLY_DATA */
@@ -1231,7 +1239,7 @@ int mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context *ssl)
size_t psk_len;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
- if (ssl->early_data_status == MBEDTLS_SSL_EARLY_DATA_STATUS_SENT) {
+ if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_IND_SENT) {
MBEDTLS_SSL_DEBUG_MSG(
1, ("Set hs psk for early data when writing the first psk"));
@@ -1294,7 +1302,7 @@ int mbedtls_ssl_tls13_finalize_client_hello(mbedtls_ssl_context *ssl)
1, ("Switch to early data keys for outbound traffic"));
mbedtls_ssl_set_outbound_transform(
ssl, ssl->handshake->transform_earlydata);
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_CAN_WRITE;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE;
#endif
}
#endif /* MBEDTLS_SSL_EARLY_DATA */
@@ -1495,7 +1503,7 @@ static int ssl_tls13_preprocess_server_hello(mbedtls_ssl_context *ssl,
* to a HelloRetryRequest), it MUST abort the handshake with an
* "unexpected_message" alert.
*/
- if (handshake->hello_retry_request_count > 0) {
+ if (handshake->hello_retry_request_flag) {
MBEDTLS_SSL_DEBUG_MSG(1, ("Multiple HRRs received"));
MBEDTLS_SSL_PEND_FATAL_ALERT(
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
@@ -1517,7 +1525,7 @@ static int ssl_tls13_preprocess_server_hello(mbedtls_ssl_context *ssl,
return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
}
- handshake->hello_retry_request_count++;
+ handshake->hello_retry_request_flag = 1;
break;
}
@@ -1672,7 +1680,7 @@ static int ssl_tls13_parse_server_hello(mbedtls_ssl_context *ssl,
* proposed in the HRR, we abort the handshake and send an
* "illegal_parameter" alert.
*/
- else if ((!is_hrr) && (handshake->hello_retry_request_count > 0) &&
+ else if ((!is_hrr) && handshake->hello_retry_request_flag &&
(cipher_suite != ssl->session_negotiate->ciphersuite)) {
fatal_alert = MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
@@ -1911,7 +1919,7 @@ static int ssl_tls13_postprocess_server_hello(mbedtls_ssl_context *ssl)
* cases we compute it here.
*/
#if defined(MBEDTLS_SSL_EARLY_DATA)
- if (ssl->early_data_status == MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT ||
+ if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT ||
handshake->key_exchange_mode ==
MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL)
#endif
@@ -1967,8 +1975,8 @@ static int ssl_tls13_postprocess_hrr(mbedtls_ssl_context *ssl)
ssl->session_negotiate->ciphersuite = ssl->handshake->ciphersuite_info->id;
#if defined(MBEDTLS_SSL_EARLY_DATA)
- if (ssl->early_data_status != MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT) {
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED;
+ if (ssl->early_data_state != MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT) {
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED;
}
#endif
@@ -2230,9 +2238,10 @@ static int ssl_tls13_process_encrypted_extensions(mbedtls_ssl_context *ssl)
return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
}
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED;
- } else if (ssl->early_data_status != MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT) {
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED;
+ } else if (ssl->early_data_state !=
+ MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT) {
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED;
}
#endif
@@ -2270,6 +2279,7 @@ cleanup:
}
+#if defined(MBEDTLS_SSL_EARLY_DATA)
/*
* Handler for MBEDTLS_SSL_END_OF_EARLY_DATA
*
@@ -2308,6 +2318,32 @@ cleanup:
return ret;
}
+int mbedtls_ssl_get_early_data_status(mbedtls_ssl_context *ssl)
+{
+ if ((ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) ||
+ (!mbedtls_ssl_is_handshake_over(ssl))) {
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
+ }
+
+ switch (ssl->early_data_state) {
+ case MBEDTLS_SSL_EARLY_DATA_STATE_NO_IND_SENT:
+ return MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_INDICATED;
+ break;
+
+ case MBEDTLS_SSL_EARLY_DATA_STATE_REJECTED:
+ return MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED;
+ break;
+
+ case MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED:
+ return MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED;
+ break;
+
+ default:
+ return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+ }
+}
+#endif /* MBEDTLS_SSL_EARLY_DATA */
+
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
/*
* STATE HANDLING: CertificateRequest
@@ -2569,8 +2605,8 @@ static int ssl_tls13_process_server_finished(mbedtls_ssl_context *ssl)
}
#if defined(MBEDTLS_SSL_EARLY_DATA)
- if (ssl->early_data_status == MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED) {
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_SERVER_FINISHED_RECEIVED;
+ if (ssl->early_data_state == MBEDTLS_SSL_EARLY_DATA_STATE_ACCEPTED) {
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_SERVER_FINISHED_RECEIVED;
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_END_OF_EARLY_DATA);
} else
#endif /* MBEDTLS_SSL_EARLY_DATA */
@@ -2881,12 +2917,17 @@ static int ssl_tls13_parse_new_session_ticket(mbedtls_ssl_context *ssl,
return ret;
}
- /* session has been updated, allow export */
- session->exported = 0;
-
return 0;
}
+/* Non negative return values for ssl_tls13_postprocess_new_session_ticket().
+ * - POSTPROCESS_NEW_SESSION_TICKET_SIGNAL, all good, we have to signal the
+ * application that a valid ticket has been received.
+ * - POSTPROCESS_NEW_SESSION_TICKET_DISCARD, no fatal error, we keep the
+ * connection alive but we do not signal the ticket to the application.
+ */
+#define POSTPROCESS_NEW_SESSION_TICKET_SIGNAL 0
+#define POSTPROCESS_NEW_SESSION_TICKET_DISCARD 1
MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_postprocess_new_session_ticket(mbedtls_ssl_context *ssl,
unsigned char *ticket_nonce,
@@ -2898,6 +2939,10 @@ static int ssl_tls13_postprocess_new_session_ticket(mbedtls_ssl_context *ssl,
psa_algorithm_t psa_hash_alg;
int hash_length;
+ if (session->ticket_lifetime == 0) {
+ return POSTPROCESS_NEW_SESSION_TICKET_DISCARD;
+ }
+
#if defined(MBEDTLS_HAVE_TIME)
/* Store ticket creation time */
session->ticket_reception_time = mbedtls_ms_time();
@@ -2954,7 +2999,7 @@ static int ssl_tls13_postprocess_new_session_ticket(mbedtls_ssl_context *ssl,
session, ssl->conf->tls13_kex_modes);
MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
- return 0;
+ return POSTPROCESS_NEW_SESSION_TICKET_SIGNAL;
}
/*
@@ -2975,12 +3020,37 @@ static int ssl_tls13_process_new_session_ticket(mbedtls_ssl_context *ssl)
ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
&buf, &buf_len));
+ /*
+ * We are about to update (maybe only partially) ticket data thus block
+ * any session export for the time being.
+ */
+ ssl->session->exported = 1;
+
MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_new_session_ticket(
ssl, buf, buf + buf_len,
&ticket_nonce, &ticket_nonce_len));
- MBEDTLS_SSL_PROC_CHK(ssl_tls13_postprocess_new_session_ticket(
- ssl, ticket_nonce, ticket_nonce_len));
+ MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_postprocess_new_session_ticket(
+ ssl, ticket_nonce, ticket_nonce_len));
+
+ switch (ret) {
+ case POSTPROCESS_NEW_SESSION_TICKET_SIGNAL:
+ /*
+ * All good, we have received a new valid ticket, session data can
+ * be exported now and we signal the ticket to the application.
+ */
+ ssl->session->exported = 0;
+ ret = MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
+ break;
+
+ case POSTPROCESS_NEW_SESSION_TICKET_DISCARD:
+ ret = 0;
+ MBEDTLS_SSL_DEBUG_MSG(2, ("Discard new session ticket"));
+ break;
+
+ default:
+ ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+ }
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
@@ -3030,9 +3100,11 @@ int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl)
ret = ssl_tls13_process_server_finished(ssl);
break;
+#if defined(MBEDTLS_SSL_EARLY_DATA)
case MBEDTLS_SSL_END_OF_EARLY_DATA:
ret = ssl_tls13_write_end_of_early_data(ssl);
break;
+#endif
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = ssl_tls13_write_client_certificate(ssl);
@@ -3061,23 +3133,17 @@ int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl)
*/
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
case MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO:
- ret = 0;
- if (ssl->handshake->ccs_count == 0) {
- ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
- if (ret != 0) {
- break;
- }
+ ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
+ if (ret != 0) {
+ break;
}
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
break;
case MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED:
- ret = 0;
- if (ssl->handshake->ccs_count == 0) {
- ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
- if (ret != 0) {
- break;
- }
+ ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
+ if (ret != 0) {
+ break;
}
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
break;
@@ -3092,7 +3158,7 @@ int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl)
1, ("Switch to early data keys for outbound traffic"));
mbedtls_ssl_set_outbound_transform(
ssl, ssl->handshake->transform_earlydata);
- ssl->early_data_status = MBEDTLS_SSL_EARLY_DATA_STATUS_CAN_WRITE;
+ ssl->early_data_state = MBEDTLS_SSL_EARLY_DATA_STATE_CAN_WRITE;
}
break;
#endif /* MBEDTLS_SSL_EARLY_DATA */
@@ -3101,10 +3167,6 @@ int mbedtls_ssl_tls13_handshake_client_step(mbedtls_ssl_context *ssl)
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET:
ret = ssl_tls13_process_new_session_ticket(ssl);
- if (ret != 0) {
- break;
- }
- ret = MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
diff --git a/library/ssl_tls13_generic.c b/library/ssl_tls13_generic.c
index 064f616..d448a05 100644
--- a/library/ssl_tls13_generic.c
+++ b/library/ssl_tls13_generic.c
@@ -1379,6 +1379,12 @@ int mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context *ssl)
MBEDTLS_SSL_DEBUG_MSG(2, ("=> write change cipher spec"));
+ /* Only one CCS to send. */
+ if (ssl->handshake->ccs_sent) {
+ ret = 0;
+ goto cleanup;
+ }
+
/* Write CCS message */
MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_change_cipher_spec_body(
ssl, ssl->out_msg,
@@ -1390,7 +1396,7 @@ int mbedtls_ssl_tls13_write_change_cipher_spec(mbedtls_ssl_context *ssl)
/* Dispatch message */
MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_write_record(ssl, 0));
- ssl->handshake->ccs_count++;
+ ssl->handshake->ccs_sent = 1;
cleanup:
@@ -1448,6 +1454,54 @@ int mbedtls_ssl_tls13_write_early_data_ext(mbedtls_ssl_context *ssl,
return 0;
}
+
+#if defined(MBEDTLS_SSL_SRV_C)
+int mbedtls_ssl_tls13_check_early_data_len(mbedtls_ssl_context *ssl,
+ size_t early_data_len)
+{
+ /*
+ * This function should be called only while an handshake is in progress
+ * and thus a session under negotiation. Add a sanity check to detect a
+ * misuse.
+ */
+ if (ssl->session_negotiate == NULL) {
+ return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
+ }
+
+ /* RFC 8446 section 4.6.1
+ *
+ * A server receiving more than max_early_data_size bytes of 0-RTT data
+ * SHOULD terminate the connection with an "unexpected_message" alert.
+ * Note that if it is still possible to send early_data_len bytes of early
+ * data, it means that early_data_len is smaller than max_early_data_size
+ * (type uint32_t) and can fit in an uint32_t. We use this further
+ * down.
+ */
+ if (early_data_len >
+ (ssl->session_negotiate->max_early_data_size -
+ ssl->total_early_data_size)) {
+
+ MBEDTLS_SSL_DEBUG_MSG(
+ 2, ("EarlyData: Too much early data received, %u + %" MBEDTLS_PRINTF_SIZET " > %u",
+ ssl->total_early_data_size, early_data_len,
+ ssl->session_negotiate->max_early_data_size));
+
+ MBEDTLS_SSL_PEND_FATAL_ALERT(
+ MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
+ MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
+ return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
+ }
+
+ /*
+ * early_data_len has been checked to be less than max_early_data_size
+ * that is uint32_t. Its cast to an uint32_t below is thus safe. We need
+ * the cast to appease some compilers.
+ */
+ ssl->total_early_data_size += (uint32_t) early_data_len;
+
+ return 0;
+}
+#endif /* MBEDTLS_SSL_SRV_C */
#endif /* MBEDTLS_SSL_EARLY_DATA */
/* Reset SSL context and update hash for handling HRR.
diff --git a/library/ssl_tls13_server.c b/library/ssl_tls13_server.c
index 1411446..2760d76 100644
--- a/library/ssl_tls13_server.c
+++ b/library/ssl_tls13_server.c
@@ -39,6 +39,63 @@ static const mbedtls_ssl_ciphersuite_t *ssl_tls13_validate_peer_ciphersuite(
return ciphersuite_info;
}
+static void ssl_tls13_select_ciphersuite(
+ mbedtls_ssl_context *ssl,
+ const unsigned char *cipher_suites,
+ const unsigned char *cipher_suites_end,
+ int psk_ciphersuite_id,
+ psa_algorithm_t psk_hash_alg,
+ const mbedtls_ssl_ciphersuite_t **selected_ciphersuite_info)
+{
+ *selected_ciphersuite_info = NULL;
+
+ /*
+ * In a compliant ClientHello the byte-length of the list of ciphersuites
+ * is even and this function relies on this fact. This should have been
+ * checked in the main ClientHello parsing function. Double check here.
+ */
+ if ((cipher_suites_end - cipher_suites) & 1) {
+ return;
+ }
+
+ for (const unsigned char *p = cipher_suites;
+ p < cipher_suites_end; p += 2) {
+ /*
+ * "cipher_suites_end - p is even" is an invariant of the loop. As
+ * cipher_suites_end - p > 0, we have cipher_suites_end - p >= 2 and it
+ * is thus safe to read two bytes.
+ */
+ uint16_t id = MBEDTLS_GET_UINT16_BE(p, 0);
+
+ const mbedtls_ssl_ciphersuite_t *info =
+ ssl_tls13_validate_peer_ciphersuite(ssl, id);
+ if (info == NULL) {
+ continue;
+ }
+
+ /*
+ * If a valid PSK ciphersuite identifier has been passed in, we want
+ * an exact match.
+ */
+ if (psk_ciphersuite_id != 0) {
+ if (id != psk_ciphersuite_id) {
+ continue;
+ }
+ } else if (psk_hash_alg != PSA_ALG_NONE) {
+ if (mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) info->mac) !=
+ psk_hash_alg) {
+ continue;
+ }
+ }
+
+ *selected_ciphersuite_info = info;
+ return;
+ }
+
+ MBEDTLS_SSL_DEBUG_MSG(2, ("No matched ciphersuite, psk_ciphersuite_id=%x, psk_hash_alg=%x",
+ (unsigned) psk_ciphersuite_id, psk_hash_alg));
+}
+
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
/* From RFC 8446:
*
@@ -90,8 +147,30 @@ static int ssl_tls13_parse_key_exchange_modes_ext(mbedtls_ssl_context *ssl,
return 0;
}
-#define SSL_TLS1_3_OFFERED_PSK_NOT_MATCH 1
-#define SSL_TLS1_3_OFFERED_PSK_MATCH 0
+/*
+ * Non-error return values of
+ * ssl_tls13_offered_psks_check_identity_match_ticket() and
+ * ssl_tls13_offered_psks_check_identity_match(). They are positive to
+ * not collide with error codes that are negative. Zero
+ * (SSL_TLS1_3_PSK_IDENTITY_MATCH) in case of success as it may be propagated
+ * up by the callers of this function as a generic success condition.
+ *
+ * The return value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE means
+ * that the pre-shared-key identity matches that of a ticket or an externally-
+ * provisioned pre-shared-key. We have thus been able to retrieve the
+ * attributes of the pre-shared-key but at least one of them does not meet
+ * some criteria and the pre-shared-key cannot be used. For example, a ticket
+ * is expired or its version is not TLS 1.3. Note eventually that the return
+ * value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE does not have
+ * anything to do with binder check. A binder check is done only when a
+ * suitable pre-shared-key has been selected and only for that selected
+ * pre-shared-key: if the binder check fails, we fail the handshake and we do
+ * not try to find another pre-shared-key for which the binder check would
+ * succeed as recommended by the specification.
+ */
+#define SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH 2
+#define SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE 1
+#define SSL_TLS1_3_PSK_IDENTITY_MATCH 0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
MBEDTLS_CHECK_RETURN_CRITICAL
@@ -109,7 +188,6 @@ static int ssl_tls13_offered_psks_check_identity_match_ticket(
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *ticket_buffer;
- unsigned int key_exchanges;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_ms_time_t now;
mbedtls_ms_time_t server_age;
@@ -123,7 +201,7 @@ static int ssl_tls13_offered_psks_check_identity_match_ticket(
/* Ticket parser is not configured, Skip */
if (ssl->conf->f_ticket_parse == NULL || identity_len == 0) {
- return 0;
+ return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
}
/* We create a copy of the encrypted ticket since the ticket parsing
@@ -133,63 +211,51 @@ static int ssl_tls13_offered_psks_check_identity_match_ticket(
*/
ticket_buffer = mbedtls_calloc(1, identity_len);
if (ticket_buffer == NULL) {
- MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
return MBEDTLS_ERR_SSL_ALLOC_FAILED;
}
memcpy(ticket_buffer, identity, identity_len);
- if ((ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket,
- session,
- ticket_buffer, identity_len)) != 0) {
- if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
- MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
- } else if (ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) {
+ ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket,
+ session,
+ ticket_buffer, identity_len);
+ switch (ret) {
+ case 0:
+ ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
+ break;
+
+ case MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED:
MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
- } else {
+ ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
+ break;
+
+ case MBEDTLS_ERR_SSL_INVALID_MAC:
+ MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
+ ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
+ break;
+
+ default:
MBEDTLS_SSL_DEBUG_RET(1, "ticket_parse", ret);
- }
+ ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
}
/* We delete the temporary buffer */
mbedtls_free(ticket_buffer);
- if (ret == 0 && session->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
- MBEDTLS_SSL_DEBUG_MSG(3, ("Ticket TLS version is not 1.3."));
- /* TODO: Define new return value for this case. */
- ret = MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
- }
-
- if (ret != 0) {
+ if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
goto exit;
}
- /* RFC 8446 section 4.2.9
- *
- * Servers SHOULD NOT send NewSessionTicket with tickets that are not
- * compatible with the advertised modes; however, if a server does so,
- * the impact will just be that the client's attempts at resumption fail.
- *
- * We regard the ticket with incompatible key exchange modes as not match.
+ /*
+ * The identity matches that of a ticket. Now check that it has suitable
+ * attributes and bet it will not be the case.
*/
- ret = MBEDTLS_ERR_ERROR_GENERIC_ERROR;
- MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
-
- key_exchanges = 0;
- if (mbedtls_ssl_tls13_session_ticket_allow_psk_ephemeral(session) &&
- ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
- key_exchanges |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
- }
- if (mbedtls_ssl_tls13_session_ticket_allow_psk(session) &&
- ssl_tls13_key_exchange_is_psk_available(ssl)) {
- key_exchanges |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
- }
+ ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
- if (key_exchanges == 0) {
- MBEDTLS_SSL_DEBUG_MSG(3, ("No suitable key exchange mode"));
+ if (session->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
+ MBEDTLS_SSL_DEBUG_MSG(3, ("Ticket TLS version is not 1.3."));
goto exit;
}
- ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED;
#if defined(MBEDTLS_HAVE_TIME)
now = mbedtls_ms_time();
@@ -242,13 +308,15 @@ static int ssl_tls13_offered_psks_check_identity_match_ticket(
age_diff));
goto exit;
}
-
- ret = 0;
-
#endif /* MBEDTLS_HAVE_TIME */
+ /*
+ * All good, we have found a suitable ticket.
+ */
+ ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
+
exit:
- if (ret != 0) {
+ if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
mbedtls_ssl_session_free(session);
}
@@ -273,13 +341,11 @@ static int ssl_tls13_offered_psks_check_identity_match(
*psk_type = MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL;
MBEDTLS_SSL_DEBUG_BUF(4, "identity", identity, identity_len);
- ssl->handshake->resume = 0;
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
- if (ssl_tls13_offered_psks_check_identity_match_ticket(
- ssl, identity, identity_len, obfuscated_ticket_age,
- session) == SSL_TLS1_3_OFFERED_PSK_MATCH) {
- ssl->handshake->resume = 1;
+ ret = ssl_tls13_offered_psks_check_identity_match_ticket(
+ ssl, identity, identity_len, obfuscated_ticket_age, session);
+ if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH) {
*psk_type = MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION;
ret = mbedtls_ssl_set_hs_psk(ssl,
session->resumption_key,
@@ -294,7 +360,9 @@ static int ssl_tls13_offered_psks_check_identity_match(
session->resumption_key_len);
MBEDTLS_SSL_DEBUG_MSG(4, ("ticket: obfuscated_ticket_age: %u",
(unsigned) obfuscated_ticket_age));
- return SSL_TLS1_3_OFFERED_PSK_MATCH;
+ return SSL_TLS1_3_PSK_IDENTITY_MATCH;
+ } else if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE) {
+ return SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
@@ -302,9 +370,9 @@ static int ssl_tls13_offered_psks_check_identity_match(
if (ssl->conf->f_psk != NULL) {
if (ssl->conf->f_psk(
ssl->conf->p_psk, ssl, identity, identity_len) == 0) {
- return SSL_TLS1_3_OFFERED_PSK_MATCH;
+ return SSL_TLS1_3_PSK_IDENTITY_MATCH;
}
- return SSL_TLS1_3_OFFERED_PSK_NOT_MATCH;
+ return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
}
MBEDTLS_SSL_DEBUG_BUF(5, "identity", identity, identity_len);
@@ -318,12 +386,20 @@ static int ssl_tls13_offered_psks_check_identity_match(
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
return ret;
}
- return SSL_TLS1_3_OFFERED_PSK_MATCH;
+ return SSL_TLS1_3_PSK_IDENTITY_MATCH;
}
- return SSL_TLS1_3_OFFERED_PSK_NOT_MATCH;
+ return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
}
+/*
+ * Non-error return values of ssl_tls13_offered_psks_check_binder_match().
+ * They are positive to not collide with error codes that are negative. Zero
+ * (SSL_TLS1_3_BINDER_MATCH) in case of success as it may be propagated up
+ * by the callers of this function as a generic success condition.
+ */
+#define SSL_TLS1_3_BINDER_DOES_NOT_MATCH 1
+#define SSL_TLS1_3_BINDER_MATCH 0
MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_offered_psks_check_binder_match(
mbedtls_ssl_context *ssl,
@@ -338,6 +414,10 @@ static int ssl_tls13_offered_psks_check_binder_match(
size_t psk_len;
unsigned char server_computed_binder[PSA_HASH_MAX_SIZE];
+ if (binder_len != PSA_HASH_LENGTH(psk_hash_alg)) {
+ return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
+ }
+
/* Get current state of handshake transcript. */
ret = mbedtls_ssl_get_handshake_transcript(
ssl, mbedtls_md_type_from_psa_alg(psk_hash_alg),
@@ -367,101 +447,19 @@ static int ssl_tls13_offered_psks_check_binder_match(
server_computed_binder, transcript_len);
MBEDTLS_SSL_DEBUG_BUF(3, "psk binder ( received ): ", binder, binder_len);
- if (mbedtls_ct_memcmp(server_computed_binder, binder, binder_len) == 0) {
- return SSL_TLS1_3_OFFERED_PSK_MATCH;
+ if (mbedtls_ct_memcmp(server_computed_binder,
+ binder,
+ PSA_HASH_LENGTH(psk_hash_alg)) == 0) {
+ return SSL_TLS1_3_BINDER_MATCH;
}
mbedtls_platform_zeroize(server_computed_binder,
sizeof(server_computed_binder));
- return SSL_TLS1_3_OFFERED_PSK_NOT_MATCH;
-}
-
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_select_ciphersuite_for_psk(
- mbedtls_ssl_context *ssl,
- const unsigned char *cipher_suites,
- const unsigned char *cipher_suites_end,
- uint16_t *selected_ciphersuite,
- const mbedtls_ssl_ciphersuite_t **selected_ciphersuite_info)
-{
- psa_algorithm_t psk_hash_alg = PSA_ALG_SHA_256;
-
- *selected_ciphersuite = 0;
- *selected_ciphersuite_info = NULL;
-
- /* RFC 8446, page 55.
- *
- * For externally established PSKs, the Hash algorithm MUST be set when the
- * PSK is established or default to SHA-256 if no such algorithm is defined.
- *
- */
-
- /*
- * Search for a matching ciphersuite
- */
- for (const unsigned char *p = cipher_suites;
- p < cipher_suites_end; p += 2) {
- uint16_t cipher_suite;
- const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
-
- cipher_suite = MBEDTLS_GET_UINT16_BE(p, 0);
- ciphersuite_info = ssl_tls13_validate_peer_ciphersuite(ssl,
- cipher_suite);
- if (ciphersuite_info == NULL) {
- continue;
- }
-
- /* MAC of selected ciphersuite MUST be same with PSK binder if exist.
- * Otherwise, client should reject.
- */
- if (psk_hash_alg ==
- mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac)) {
- *selected_ciphersuite = cipher_suite;
- *selected_ciphersuite_info = ciphersuite_info;
- return 0;
- }
- }
- MBEDTLS_SSL_DEBUG_MSG(2, ("No matched ciphersuite"));
- return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
+ return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_select_ciphersuite_for_resumption(
- mbedtls_ssl_context *ssl,
- const unsigned char *cipher_suites,
- const unsigned char *cipher_suites_end,
- mbedtls_ssl_session *session,
- uint16_t *selected_ciphersuite,
- const mbedtls_ssl_ciphersuite_t **selected_ciphersuite_info)
-{
-
- *selected_ciphersuite = 0;
- *selected_ciphersuite_info = NULL;
- for (const unsigned char *p = cipher_suites; p < cipher_suites_end; p += 2) {
- uint16_t cipher_suite = MBEDTLS_GET_UINT16_BE(p, 0);
- const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
-
- if (cipher_suite != session->ciphersuite) {
- continue;
- }
-
- ciphersuite_info = ssl_tls13_validate_peer_ciphersuite(ssl,
- cipher_suite);
- if (ciphersuite_info == NULL) {
- continue;
- }
-
- *selected_ciphersuite = cipher_suite;
- *selected_ciphersuite_info = ciphersuite_info;
-
- return 0;
- }
-
- return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
-}
-
-MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_session_copy_ticket(mbedtls_ssl_session *dst,
const mbedtls_ssl_session *src)
{
@@ -475,12 +473,26 @@ static int ssl_tls13_session_copy_ticket(mbedtls_ssl_session *dst,
#if defined(MBEDTLS_SSL_EARLY_DATA)
dst->max_early_data_size = src->max_early_data_size;
-#endif
+
+#if defined(MBEDTLS_SSL_ALPN)
+ int ret = mbedtls_ssl_session_set_ticket_alpn(dst, src->ticket_alpn);
+ if (ret != 0) {
+ return ret;
+ }
+#endif /* MBEDTLS_SSL_ALPN */
+#endif /* MBEDTLS_SSL_EARLY_DATA*/
return 0;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
+struct psk_attributes {
+ int type;
+ int key_exchange_mode;
+ const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
+};
+#define PSK_ATTRIBUTES_INIT { 0, 0, NULL }
+
/* Parser for pre_shared_key extension in client hello
* struct {
* opaque identity<1..2^16-1>;
@@ -507,7 +519,8 @@ static int ssl_tls13_parse_pre_shared_key_ext(
const unsigned char *pre_shared_key_ext,
const unsigned char *pre_shared_key_ext_end,
const unsigned char *ciphersuites,
- const unsigned char *ciphersuites_end)
+ const unsigned char *ciphersuites_end,
+ struct psk_attributes *psk)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const unsigned char *identities = pre_shared_key_ext;
@@ -558,9 +571,10 @@ static int ssl_tls13_parse_pre_shared_key_ext(
uint32_t obfuscated_ticket_age;
const unsigned char *binder;
size_t binder_len;
- int psk_type;
- uint16_t cipher_suite;
- const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
+ int psk_ciphersuite_id;
+ psa_algorithm_t psk_hash_alg;
+ int allowed_key_exchange_modes;
+
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
mbedtls_ssl_session session;
mbedtls_ssl_session_init(&session);
@@ -586,47 +600,74 @@ static int ssl_tls13_parse_pre_shared_key_ext(
ret = ssl_tls13_offered_psks_check_identity_match(
ssl, identity, identity_len, obfuscated_ticket_age,
- &psk_type, &session);
- if (ret != SSL_TLS1_3_OFFERED_PSK_MATCH) {
+ &psk->type, &session);
+ if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
continue;
}
MBEDTLS_SSL_DEBUG_MSG(4, ("found matched identity"));
- switch (psk_type) {
+
+ switch (psk->type) {
case MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL:
- ret = ssl_tls13_select_ciphersuite_for_psk(
- ssl, ciphersuites, ciphersuites_end,
- &cipher_suite, &ciphersuite_info);
+ psk_ciphersuite_id = 0;
+ psk_hash_alg = PSA_ALG_SHA_256;
+ allowed_key_exchange_modes =
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
break;
- case MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION:
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
- ret = ssl_tls13_select_ciphersuite_for_resumption(
- ssl, ciphersuites, ciphersuites_end, &session,
- &cipher_suite, &ciphersuite_info);
- if (ret != 0) {
- mbedtls_ssl_session_free(&session);
- }
-#else
- ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
-#endif
+ case MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION:
+ psk_ciphersuite_id = session.ciphersuite;
+ psk_hash_alg = PSA_ALG_NONE;
+ ssl->session_negotiate->ticket_flags = session.ticket_flags;
+ allowed_key_exchange_modes =
+ session.ticket_flags &
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
break;
+#endif
default:
return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
}
- if (ret != 0) {
- /* See below, no cipher_suite available, abort handshake */
+
+ psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE;
+
+ if ((allowed_key_exchange_modes &
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) &&
+ ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
+ psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
+ } else if ((allowed_key_exchange_modes &
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) &&
+ ssl_tls13_key_exchange_is_psk_available(ssl)) {
+ psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
+ }
+
+ if (psk->key_exchange_mode == MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE) {
+ MBEDTLS_SSL_DEBUG_MSG(3, ("No suitable PSK key exchange mode"));
+ continue;
+ }
+
+ ssl_tls13_select_ciphersuite(ssl, ciphersuites, ciphersuites_end,
+ psk_ciphersuite_id, psk_hash_alg,
+ &psk->ciphersuite_info);
+
+ if (psk->ciphersuite_info == NULL) {
+#if defined(MBEDTLS_SSL_SESSION_TICKETS)
+ mbedtls_ssl_session_free(&session);
+#endif
+ /*
+ * We consider finding a ciphersuite suitable for the PSK as part
+ * of the validation of its binder. Thus if we do not find one, we
+ * abort the handshake with a decrypt_error alert.
+ */
MBEDTLS_SSL_PEND_FATAL_ALERT(
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
- MBEDTLS_SSL_DEBUG_RET(
- 2, "ssl_tls13_select_ciphersuite", ret);
- return ret;
+ return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
}
ret = ssl_tls13_offered_psks_check_binder_match(
- ssl, binder, binder_len, psk_type,
- mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac));
- if (ret != SSL_TLS1_3_OFFERED_PSK_MATCH) {
+ ssl, binder, binder_len, psk->type,
+ mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) psk->ciphersuite_info->mac));
+ if (ret != SSL_TLS1_3_BINDER_MATCH) {
/* For security reasons, the handshake should be aborted when we
* fail to validate a binder value. See RFC 8446 section 4.2.11.2
* and appendix E.6. */
@@ -644,13 +685,8 @@ static int ssl_tls13_parse_pre_shared_key_ext(
matched_identity = identity_id;
- /* Update handshake parameters */
- ssl->handshake->ciphersuite_info = ciphersuite_info;
- ssl->session_negotiate->ciphersuite = cipher_suite;
- MBEDTLS_SSL_DEBUG_MSG(2, ("overwrite ciphersuite: %04x - %s",
- cipher_suite, ciphersuite_info->name));
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
- if (psk_type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
+ if (psk->type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
ret = ssl_tls13_session_copy_ticket(ssl->session_negotiate,
&session);
mbedtls_ssl_session_free(&session);
@@ -676,7 +712,7 @@ static int ssl_tls13_parse_pre_shared_key_ext(
return ret;
}
if (matched_identity == -1) {
- MBEDTLS_SSL_DEBUG_MSG(3, ("No matched PSK or ticket."));
+ MBEDTLS_SSL_DEBUG_MSG(3, ("No usable PSK or ticket."));
return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
@@ -1003,43 +1039,10 @@ static int ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_ticket_is_kex_mode_permitted(mbedtls_ssl_context *ssl,
- unsigned int kex_mode)
-{
-#if defined(MBEDTLS_SSL_SESSION_TICKETS)
- if (ssl->handshake->resume) {
- if (!mbedtls_ssl_tls13_session_ticket_has_flags(
- ssl->session_negotiate, kex_mode)) {
- return 0;
- }
- }
-#else
- ((void) ssl);
- ((void) kex_mode);
-#endif
- return 1;
-}
-#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
-
-MBEDTLS_CHECK_RETURN_CRITICAL
-static int ssl_tls13_key_exchange_is_ephemeral_available(mbedtls_ssl_context *ssl)
-{
-#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
- return mbedtls_ssl_conf_tls13_is_ephemeral_enabled(ssl) &&
- ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(ssl);
-#else
- ((void) ssl);
- return 0;
-#endif
-}
-
-MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context *ssl)
{
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
- return ssl_tls13_ticket_is_kex_mode_permitted(
- ssl, MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) &&
- mbedtls_ssl_conf_tls13_is_psk_enabled(ssl) &&
+ return mbedtls_ssl_conf_tls13_is_psk_enabled(ssl) &&
mbedtls_ssl_tls13_is_psk_supported(ssl) &&
ssl_tls13_client_hello_has_exts_for_psk_key_exchange(ssl);
#else
@@ -1052,9 +1055,7 @@ MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context *ssl)
{
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
- return ssl_tls13_ticket_is_kex_mode_permitted(
- ssl, MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) &&
- mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(ssl) &&
+ return mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(ssl) &&
mbedtls_ssl_tls13_is_psk_ephemeral_supported(ssl) &&
ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(ssl);
#else
@@ -1062,52 +1063,18 @@ static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context
return 0;
#endif
}
+#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
-static int ssl_tls13_determine_key_exchange_mode(mbedtls_ssl_context *ssl)
+MBEDTLS_CHECK_RETURN_CRITICAL
+static int ssl_tls13_key_exchange_is_ephemeral_available(mbedtls_ssl_context *ssl)
{
- /*
- * Determine the key exchange algorithm to use.
- * There are three types of key exchanges supported in TLS 1.3:
- * - (EC)DH with ECDSA,
- * - (EC)DH with PSK,
- * - plain PSK.
- *
- * The PSK-based key exchanges may additionally be used with 0-RTT.
- *
- * Our built-in order of preference is
- * 1 ) (EC)DHE-PSK Mode ( psk_ephemeral )
- * 2 ) Certificate Mode ( ephemeral )
- * 3 ) Plain PSK Mode ( psk )
- */
-
- ssl->handshake->key_exchange_mode =
- MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE;
-
- if (ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
- ssl->handshake->key_exchange_mode =
- MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
- MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk_ephemeral"));
- } else
- if (ssl_tls13_key_exchange_is_ephemeral_available(ssl)) {
- ssl->handshake->key_exchange_mode =
- MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
- MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: ephemeral"));
- } else
- if (ssl_tls13_key_exchange_is_psk_available(ssl)) {
- ssl->handshake->key_exchange_mode =
- MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
- MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk"));
- } else {
- MBEDTLS_SSL_DEBUG_MSG(
- 1,
- ("ClientHello message misses mandatory extensions."));
- MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION,
- MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
- return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
- }
-
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
+ return mbedtls_ssl_conf_tls13_is_ephemeral_enabled(ssl) &&
+ ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(ssl);
+#else
+ ((void) ssl);
return 0;
-
+#endif
}
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
@@ -1301,6 +1268,8 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
int no_usable_share_for_key_agreement = 0;
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+ int got_psk = 0;
+ struct psk_attributes psk = PSK_ATTRIBUTES_INIT;
const unsigned char *pre_shared_key_ext = NULL;
const unsigned char *pre_shared_key_ext_end = NULL;
#endif
@@ -1464,37 +1433,20 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
*/
MBEDTLS_SSL_DEBUG_BUF(3, "client hello, list of cipher suites",
cipher_suites, cipher_suites_len);
- for (const unsigned char *cipher_suites_p = cipher_suites;
- cipher_suites_p < cipher_suites_end; cipher_suites_p += 2) {
- uint16_t cipher_suite;
- const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
- /*
- * "cipher_suites_end - cipher_suites_p is even" is an invariant of the
- * loop. As cipher_suites_end - cipher_suites_p > 0, we have
- * cipher_suites_end - cipher_suites_p >= 2 and it is thus safe to read
- * two bytes.
- */
- cipher_suite = MBEDTLS_GET_UINT16_BE(cipher_suites_p, 0);
- ciphersuite_info = ssl_tls13_validate_peer_ciphersuite(
- ssl, cipher_suite);
- if (ciphersuite_info == NULL) {
- continue;
- }
-
- ssl->session_negotiate->ciphersuite = cipher_suite;
- handshake->ciphersuite_info = ciphersuite_info;
- MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %04x - %s",
- cipher_suite,
- ciphersuite_info->name));
- break;
- }
+ ssl_tls13_select_ciphersuite(ssl, cipher_suites, cipher_suites_end,
+ 0, PSA_ALG_NONE, &handshake->ciphersuite_info);
if (handshake->ciphersuite_info == NULL) {
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
}
+ ssl->session_negotiate->ciphersuite = handshake->ciphersuite_info->id;
+
+ MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %04x - %s",
+ ((unsigned) handshake->ciphersuite_info->id),
+ handshake->ciphersuite_info->name));
/* ...
* opaque legacy_compression_methods<1..2^8-1>;
@@ -1531,7 +1483,7 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
const unsigned char *extension_data_end;
uint32_t allowed_exts = MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH;
- if (ssl->handshake->hello_retry_request_count > 0) {
+ if (ssl->handshake->hello_retry_request_flag) {
/* Do not accept early data extension in 2nd ClientHello */
allowed_exts &= ~MBEDTLS_SSL_EXT_MASK(EARLY_DATA);
}
@@ -1734,10 +1686,11 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
/* Update checksum with either
* - The entire content of the CH message, if no PSK extension is present
* - The content up to but excluding the PSK extension, if present.
+ * Always parse the pre-shared-key extension when present in the
+ * ClientHello even if some pre-requisites for PSK key exchange modes are
+ * not met. That way we always validate the syntax of the extension.
*/
- /* If we've settled on a PSK-based exchange, parse PSK identity ext */
- if (ssl_tls13_key_exchange_is_psk_available(ssl) ||
- ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
+ if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)) {
ret = handshake->update_checksum(ssl, buf,
pre_shared_key_ext - buf);
if (0 != ret) {
@@ -1748,10 +1701,11 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
pre_shared_key_ext,
pre_shared_key_ext_end,
cipher_suites,
- cipher_suites_end);
- if (ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
- handshake->received_extensions &= ~MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY);
- } else if (ret != 0) {
+ cipher_suites_end,
+ &psk);
+ if (ret == 0) {
+ got_psk = 1;
+ } else if (ret != MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
MBEDTLS_SSL_DEBUG_RET(
1, "ssl_tls13_parse_pre_shared_key_ext", ret);
return ret;
@@ -1766,12 +1720,68 @@ static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
}
}
- ret = ssl_tls13_determine_key_exchange_mode(ssl);
- if (ret < 0) {
- return ret;
+ /*
+ * Determine the key exchange algorithm to use.
+ * There are three types of key exchanges supported in TLS 1.3:
+ * - (EC)DH with ECDSA,
+ * - (EC)DH with PSK,
+ * - plain PSK.
+ *
+ * The PSK-based key exchanges may additionally be used with 0-RTT.
+ *
+ * Our built-in order of preference is
+ * 1 ) (EC)DHE-PSK Mode ( psk_ephemeral )
+ * 2 ) Certificate Mode ( ephemeral )
+ * 3 ) Plain PSK Mode ( psk )
+ */
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+ if (got_psk && (psk.key_exchange_mode ==
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL)) {
+ handshake->key_exchange_mode =
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
+ MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk_ephemeral"));
+
+ } else
+#endif
+ if (ssl_tls13_key_exchange_is_ephemeral_available(ssl)) {
+ handshake->key_exchange_mode =
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
+ MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: ephemeral"));
+
+ }
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+ else if (got_psk && (psk.key_exchange_mode ==
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK)) {
+ handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
+ MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk"));
+ }
+#endif
+ else {
+ MBEDTLS_SSL_DEBUG_MSG(
+ 1,
+ ("ClientHello message misses mandatory extensions."));
+ MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION,
+ MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
+ return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
+ }
+
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+ if (handshake->key_exchange_mode &
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL) {
+ handshake->ciphersuite_info = psk.ciphersuite_info;
+ ssl->session_negotiate->ciphersuite = psk.ciphersuite_info->id;
+
+ MBEDTLS_SSL_DEBUG_MSG(2, ("Select PSK ciphersuite: %04x - %s",
+ ((unsigned) psk.ciphersuite_info->id),
+ psk.ciphersuite_info->name));
+
+ if (psk.type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
+ handshake->resume = 1;
+ }
}
+#endif
- if (ssl->handshake->key_exchange_mode !=
+ if (handshake->key_exchange_mode !=
MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) {
hrr_required = (no_usable_share_for_key_agreement != 0);
}
@@ -1815,7 +1825,6 @@ static int ssl_tls13_check_early_data_requirements(mbedtls_ssl_context *ssl)
* NOTE:
* - The TLS version number is checked in
* ssl_tls13_offered_psks_check_identity_match_ticket().
- * - ALPN is not checked for the time being (TODO).
*/
if (handshake->selected_identity != 0) {
@@ -1842,6 +1851,28 @@ static int ssl_tls13_check_early_data_requirements(mbedtls_ssl_context *ssl)
return -1;
}
+#if defined(MBEDTLS_SSL_ALPN)
+ const char *alpn = mbedtls_ssl_get_alpn_protocol(ssl);
+ size_t alpn_len;
+
+ if (alpn == NULL && ssl->session_negotiate->ticket_alpn == NULL) {
+ return 0;
+ }
+
+ if (alpn != NULL) {
+ alpn_len = strlen(alpn);
+ }
+
+ if (alpn == NULL ||
+ ssl->session_negotiate->ticket_alpn == NULL ||
+ alpn_len != strlen(ssl->session_negotiate->ticket_alpn) ||
+ (memcmp(alpn, ssl->session_negotiate->ticket_alpn, alpn_len) != 0)) {
+ MBEDTLS_SSL_DEBUG_MSG(1, ("EarlyData: rejected, the selected ALPN is different "
+ "from the one associated with the pre-shared key."));
+ return -1;
+ }
+#endif
+
return 0;
}
#endif /* MBEDTLS_SSL_EARLY_DATA */
@@ -1973,10 +2004,6 @@ static int ssl_tls13_prepare_server_hello(mbedtls_ssl_context *ssl)
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *server_randbytes =
ssl->handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
- if (ssl->conf->f_rng == NULL) {
- MBEDTLS_SSL_DEBUG_MSG(1, ("no RNG provided"));
- return MBEDTLS_ERR_SSL_NO_RNG;
- }
if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, server_randbytes,
MBEDTLS_SERVER_HELLO_RANDOM_LEN)) != 0) {
@@ -2427,7 +2454,7 @@ MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_tls13_prepare_hello_retry_request(mbedtls_ssl_context *ssl)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
- if (ssl->handshake->hello_retry_request_count > 0) {
+ if (ssl->handshake->hello_retry_request_flag) {
MBEDTLS_SSL_DEBUG_MSG(1, ("Too many HRRs"));
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
@@ -2474,7 +2501,7 @@ static int ssl_tls13_write_hello_retry_request(mbedtls_ssl_context *ssl)
MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(ssl, buf_len,
msg_len));
- ssl->handshake->hello_retry_request_count++;
+ ssl->handshake->hello_retry_request_flag = 1;
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
/* The server sends a dummy change_cipher_spec record immediately
@@ -2913,17 +2940,14 @@ static int ssl_tls13_end_of_early_data_coordinate(mbedtls_ssl_context *ssl)
}
if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
- MBEDTLS_SSL_DEBUG_MSG(3, ("Received early data"));
- /* RFC 8446 section 4.6.1
- *
- * A server receiving more than max_early_data_size bytes of 0-RTT data
- * SHOULD terminate the connection with an "unexpected_message" alert.
- *
- * TODO: Add received data size check here.
- */
if (ssl->in_offt == NULL) {
+ MBEDTLS_SSL_DEBUG_MSG(3, ("Received early data"));
/* Set the reading pointer */
ssl->in_offt = ssl->in_msg;
+ ret = mbedtls_ssl_tls13_check_early_data_len(ssl, ssl->in_msglen);
+ if (ret != 0) {
+ return ret;
+ }
}
return SSL_GOT_EARLY_DATA;
}
@@ -3141,11 +3165,21 @@ static int ssl_tls13_prepare_new_session_ticket(mbedtls_ssl_context *ssl,
ssl->conf->max_early_data_size > 0) {
mbedtls_ssl_tls13_session_set_ticket_flags(
session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
+ session->max_early_data_size = ssl->conf->max_early_data_size;
}
#endif /* MBEDTLS_SSL_EARLY_DATA */
MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
+ if (session->ticket_alpn == NULL) {
+ ret = mbedtls_ssl_session_set_ticket_alpn(session, ssl->alpn_chosen);
+ if (ret != 0) {
+ return ret;
+ }
+ }
+#endif
+
/* Generate ticket_age_add */
if ((ret = ssl->conf->f_rng(ssl->conf->p_rng,
(unsigned char *) &session->ticket_age_add,
@@ -3275,20 +3309,21 @@ static int ssl_tls13_write_new_session_ticket_body(mbedtls_ssl_context *ssl,
MBEDTLS_SSL_DEBUG_RET(1, "write_ticket", ret);
return ret;
}
- /* RFC 8446 4.6.1
+
+ /* RFC 8446 section 4.6.1
+ *
* ticket_lifetime: Indicates the lifetime in seconds as a 32-bit
- * unsigned integer in network byte order from the time of ticket
- * issuance. Servers MUST NOT use any value greater than
- * 604800 seconds (7 days). The value of zero indicates that the
- * ticket should be discarded immediately. Clients MUST NOT cache
- * tickets for longer than 7 days, regardless of the ticket_lifetime,
- * and MAY delete tickets earlier based on local policy. A server
- * MAY treat a ticket as valid for a shorter period of time than what
- * is stated in the ticket_lifetime.
+ * unsigned integer in network byte order from the time of ticket
+ * issuance. Servers MUST NOT use any value greater than
+ * 604800 seconds (7 days) ...
*/
if (ticket_lifetime > MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME) {
- ticket_lifetime = MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME;
+ MBEDTLS_SSL_DEBUG_MSG(
+ 1, ("Ticket lifetime (%u) is greater than 7 days.",
+ (unsigned int) ticket_lifetime));
+ return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
+
MBEDTLS_PUT_UINT32_BE(ticket_lifetime, p, 0);
MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_lifetime: %u",
(unsigned int) ticket_lifetime));
@@ -3477,12 +3512,9 @@ int mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context *ssl)
break;
case MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO:
- ret = 0;
- if (ssl->handshake->ccs_count == 0) {
- ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
- if (ret != 0) {
- break;
- }
+ ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
+ if (ret != 0) {
+ break;
}
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
break;
diff --git a/library/threading.c b/library/threading.c
index c28290f..85db243 100644
--- a/library/threading.c
+++ b/library/threading.c
@@ -150,6 +150,8 @@ void mbedtls_threading_set_alt(void (*mutex_init)(mbedtls_threading_mutex_t *),
#endif
#if defined(MBEDTLS_PSA_CRYPTO_C)
mbedtls_mutex_init(&mbedtls_threading_key_slot_mutex);
+ mbedtls_mutex_init(&mbedtls_threading_psa_globaldata_mutex);
+ mbedtls_mutex_init(&mbedtls_threading_psa_rngdata_mutex);
#endif
}
@@ -166,6 +168,8 @@ void mbedtls_threading_free_alt(void)
#endif
#if defined(MBEDTLS_PSA_CRYPTO_C)
mbedtls_mutex_free(&mbedtls_threading_key_slot_mutex);
+ mbedtls_mutex_free(&mbedtls_threading_psa_globaldata_mutex);
+ mbedtls_mutex_free(&mbedtls_threading_psa_rngdata_mutex);
#endif
}
#endif /* MBEDTLS_THREADING_ALT */
@@ -184,6 +188,8 @@ mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT;
#endif
#if defined(MBEDTLS_PSA_CRYPTO_C)
mbedtls_threading_mutex_t mbedtls_threading_key_slot_mutex MUTEX_INIT;
+mbedtls_threading_mutex_t mbedtls_threading_psa_globaldata_mutex MUTEX_INIT;
+mbedtls_threading_mutex_t mbedtls_threading_psa_rngdata_mutex MUTEX_INIT;
#endif
#endif /* MBEDTLS_THREADING_C */
diff --git a/library/x509_crt.c b/library/x509_crt.c
index 7f0160a..2fd56fb 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -3290,4 +3290,12 @@ void mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx *ctx)
}
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+int mbedtls_x509_crt_get_ca_istrue(const mbedtls_x509_crt *crt)
+{
+ if ((crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS) != 0) {
+ return crt->MBEDTLS_PRIVATE(ca_istrue);
+ }
+ return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
+}
+
#endif /* MBEDTLS_X509_CRT_PARSE_C */