From 7ba359a4a614cdaa0c71500ad5194de36d93789d Mon Sep 17 00:00:00 2001 From: Mohammad AboMokh Date: Tue, 13 Nov 2018 06:54:43 +0200 Subject: [PATCH 1/6] Update mbedtls importer to import mbed-crypto --- features/mbedtls/importer/Makefile | 42 +++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/features/mbedtls/importer/Makefile b/features/mbedtls/importer/Makefile index a8d55cf91ad..d2393971906 100644 --- a/features/mbedtls/importer/Makefile +++ b/features/mbedtls/importer/Makefile @@ -31,16 +31,35 @@ MBED_TLS_RELEASE ?= mbedtls-2.13.1 # Translate between mbed TLS namespace and mbed namespace TARGET_PREFIX:=../ +TARGET_PREFIX_CRYPTO:=../mbed-crypto/ TARGET_SRC:=$(TARGET_PREFIX)src TARGET_INC:=$(TARGET_PREFIX)inc TARGET_TESTS:=$(TARGET_PREFIX)TESTS +# New folder structure is introduced here for targets with Secured-Partition-Environment +# and Non-Secured-Partition-Environment, below documentation for each folder: +# COMPONENT_PSA_SRV_IMPL - include secure service business logic implementation +# code. For example Mbed Crypto or secure time core logic +TARGET_SRV_IMPL:=$(TARGET_PREFIX_CRYPTO)/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL +# COMPONENT_SPE - include code that compiles ONLY to secure image and never +# compiles to non-secure image +TARGET_SPE:=$(TARGET_PREFIX_CRYPTO)/platform/TARGET_PSA/COMPONENT_SPE +# The folder contain specific target implementation using hardware. +TARGET_PSA_DRIVERS:=$(TARGET_PREFIX_CRYPTO)/targets +# COMPONENT_NSPE - include code that compiles ONLY to non-secure image and +# never compiles to secure image +TARGET_NSPE:=$(TARGET_SRV_IMPL)/COMPONENT_NSPE + # mbed TLS source directory - hidden from mbed via TARGET_IGNORE MBED_TLS_URL:=git@github.com:ARMmbed/mbedtls-restricted.git MBED_TLS_DIR:=TARGET_IGNORE/mbedtls MBED_TLS_API:=$(MBED_TLS_DIR)/include/mbedtls MBED_TLS_GIT_CFG=$(MBED_TLS_DIR)/.git/config +# Mbed Crypto directory - hidden from mbed via TARGET_IGNORE +MBED_CRYPTO_DIR:=$(MBED_TLS_DIR)/crypto +MBED_CRYPTO_API:=$(MBED_CRYPTO_DIR)/include/psa + .PHONY: all deploy deploy-tests rsync mbedtls clean update all: mbedtls @@ -62,6 +81,23 @@ rsync: cp $(MBED_TLS_DIR)/LICENSE $(TARGET_PREFIX) cp $(MBED_TLS_DIR)/apache-2.0.txt $(TARGET_PREFIX) # + # Create Mbed Crypto target folder + mkdir -p $(TARGET_PREFIX_CRYPTO) + # + # Copying Mbed Crypto into Mbed OS.. + rm -rf $(TARGET_SRV_IMPL) + rm -rf $(TARGET_SPE) + + mkdir -p $(TARGET_SRV_IMPL) + mkdir -p $(TARGET_SPE) + mkdir -p $(TARGET_NSPE) + mkdir -p $(TARGET_PSA_DRIVERS) + + rsync -a --delete --exclude='crypto_struct.h' $(MBED_CRYPTO_API) $(TARGET_INC) + rsync -a --delete $(MBED_CRYPTO_API)/crypto_struct.h $(TARGET_NSPE) + rsync -a --delete $(MBED_CRYPTO_API)/crypto_struct.h $(TARGET_SPE)/crypto_struct_spe.h + rsync -a --delete $(MBED_CRYPTO_DIR)/library/psa_*.c $(TARGET_SRV_IMPL) + rsync -a --delete $(MBED_CRYPTO_DIR)/library/psa_*.h $(TARGET_SRV_IMPL) deploy: rsync # @@ -92,6 +128,9 @@ update: $(MBED_TLS_GIT_CFG) $(MBED_TLS_HA_GIT_CFG) # Checking out the required release git -C $(MBED_TLS_DIR) checkout $(MBED_TLS_RELEASE) # + # Update and checkout git submodules + git -C $(MBED_TLS_DIR) submodule update --init --recursive + # # Updating checked out version tag echo $(MBED_TLS_RELEASE) > $(TARGET_PREFIX)VERSION.txt @@ -107,4 +146,5 @@ clean: rm -rf $(TARGET_SRC) rm -rf $(TARGET_INC) rm -rf $(MBED_TLS_DIR) - + rm -rf $(TARGET_SRV_IMPL) + rm -rf $(TARGET_SPE) From 15945687bc09165bf4aa7c6f43de0f26b406cc44 Mon Sep 17 00:00:00 2001 From: Mohammad AboMokh Date: Sun, 18 Nov 2018 17:02:11 +0200 Subject: [PATCH 2/6] Record Mbed Crypto version Record the version of Mbed Crypto into VERSION.txt for easy reference. --- features/mbedtls/importer/Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/features/mbedtls/importer/Makefile b/features/mbedtls/importer/Makefile index d2393971906..5b7ef5e1cf4 100644 --- a/features/mbedtls/importer/Makefile +++ b/features/mbedtls/importer/Makefile @@ -133,6 +133,9 @@ update: $(MBED_TLS_GIT_CFG) $(MBED_TLS_HA_GIT_CFG) # # Updating checked out version tag echo $(MBED_TLS_RELEASE) > $(TARGET_PREFIX)VERSION.txt + # + # Updating Mbed Crypto checked out version tag + git -C $(MBED_CRYPTO_DIR) describe --tags --abbrev=12 --dirty --always >> $(TARGET_PREFIX)VERSION.txt $(MBED_TLS_GIT_CFG): rm -rf $(MBED_TLS_DIR) From b85db484b01fdd74f92cf163bda7b9ecc98c96d9 Mon Sep 17 00:00:00 2001 From: itayzafrir Date: Tue, 20 Nov 2018 13:57:44 +0200 Subject: [PATCH 3/6] Update adjust-config.sh to enable persistent keys In adjust-config.h, set and unset Mbed Crypto storage configuration options in order to use persistent keys with PSA ITS storage. --- features/mbedtls/importer/adjust-config.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/features/mbedtls/importer/adjust-config.sh b/features/mbedtls/importer/adjust-config.sh index a4cfe005fc5..b42f6d1f611 100755 --- a/features/mbedtls/importer/adjust-config.sh +++ b/features/mbedtls/importer/adjust-config.sh @@ -140,3 +140,8 @@ conf unset MBEDTLS_SSL_TRUNCATED_HMAC conf unset MBEDTLS_PLATFORM_TIME_TYPE_MACRO +# The following configurations are a needed for Mbed Crypto submodule. +# They are related to the persistent key storage feature. +conf set MBEDTLS_PSA_CRYPTO_STORAGE_C +conf set MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C +conf unset MBEDTLS_PSA_CRYPTO_STORAGE_FILE_C From 1f4584fc702c9bb8e11039b93a0998c44172a8c0 Mon Sep 17 00:00:00 2001 From: Mohammad AboMokh Date: Thu, 15 Nov 2018 18:14:40 +0200 Subject: [PATCH 4/6] Add mbed_lib.json for Mbed Crypto --- .../mbedtls/mbed-crypto/platform/TARGET_PSA/mbed_lib.json | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/mbed_lib.json diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/mbed_lib.json b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/mbed_lib.json new file mode 100644 index 00000000000..2addde4c150 --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/mbed_lib.json @@ -0,0 +1,4 @@ +{ + "name": "mbed-crypto", + "macros": ["MBEDTLS_PSA_HAS_ITS_IO"] +} From 70f9497918c51aa15e72c4e2f721033c8db7bc85 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Fri, 23 Nov 2018 16:51:45 +0000 Subject: [PATCH 5/6] Mbed TLS importer: Call `config.pl --force` to accept unknown option The new PSA-aware Mbed TLS importer script calls `config.pl` on the Mbed TLS config.h to set the PSA configuration option MBEDTLS_PSA_CRYPTO_STORAGE_C which isn't documented in config.h. config.pl therefore fails, and so does the importer. This commit fixes this by calling `config.pl` with the `--force` option which amends the given `config.h` by a `#define` for the requested option if the option isn't present in the file. --- features/mbedtls/importer/adjust-config.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/mbedtls/importer/adjust-config.sh b/features/mbedtls/importer/adjust-config.sh index b42f6d1f611..d6cc758a73f 100755 --- a/features/mbedtls/importer/adjust-config.sh +++ b/features/mbedtls/importer/adjust-config.sh @@ -22,7 +22,7 @@ SCRIPT=$1 FILE=$2 conf() { - $SCRIPT -f $FILE $@ + $SCRIPT -f $FILE --force $@ } add_code() { From 3900b81d02eb0e8fcf3a511601d9907b8c31aea4 Mon Sep 17 00:00:00 2001 From: Jaeden Amero Date: Fri, 23 Nov 2018 18:02:14 +0000 Subject: [PATCH 6/6] Update Mbed TLS to mbedtls-2.15.0 --- features/mbedtls/VERSION.txt | 3 +- features/mbedtls/importer/Makefile | 2 +- features/mbedtls/inc/mbedtls/aes.h | 4 + features/mbedtls/inc/mbedtls/arc4.h | 1 + features/mbedtls/inc/mbedtls/aria.h | 5 + features/mbedtls/inc/mbedtls/asn1write.h | 310 +- features/mbedtls/inc/mbedtls/bignum.h | 61 +- features/mbedtls/inc/mbedtls/blowfish.h | 4 + features/mbedtls/inc/mbedtls/bn_mul.h | 22 +- features/mbedtls/inc/mbedtls/camellia.h | 3 + features/mbedtls/inc/mbedtls/ccm.h | 2 + features/mbedtls/inc/mbedtls/chacha20.h | 6 + features/mbedtls/inc/mbedtls/check_config.h | 20 + features/mbedtls/inc/mbedtls/cipher.h | 231 +- .../mbedtls/inc/mbedtls/cipher_internal.h | 28 + features/mbedtls/inc/mbedtls/cmac.h | 1 + features/mbedtls/inc/mbedtls/config.h | 94 +- features/mbedtls/inc/mbedtls/ctr_drbg.h | 15 +- features/mbedtls/inc/mbedtls/des.h | 2 + features/mbedtls/inc/mbedtls/dhm.h | 3 + features/mbedtls/inc/mbedtls/ecdh.h | 43 +- features/mbedtls/inc/mbedtls/ecdsa.h | 158 +- features/mbedtls/inc/mbedtls/ecp.h | 229 + features/mbedtls/inc/mbedtls/error.h | 7 +- features/mbedtls/inc/mbedtls/gcm.h | 14 +- features/mbedtls/inc/mbedtls/md.h | 2 + features/mbedtls/inc/mbedtls/md2.h | 1 + features/mbedtls/inc/mbedtls/md4.h | 1 + features/mbedtls/inc/mbedtls/md5.h | 1 + features/mbedtls/inc/mbedtls/pk.h | 158 +- features/mbedtls/inc/mbedtls/pk_internal.h | 27 + features/mbedtls/inc/mbedtls/platform.h | 3 + features/mbedtls/inc/mbedtls/poly1305.h | 6 + features/mbedtls/inc/mbedtls/psa_util.h | 264 + features/mbedtls/inc/mbedtls/ripemd160.h | 2 + features/mbedtls/inc/mbedtls/rsa.h | 47 +- features/mbedtls/inc/mbedtls/sha1.h | 1 + features/mbedtls/inc/mbedtls/sha256.h | 1 + features/mbedtls/inc/mbedtls/sha512.h | 1 + features/mbedtls/inc/mbedtls/ssl.h | 387 +- features/mbedtls/inc/mbedtls/ssl_internal.h | 26 +- features/mbedtls/inc/mbedtls/threading.h | 3 + features/mbedtls/inc/mbedtls/version.h | 10 +- features/mbedtls/inc/mbedtls/x509_crt.h | 100 + features/mbedtls/inc/mbedtls/xtea.h | 2 + features/mbedtls/inc/psa/crypto.h | 3479 +++++++++++++ features/mbedtls/inc/psa/crypto_driver.h | 1787 +++++++ features/mbedtls/inc/psa/crypto_extra.h | 128 + features/mbedtls/inc/psa/crypto_platform.h | 52 + features/mbedtls/inc/psa/crypto_sizes.h | 527 ++ .../COMPONENT_NSPE/crypto_struct.h | 211 + .../COMPONENT_PSA_SRV_IMPL/psa_crypto.c | 4479 +++++++++++++++++ .../psa_crypto_storage.c | 219 + .../psa_crypto_storage.h | 177 + .../psa_crypto_storage_backend.h | 112 + .../psa_crypto_storage_file.c | 218 + .../psa_crypto_storage_its.c | 184 + .../COMPONENT_SPE/crypto_struct_spe.h | 211 + features/mbedtls/src/Makefile | 16 +- features/mbedtls/src/aes.c | 13 +- features/mbedtls/src/asn1write.c | 31 +- features/mbedtls/src/bignum.c | 88 +- features/mbedtls/src/certs.c | 43 +- features/mbedtls/src/cipher.c | 418 +- features/mbedtls/src/cipher_wrap.c | 9 +- features/mbedtls/src/ctr_drbg.c | 63 + features/mbedtls/src/ecdh.c | 156 +- features/mbedtls/src/ecdsa.c | 500 +- features/mbedtls/src/ecp.c | 1009 +++- features/mbedtls/src/error.c | 15 + features/mbedtls/src/gcm.c | 5 +- features/mbedtls/src/pk.c | 240 +- features/mbedtls/src/pk_wrap.c | 537 +- features/mbedtls/src/pkparse.c | 36 +- features/mbedtls/src/pkwrite.c | 29 + features/mbedtls/src/platform.c | 13 +- features/mbedtls/src/rsa.c | 35 +- features/mbedtls/src/rsa_internal.c | 9 +- features/mbedtls/src/ssl_cli.c | 197 +- features/mbedtls/src/ssl_srv.c | 75 +- features/mbedtls/src/ssl_ticket.c | 82 +- features/mbedtls/src/ssl_tls.c | 577 ++- features/mbedtls/src/timing.c | 12 +- features/mbedtls/src/version_features.c | 9 + features/mbedtls/src/x509_create.c | 171 +- features/mbedtls/src/x509_crt.c | 699 ++- features/mbedtls/src/x509write_csr.c | 27 +- 87 files changed, 17924 insertions(+), 1285 deletions(-) create mode 100644 features/mbedtls/inc/mbedtls/psa_util.h create mode 100644 features/mbedtls/inc/psa/crypto.h create mode 100644 features/mbedtls/inc/psa/crypto_driver.h create mode 100644 features/mbedtls/inc/psa/crypto_extra.h create mode 100644 features/mbedtls/inc/psa/crypto_platform.h create mode 100644 features/mbedtls/inc/psa/crypto_sizes.h create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/COMPONENT_NSPE/crypto_struct.h create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto.c create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.c create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.h create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_backend.h create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_file.c create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_its.c create mode 100644 features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_SPE/crypto_struct_spe.h diff --git a/features/mbedtls/VERSION.txt b/features/mbedtls/VERSION.txt index e97cf88ec7a..31b45ded6e8 100644 --- a/features/mbedtls/VERSION.txt +++ b/features/mbedtls/VERSION.txt @@ -1 +1,2 @@ -mbedtls-2.13.1 +mbedtls-2.15.0 +mbedcrypto-0.1.0b diff --git a/features/mbedtls/importer/Makefile b/features/mbedtls/importer/Makefile index 5b7ef5e1cf4..1ae8af23800 100644 --- a/features/mbedtls/importer/Makefile +++ b/features/mbedtls/importer/Makefile @@ -27,7 +27,7 @@ # # Set the mbed TLS release to import (this can/should be edited before import) -MBED_TLS_RELEASE ?= mbedtls-2.13.1 +MBED_TLS_RELEASE ?= mbedtls-2.15.0 # Translate between mbed TLS namespace and mbed namespace TARGET_PREFIX:=../ diff --git a/features/mbedtls/inc/mbedtls/aes.h b/features/mbedtls/inc/mbedtls/aes.h index 4c8dab31519..cfb20c4fc00 100644 --- a/features/mbedtls/inc/mbedtls/aes.h +++ b/features/mbedtls/inc/mbedtls/aes.h @@ -60,7 +60,11 @@ /* Error codes in range 0x0021-0x0025 */ #define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ + +/* MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */ #define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ + +/* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ diff --git a/features/mbedtls/inc/mbedtls/arc4.h b/features/mbedtls/inc/mbedtls/arc4.h index 83a7461f3f2..c43f4065f13 100644 --- a/features/mbedtls/inc/mbedtls/arc4.h +++ b/features/mbedtls/inc/mbedtls/arc4.h @@ -36,6 +36,7 @@ #include +/* MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED -0x0019 /**< ARC4 hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/aria.h b/features/mbedtls/inc/mbedtls/aria.h index 4a79c13872e..483d4c2998f 100644 --- a/features/mbedtls/inc/mbedtls/aria.h +++ b/features/mbedtls/inc/mbedtls/aria.h @@ -48,7 +48,12 @@ #define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH -0x005C /**< Invalid key length. */ #define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ + +/* MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE is deprecated and should not be used. + */ #define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ + +/* MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ #if !defined(MBEDTLS_ARIA_ALT) diff --git a/features/mbedtls/inc/mbedtls/asn1write.h b/features/mbedtls/inc/mbedtls/asn1write.h index f76fc807d07..76c1780b595 100644 --- a/features/mbedtls/inc/mbedtls/asn1write.h +++ b/features/mbedtls/inc/mbedtls/asn1write.h @@ -26,191 +26,272 @@ #include "asn1.h" -#define MBEDTLS_ASN1_CHK_ADD(g, f) do { if( ( ret = f ) < 0 ) return( ret ); else \ - g += ret; } while( 0 ) +#define MBEDTLS_ASN1_CHK_ADD(g, f) \ + do { \ + if( ( ret = f ) < 0 ) \ + return( ret ); \ + else \ + g += ret; \ + } while( 0 ) #ifdef __cplusplus extern "C" { #endif /** - * \brief Write a length field in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a length field in ASN.1 format. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param len the length to write + * \note This function works backwards in data buffer. * - * \return the length written or a negative error code + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param len The length value to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ -int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len ); - +int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, + size_t len ); /** - * \brief Write a ASN.1 tag in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write an ASN.1 tag in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param tag the tag to write + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param tag The tag to write. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, - unsigned char tag ); + unsigned char tag ); /** - * \brief Write raw buffer data - * Note: function works backwards in data buffer + * \brief Write raw buffer data. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param buf data buffer to write - * \param size length of the data buffer + * \note This function works backwards in data buffer. * - * \return the length written or a negative error code + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The data buffer to write. + * \param size The length of the data buffer. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start, - const unsigned char *buf, size_t size ); + const unsigned char *buf, size_t size ); #if defined(MBEDTLS_BIGNUM_C) /** - * \brief Write a big number (MBEDTLS_ASN1_INTEGER) in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a arbitrary-precision number (#MBEDTLS_ASN1_INTEGER) + * in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param X the MPI to write + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param X The MPI to write. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ -int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, const mbedtls_mpi *X ); +int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, + const mbedtls_mpi *X ); #endif /* MBEDTLS_BIGNUM_C */ /** - * \brief Write a NULL tag (MBEDTLS_ASN1_NULL) with zero data in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a NULL tag (#MBEDTLS_ASN1_NULL) with zero data + * in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start ); /** - * \brief Write an OID tag (MBEDTLS_ASN1_OID) and data in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write an OID tag (#MBEDTLS_ASN1_OID) and data + * in ASN.1 format. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param oid the OID to write - * \param oid_len length of the OID + * \note This function works backwards in data buffer. * - * \return the length written or a negative error code + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param oid The OID to write. + * \param oid_len The length of the OID. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start, - const char *oid, size_t oid_len ); + const char *oid, size_t oid_len ); /** - * \brief Write an AlgorithmIdentifier sequence in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write an AlgorithmIdentifier sequence in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param oid the OID of the algorithm - * \param oid_len length of the OID - * \param par_len length of parameters, which must be already written. + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param oid The OID of the algorithm to write. + * \param oid_len The length of the algorithm's OID. + * \param par_len The length of the parameters, which must be already written. * If 0, NULL parameters are added * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ -int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, unsigned char *start, - const char *oid, size_t oid_len, - size_t par_len ); +int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, + unsigned char *start, + const char *oid, size_t oid_len, + size_t par_len ); /** - * \brief Write a boolean tag (MBEDTLS_ASN1_BOOLEAN) and value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value + * in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param boolean 0 or 1 + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param boolean The boolean value to write, either \c 0 or \c 1. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ -int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, int boolean ); +int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, + int boolean ); /** - * \brief Write an int tag (MBEDTLS_ASN1_INTEGER) and value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write an int tag (#MBEDTLS_ASN1_INTEGER) and value + * in ASN.1 format. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param val the integer value + * \note This function works backwards in data buffer. * - * \return the length written or a negative error code + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param val The integer value to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. */ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val ); /** - * \brief Write a printable string tag (MBEDTLS_ASN1_PRINTABLE_STRING) and - * value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a string in ASN.1 format using a specific + * string encoding tag. + + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param tag The string encoding tag to write, e.g. + * #MBEDTLS_ASN1_UTF8_STRING. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start, + int tag, const char *text, + size_t text_len ); + +/** + * \brief Write a string in ASN.1 format using the PrintableString + * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING). + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_printable_string( unsigned char **p, + unsigned char *start, + const char *text, size_t text_len ); + +/** + * \brief Write a UTF8 string in ASN.1 format using the UTF8String + * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING). + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param text the text to write - * \param text_len length of the text + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. */ -int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start, - const char *text, size_t text_len ); +int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ); /** - * \brief Write an IA5 string tag (MBEDTLS_ASN1_IA5_STRING) and - * value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a string in ASN.1 format using the IA5String + * string encoding tag (#MBEDTLS_ASN1_IA5_STRING). * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param text the text to write - * \param text_len length of the text + * \note This function works backwards in data buffer. * - * \return the length written or a negative error code + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. */ int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start, - const char *text, size_t text_len ); + const char *text, size_t text_len ); /** - * \brief Write a bitstring tag (MBEDTLS_ASN1_BIT_STRING) and - * value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and + * value in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param buf the bitstring - * \param bits the total number of bits in the bitstring + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The bitstring to write. + * \param bits The total number of bits in the bitstring. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. */ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start, - const unsigned char *buf, size_t bits ); + const unsigned char *buf, size_t bits ); /** - * \brief Write an octet string tag (MBEDTLS_ASN1_OCTET_STRING) and - * value in ASN.1 format - * Note: function works backwards in data buffer + * \brief Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING) + * and value in ASN.1 format. + * + * \note This function works backwards in data buffer. * - * \param p reference to current position pointer - * \param start start of the buffer (for bounds-checking) - * \param buf data buffer to write - * \param size length of the data buffer + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The buffer holding the data to write. + * \param size The length of the data buffer \p buf. * - * \return the length written or a negative error code + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. */ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start, - const unsigned char *buf, size_t size ); + const unsigned char *buf, size_t size ); /** * \brief Create or find a specific named_data entry for writing in a @@ -218,15 +299,16 @@ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start, * a new entry is added to the head of the list. * Warning: Destructive behaviour for the val data! * - * \param list Pointer to the location of the head of the list to seek - * through (will be updated in case of a new entry) - * \param oid The OID to look for - * \param oid_len Size of the OID - * \param val Data to store (can be NULL if you want to fill it by hand) - * \param val_len Minimum length of the data buffer needed + * \param list The pointer to the location of the head of the list to seek + * through (will be updated in case of a new entry). + * \param oid The OID to look for. + * \param oid_len The size of the OID. + * \param val The data to store (can be \c NULL if you want to fill + * it by hand). + * \param val_len The minimum length of the data buffer needed. * - * \return NULL if if there was a memory allocation error, or a pointer - * to the new / existing entry. + * \return A pointer to the new / existing entry on success. + * \return \c NULL if if there was a memory allocation error. */ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **list, const char *oid, size_t oid_len, diff --git a/features/mbedtls/inc/mbedtls/bignum.h b/features/mbedtls/inc/mbedtls/bignum.h index 732ecbef1cf..40cfab49af3 100644 --- a/features/mbedtls/inc/mbedtls/bignum.h +++ b/features/mbedtls/inc/mbedtls/bignum.h @@ -725,10 +725,49 @@ int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B */ int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N ); +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Miller-Rabin primality test with error probability of + * 2-80 + * + * \deprecated Superseded by mbedtls_mpi_is_prime_ext() which allows + * specifying the number of Miller-Rabin rounds. + * + * \param X MPI to check + * \param f_rng RNG function + * \param p_rng RNG parameter + * + * \return 0 if successful (probably prime), + * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, + * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if X is not prime + */ +MBEDTLS_DEPRECATED int mbedtls_mpi_is_prime( const mbedtls_mpi *X, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + /** - * \brief Miller-Rabin primality test + * \brief Miller-Rabin primality test. + * + * \warning If \p X is potentially generated by an adversary, for example + * when validating cryptographic parameters that you didn't + * generate yourself and that are supposed to be prime, then + * \p rounds should be at least the half of the security + * strength of the cryptographic algorithm. On the other hand, + * if \p X is chosen uniformly or non-adversially (as is the + * case when mbedtls_mpi_gen_prime calls this function), then + * \p rounds can be much lower. * * \param X MPI to check + * \param rounds Number of bases to perform Miller-Rabin primality test for. + * The probability of returning 0 on a composite is at most + * 2-2*\p rounds. * \param f_rng RNG function * \param p_rng RNG parameter * @@ -736,9 +775,19 @@ int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if X is not prime */ -int mbedtls_mpi_is_prime( const mbedtls_mpi *X, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ); +int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +/** + * \brief Flags for mbedtls_mpi_gen_prime() + * + * Each of these flags is a constraint on the result X returned by + * mbedtls_mpi_gen_prime(). + */ +typedef enum { + MBEDTLS_MPI_GEN_PRIME_FLAG_DH = 0x0001, /**< (X-1)/2 is prime too */ + MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2-80 to 2-128 */ +} mbedtls_mpi_gen_prime_flag_t; /** * \brief Prime number generation @@ -746,7 +795,7 @@ int mbedtls_mpi_is_prime( const mbedtls_mpi *X, * \param X Destination MPI * \param nbits Required size of X in bits * ( 3 <= nbits <= MBEDTLS_MPI_MAX_BITS ) - * \param dh_flag If 1, then (X-1)/2 will be prime too + * \param flags Mask of flags of type #mbedtls_mpi_gen_prime_flag_t * \param f_rng RNG function * \param p_rng RNG parameter * @@ -754,7 +803,7 @@ int mbedtls_mpi_is_prime( const mbedtls_mpi *X, * MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_MPI_BAD_INPUT_DATA if nbits is < 3 */ -int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, +int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); diff --git a/features/mbedtls/inc/mbedtls/blowfish.h b/features/mbedtls/inc/mbedtls/blowfish.h index eea6882f75d..82b772ada53 100644 --- a/features/mbedtls/inc/mbedtls/blowfish.h +++ b/features/mbedtls/inc/mbedtls/blowfish.h @@ -41,7 +41,11 @@ #define MBEDTLS_BLOWFISH_BLOCKSIZE 8 /* Blowfish uses 64 bit blocks */ #define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH -0x0016 /**< Invalid key length. */ + +/* MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED is deprecated and should not be used. + */ #define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED -0x0017 /**< Blowfish hardware accelerator failed. */ + #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/bn_mul.h b/features/mbedtls/inc/mbedtls/bn_mul.h index b587317d959..0af694c7c5e 100644 --- a/features/mbedtls/inc/mbedtls/bn_mul.h +++ b/features/mbedtls/inc/mbedtls/bn_mul.h @@ -565,9 +565,8 @@ #endif /* TriCore */ /* - * gcc -O0 by default uses r7 for the frame pointer, so it complains about our - * use of r7 below, unless -fomit-frame-pointer is passed. Unfortunately, - * passing that option is not easy when building with yotta. + * Note, gcc -O0 by default uses r7 for the frame pointer, so it complains about + * our use of r7 below, unless -fomit-frame-pointer is passed. * * On the other hand, -fomit-frame-pointer is implied by any -Ox options with * x !=0, which we can detect using __OPTIMIZE__ (which is also defined by @@ -637,6 +636,23 @@ "r6", "r7", "r8", "r9", "cc" \ ); +#elif defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1) + +#define MULADDC_INIT \ + asm( + +#define MULADDC_CORE \ + "ldr r0, [%0], #4 \n\t" \ + "ldr r1, [%1] \n\t" \ + "umaal r1, %2, %3, r0 \n\t" \ + "str r1, [%1], #4 \n\t" + +#define MULADDC_STOP \ + : "=r" (s), "=r" (d), "=r" (c) \ + : "r" (b), "0" (s), "1" (d), "2" (c) \ + : "r0", "r1", "memory" \ + ); + #else #define MULADDC_INIT \ diff --git a/features/mbedtls/inc/mbedtls/camellia.h b/features/mbedtls/inc/mbedtls/camellia.h index fa1e05ee7fb..1555867cffb 100644 --- a/features/mbedtls/inc/mbedtls/camellia.h +++ b/features/mbedtls/inc/mbedtls/camellia.h @@ -38,6 +38,9 @@ #define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH -0x0024 /**< Invalid key length. */ #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */ + +/* MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED is deprecated and should not be used. + */ #define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/ccm.h b/features/mbedtls/inc/mbedtls/ccm.h index e1dc124b89f..dfb1b5e566b 100644 --- a/features/mbedtls/inc/mbedtls/ccm.h +++ b/features/mbedtls/inc/mbedtls/ccm.h @@ -53,6 +53,8 @@ #define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to the function. */ #define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ + +/* MBEDTLS_ERR_CCM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */ diff --git a/features/mbedtls/inc/mbedtls/chacha20.h b/features/mbedtls/inc/mbedtls/chacha20.h index cfea40a5740..529f22d9c95 100644 --- a/features/mbedtls/inc/mbedtls/chacha20.h +++ b/features/mbedtls/inc/mbedtls/chacha20.h @@ -43,7 +43,13 @@ #include #define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */ + +/* MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ #define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */ + +/* MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED is deprecated and should not be used. + */ #define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/check_config.h b/features/mbedtls/inc/mbedtls/check_config.h index 9e6bb8a46aa..0a6f4bf505b 100644 --- a/features/mbedtls/inc/mbedtls/check_config.h +++ b/features/mbedtls/inc/mbedtls/check_config.h @@ -108,6 +108,16 @@ #error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_ECP_RESTARTABLE) && \ + ( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \ + defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \ + defined(MBEDTLS_ECDSA_SIGN_ALT) || \ + defined(MBEDTLS_ECDSA_VERIFY_ALT) || \ + defined(MBEDTLS_ECDSA_GENKEY_ALT) || \ + defined(MBEDTLS_ECP_ALT) ) +#error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative ECP implementation" +#endif + #if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C) #error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites" #endif @@ -486,6 +496,12 @@ #error "MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously" #endif +#if defined(MBEDTLS_PSA_CRYPTO_C) && \ + !( defined(MBEDTLS_CTR_DRBG_C) && \ + defined(MBEDTLS_ENTROPY_C) ) +#error "MBEDTLS_PSA_CRYPTO_C defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ !defined(MBEDTLS_OID_C) ) #error "MBEDTLS_RSA_C defined, but not all prerequisites" @@ -628,6 +644,10 @@ #endif #undef MBEDTLS_THREADING_IMPL +#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_PSA_CRYPTO_C) +#error "MBEDTLS_USE_PSA_CRYPTO defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C) #error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites" #endif diff --git a/features/mbedtls/inc/mbedtls/cipher.h b/features/mbedtls/inc/mbedtls/cipher.h index dfb1541103c..d6ecac65204 100644 --- a/features/mbedtls/inc/mbedtls/cipher.h +++ b/features/mbedtls/inc/mbedtls/cipher.h @@ -62,6 +62,8 @@ #define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280 /**< Decryption of block requires a full block. */ #define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300 /**< Authentication failed (for AEAD modes). */ #define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380 /**< The context is invalid. For example, because it was freed. */ + +/* MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED -0x6400 /**< Cipher hardware accelerator failed. */ #define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /**< Cipher accepts IVs of variable length. */ @@ -177,16 +179,16 @@ typedef enum { /** Supported cipher modes. */ typedef enum { - MBEDTLS_MODE_NONE = 0, /**< None. */ - MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ - MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ - MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ - MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */ - MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ - MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ - MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ - MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ - MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */ + MBEDTLS_MODE_NONE = 0, /**< None. */ + MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ + MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ + MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ + MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */ + MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ + MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ + MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ + MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ + MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */ MBEDTLS_MODE_CHACHAPOLY, /**< The ChaCha-Poly cipher mode. */ } mbedtls_cipher_mode_t; @@ -319,14 +321,32 @@ typedef struct mbedtls_cipher_context_t /** CMAC-specific context. */ mbedtls_cmac_context_t *cmac_ctx; #endif + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /** Indicates whether the cipher operations should be performed + * by Mbed TLS' own crypto library or an external implementation + * of the PSA Crypto API. + * This is unset if the cipher context was established through + * mbedtls_cipher_setup(), and set if it was established through + * mbedtls_cipher_setup_psa(). + */ + unsigned char psa_enabled; +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + } mbedtls_cipher_context_t; /** - * \brief This function retrieves the list of ciphers supported by the generic - * cipher module. + * \brief This function retrieves the list of ciphers supported + * by the generic cipher module. * - * \return A statically-allocated array of ciphers. The last entry - * is zero. + * For any cipher identifier in the returned list, you can + * obtain the corresponding generic cipher information structure + * via mbedtls_cipher_info_from_type(), which can then be used + * to prepare a cipher context via mbedtls_cipher_setup(). + * + * + * \return A statically-allocated array of cipher identifiers + * of type cipher_type_t. The last entry is zero. */ const int *mbedtls_cipher_list( void ); @@ -386,9 +406,8 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); /** - * \brief This function initializes and fills the cipher-context - * structure with the appropriate values. It also clears - * the structure. + * \brief This function initializes a cipher context for + * use with the given cipher primitive. * * \param ctx The context to initialize. May not be NULL. * \param cipher_info The cipher to use. @@ -403,7 +422,35 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); * In future versions, the caller will be required to call * mbedtls_cipher_init() on the structure first. */ -int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ); +int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, + const mbedtls_cipher_info_t *cipher_info ); + +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * \brief This function initializes a cipher context for + * PSA-based use with the given cipher primitive. + * + * \note See #MBEDTLS_USE_PSA_CRYPTO for information on PSA. + * + * \param ctx The context to initialize. May not be \c NULL. + * \param cipher_info The cipher to use. + * \param taglen For AEAD ciphers, the length in bytes of the + * authentication tag to use. Subsequent uses of + * mbedtls_cipher_auth_encrypt() or + * mbedtls_cipher_auth_decrypt() must provide + * the same tag length. + * For non-AEAD ciphers, the value must be \c 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the + * cipher-specific context fails. + */ +int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx, + const mbedtls_cipher_info_t *cipher_info, + size_t taglen ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ /** * \brief This function returns the block size of the given cipher. @@ -413,7 +460,8 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_in * \return The size of the blocks of the cipher. * \return 0 if \p ctx has not been initialized. */ -static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx ) +static inline unsigned int mbedtls_cipher_get_block_size( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return 0; @@ -430,7 +478,8 @@ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_c * \return The mode of operation. * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized. */ -static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx ) +static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return MBEDTLS_MODE_NONE; @@ -448,7 +497,8 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtl * \return \c 0 for ciphers not using an IV or a nonce. * \return The actual size if an IV has been set. */ -static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx ) +static inline int mbedtls_cipher_get_iv_size( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return 0; @@ -467,7 +517,8 @@ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ct * \return The type of the cipher. * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized. */ -static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx ) +static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return MBEDTLS_CIPHER_NONE; @@ -484,7 +535,8 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_ciphe * \return The name of the cipher. * \return NULL if \p ctx has not been not initialized. */ -static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx ) +static inline const char *mbedtls_cipher_get_name( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return 0; @@ -501,7 +553,8 @@ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_ * \return #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been * initialized. */ -static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx ) +static inline int mbedtls_cipher_get_key_bitlen( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return MBEDTLS_KEY_LENGTH_NONE; @@ -517,7 +570,8 @@ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized. */ -static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx ) +static inline mbedtls_operation_t mbedtls_cipher_get_operation( + const mbedtls_cipher_context_t *ctx ) { if( NULL == ctx || NULL == ctx->cipher_info ) return MBEDTLS_OPERATION_NONE; @@ -541,8 +595,10 @@ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_ci * parameter-verification failure. * \return A cipher-specific error code on failure. */ -int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, - int key_bitlen, const mbedtls_operation_t operation ); +int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, + const unsigned char *key, + int key_bitlen, + const mbedtls_operation_t operation ); #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) /** @@ -560,7 +616,8 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode * does not support padding. */ -int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ); +int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, + mbedtls_cipher_padding_t mode ); #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ /** @@ -580,7 +637,7 @@ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_ciph * parameter-verification failure. */ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, - const unsigned char *iv, size_t iv_len ); + const unsigned char *iv, size_t iv_len ); /** * \brief This function resets the cipher state. @@ -595,16 +652,16 @@ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** - * \brief This function adds additional data for AEAD ciphers. - * Currently supported with GCM and ChaCha20+Poly1305. - * Must be called exactly once, after mbedtls_cipher_reset(). + * \brief This function adds additional data for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. + * Must be called exactly once, after mbedtls_cipher_reset(). * - * \param ctx The generic cipher context. - * \param ad The additional data to use. - * \param ad_len the Length of \p ad. + * \param ctx The generic cipher context. + * \param ad The additional data to use. + * \param ad_len the Length of \p ad. * - * \return \c 0 on success. - * \return A specific error code on failure. + * \return \c 0 on success. + * \return A specific error code on failure. */ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ); @@ -641,8 +698,10 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, * unsupported mode for a cipher. * \return A cipher-specific error code on failure. */ -int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, - size_t ilen, unsigned char *output, size_t *olen ); +int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, + const unsigned char *input, + size_t ilen, unsigned char *output, + size_t *olen ); /** * \brief The generic cipher finalization function. If data still @@ -734,27 +793,27 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, #if defined(MBEDTLS_CIPHER_MODE_AEAD) /** - * \brief The generic autenticated encryption (AEAD) function. - * - * \param ctx The generic cipher context. - * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. - * \param iv_len The IV length for ciphers with variable-size IV. - * This parameter is discarded by ciphers with fixed-size IV. - * \param ad The additional data to authenticate. - * \param ad_len The length of \p ad. - * \param input The buffer holding the input data. - * \param ilen The length of the input data. - * \param output The buffer for the output data. - * Must be able to hold at least \p ilen. - * \param olen The length of the output data, to be updated with the - * actual number of Bytes written. - * \param tag The buffer for the authentication tag. - * \param tag_len The desired length of the authentication tag. - * - * \return \c 0 on success. - * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on - * parameter-verification failure. - * \return A cipher-specific error code on failure. + * \brief The generic autenticated encryption (AEAD) function. + * + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to authenticate. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. + * Must be able to hold at least \p ilen. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * \param tag The buffer for the authentication tag. + * \param tag_len The desired length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, @@ -764,32 +823,32 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, unsigned char *tag, size_t tag_len ); /** - * \brief The generic autenticated decryption (AEAD) function. - * - * \note If the data is not authentic, then the output buffer - * is zeroed out to prevent the unauthentic plaintext being - * used, making this interface safer. - * - * \param ctx The generic cipher context. - * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. - * \param iv_len The IV length for ciphers with variable-size IV. - * This parameter is discarded by ciphers with fixed-size IV. - * \param ad The additional data to be authenticated. - * \param ad_len The length of \p ad. - * \param input The buffer holding the input data. - * \param ilen The length of the input data. - * \param output The buffer for the output data. - * Must be able to hold at least \p ilen. - * \param olen The length of the output data, to be updated with the - * actual number of Bytes written. - * \param tag The buffer holding the authentication tag. - * \param tag_len The length of the authentication tag. - * - * \return \c 0 on success. - * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on - * parameter-verification failure. - * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. - * \return A cipher-specific error code on failure. + * \brief The generic autenticated decryption (AEAD) function. + * + * \note If the data is not authentic, then the output buffer + * is zeroed out to prevent the unauthentic plaintext being + * used, making this interface safer. + * + * \param ctx The generic cipher context. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to be authenticated. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the output data. + * Must be able to hold at least \p ilen. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. + * \param tag The buffer holding the authentication tag. + * \param tag_len The length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. + * \return A cipher-specific error code on failure. */ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len, diff --git a/features/mbedtls/inc/mbedtls/cipher_internal.h b/features/mbedtls/inc/mbedtls/cipher_internal.h index c6def0bef75..6687b362de4 100644 --- a/features/mbedtls/inc/mbedtls/cipher_internal.h +++ b/features/mbedtls/inc/mbedtls/cipher_internal.h @@ -34,6 +34,10 @@ #include "cipher.h" +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #ifdef __cplusplus extern "C" { #endif @@ -114,6 +118,30 @@ typedef struct const mbedtls_cipher_info_t *info; } mbedtls_cipher_definition_t; +#if defined(MBEDTLS_USE_PSA_CRYPTO) +typedef enum +{ + MBEDTLS_CIPHER_PSA_KEY_UNSET = 0, + MBEDTLS_CIPHER_PSA_KEY_OWNED, /* Used for PSA-based cipher contexts which */ + /* use raw key material internally imported */ + /* into a allocated key slot, and which */ + /* hence need to destroy that key slot */ + /* when they are no longer needed. */ + MBEDTLS_CIPHER_PSA_KEY_NOT_OWNED, /* Used for PSA-based cipher contexts */ + /* which use a key from a key slot */ + /* provided by the user, and which */ + /* hence should not be destroyed when */ + /* the context is no longer needed. */ +} mbedtls_cipher_psa_key_ownership; + +typedef struct +{ + psa_algorithm_t alg; + psa_key_slot_t slot; + mbedtls_cipher_psa_key_ownership slot_state; +} mbedtls_cipher_context_psa; +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + extern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[]; extern int mbedtls_cipher_supported[]; diff --git a/features/mbedtls/inc/mbedtls/cmac.h b/features/mbedtls/inc/mbedtls/cmac.h index a4fd5525655..c1967935319 100644 --- a/features/mbedtls/inc/mbedtls/cmac.h +++ b/features/mbedtls/inc/mbedtls/cmac.h @@ -34,6 +34,7 @@ extern "C" { #endif +/* MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A /**< CMAC hardware accelerator failed. */ #define MBEDTLS_AES_BLOCK_SIZE 16 diff --git a/features/mbedtls/inc/mbedtls/config.h b/features/mbedtls/inc/mbedtls/config.h index 5d1d5686cfa..b7e64705025 100644 --- a/features/mbedtls/inc/mbedtls/config.h +++ b/features/mbedtls/inc/mbedtls/config.h @@ -34,7 +34,8 @@ * Only use features that do not require an entropy source when * DEVICE_ENTROPY_SOURCE is not defined in mbed OS. */ -#if !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) && !defined(MBEDTLS_TEST_NULL_ENTROPY) +#if !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) && !defined(MBEDTLS_TEST_NULL_ENTROPY) && \ + !defined(MBEDTLS_ENTROPY_NV_SEED) #include "mbedtls/config-no-entropy.h" #if defined(MBEDTLS_USER_CONFIG_FILE) @@ -692,6 +693,30 @@ */ #define MBEDTLS_ECP_NIST_OPTIM +/** + * \def MBEDTLS_ECP_RESTARTABLE + * + * Enable "non-blocking" ECC operations that can return early and be resumed. + * + * This allows various functions to pause by returning + * #MBEDTLS_ERR_ECP_IN_PROGRESS (or, for functions in the SSL module, + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) and then be called later again in + * order to further progress and eventually complete their operation. This is + * controlled through mbedtls_ecp_set_max_ops() which limits the maximum + * number of ECC operations a function may perform before pausing; see + * mbedtls_ecp_set_max_ops() for more information. + * + * This is useful in non-threaded environments if you want to avoid blocking + * for too long on ECC (and, hence, X.509 or SSL/TLS) operations. + * + * Uncomment this macro to enable restartable ECC computations. + * + * \note This option only works with the default software implementation of + * elliptic curve functionality. It is incompatible with + * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT and MBEDTLS_ECDSA_XXX_ALT. + */ +//#define MBEDTLS_ECP_RESTARTABLE + /** * \def MBEDTLS_ECDSA_DETERMINISTIC * @@ -1303,7 +1328,7 @@ /** * \def MBEDTLS_SSL_RENEGOTIATION * - * Disable support for TLS renegotiation. + * Enable support for TLS renegotiation. * * The two main uses of renegotiation are (1) refresh keys on long-lived * connections and (2) client authentication after the initial handshake. @@ -1573,6 +1598,24 @@ */ //#define MBEDTLS_THREADING_PTHREAD +/** + * \def MBEDTLS_USE_PSA_CRYPTO + * + * Make the X.509 and TLS library use PSA for cryptographic operations, see + * #MBEDTLS_PSA_CRYPTO_C. + * + * Note: this option is still in progress, the full X.509 and TLS modules are + * not covered yet, but parts that are not ported to PSA yet will still work + * as usual, so enabling this option should not break backwards compatibility. + * + * \warning Support for PSA is still an experimental feature. + * Any public API that depends on this option may change + * at any time until this warning is removed. + * + * Requires: MBEDTLS_PSA_CRYPTO_C. + */ +//#define MBEDTLS_USE_PSA_CRYPTO + /** * \def MBEDTLS_VERSION_FEATURES * @@ -2042,14 +2085,16 @@ /** * \def MBEDTLS_CTR_DRBG_C * - * Enable the CTR_DRBG AES-256-based random generator. + * Enable the CTR_DRBG AES-based random generator. + * The CTR_DRBG generator uses AES-256 by default. + * To use AES-128 instead, enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY below. * * Module: library/ctr_drbg.c * Caller: * * Requires: MBEDTLS_AES_C * - * This module provides the CTR_DRBG AES-256 random number generator. + * This module provides the CTR_DRBG AES random number generator. */ #define MBEDTLS_CTR_DRBG_C @@ -2579,6 +2624,25 @@ */ #define MBEDTLS_POLY1305_C +/** + * \def MBEDTLS_PSA_CRYPTO_C + * + * Enable the Platform Security Architecture cryptography API. + * + * \note This option only has an effect when the build option + * USE_CRYPTO_SUBMODULE is also in use. + * + * \warning This feature is experimental and available on an opt-in basis only. + * PSA APIs are subject to change at any time. The implementation comes with + * less assurance and support than the rest of Mbed TLS. + * + * Module: crypto/library/psa_crypto.c + * + * Requires: MBEDTLS_CTR_DRBG_C, MBEDTLS_ENTROPY_C + * + */ +//#define MBEDTLS_PSA_CRYPTO_C + /** * \def MBEDTLS_RIPEMD160_C * @@ -2934,6 +2998,7 @@ //#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ //#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ //#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ +//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY /**< Use 128-bit key for CTR_DRBG - may reduce security (see ctr_drbg.h) */ /* HMAC_DRBG options */ //#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ @@ -3145,29 +3210,18 @@ /* \} name SECTION: Customisation configuration options */ -/* Target and application specific configurations */ -//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "target_config.h" - -#if defined(TARGET_LIKE_MBED) && defined(YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE) -#include YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE -#endif - -/* +/* Target and application specific configurations + * * Allow user to override any previous default. * - * Use two macro names for that, as: - * - with yotta the prefix YOTTA_CFG_ is forced - * - without yotta is looks weird to have a YOTTA prefix. */ -#if defined(YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE) -#include YOTTA_CFG_MBEDTLS_USER_CONFIG_FILE -#elif defined(MBEDTLS_USER_CONFIG_FILE) +#if defined(MBEDTLS_USER_CONFIG_FILE) #include MBEDTLS_USER_CONFIG_FILE #endif #include "check_config.h" -#endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_TEST_NULL_ENTROPY */ +#endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_TEST_NULL_ENTROPY && !MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_TEST_NULL_ENTROPY) #warning "MBEDTLS_TEST_NULL_ENTROPY has been enabled. This " \ @@ -3181,3 +3235,5 @@ #endif #endif /* MBEDTLS_CONFIG_H */ +#define MBEDTLS_PSA_CRYPTO_STORAGE_C +#define MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C diff --git a/features/mbedtls/inc/mbedtls/ctr_drbg.h b/features/mbedtls/inc/mbedtls/ctr_drbg.h index 3a4b7f3f13d..c91ca58b359 100644 --- a/features/mbedtls/inc/mbedtls/ctr_drbg.h +++ b/features/mbedtls/inc/mbedtls/ctr_drbg.h @@ -8,8 +8,11 @@ * Recommendation for Random Number Generation Using Deterministic Random * Bit Generators. * - * The Mbed TLS implementation of CTR_DRBG uses AES-256 as the underlying - * block cipher. + * The Mbed TLS implementation of CTR_DRBG uses AES-256 (default) or AES-128 + * as the underlying block cipher. + * + * \warning Using 128-bit keys for CTR_DRBG limits the security of generated + * keys and operations that use random values generated to 128-bit security. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -45,7 +48,13 @@ #define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read or write error in file. */ #define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */ -#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< The key size used by the cipher. */ + +#if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) +#define MBEDTLS_CTR_DRBG_KEYSIZE 16 /**< The key size used by the cipher (compile-time choice: 128 bits). */ +#else +#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< The key size used by the cipher (compile-time choice: 256 bits). */ +#endif + #define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */ #define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */ diff --git a/features/mbedtls/inc/mbedtls/des.h b/features/mbedtls/inc/mbedtls/des.h index 91d16b6fb48..d62042d14ef 100644 --- a/features/mbedtls/inc/mbedtls/des.h +++ b/features/mbedtls/inc/mbedtls/des.h @@ -42,6 +42,8 @@ #define MBEDTLS_DES_DECRYPT 0 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032 /**< The data input has an invalid length. */ + +/* MBEDTLS_ERR_DES_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_DES_HW_ACCEL_FAILED -0x0033 /**< DES hardware accelerator failed. */ #define MBEDTLS_DES_KEY_SIZE 8 diff --git a/features/mbedtls/inc/mbedtls/dhm.h b/features/mbedtls/inc/mbedtls/dhm.h index 3e1178940a4..8e2d0208d4d 100644 --- a/features/mbedtls/inc/mbedtls/dhm.h +++ b/features/mbedtls/inc/mbedtls/dhm.h @@ -84,7 +84,10 @@ #define MBEDTLS_ERR_DHM_INVALID_FORMAT -0x3380 /**< The ASN.1 data is not formatted correctly. */ #define MBEDTLS_ERR_DHM_ALLOC_FAILED -0x3400 /**< Allocation of memory failed. */ #define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480 /**< Read or write of file failed. */ + +/* MBEDTLS_ERR_DHM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED -0x3500 /**< DHM hardware accelerator failed. */ + #define MBEDTLS_ERR_DHM_SET_GROUP_FAILED -0x3580 /**< Setting the modulus and generator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/ecdh.h b/features/mbedtls/inc/mbedtls/ecdh.h index 95f39805c6d..27f2ffc6aa7 100644 --- a/features/mbedtls/inc/mbedtls/ecdh.h +++ b/features/mbedtls/inc/mbedtls/ecdh.h @@ -50,6 +50,10 @@ typedef enum } mbedtls_ecdh_side; /** + * + * \warning Performing multiple operations concurrently on the same + * ECDSA context is not supported; objects of this type + * should not be shared between multiple threads. * \brief The ECDH context structure. */ typedef struct mbedtls_ecdh_context @@ -63,6 +67,10 @@ typedef struct mbedtls_ecdh_context mbedtls_ecp_point Vi; /*!< The blinding value. */ mbedtls_ecp_point Vf; /*!< The unblinding value. */ mbedtls_mpi _d; /*!< The previous \p d. */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + int restart_enabled; /*!< The flag for restartable mode. */ + mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */ +#endif } mbedtls_ecdh_context; @@ -83,9 +91,8 @@ mbedtls_ecdh_context; * \param p_rng The RNG context. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX or + * \return Another \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. - * */ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), @@ -112,7 +119,7 @@ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp * \param p_rng The RNG context. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX or + * \return Another \c MBEDTLS_ERR_ECP_XXX or * \c MBEDTLS_MPI_XXX error code on failure. */ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, @@ -155,7 +162,9 @@ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ); * \param p_rng The RNG context. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -197,7 +206,7 @@ int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, * 0: The key of the peer. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. * */ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key, @@ -220,7 +229,9 @@ int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypai * \param p_rng The RNG context. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, @@ -266,13 +277,31 @@ int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, * \param p_rng The RNG context. * * \return \c 0 on success. - * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. */ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief This function enables restartable EC computations for this + * context. (Default: disabled.) + * + * \see \c mbedtls_ecp_set_max_ops() + * + * \note It is not possible to safely disable restartable + * computations once enabled, except by free-ing the context, + * which cancels possible in-progress operations. + * + * \param ctx The ECDH context. + */ +void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + #ifdef __cplusplus } #endif diff --git a/features/mbedtls/inc/mbedtls/ecdsa.h b/features/mbedtls/inc/mbedtls/ecdsa.h index ce1a03d7913..5245c6ee36f 100644 --- a/features/mbedtls/inc/mbedtls/ecdsa.h +++ b/features/mbedtls/inc/mbedtls/ecdsa.h @@ -35,34 +35,89 @@ #include "ecp.h" #include "md.h" -/* - * RFC-4492 page 20: +/** + * \brief Maximum ECDSA signature size for a given curve bit size + * + * \param bits Curve size in bits + * \return Maximum signature size in bytes * + * \note This macro returns a compile-time constant if its argument + * is one. It may evaluate its argument multiple times. + */ +/* * Ecdsa-Sig-Value ::= SEQUENCE { * r INTEGER, * s INTEGER * } * - * Size is at most - * 1 (tag) + 1 (len) + 1 (initial 0) + ECP_MAX_BYTES for each of r and s, - * twice that + 1 (tag) + 2 (len) for the sequence - * (assuming ECP_MAX_BYTES is less than 126 for r and s, - * and less than 124 (total len <= 255) for the sequence) + * For each of r and s, the value (V) may include an extra initial "0" bit. */ -#if MBEDTLS_ECP_MAX_BYTES > 124 -#error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN" -#endif +#define MBEDTLS_ECDSA_MAX_SIG_LEN( bits ) \ + ( /*T,L of SEQUENCE*/ ( ( bits ) >= 61 * 8 ? 3 : 2 ) + \ + /*T,L of r,s*/ 2 * ( ( ( bits ) >= 127 * 8 ? 3 : 2 ) + \ + /*V of r,s*/ ( ( bits ) + 8 ) / 8 ) ) + /** The maximal size of an ECDSA signature in Bytes. */ -#define MBEDTLS_ECDSA_MAX_LEN ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) ) +#define MBEDTLS_ECDSA_MAX_LEN MBEDTLS_ECDSA_MAX_SIG_LEN( MBEDTLS_ECP_MAX_BITS ) + +#ifdef __cplusplus +extern "C" { +#endif /** * \brief The ECDSA context structure. + * + * \warning Performing multiple operations concurrently on the same + * ECDSA context is not supported; objects of this type + * should not be shared between multiple threads. */ typedef mbedtls_ecp_keypair mbedtls_ecdsa_context; -#ifdef __cplusplus -extern "C" { +#if defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Internal restart context for ecdsa_verify() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_ver mbedtls_ecdsa_restart_ver_ctx; + +/** + * \brief Internal restart context for ecdsa_sign() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_sig mbedtls_ecdsa_restart_sig_ctx; + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) +/** + * \brief Internal restart context for ecdsa_sign_det() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_det mbedtls_ecdsa_restart_det_ctx; +#endif + +/** + * \brief General context for resuming ECDSA operations + */ +typedef struct +{ + mbedtls_ecp_restart_ctx ecp; /*!< base context for ECP restart and + shared administrative info */ + mbedtls_ecdsa_restart_ver_ctx *ver; /*!< ecdsa_verify() sub-context */ + mbedtls_ecdsa_restart_sig_ctx *sig; /*!< ecdsa_sign() sub-context */ +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + mbedtls_ecdsa_restart_det_ctx *det; /*!< ecdsa_sign_det() sub-context */ #endif +} mbedtls_ecdsa_restart_ctx; + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_ecdsa_restart_ctx; + +#endif /* MBEDTLS_ECP_RESTARTABLE */ /** * \brief This function computes the ECDSA signature of a @@ -205,6 +260,40 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +/** + * \brief This function computes the ECDSA signature and writes it + * to a buffer, in a restartable way. + * + * \see \c mbedtls_ecdsa_write_signature() + * + * \note This function is like \c mbedtls_ecdsa_write_signature() + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param ctx The ECDSA context. + * \param md_alg The message digest that was used to hash the message. + * \param hash The message hash. + * \param hlen The length of the hash. + * \param sig The buffer that holds the signature. + * \param slen The length of the signature written. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hlen, + unsigned char *sig, size_t *slen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + mbedtls_ecdsa_restart_ctx *rs_ctx ); + #if defined(MBEDTLS_ECDSA_DETERMINISTIC) #if ! defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) @@ -288,6 +377,37 @@ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ); +/** + * \brief This function reads and verifies an ECDSA signature, + * in a restartable way. + * + * \see \c mbedtls_ecdsa_read_signature() + * + * \note This function is like \c mbedtls_ecdsa_read_signature() + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param ctx The ECDSA context. + * \param hash The message hash. + * \param hlen The size of the hash. + * \param sig The signature to read and verify. + * \param slen The size of \p sig. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. + * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid + * signature in \p sig, but its length is less than \p siglen. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX + * error code on failure for any other reason. + */ +int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, + const unsigned char *hash, size_t hlen, + const unsigned char *sig, size_t slen, + mbedtls_ecdsa_restart_ctx *rs_ctx ); + /** * \brief This function generates an ECDSA keypair on the given curve. * @@ -332,6 +452,18 @@ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ); */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ); +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + */ +void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + */ +void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + #ifdef __cplusplus } #endif diff --git a/features/mbedtls/inc/mbedtls/ecp.h b/features/mbedtls/inc/mbedtls/ecp.h index ed1b9d73681..2fb1af49a2e 100644 --- a/features/mbedtls/inc/mbedtls/ecp.h +++ b/features/mbedtls/inc/mbedtls/ecp.h @@ -49,8 +49,12 @@ #define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as ephemeral key, failed. */ #define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80 /**< Invalid private or public key. */ #define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< The buffer contains a valid signature followed by more data. */ + +/* MBEDTLS_ERR_ECP_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< The ECP hardware accelerator failed. */ +#define MBEDTLS_ERR_ECP_IN_PROGRESS -0x4B00 /**< Operation in progress, call again with the same parameters to continue. */ + #ifdef __cplusplus extern "C" { #endif @@ -181,6 +185,70 @@ typedef struct mbedtls_ecp_group } mbedtls_ecp_group; +#if defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Internal restart context for multiplication + * + * \note Opaque struct + */ +typedef struct mbedtls_ecp_restart_mul mbedtls_ecp_restart_mul_ctx; + +/** + * \brief Internal restart context for ecp_muladd() + * + * \note Opaque struct + */ +typedef struct mbedtls_ecp_restart_muladd mbedtls_ecp_restart_muladd_ctx; + +/** + * \brief General context for resuming ECC operations + */ +typedef struct +{ + unsigned ops_done; /*!< current ops count */ + unsigned depth; /*!< call depth (0 = top-level) */ + mbedtls_ecp_restart_mul_ctx *rsm; /*!< ecp_mul_comb() sub-context */ + mbedtls_ecp_restart_muladd_ctx *ma; /*!< ecp_muladd() sub-context */ +} mbedtls_ecp_restart_ctx; + +/* + * Operation counts for restartable functions + */ +#define MBEDTLS_ECP_OPS_CHK 3 /*!< basic ops count for ecp_check_pubkey() */ +#define MBEDTLS_ECP_OPS_DBL 8 /*!< basic ops count for ecp_double_jac() */ +#define MBEDTLS_ECP_OPS_ADD 11 /*!< basic ops count for see ecp_add_mixed() */ +#define MBEDTLS_ECP_OPS_INV 120 /*!< empirical equivalent for mpi_mod_inv() */ + +/** + * \brief Internal; for restartable functions in other modules. + * Check and update basic ops budget. + * + * \param grp Group structure + * \param rs_ctx Restart context + * \param ops Number of basic ops to do + * + * \return \c 0 if doing \p ops basic ops is still allowed, + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS otherwise. + */ +int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, + mbedtls_ecp_restart_ctx *rs_ctx, + unsigned ops ); + +/* Utility macro for checking and updating ops budget */ +#define MBEDTLS_ECP_BUDGET( ops ) \ + MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, rs_ctx, \ + (unsigned) (ops) ) ); + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +#define MBEDTLS_ECP_BUDGET( ops ) /* no-op; for compatibility */ + +/* We want to declare restartable versions of existing functions anyway */ +typedef void mbedtls_ecp_restart_ctx; + +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /** * \name SECTION: Module settings * @@ -270,6 +338,75 @@ mbedtls_ecp_keypair; */ #define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */ +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Set the maximum number of basic operations done in a row. + * + * If more operations are needed to complete a computation, + * #MBEDTLS_ERR_ECP_IN_PROGRESS will be returned by the + * function performing the computation. It is then the + * caller's responsibility to either call again with the same + * parameters until it returns 0 or an error code; or to free + * the restart context if the operation is to be aborted. + * + * It is strictly required that all input parameters and the + * restart context be the same on successive calls for the + * same operation, but output parameters need not be the + * same; they must not be used until the function finally + * returns 0. + * + * This only applies to functions whose documentation + * mentions they may return #MBEDTLS_ERR_ECP_IN_PROGRESS (or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS for functions in the + * SSL module). For functions that accept a "restart context" + * argument, passing NULL disables restart and makes the + * function equivalent to the function with the same name + * with \c _restartable removed. For functions in the ECDH + * module, restart is disabled unless the function accepts + * an "ECDH context" argument and + * mbedtls_ecdh_enable_restart() was previously called on + * that context. For function in the SSL module, restart is + * only enabled for specific sides and key exchanges + * (currently only for clients and ECDHE-ECDSA). + * + * \param max_ops Maximum number of basic operations done in a row. + * Default: 0 (unlimited). + * Lower (non-zero) values mean ECC functions will block for + * a lesser maximum amount of time. + * + * \note A "basic operation" is defined as a rough equivalent of a + * multiplication in GF(p) for the NIST P-256 curve. + * As an indication, with default settings, a scalar + * multiplication (full run of \c mbedtls_ecp_mul()) is: + * - about 3300 basic operations for P-256 + * - about 9400 basic operations for P-384 + * + * \note Very low values are not always respected: sometimes + * functions need to block for a minimum number of + * operations, and will do so even if max_ops is set to a + * lower value. That minimum depends on the curve size, and + * can be made lower by decreasing the value of + * \c MBEDTLS_ECP_WINDOW_SIZE. As an indication, here is the + * lowest effective value for various curves and values of + * that parameter (w for short): + * w=6 w=5 w=4 w=3 w=2 + * P-256 208 208 160 136 124 + * P-384 682 416 320 272 248 + * P-521 1364 832 640 544 496 + * + * \note This setting is currently ignored by Curve25519. + */ +void mbedtls_ecp_set_max_ops( unsigned max_ops ); + +/** + * \brief Check if restart is enabled (max_ops != 0) + * + * \return \c 0 if \c max_ops == 0 (restart disabled) + * \return \c 1 otherwise (restart enabled) + */ +int mbedtls_ecp_restart_is_enabled( void ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /** * \brief This function retrieves the information defined in * mbedtls_ecp_curve_info() for all supported curves in order @@ -366,6 +503,18 @@ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ); */ void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ); +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + */ +void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + */ +void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /** * \brief This function copies the contents of point \p Q into * point \p P. @@ -597,6 +746,36 @@ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +/** + * \brief This function performs multiplication of a point by + * an integer: \p R = \p m * \p P in a restartable way. + * + * \see mbedtls_ecp_mul() + * + * \note This function does the same as \c mbedtls_ecp_mul(), but + * it can return early and restart according to the limit set + * with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply. + * \param P The point to multiply. + * \param f_rng The RNG function. + * \param p_rng The RNG context. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private + * key, or \p P is not a valid public key. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ); + /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q @@ -623,6 +802,39 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q ); +/** + * \brief This function performs multiplication and addition of two + * points by integers: \p R = \p m * \p P + \p n * \p Q in a + * restartable way. + * + * \see \c mbedtls_ecp_muladd() + * + * \note This function works the same as \c mbedtls_ecp_muladd(), + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param grp The ECP group. + * \param R The destination point. + * \param m The integer by which to multiply \p P. + * \param P The point to multiply by \p m. + * \param n The integer by which to multiply \p Q. + * \param Q The point to be multiplied by \p n. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not + * valid private keys, or \p P or \p Q are not valid public + * keys. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_ecp_muladd_restartable( + mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + const mbedtls_mpi *n, const mbedtls_ecp_point *Q, + mbedtls_ecp_restart_ctx *rs_ctx ); + /** * \brief This function checks that a point is a valid public key * on this curve. @@ -665,6 +877,23 @@ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_po */ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d ); +/** + * \brief This function generates a private key. + * + * \param grp The ECP group. + * \param d The destination MPI (secret part). + * \param f_rng The RNG function. + * \param p_rng The RNG parameter. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. + */ +int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, + mbedtls_mpi *d, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + /** * \brief This function generates a keypair with a configurable base * point. diff --git a/features/mbedtls/inc/mbedtls/error.h b/features/mbedtls/inc/mbedtls/error.h index 6b82d4fbbe8..0c388898788 100644 --- a/features/mbedtls/inc/mbedtls/error.h +++ b/features/mbedtls/inc/mbedtls/error.h @@ -80,6 +80,7 @@ * CHACHA20 3 0x0051-0x0055 * POLY1305 3 0x0057-0x005B * CHACHAPOLY 2 0x0054-0x0056 + * PLATFORM 1 0x0070-0x0072 * * High-level module nr (3 bits - 0x0...-0x7...) * Name ID Nr of Errors @@ -90,12 +91,12 @@ * DHM 3 11 * PK 3 15 (Started from top) * RSA 4 11 - * ECP 4 9 (Started from top) + * ECP 4 10 (Started from top) * MD 5 5 * HKDF 5 1 (Started from top) * CIPHER 6 8 - * SSL 6 22 (Started from top) - * SSL 7 31 + * SSL 6 23 (Started from top) + * SSL 7 32 * * Module dependent error code (5 bits 0x.00.-0x.F8.) */ diff --git a/features/mbedtls/inc/mbedtls/gcm.h b/features/mbedtls/inc/mbedtls/gcm.h index d2098eb9f90..93d15ee8022 100644 --- a/features/mbedtls/inc/mbedtls/gcm.h +++ b/features/mbedtls/inc/mbedtls/gcm.h @@ -41,7 +41,10 @@ #define MBEDTLS_GCM_DECRYPT 0 #define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */ + +/* MBEDTLS_ERR_GCM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */ + #define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ #ifdef __cplusplus @@ -146,9 +149,9 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, * \return \c 0 if the encryption or decryption was performed * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, * this does not indicate that the data is authentic. - * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. - * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific - * error code if the encryption or decryption failed. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid or + * a cipher-specific error code if the encryption + * or decryption failed. */ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, @@ -185,9 +188,8 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, * * \return \c 0 if successful and authenticated. * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. - * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. - * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific - * error code if the decryption failed. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid or + * a cipher-specific error code if the decryption failed. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, diff --git a/features/mbedtls/inc/mbedtls/md.h b/features/mbedtls/inc/mbedtls/md.h index bf29524983c..8bcf766a6ca 100644 --- a/features/mbedtls/inc/mbedtls/md.h +++ b/features/mbedtls/inc/mbedtls/md.h @@ -39,6 +39,8 @@ #define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ #define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */ + +/* MBEDTLS_ERR_MD_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /**< MD hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/md2.h b/features/mbedtls/inc/mbedtls/md2.h index a46bddb74b1..f9bd98f8049 100644 --- a/features/mbedtls/inc/mbedtls/md2.h +++ b/features/mbedtls/inc/mbedtls/md2.h @@ -37,6 +37,7 @@ #include +/* MBEDTLS_ERR_MD2_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED -0x002B /**< MD2 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/md4.h b/features/mbedtls/inc/mbedtls/md4.h index 1672e9074ef..dc3c0489491 100644 --- a/features/mbedtls/inc/mbedtls/md4.h +++ b/features/mbedtls/inc/mbedtls/md4.h @@ -38,6 +38,7 @@ #include #include +/* MBEDTLS_ERR_MD4_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED -0x002D /**< MD4 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/md5.h b/features/mbedtls/inc/mbedtls/md5.h index 4c9509010b6..6c3354fd305 100644 --- a/features/mbedtls/inc/mbedtls/md5.h +++ b/features/mbedtls/inc/mbedtls/md5.h @@ -37,6 +37,7 @@ #include #include +/* MBEDTLS_ERR_MD5_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/pk.h b/features/mbedtls/inc/mbedtls/pk.h index db54c6a6ef5..862065eedef 100644 --- a/features/mbedtls/inc/mbedtls/pk.h +++ b/features/mbedtls/inc/mbedtls/pk.h @@ -45,6 +45,10 @@ #include "ecdsa.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#endif + #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline @@ -64,6 +68,8 @@ #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */ #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */ #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The buffer contains a valid signature followed by more data. */ + +/* MBEDTLS_ERR_PK_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_PK_HW_ACCEL_FAILED -0x3880 /**< PK hardware accelerator failed. */ #ifdef __cplusplus @@ -81,6 +87,7 @@ typedef enum { MBEDTLS_PK_ECDSA, MBEDTLS_PK_RSA_ALT, MBEDTLS_PK_RSASSA_PSS, + MBEDTLS_PK_OPAQUE, } mbedtls_pk_type_t; /** @@ -127,10 +134,24 @@ typedef struct mbedtls_pk_info_t mbedtls_pk_info_t; */ typedef struct mbedtls_pk_context { - const mbedtls_pk_info_t * pk_info; /**< Public key informations */ + const mbedtls_pk_info_t * pk_info; /**< Public key information */ void * pk_ctx; /**< Underlying public key context */ } mbedtls_pk_context; +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Context for resuming operations + */ +typedef struct +{ + const mbedtls_pk_info_t * pk_info; /**< Public key information */ + void * rs_ctx; /**< Underlying restart context */ +} mbedtls_pk_restart_ctx; +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_pk_restart_ctx; +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + #if defined(MBEDTLS_RSA_C) /** * Quick access to an RSA context inside a PK context. @@ -187,9 +208,26 @@ void mbedtls_pk_init( mbedtls_pk_context *ctx ); /** * \brief Free a mbedtls_pk_context + * + * \note For contexts that have been set up with + * mbedtls_pk_setup_opaque(), this does not free the underlying + * key slot and you still need to call psa_destroy_key() + * independently if you want to destroy that key. */ void mbedtls_pk_free( mbedtls_pk_context *ctx ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + */ +void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + */ +void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + /** * \brief Initialize a PK context with the information given * and allocates the type-specific PK subcontext. @@ -206,6 +244,38 @@ void mbedtls_pk_free( mbedtls_pk_context *ctx ); */ int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * \brief Initialize a PK context to wrap a PSA key slot. + * + * \note This function replaces mbedtls_pk_setup() for contexts + * that wrap a (possibly opaque) PSA key slot instead of + * storing and manipulating the key material directly. + * + * \param ctx The context to initialize. It must be empty (type NONE). + * \param key The PSA key slot to wrap, which must hold an ECC key pair + * (see notes below). + * + * \note The wrapped key slot must remain valid as long as the + * wrapping PK context is in use, that is at least between + * the point this function is called and the point + * mbedtls_pk_free() is called on this context. The wrapped + * key slot might then be independently used or destroyed. + * + * \note This function is currently only available for ECC key + * pairs (that is, ECC keys containing private key material). + * Support for other key types may be added later. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input + * (context already used, invalid key slot). + * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the key is not an + * ECC key pair. + * \return #MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure. + */ +int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx, const psa_key_slot_t key ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) /** * \brief Initialize an RSA-alt context @@ -286,6 +356,32 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ); +/** + * \brief Restartable version of \c mbedtls_pk_verify() + * + * \note Performs the same job as \c mbedtls_pk_verify(), but can + * return early and restart according to the limit set with + * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC + * operations. For RSA, same as \c mbedtls_pk_verify(). + * + * \param ctx PK context to use + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Signature to verify + * \param sig_len Signature length + * \param rs_ctx Restart context (NULL to disable restart) + * + * \return See \c mbedtls_pk_verify(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + mbedtls_pk_restart_ctx *rs_ctx ); + /** * \brief Verify signature, with options. * (Includes verification of the padding depending on type.) @@ -349,6 +445,35 @@ int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, unsigned char *sig, size_t *sig_len, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +/** + * \brief Restartable version of \c mbedtls_pk_sign() + * + * \note Performs the same job as \c mbedtls_pk_sign(), but can + * return early and restart according to the limit set with + * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC + * operations. For RSA, same as \c mbedtls_pk_sign(). + * + * \param ctx PK context to use - must hold a private key + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Place to write the signature + * \param sig_len Number of bytes written + * \param f_rng RNG function + * \param p_rng RNG parameter + * \param rs_ctx Restart context (NULL to disable restart) + * + * \return See \c mbedtls_pk_sign(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_pk_restart_ctx *rs_ctx ); + /** * \brief Decrypt message (including padding if relevant). * @@ -397,7 +522,11 @@ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx, * \param pub Context holding a public key. * \param prv Context holding a private (and public) key. * - * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA + * \return \c 0 on success (keys were checked and match each other). + * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not + * be checked - in that case they may or may not match. + * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid. + * \return Another non-zero value if the keys do not match. */ int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv ); @@ -611,6 +740,31 @@ int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start, int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n ); #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * \brief Turn an EC key into an Opaque one + * + * \warning This is a temporary utility function for tests. It might + * change or be removed at any time without notice. + * + * \note Only ECDSA keys are supported so far. Signing with the + * specified hash is the only allowed use of that key. + * + * \param pk Input: the EC key to transfer to a PSA key slot. + * Output: a PK context wrapping that PSA key slot. + * \param slot Output: the chosen slot for storing the key. + * It's the caller's responsibility to destroy that slot + * after calling mbedtls_pk_free() on the PK context. + * \param hash_alg The hash algorithm to allow for use with that key. + * + * \return \c 0 if successful. + * \return An Mbed TLS error code otherwise. + */ +int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk, + psa_key_slot_t *slot, + psa_algorithm_t hash_alg ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #ifdef __cplusplus } #endif diff --git a/features/mbedtls/inc/mbedtls/pk_internal.h b/features/mbedtls/inc/mbedtls/pk_internal.h index 3dae0fc5b27..fc9ba13fe8b 100644 --- a/features/mbedtls/inc/mbedtls/pk_internal.h +++ b/features/mbedtls/inc/mbedtls/pk_internal.h @@ -59,6 +59,21 @@ struct mbedtls_pk_info_t int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /** Verify signature (restartable) */ + int (*verify_rs_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + void *rs_ctx ); + + /** Make signature (restartable) */ + int (*sign_rs_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, void *rs_ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + /** Decrypt message */ int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen, unsigned char *output, size_t *olen, size_t osize, @@ -80,6 +95,14 @@ struct mbedtls_pk_info_t /** Free the given context */ void (*ctx_free_func)( void *ctx ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /** Allocate the restart context */ + void * (*rs_alloc_func)( void ); + + /** Free the restart context */ + void (*rs_free_func)( void *rs_ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + /** Interface with the debug module */ void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items ); @@ -112,4 +135,8 @@ extern const mbedtls_pk_info_t mbedtls_ecdsa_info; extern const mbedtls_pk_info_t mbedtls_rsa_alt_info; #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +extern const mbedtls_pk_info_t mbedtls_pk_opaque_info; +#endif + #endif /* MBEDTLS_PK_WRAP_H */ diff --git a/features/mbedtls/inc/mbedtls/platform.h b/features/mbedtls/inc/mbedtls/platform.h index a40a64f9c6b..89fe8a7b197 100644 --- a/features/mbedtls/inc/mbedtls/platform.h +++ b/features/mbedtls/inc/mbedtls/platform.h @@ -43,6 +43,9 @@ #include "platform_time.h" #endif +#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */ +#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */ + #ifdef __cplusplus extern "C" { #endif diff --git a/features/mbedtls/inc/mbedtls/poly1305.h b/features/mbedtls/inc/mbedtls/poly1305.h index c490cdf2bd1..b02f968b5ef 100644 --- a/features/mbedtls/inc/mbedtls/poly1305.h +++ b/features/mbedtls/inc/mbedtls/poly1305.h @@ -43,7 +43,13 @@ #include #define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /**< Invalid input parameter(s). */ + +/* MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ #define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */ + +/* MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED is deprecated and should not be used. + */ #define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /**< Poly1305 hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/psa_util.h b/features/mbedtls/inc/mbedtls/psa_util.h new file mode 100644 index 00000000000..57661330970 --- /dev/null +++ b/features/mbedtls/inc/mbedtls/psa_util.h @@ -0,0 +1,264 @@ +/** + * \file psa_util.h + * + * \brief Utility functions for the use of the PSA Crypto library. + * + * \warning This function is not part of the public API and may + * change at any time. + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_PSA_UTIL_H +#define MBEDTLS_PSA_UTIL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + +#include "psa/crypto.h" + +#include "ecp.h" +#include "md.h" +#include "pk.h" + +/* Slot allocation */ + +static inline psa_status_t mbedtls_psa_get_free_key_slot( psa_key_slot_t *key ) +{ + for( psa_key_slot_t slot = 1; slot <= 32; slot++ ) + { + if( psa_get_key_information( slot, NULL, NULL ) == PSA_ERROR_EMPTY_SLOT ) + { + *key = slot; + return( PSA_SUCCESS ); + } + } + return( PSA_ERROR_INSUFFICIENT_MEMORY ); +} + +/* Translations for symmetric crypto. */ + +static inline psa_key_type_t mbedtls_psa_translate_cipher_type( + mbedtls_cipher_type_t cipher ) +{ + switch( cipher ) + { + case MBEDTLS_CIPHER_AES_128_CCM: + case MBEDTLS_CIPHER_AES_192_CCM: + case MBEDTLS_CIPHER_AES_256_CCM: + case MBEDTLS_CIPHER_AES_128_GCM: + case MBEDTLS_CIPHER_AES_192_GCM: + case MBEDTLS_CIPHER_AES_256_GCM: + case MBEDTLS_CIPHER_AES_128_CBC: + case MBEDTLS_CIPHER_AES_192_CBC: + case MBEDTLS_CIPHER_AES_256_CBC: + return( PSA_KEY_TYPE_AES ); + + /* ARIA not yet supported in PSA. */ + /* case MBEDTLS_CIPHER_ARIA_128_CCM: + case MBEDTLS_CIPHER_ARIA_192_CCM: + case MBEDTLS_CIPHER_ARIA_256_CCM: + case MBEDTLS_CIPHER_ARIA_128_GCM: + case MBEDTLS_CIPHER_ARIA_192_GCM: + case MBEDTLS_CIPHER_ARIA_256_GCM: + case MBEDTLS_CIPHER_ARIA_128_CBC: + case MBEDTLS_CIPHER_ARIA_192_CBC: + case MBEDTLS_CIPHER_ARIA_256_CBC: + return( PSA_KEY_TYPE_ARIA ); */ + + default: + return( 0 ); + } +} + +static inline psa_algorithm_t mbedtls_psa_translate_cipher_mode( + mbedtls_cipher_mode_t mode, size_t taglen ) +{ + switch( mode ) + { + case MBEDTLS_MODE_GCM: + return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, taglen ) ); + case MBEDTLS_MODE_CCM: + return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, taglen ) ); + case MBEDTLS_MODE_CBC: + if( taglen == 0 ) + return( PSA_ALG_CBC_NO_PADDING ); + /* Intentional fallthrough for taglen != 0 */ + default: + return( 0 ); + } +} + +static inline psa_key_usage_t mbedtls_psa_translate_cipher_operation( + mbedtls_operation_t op ) +{ + switch( op ) + { + case MBEDTLS_ENCRYPT: + return( PSA_KEY_USAGE_ENCRYPT ); + case MBEDTLS_DECRYPT: + return( PSA_KEY_USAGE_DECRYPT ); + default: + return( 0 ); + } +} + +/* Translations for hashing. */ + +static inline psa_algorithm_t mbedtls_psa_translate_md( mbedtls_md_type_t md_alg ) +{ + switch( md_alg ) + { +#if defined(MBEDTLS_MD2_C) + case MBEDTLS_MD_MD2: + return( PSA_ALG_MD2 ); +#endif +#if defined(MBEDTLS_MD4_C) + case MBEDTLS_MD_MD4: + return( PSA_ALG_MD4 ); +#endif +#if defined(MBEDTLS_MD5_C) + case MBEDTLS_MD_MD5: + return( PSA_ALG_MD5 ); +#endif +#if defined(MBEDTLS_SHA1_C) + case MBEDTLS_MD_SHA1: + return( PSA_ALG_SHA_1 ); +#endif +#if defined(MBEDTLS_SHA256_C) + case MBEDTLS_MD_SHA224: + return( PSA_ALG_SHA_224 ); + case MBEDTLS_MD_SHA256: + return( PSA_ALG_SHA_256 ); +#endif +#if defined(MBEDTLS_SHA512_C) + case MBEDTLS_MD_SHA384: + return( PSA_ALG_SHA_384 ); + case MBEDTLS_MD_SHA512: + return( PSA_ALG_SHA_512 ); +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case MBEDTLS_MD_RIPEMD160: + return( PSA_ALG_RIPEMD160 ); +#endif + case MBEDTLS_MD_NONE: /* Intentional fallthrough */ + default: + return( 0 ); + } +} + +/* Translations for ECC. */ + +static inline psa_ecc_curve_t mbedtls_psa_translate_ecc_group( mbedtls_ecp_group_id grpid ) +{ + switch( grpid ) + { +#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) + case MBEDTLS_ECP_DP_SECP192R1: + return( PSA_ECC_CURVE_SECP192R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) + case MBEDTLS_ECP_DP_SECP224R1: + return( PSA_ECC_CURVE_SECP224R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) + case MBEDTLS_ECP_DP_SECP256R1: + return( PSA_ECC_CURVE_SECP256R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) + case MBEDTLS_ECP_DP_SECP384R1: + return( PSA_ECC_CURVE_SECP384R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) + case MBEDTLS_ECP_DP_SECP521R1: + return( PSA_ECC_CURVE_SECP521R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) + case MBEDTLS_ECP_DP_BP256R1: + return( PSA_ECC_CURVE_BRAINPOOL_P256R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) + case MBEDTLS_ECP_DP_BP384R1: + return( PSA_ECC_CURVE_BRAINPOOL_P384R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) + case MBEDTLS_ECP_DP_BP512R1: + return( PSA_ECC_CURVE_BRAINPOOL_P512R1 ); +#endif +#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) + case MBEDTLS_ECP_DP_CURVE25519: + return( PSA_ECC_CURVE_CURVE25519 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) + case MBEDTLS_ECP_DP_SECP192K1: + return( PSA_ECC_CURVE_SECP192K1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) + case MBEDTLS_ECP_DP_SECP224K1: + return( PSA_ECC_CURVE_SECP224K1 ); +#endif +#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) + case MBEDTLS_ECP_DP_SECP256K1: + return( PSA_ECC_CURVE_SECP256K1 ); +#endif +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + case MBEDTLS_ECP_DP_CURVE448: + return( PSA_ECC_CURVE_CURVE448 ); +#endif + default: + return( 0 ); + } +} + +/* Translations for PK layer */ + +static inline int mbedtls_psa_err_translate_pk( psa_status_t status ) +{ + switch( status ) + { + case PSA_SUCCESS: + return( 0 ); + case PSA_ERROR_NOT_SUPPORTED: + return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); + case PSA_ERROR_INSUFFICIENT_MEMORY: + return( MBEDTLS_ERR_PK_ALLOC_FAILED ); + case PSA_ERROR_INSUFFICIENT_ENTROPY: + return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); + case PSA_ERROR_BAD_STATE: + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + /* All other failures */ + case PSA_ERROR_COMMUNICATION_FAILURE: + case PSA_ERROR_HARDWARE_FAILURE: + case PSA_ERROR_TAMPERING_DETECTED: + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + default: /* We return the same as for the 'other failures', + * but list them separately nonetheless to indicate + * which failure conditions we have considered. */ + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + } +} + +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + +#endif /* MBEDTLS_PSA_UTIL_H */ diff --git a/features/mbedtls/inc/mbedtls/ripemd160.h b/features/mbedtls/inc/mbedtls/ripemd160.h index 0c8e568b9ec..c74b7d2c6c8 100644 --- a/features/mbedtls/inc/mbedtls/ripemd160.h +++ b/features/mbedtls/inc/mbedtls/ripemd160.h @@ -33,6 +33,8 @@ #include #include +/* MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED is deprecated and should not be used. + */ #define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/rsa.h b/features/mbedtls/inc/mbedtls/rsa.h index 6eea5af2f09..406a317d4ff 100644 --- a/features/mbedtls/inc/mbedtls/rsa.h +++ b/features/mbedtls/inc/mbedtls/rsa.h @@ -55,7 +55,12 @@ #define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */ #define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */ #define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */ + +/* MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION is deprecated and should not be used. + */ #define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION -0x4500 /**< The implementation does not offer the requested operation, for example, because of security violations or lack of functionality. */ + +/* MBEDTLS_ERR_RSA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_RSA_HW_ACCEL_FAILED -0x4580 /**< RSA hardware accelerator failed. */ /* @@ -281,7 +286,7 @@ int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); * zero Bytes. * * Possible reasons for returning - * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
    + * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
      *
    • An alternative RSA implementation is in use, which * stores the key externally, and either cannot or should * not export it into RAM.
    • @@ -301,7 +306,7 @@ int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); * \param E The MPI to hold the public exponent, or NULL. * * \return \c 0 on success. - * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the * requested parameters cannot be done due to missing * functionality or because of security policies. * \return A non-zero return code on any other failure. @@ -321,7 +326,7 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, * zero Bytes. * * Possible reasons for returning - * #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
        + * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
          *
        • An alternative RSA implementation is in use, which * stores the key externally, and either cannot or should * not export it into RAM.
        • @@ -350,7 +355,7 @@ int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, * \param E_len The size of the buffer for the public exponent. * * \return \c 0 on success. - * \return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION if exporting the + * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the * requested parameters cannot be done due to missing * functionality or because of security policies. * \return A non-zero return code on any other failure. @@ -563,7 +568,7 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for padding, PKCS#1 v2.1 @@ -598,7 +603,7 @@ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for padding and @@ -633,7 +638,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for padding and PKCS#1 v2.1 @@ -682,7 +687,7 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -725,7 +730,7 @@ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -770,7 +775,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -817,7 +822,7 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for @@ -856,7 +861,7 @@ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -894,6 +899,16 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, * Specifications it is advised to keep both hashes the * same. * + * \note This function always uses the maximum possible salt size, + * up to the length of the payload hash. This choice of salt + * size complies with FIPS 186-4 §5.5 (e) and RFC 8017 (PKCS#1 + * v2.2) §9.1.1 step 3. Furthermore this function enforces a + * minimum salt size which is the hash size minus 2 bytes. If + * this minimum size is too large given the key size (the salt + * size, plus the hash size, plus 2 bytes must be no more than + * the key size in bytes), this function returns + * #MBEDTLS_ERR_RSA_BAD_INPUT_DATA. + * * \deprecated It is deprecated and discouraged to call this function * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library * are likely to remove the \p mode argument and have it @@ -901,7 +916,7 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PUBLIC and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA context. * \param f_rng The RNG function. Needed for PKCS#1 v2.1 encoding and for @@ -947,7 +962,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA public key context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -985,7 +1000,7 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA public key context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. @@ -1034,7 +1049,7 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, * * \note Alternative implementations of RSA need not support * mode being set to #MBEDTLS_RSA_PRIVATE and might instead - * return #MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION. + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. * * \param ctx The RSA public key context. * \param f_rng The RNG function. Only needed for #MBEDTLS_RSA_PRIVATE. diff --git a/features/mbedtls/inc/mbedtls/sha1.h b/features/mbedtls/inc/mbedtls/sha1.h index 7a19da0a485..bcaeab5eb94 100644 --- a/features/mbedtls/inc/mbedtls/sha1.h +++ b/features/mbedtls/inc/mbedtls/sha1.h @@ -40,6 +40,7 @@ #include #include +/* MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/sha256.h b/features/mbedtls/inc/mbedtls/sha256.h index 33aff28314a..47a31e83af6 100644 --- a/features/mbedtls/inc/mbedtls/sha256.h +++ b/features/mbedtls/inc/mbedtls/sha256.h @@ -36,6 +36,7 @@ #include #include +/* MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/sha512.h b/features/mbedtls/inc/mbedtls/sha512.h index 0145890424f..020f95de619 100644 --- a/features/mbedtls/inc/mbedtls/sha512.h +++ b/features/mbedtls/inc/mbedtls/sha512.h @@ -35,6 +35,7 @@ #include #include +/* MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/mbedtls/ssl.h b/features/mbedtls/inc/mbedtls/ssl.h index 83849a56450..f7c9d936a9c 100644 --- a/features/mbedtls/inc/mbedtls/ssl.h +++ b/features/mbedtls/inc/mbedtls/ssl.h @@ -65,6 +65,10 @@ #include "platform_time.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + /* * SSL Error codes */ @@ -122,6 +126,7 @@ #define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580 /**< Internal-only message signaling that further message-processing should be done */ #define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS -0x6500 /**< The asynchronous operation is not completed yet. */ #define MBEDTLS_ERR_SSL_EARLY_MESSAGE -0x6480 /**< Internal-only message signaling that a message arrived early. */ +#define MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS -0x7000 /**< A cryptographic operation is in progress. Try again later. */ /* * Various constants @@ -922,19 +927,37 @@ struct mbedtls_ssl_config #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) - unsigned char *psk; /*!< pre-shared key. This field should - only be set via - mbedtls_ssl_conf_psk() */ - size_t psk_len; /*!< length of the pre-shared key. This - field should only be set via - mbedtls_ssl_conf_psk() */ - unsigned char *psk_identity; /*!< identity for PSK negotiation. This - field should only be set via - mbedtls_ssl_conf_psk() */ - size_t psk_identity_len;/*!< length of identity. This field should - only be set via - mbedtls_ssl_conf_psk() */ -#endif + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + psa_key_slot_t psk_opaque; /*!< PSA key slot holding opaque PSK. + * This field should only be set via + * mbedtls_ssl_conf_psk_opaque(). + * If either no PSK or a raw PSK have + * been configured, this has value \c 0. */ +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + + unsigned char *psk; /*!< The raw pre-shared key. This field should + * only be set via mbedtls_ssl_conf_psk(). + * If either no PSK or an opaque PSK + * have been configured, this has value NULL. */ + size_t psk_len; /*!< The length of the raw pre-shared key. + * This field should only be set via + * mbedtls_ssl_conf_psk(). + * Its value is non-zero if and only if + * \c psk is not \c NULL. */ + + unsigned char *psk_identity; /*!< The PSK identity for PSK negotiation. + * This field should only be set via + * mbedtls_ssl_conf_psk(). + * This is set if and only if either + * \c psk or \c psk_opaque are set. */ + size_t psk_identity_len;/*!< The length of PSK identity. + * This field should only be set via + * mbedtls_ssl_conf_psk(). + * Its value is non-zero if and only if + * \c psk is not \c NULL or \c psk_opaque + * is not \c 0. */ +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_SSL_ALPN) const char **alpn_list; /*!< ordered list of protocols */ @@ -2056,68 +2079,146 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) /** - * \brief Set the Pre Shared Key (PSK) and the expected identity name + * \brief Configure a pre-shared key (PSK) and identity + * to be used in PSK-based ciphersuites. * * \note This is mainly useful for clients. Servers will usually * want to use \c mbedtls_ssl_conf_psk_cb() instead. * - * \note Currently clients can only register one pre-shared key. - * In other words, the servers' identity hint is ignored. + * \warning Currently, clients can only register a single pre-shared key. + * Calling this function or mbedtls_ssl_conf_psk_opaque() more + * than once will overwrite values configured in previous calls. * Support for setting multiple PSKs on clients and selecting - * one based on the identity hint is not a planned feature but - * feedback is welcomed. + * one based on the identity hint is not a planned feature, + * but feedback is welcomed. * - * \param conf SSL configuration - * \param psk pointer to the pre-shared key - * \param psk_len pre-shared key length - * \param psk_identity pointer to the pre-shared key identity - * \param psk_identity_len identity key length + * \param conf The SSL configuration to register the PSK with. + * \param psk The pointer to the pre-shared key to use. + * \param psk_len The length of the pre-shared key in bytes. + * \param psk_identity The pointer to the pre-shared key identity. + * \param psk_identity_len The length of the pre-shared key identity + * in bytes. * - * \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED + * \note The PSK and its identity are copied internally and + * hence need not be preserved by the caller for the lifetime + * of the SSL configuration. + * + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. */ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, const unsigned char *psk, size_t psk_len, const unsigned char *psk_identity, size_t psk_identity_len ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * \brief Configure an opaque pre-shared key (PSK) and identity + * to be used in PSK-based ciphersuites. + * + * \note This is mainly useful for clients. Servers will usually + * want to use \c mbedtls_ssl_conf_psk_cb() instead. + * + * \warning Currently, clients can only register a single pre-shared key. + * Calling this function or mbedtls_ssl_conf_psk() more than + * once will overwrite values configured in previous calls. + * Support for setting multiple PSKs on clients and selecting + * one based on the identity hint is not a planned feature, + * but feedback is welcomed. + * + * \param conf The SSL configuration to register the PSK with. + * \param psk The identifier of the key slot holding the PSK. + * Until \p conf is destroyed or this function is successfully + * called again, the key slot \p psk must be populated with a + * key of type #PSA_ALG_CATEGORY_KEY_DERIVATION whose policy + * allows its use for the key derivation algorithm applied + * in the handshake. + * \param psk_identity The pointer to the pre-shared key identity. + * \param psk_identity_len The length of the pre-shared key identity + * in bytes. + * + * \note The PSK identity hint is copied internally and hence need + * not be preserved by the caller for the lifetime of the + * SSL configuration. + * + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. + */ +int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf, + psa_key_slot_t psk, + const unsigned char *psk_identity, + size_t psk_identity_len ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ /** - * \brief Set the Pre Shared Key (PSK) for the current handshake + * \brief Set the pre-shared Key (PSK) for the current handshake. * * \note This should only be called inside the PSK callback, - * ie the function passed to \c mbedtls_ssl_conf_psk_cb(). + * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb(). * - * \param ssl SSL context - * \param psk pointer to the pre-shared key - * \param psk_len pre-shared key length + * \param ssl The SSL context to configure a PSK for. + * \param psk The pointer to the pre-shared key. + * \param psk_len The length of the pre-shared key in bytes. * - * \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. */ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, const unsigned char *psk, size_t psk_len ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * \brief Set an opaque pre-shared Key (PSK) for the current handshake. + * + * \note This should only be called inside the PSK callback, + * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb(). + * + * \param ssl The SSL context to configure a PSK for. + * \param psk The identifier of the key slot holding the PSK. + * For the duration of the current handshake, the key slot + * must be populated with a key of type + * #PSA_ALG_CATEGORY_KEY_DERIVATION whose policy allows its + * use for the key derivation algorithm + * applied in the handshake. + * + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure. + */ +int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl, + psa_key_slot_t psk ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + /** * \brief Set the PSK callback (server-side only). * * If set, the PSK callback is called for each - * handshake where a PSK ciphersuite was negotiated. + * handshake where a PSK-based ciphersuite was negotiated. * The caller provides the identity received and wants to * receive the actual PSK data and length. * - * The callback has the following parameters: (void *parameter, - * mbedtls_ssl_context *ssl, const unsigned char *psk_identity, - * size_t identity_len) + * The callback has the following parameters: + * - \c void*: The opaque pointer \p p_psk. + * - \c mbedtls_ssl_context*: The SSL context to which + * the operation applies. + * - \c const unsigned char*: The PSK identity + * selected by the client. + * - \c size_t: The length of the PSK identity + * selected by the client. + * * If a valid PSK identity is found, the callback should use - * \c mbedtls_ssl_set_hs_psk() on the ssl context to set the - * correct PSK and return 0. + * \c mbedtls_ssl_set_hs_psk() or + * \c mbedtls_ssl_set_hs_psk_opaque() + * on the SSL context to set the correct PSK and return \c 0. * Any other return value will result in a denied PSK identity. * * \note If you set a PSK callback using this function, then you * don't need to set a PSK key and identity using * \c mbedtls_ssl_conf_psk(). * - * \param conf SSL configuration - * \param f_psk PSK identity function - * \param p_psk PSK identity parameter + * \param conf The SSL configuration to register the callback with. + * \param f_psk The callback for selecting and setting the PSK based + * in the PSK identity chosen by the client. + * \param p_psk A pointer to an opaque structure to be passed to + * the callback, for example a PSK store. */ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, @@ -2773,13 +2874,14 @@ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ); /** * \brief Return the result of the certificate verification * - * \param ssl SSL context + * \param ssl The SSL context to use. * - * \return 0 if successful, - * -1 if result is not available (eg because the handshake was - * aborted too early), or - * a combination of BADCERT_xxx and BADCRL_xxx flags, see - * x509.h + * \return \c 0 if the certificate verification was successful. + * \return \c -1u if the result is not available. This may happen + * e.g. if the handshake aborts early, or a verification + * callback returned a fatal error. + * \return A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX + * and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h. */ uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ); @@ -2913,35 +3015,50 @@ int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session * * \param ssl SSL context * - * \return 0 if successful, or - * MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or - * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED (see below), or - * a specific SSL error code. + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED if DTLS is in use + * and the client did not demonstrate reachability yet - in + * this case you must stop using the context (see below). + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. * - * If this function returns MBEDTLS_ERR_SSL_WANT_READ, the - * handshake is unfinished and no further data is available - * from the underlying transport. In this case, you must call - * the function again at some later stage. + * \note If DTLS is in use, then you may choose to handle + * #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging + * purposes, as it is an expected return value rather than an + * actual error, but you still need to reset/free the context. * * \note Remarks regarding event-driven DTLS: - * If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram * from the underlying transport layer is currently being processed, * and it is safe to idle until the timer or the underlying transport * signal a new event. This is not true for a successful handshake, * in which case the datagram of the underlying transport that is * currently being processed might or might not contain further * DTLS records. - * - * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using - * the SSL context for reading or writing, and either free it or - * call \c mbedtls_ssl_session_reset() on it before re-using it - * for a new connection; the current connection must be closed. - * - * \note If DTLS is in use, then you may choose to handle - * MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging - * purposes, as it is an expected return value rather than an - * actual error, but you still need to reset/free the context. */ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ); @@ -2949,20 +3066,21 @@ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ); * \brief Perform a single step of the SSL handshake * * \note The state of the context (ssl->state) will be at - * the next state after execution of this function. Do not + * the next state after this function returns \c 0. Do not * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. * - * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using - * the SSL context for reading or writing, and either free it or - * call \c mbedtls_ssl_session_reset() on it before re-using it - * for a new connection; the current connection must be closed. - * * \param ssl SSL context * - * \return 0 if successful, or - * MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE, or - * a specific SSL error code. + * \return See mbedtls_ssl_handshake(). + * + * \warning If this function returns something other than \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using + * the SSL context for reading or writing, and either free it + * or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. */ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ); @@ -2977,13 +3095,18 @@ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ); * \param ssl SSL context * * \return 0 if successful, or any mbedtls_ssl_handshake() return - * value. + * value except #MBEDTLS_ERR_SSL_CLIENT_RECONNECT that can't + * happen during a renegotiation. + * + * \warning If this function returns something other than \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using + * the SSL context for reading or writing, and either free it + * or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. * - * \note If this function returns something other than 0 or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using - * the SSL context for reading or writing, and either free it or - * call \c mbedtls_ssl_session_reset() on it before re-using it - * for a new connection; the current connection must be closed. */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); #endif /* MBEDTLS_SSL_RENEGOTIATION */ @@ -2995,42 +3118,56 @@ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); * \param buf buffer that will hold the data * \param len maximum number of bytes to read * - * \return One of the following: - * - 0 if the read end of the underlying transport was closed, - * - the (positive) number of bytes read, or - * - a negative error code on failure. - * - * If MBEDTLS_ERR_SSL_WANT_READ is returned, no application data - * is available from the underlying transport. In this case, - * the function needs to be called again at some later stage. - * - * If MBEDTLS_ERR_SSL_WANT_WRITE is returned, a write is pending - * but the underlying transport isn't available for writing. In this - * case, the function needs to be called again at some later stage. + * \return The (positive) number of bytes read if successful. + * \return \c 0 if the read end of the underlying transport was closed + * - in this case you must stop using the context (see below). + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return #MBEDTLS_ERR_SSL_CLIENT_RECONNECT if we're at the server + * side of a DTLS connection and the client is initiating a + * new connection using the same source port. See below. + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * a positive value, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CLIENT_RECONNECT, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. * - * When this function return MBEDTLS_ERR_SSL_CLIENT_RECONNECT + * \note When this function returns #MBEDTLS_ERR_SSL_CLIENT_RECONNECT * (which can only happen server-side), it means that a client * is initiating a new connection using the same source port. * You can either treat that as a connection close and wait * for the client to resend a ClientHello, or directly * continue with \c mbedtls_ssl_handshake() with the same - * context (as it has beeen reset internally). Either way, you - * should make sure this is seen by the application as a new + * context (as it has been reset internally). Either way, you + * must make sure this is seen by the application as a new * connection: application state, if any, should be reset, and * most importantly the identity of the client must be checked * again. WARNING: not validating the identity of the client * again, or not transmitting the new identity to the * application layer, would allow authentication bypass! * - * \note If this function returns something other than a positive value - * or MBEDTLS_ERR_SSL_WANT_READ/WRITE or MBEDTLS_ERR_SSL_CLIENT_RECONNECT, - * you must stop using the SSL context for reading or writing, - * and either free it or call \c mbedtls_ssl_session_reset() on it - * before re-using it for a new connection; the current connection - * must be closed. - * * \note Remarks regarding event-driven DTLS: - * - If the function returns MBEDTLS_ERR_SSL_WANT_READ, no datagram + * - If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram * from the underlying transport layer is currently being processed, * and it is safe to idle until the timer or the underlying transport * signal a new event. @@ -3059,21 +3196,39 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * \param buf buffer holding the data * \param len how many bytes must be written * - * \return the number of bytes actually written (may be less than len), - * or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ, - * or another negative error code. - * - * \note If this function returns something other than 0, a positive - * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop - * using the SSL context for reading or writing, and either - * free it or call \c mbedtls_ssl_session_reset() on it before - * re-using it for a new connection; the current connection - * must be closed. + * \return The (non-negative) number of bytes actually written if + * successful (may be less than \p len). + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * a non-negative value, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. * - * \note When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, + * \note When this function returns #MBEDTLS_ERR_SSL_WANT_WRITE/READ, * it must be called later with the *same* arguments, * until it returns a value greater that or equal to 0. When - * the function returns MBEDTLS_ERR_SSL_WANT_WRITE there may be + * the function returns #MBEDTLS_ERR_SSL_WANT_WRITE there may be * some partial data in the output buffer, however this is not * yet sent. * diff --git a/features/mbedtls/inc/mbedtls/ssl_internal.h b/features/mbedtls/inc/mbedtls/ssl_internal.h index 4b4417a5fae..318d13fd840 100644 --- a/features/mbedtls/inc/mbedtls/ssl_internal.h +++ b/features/mbedtls/inc/mbedtls/ssl_internal.h @@ -93,6 +93,14 @@ #endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ +/* Shorthand for restartable ECC */ +#if defined(MBEDTLS_ECP_RESTARTABLE) && \ + defined(MBEDTLS_SSL_CLI_C) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) +#define MBEDTLS_SSL__ECP_RESTARTABLE +#endif + #define MBEDTLS_SSL_INITIAL_HANDSHAKE 0 #define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS 1 /* In progress */ #define MBEDTLS_SSL_RENEGOTIATION_DONE 2 /* Done or aborted */ @@ -275,9 +283,12 @@ struct mbedtls_ssl_handshake_params const mbedtls_ecp_curve_info **curves; /*!< Supported elliptic curves */ #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) +#if defined(MBEDTLS_USE_PSA_CRYPTO) + psa_key_slot_t psk_opaque; /*!< Opaque PSK from the callback */ +#endif /* MBEDTLS_USE_PSA_CRYPTO */ unsigned char *psk; /*!< PSK from the callback */ size_t psk_len; /*!< Length of PSK from callback */ -#endif +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) mbedtls_ssl_key_cert *key_cert; /*!< chosen key/cert pair (server) */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) @@ -287,7 +298,18 @@ struct mbedtls_ssl_handshake_params mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */ #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ - +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + int ecrs_enabled; /*!< Handshake supports EC restart? */ + mbedtls_x509_crt_restart_ctx ecrs_ctx; /*!< restart context */ + enum { /* this complements ssl->state with info on intra-state operations */ + ssl_ecrs_none = 0, /*!< nothing going on (yet) */ + ssl_ecrs_crt_verify, /*!< Certificate: crt_verify() */ + ssl_ecrs_ske_start_processing, /*!< ServerKeyExchange: pk_verify() */ + ssl_ecrs_cke_ecdh_calc_secret, /*!< ClientKeyExchange: ECDH step 2 */ + ssl_ecrs_crt_vrfy_sign, /*!< CertificateVerify: pk_sign() */ + } ecrs_state; /*!< current (or last) operation */ + size_t ecrs_n; /*!< place for saving a length */ +#endif #if defined(MBEDTLS_SSL_PROTO_DTLS) unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */ unsigned int in_msg_seq; /*!< Incoming handshake sequence number */ diff --git a/features/mbedtls/inc/mbedtls/threading.h b/features/mbedtls/inc/mbedtls/threading.h index 75298bf8a38..92e6e6b987e 100644 --- a/features/mbedtls/inc/mbedtls/threading.h +++ b/features/mbedtls/inc/mbedtls/threading.h @@ -36,7 +36,10 @@ extern "C" { #endif +/* MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ #define MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE -0x001A /**< The selected feature is not available. */ + #define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA -0x001C /**< Bad input parameters to function. */ #define MBEDTLS_ERR_THREADING_MUTEX_ERROR -0x001E /**< Locking / unlocking / free failed with error code. */ diff --git a/features/mbedtls/inc/mbedtls/version.h b/features/mbedtls/inc/mbedtls/version.h index 326b8bd4516..a9366bb11f1 100644 --- a/features/mbedtls/inc/mbedtls/version.h +++ b/features/mbedtls/inc/mbedtls/version.h @@ -39,17 +39,17 @@ * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 -#define MBEDTLS_VERSION_MINOR 13 -#define MBEDTLS_VERSION_PATCH 1 +#define MBEDTLS_VERSION_MINOR 15 +#define MBEDTLS_VERSION_PATCH 0 /** * The single version number has the following structure: * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x020D0100 -#define MBEDTLS_VERSION_STRING "2.13.1" -#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.13.1" +#define MBEDTLS_VERSION_NUMBER 0x020F0000 +#define MBEDTLS_VERSION_STRING "2.15.0" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.15.0" #if defined(MBEDTLS_VERSION_C) diff --git a/features/mbedtls/inc/mbedtls/x509_crt.h b/features/mbedtls/inc/mbedtls/x509_crt.h index d41ec93a66e..afeefca60e2 100644 --- a/features/mbedtls/inc/mbedtls/x509_crt.h +++ b/features/mbedtls/inc/mbedtls/x509_crt.h @@ -143,6 +143,63 @@ typedef struct mbedtls_x509write_cert } mbedtls_x509write_cert; +/** + * Item in a verification chain: cert and flags for it + */ +typedef struct { + mbedtls_x509_crt *crt; + uint32_t flags; +} mbedtls_x509_crt_verify_chain_item; + +/** + * Max size of verification chain: end-entity + intermediates + trusted root + */ +#define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) + +/** + * Verification chain as built by \c mbedtls_crt_verify_chain() + */ +typedef struct +{ + mbedtls_x509_crt_verify_chain_item items[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE]; + unsigned len; +} mbedtls_x509_crt_verify_chain; + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Context for resuming X.509 verify operations + */ +typedef struct +{ + /* for check_signature() */ + mbedtls_pk_restart_ctx pk; + + /* for find_parent_in() */ + mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */ + mbedtls_x509_crt *fallback_parent; + int fallback_signature_is_good; + + /* for find_parent() */ + int parent_is_trusted; /* -1 if find_parent is not in progress */ + + /* for verify_chain() */ + enum { + x509_crt_rs_none, + x509_crt_rs_find_parent, + } in_progress; /* none if no operation is in progress */ + int self_cnt; + mbedtls_x509_crt_verify_chain ver_chain; + +} mbedtls_x509_crt_restart_ctx; + +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_x509_crt_restart_ctx; + +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + #if defined(MBEDTLS_X509_CRT_PARSE_C) /** * Default security profile. Should provide a good balance between security @@ -353,6 +410,37 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ); +/** + * \brief Restartable version of \c mbedtls_crt_verify_with_profile() + * + * \note Performs the same job as \c mbedtls_crt_verify_with_profile() + * but can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param crt a certificate (chain) to be verified + * \param trust_ca the list of trusted CAs + * \param ca_crl the list of CRLs for trusted CAs + * \param profile security profile for verification + * \param cn expected Common Name (can be set to + * NULL if the CN must not be verified) + * \param flags result of the verification + * \param f_vrfy verification function + * \param p_vrfy verification parameter + * \param rs_ctx restart context (NULL to disable restart) + * + * \return See \c mbedtls_crt_verify_with_profile(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + const char *cn, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy, + mbedtls_x509_crt_restart_ctx *rs_ctx ); + #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) /** * \brief Check usage of certificate against keyUsage extension. @@ -424,6 +512,18 @@ void mbedtls_x509_crt_init( mbedtls_x509_crt *crt ); * \param crt Certificate chain to free */ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + */ +void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + */ +void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* \} name */ diff --git a/features/mbedtls/inc/mbedtls/xtea.h b/features/mbedtls/inc/mbedtls/xtea.h index c70c3fe2654..6430c1318a5 100644 --- a/features/mbedtls/inc/mbedtls/xtea.h +++ b/features/mbedtls/inc/mbedtls/xtea.h @@ -37,6 +37,8 @@ #define MBEDTLS_XTEA_DECRYPT 0 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */ + +/* MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */ #ifdef __cplusplus diff --git a/features/mbedtls/inc/psa/crypto.h b/features/mbedtls/inc/psa/crypto.h new file mode 100644 index 00000000000..1ca64922e5e --- /dev/null +++ b/features/mbedtls/inc/psa/crypto.h @@ -0,0 +1,3479 @@ +/** + * \file psa/crypto.h + * \brief Platform Security Architecture cryptography module + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PSA_CRYPTO_H +#define PSA_CRYPTO_H + +#include "crypto_platform.h" + +#include + +#ifdef __DOXYGEN_ONLY__ +/* This __DOXYGEN_ONLY__ block contains mock definitions for things that + * must be defined in the crypto_platform.h header. These mock definitions + * are present in this file as a convenience to generate pretty-printed + * documentation that includes those definitions. */ + +/** \defgroup platform Implementation-specific definitions + * @{ + */ + +/** \brief Key slot number. + * + * This type represents key slots. It must be an unsigned integral + * type. The choice of type is implementation-dependent. + * 0 is not a valid key slot number. The meaning of other values is + * implementation dependent. + * + * At any given point in time, each key slot either contains a + * cryptographic object, or is empty. Key slots are persistent: + * once set, the cryptographic object remains in the key slot until + * explicitly destroyed. + */ +typedef _unsigned_integral_type_ psa_key_slot_t; + +/**@}*/ +#endif /* __DOXYGEN_ONLY__ */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup basic Basic definitions + * @{ + */ + +#if defined(PSA_SUCCESS) +/* If PSA_SUCCESS is defined, assume that PSA crypto is being used + * together with PSA IPC, which also defines the identifier + * PSA_SUCCESS. We must not define PSA_SUCCESS ourselves in that case; + * the other error code names don't clash. Also define psa_status_t as + * an alias for the type used by PSA IPC. This is a temporary hack + * until we unify error reporting in PSA IPC and PSA crypto. + * + * Note that psa_defs.h must be included before this header! + */ +typedef psa_error_t psa_status_t; + +#else /* defined(PSA_SUCCESS) */ + +/** + * \brief Function return status. + * + * This is either #PSA_SUCCESS (which is zero), indicating success, + * or a nonzero value indicating that an error occurred. Errors are + * encoded as one of the \c PSA_ERROR_xxx values defined here. + */ +typedef int32_t psa_status_t; + +/** The action was completed successfully. */ +#define PSA_SUCCESS ((psa_status_t)0) + +#endif /* !defined(PSA_SUCCESS) */ + +/** An error occurred that does not correspond to any defined + * failure cause. + * + * Implementations may use this error code if none of the other standard + * error codes are applicable. */ +#define PSA_ERROR_UNKNOWN_ERROR ((psa_status_t)1) + +/** The requested operation or a parameter is not supported + * by this implementation. + * + * Implementations should return this error code when an enumeration + * parameter such as a key type, algorithm, etc. is not recognized. + * If a combination of parameters is recognized and identified as + * not valid, return #PSA_ERROR_INVALID_ARGUMENT instead. */ +#define PSA_ERROR_NOT_SUPPORTED ((psa_status_t)2) + +/** The requested action is denied by a policy. + * + * Implementations should return this error code when the parameters + * are recognized as valid and supported, and a policy explicitly + * denies the requested operation. + * + * If a subset of the parameters of a function call identify a + * forbidden operation, and another subset of the parameters are + * not valid or not supported, it is unspecified whether the function + * returns #PSA_ERROR_NOT_PERMITTED, #PSA_ERROR_NOT_SUPPORTED or + * #PSA_ERROR_INVALID_ARGUMENT. */ +#define PSA_ERROR_NOT_PERMITTED ((psa_status_t)3) + +/** An output buffer is too small. + * + * Applications can call the \c PSA_xxx_SIZE macro listed in the function + * description to determine a sufficient buffer size. + * + * Implementations should preferably return this error code only + * in cases when performing the operation with a larger output + * buffer would succeed. However implementations may return this + * error if a function has invalid or unsupported parameters in addition + * to the parameters that determine the necessary output buffer size. */ +#define PSA_ERROR_BUFFER_TOO_SMALL ((psa_status_t)4) + +/** A slot is occupied, but must be empty to carry out the + * requested action. + * + * If the slot number is invalid (i.e. the requested action could + * not be performed even after erasing the slot's content), + * implementations shall return #PSA_ERROR_INVALID_ARGUMENT instead. */ +#define PSA_ERROR_OCCUPIED_SLOT ((psa_status_t)5) + +/** A slot is empty, but must be occupied to carry out the + * requested action. + * + * If the slot number is invalid (i.e. the requested action could + * not be performed even after creating appropriate content in the slot), + * implementations shall return #PSA_ERROR_INVALID_ARGUMENT instead. */ +#define PSA_ERROR_EMPTY_SLOT ((psa_status_t)6) + +/** The requested action cannot be performed in the current state. + * + * Multipart operations return this error when one of the + * functions is called out of sequence. Refer to the function + * descriptions for permitted sequencing of functions. + * + * Implementations shall not return this error code to indicate + * that a key slot is occupied when it needs to be free or vice versa, + * but shall return #PSA_ERROR_OCCUPIED_SLOT or #PSA_ERROR_EMPTY_SLOT + * as applicable. */ +#define PSA_ERROR_BAD_STATE ((psa_status_t)7) + +/** The parameters passed to the function are invalid. + * + * Implementations may return this error any time a parameter or + * combination of parameters are recognized as invalid. + * + * Implementations shall not return this error code to indicate + * that a key slot is occupied when it needs to be free or vice versa, + * but shall return #PSA_ERROR_OCCUPIED_SLOT or #PSA_ERROR_EMPTY_SLOT + * as applicable. */ +#define PSA_ERROR_INVALID_ARGUMENT ((psa_status_t)8) + +/** There is not enough runtime memory. + * + * If the action is carried out across multiple security realms, this + * error can refer to available memory in any of the security realms. */ +#define PSA_ERROR_INSUFFICIENT_MEMORY ((psa_status_t)9) + +/** There is not enough persistent storage. + * + * Functions that modify the key storage return this error code if + * there is insufficient storage space on the host media. In addition, + * many functions that do not otherwise access storage may return this + * error code if the implementation requires a mandatory log entry for + * the requested action and the log storage space is full. */ +#define PSA_ERROR_INSUFFICIENT_STORAGE ((psa_status_t)10) + +/** There was a communication failure inside the implementation. + * + * This can indicate a communication failure between the application + * and an external cryptoprocessor or between the cryptoprocessor and + * an external volatile or persistent memory. A communication failure + * may be transient or permanent depending on the cause. + * + * \warning If a function returns this error, it is undetermined + * whether the requested action has completed or not. Implementations + * should return #PSA_SUCCESS on successful completion whenver + * possible, however functions may return #PSA_ERROR_COMMUNICATION_FAILURE + * if the requested action was completed successfully in an external + * cryptoprocessor but there was a breakdown of communication before + * the cryptoprocessor could report the status to the application. + */ +#define PSA_ERROR_COMMUNICATION_FAILURE ((psa_status_t)11) + +/** There was a storage failure that may have led to data loss. + * + * This error indicates that some persistent storage is corrupted. + * It should not be used for a corruption of volatile memory + * (use #PSA_ERROR_TAMPERING_DETECTED), for a communication error + * between the cryptoprocessor and its external storage (use + * #PSA_ERROR_COMMUNICATION_FAILURE), or when the storage is + * in a valid state but is full (use #PSA_ERROR_INSUFFICIENT_STORAGE). + * + * Note that a storage failure does not indicate that any data that was + * previously read is invalid. However this previously read data may no + * longer be readable from storage. + * + * When a storage failure occurs, it is no longer possible to ensure + * the global integrity of the keystore. Depending on the global + * integrity guarantees offered by the implementation, access to other + * data may or may not fail even if the data is still readable but + * its integrity canont be guaranteed. + * + * Implementations should only use this error code to report a + * permanent storage corruption. However application writers should + * keep in mind that transient errors while reading the storage may be + * reported using this error code. */ +#define PSA_ERROR_STORAGE_FAILURE ((psa_status_t)12) + +/** A hardware failure was detected. + * + * A hardware failure may be transient or permanent depending on the + * cause. */ +#define PSA_ERROR_HARDWARE_FAILURE ((psa_status_t)13) + +/** A tampering attempt was detected. + * + * If an application receives this error code, there is no guarantee + * that previously accessed or computed data was correct and remains + * confidential. Applications should not perform any security function + * and should enter a safe failure state. + * + * Implementations may return this error code if they detect an invalid + * state that cannot happen during normal operation and that indicates + * that the implementation's security guarantees no longer hold. Depending + * on the implementation architecture and on its security and safety goals, + * the implementation may forcibly terminate the application. + * + * This error code is intended as a last resort when a security breach + * is detected and it is unsure whether the keystore data is still + * protected. Implementations shall only return this error code + * to report an alarm from a tampering detector, to indicate that + * the confidentiality of stored data can no longer be guaranteed, + * or to indicate that the integrity of previously returned data is now + * considered compromised. Implementations shall not use this error code + * to indicate a hardware failure that merely makes it impossible to + * perform the requested operation (use #PSA_ERROR_COMMUNICATION_FAILURE, + * #PSA_ERROR_STORAGE_FAILURE, #PSA_ERROR_HARDWARE_FAILURE, + * #PSA_ERROR_INSUFFICIENT_ENTROPY or other applicable error code + * instead). + * + * This error indicates an attack against the application. Implementations + * shall not return this error code as a consequence of the behavior of + * the application itself. */ +#define PSA_ERROR_TAMPERING_DETECTED ((psa_status_t)14) + +/** There is not enough entropy to generate random data needed + * for the requested action. + * + * This error indicates a failure of a hardware random generator. + * Application writers should note that this error can be returned not + * only by functions whose purpose is to generate random data, such + * as key, IV or nonce generation, but also by functions that execute + * an algorithm with a randomized result, as well as functions that + * use randomization of intermediate computations as a countermeasure + * to certain attacks. + * + * Implementations should avoid returning this error after psa_crypto_init() + * has succeeded. Implementations should generate sufficient + * entropy during initialization and subsequently use a cryptographically + * secure pseudorandom generator (PRNG). However implementations may return + * this error at any time if a policy requires the PRNG to be reseeded + * during normal operation. */ +#define PSA_ERROR_INSUFFICIENT_ENTROPY ((psa_status_t)15) + +/** The signature, MAC or hash is incorrect. + * + * Verification functions return this error if the verification + * calculations completed successfully, and the value to be verified + * was determined to be incorrect. + * + * If the value to verify has an invalid size, implementations may return + * either #PSA_ERROR_INVALID_ARGUMENT or #PSA_ERROR_INVALID_SIGNATURE. */ +#define PSA_ERROR_INVALID_SIGNATURE ((psa_status_t)16) + +/** The decrypted padding is incorrect. + * + * \warning In some protocols, when decrypting data, it is essential that + * the behavior of the application does not depend on whether the padding + * is correct, down to precise timing. Applications should prefer + * protocols that use authenticated encryption rather than plain + * encryption. If the application must perform a decryption of + * unauthenticated data, the application writer should take care not + * to reveal whether the padding is invalid. + * + * Implementations should strive to make valid and invalid padding + * as close as possible to indistinguishable to an external observer. + * In particular, the timing of a decryption operation should not + * depend on the validity of the padding. */ +#define PSA_ERROR_INVALID_PADDING ((psa_status_t)17) + +/** The generator has insufficient capacity left. + * + * Once a function returns this error, attempts to read from the + * generator will always return this error. */ +#define PSA_ERROR_INSUFFICIENT_CAPACITY ((psa_status_t)18) + +/** + * \brief Library initialization. + * + * Applications must call this function before calling any other + * function in this module. + * + * Applications may call this function more than once. Once a call + * succeeds, subsequent calls are guaranteed to succeed. + * + * If the application calls other functions before calling psa_crypto_init(), + * the behavior is undefined. Implementations are encouraged to either perform + * the operation as if the library had been initialized or to return + * #PSA_ERROR_BAD_STATE or some other applicable error. In particular, + * implementations should not return a success status if the lack of + * initialization may have security implications, for example due to improper + * seeding of the random number generator. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + */ +psa_status_t psa_crypto_init(void); + +#define PSA_BITS_TO_BYTES(bits) (((bits) + 7) / 8) +#define PSA_BYTES_TO_BITS(bytes) ((bytes) * 8) + +/**@}*/ + +/** \defgroup crypto_types Key and algorithm types + * @{ + */ + +/** \brief Encoding of a key type. + */ +typedef uint32_t psa_key_type_t; + +/** An invalid key type value. + * + * Zero is not the encoding of any key type. + */ +#define PSA_KEY_TYPE_NONE ((psa_key_type_t)0x00000000) + +/** Vendor-defined flag + * + * Key types defined by this standard will never have the + * #PSA_KEY_TYPE_VENDOR_FLAG bit set. Vendors who define additional key types + * must use an encoding with the #PSA_KEY_TYPE_VENDOR_FLAG bit set and should + * respect the bitwise structure used by standard encodings whenever practical. + */ +#define PSA_KEY_TYPE_VENDOR_FLAG ((psa_key_type_t)0x80000000) + +#define PSA_KEY_TYPE_CATEGORY_MASK ((psa_key_type_t)0x70000000) +#define PSA_KEY_TYPE_CATEGORY_SYMMETRIC ((psa_key_type_t)0x40000000) +#define PSA_KEY_TYPE_CATEGORY_RAW ((psa_key_type_t)0x50000000) +#define PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY ((psa_key_type_t)0x60000000) +#define PSA_KEY_TYPE_CATEGORY_KEY_PAIR ((psa_key_type_t)0x70000000) + +#define PSA_KEY_TYPE_CATEGORY_FLAG_PAIR ((psa_key_type_t)0x10000000) + +/** Whether a key type is vendor-defined. */ +#define PSA_KEY_TYPE_IS_VENDOR_DEFINED(type) \ + (((type) & PSA_KEY_TYPE_VENDOR_FLAG) != 0) + +/** Whether a key type is an unstructured array of bytes. + * + * This encompasses both symmetric keys and non-key data. + */ +#define PSA_KEY_TYPE_IS_UNSTRUCTURED(type) \ + (((type) & PSA_KEY_TYPE_CATEGORY_MASK & ~(psa_key_type_t)0x10000000) == \ + PSA_KEY_TYPE_CATEGORY_SYMMETRIC) + +/** Whether a key type is asymmetric: either a key pair or a public key. */ +#define PSA_KEY_TYPE_IS_ASYMMETRIC(type) \ + (((type) & PSA_KEY_TYPE_CATEGORY_MASK \ + & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) == \ + PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY) +/** Whether a key type is the public part of a key pair. */ +#define PSA_KEY_TYPE_IS_PUBLIC_KEY(type) \ + (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY) +/** Whether a key type is a key pair containing a private part and a public + * part. */ +#define PSA_KEY_TYPE_IS_KEYPAIR(type) \ + (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_KEY_PAIR) +/** The key pair type corresponding to a public key type. + * + * You may also pass a key pair type as \p type, it will be left unchanged. + * + * \param type A public key type or key pair type. + * + * \return The corresponding key pair type. + * If \p type is not a public key or a key pair, + * the return value is undefined. + */ +#define PSA_KEY_TYPE_KEYPAIR_OF_PUBLIC_KEY(type) \ + ((type) | PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) +/** The public key type corresponding to a key pair type. + * + * You may also pass a key pair type as \p type, it will be left unchanged. + * + * \param type A public key type or key pair type. + * + * \return The corresponding public key type. + * If \p type is not a public key or a key pair, + * the return value is undefined. + */ +#define PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(type) \ + ((type) & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) + +/** Raw data. + * + * A "key" of this type cannot be used for any cryptographic operation. + * Applications may use this type to store arbitrary data in the keystore. */ +#define PSA_KEY_TYPE_RAW_DATA ((psa_key_type_t)0x50000001) + +/** HMAC key. + * + * The key policy determines which underlying hash algorithm the key can be + * used for. + * + * HMAC keys should generally have the same size as the underlying hash. + * This size can be calculated with #PSA_HASH_SIZE(\c alg) where + * \c alg is the HMAC algorithm or the underlying hash algorithm. */ +#define PSA_KEY_TYPE_HMAC ((psa_key_type_t)0x51000000) + +/** A secret for key derivation. + * + * The key policy determines which key derivation algorithm the key + * can be used for. + */ +#define PSA_KEY_TYPE_DERIVE ((psa_key_type_t)0x52000000) + +/** Key for an cipher, AEAD or MAC algorithm based on the AES block cipher. + * + * The size of the key can be 16 bytes (AES-128), 24 bytes (AES-192) or + * 32 bytes (AES-256). + */ +#define PSA_KEY_TYPE_AES ((psa_key_type_t)0x40000001) + +/** Key for a cipher or MAC algorithm based on DES or 3DES (Triple-DES). + * + * The size of the key can be 8 bytes (single DES), 16 bytes (2-key 3DES) or + * 24 bytes (3-key 3DES). + * + * Note that single DES and 2-key 3DES are weak and strongly + * deprecated and should only be used to decrypt legacy data. 3-key 3DES + * is weak and deprecated and should only be used in legacy protocols. + */ +#define PSA_KEY_TYPE_DES ((psa_key_type_t)0x40000002) + +/** Key for an cipher, AEAD or MAC algorithm based on the + * Camellia block cipher. */ +#define PSA_KEY_TYPE_CAMELLIA ((psa_key_type_t)0x40000003) + +/** Key for the RC4 stream cipher. + * + * Note that RC4 is weak and deprecated and should only be used in + * legacy protocols. */ +#define PSA_KEY_TYPE_ARC4 ((psa_key_type_t)0x40000004) + +/** RSA public key. */ +#define PSA_KEY_TYPE_RSA_PUBLIC_KEY ((psa_key_type_t)0x60010000) +/** RSA key pair (private and public key). */ +#define PSA_KEY_TYPE_RSA_KEYPAIR ((psa_key_type_t)0x70010000) +/** Whether a key type is an RSA key (pair or public-only). */ +#define PSA_KEY_TYPE_IS_RSA(type) \ + (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY) + +/** DSA public key. */ +#define PSA_KEY_TYPE_DSA_PUBLIC_KEY ((psa_key_type_t)0x60020000) +/** DSA key pair (private and public key). */ +#define PSA_KEY_TYPE_DSA_KEYPAIR ((psa_key_type_t)0x70020000) +/** Whether a key type is an DSA key (pair or public-only). */ +#define PSA_KEY_TYPE_IS_DSA(type) \ + (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY) + +#define PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((psa_key_type_t)0x60030000) +#define PSA_KEY_TYPE_ECC_KEYPAIR_BASE ((psa_key_type_t)0x70030000) +#define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t)0x0000ffff) +/** Elliptic curve key pair. */ +#define PSA_KEY_TYPE_ECC_KEYPAIR(curve) \ + (PSA_KEY_TYPE_ECC_KEYPAIR_BASE | (curve)) +/** Elliptic curve public key. */ +#define PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve) \ + (PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve)) + +/** Whether a key type is an elliptic curve key (pair or public-only). */ +#define PSA_KEY_TYPE_IS_ECC(type) \ + ((PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(type) & \ + ~PSA_KEY_TYPE_ECC_CURVE_MASK) == PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) +#define PSA_KEY_TYPE_IS_ECC_KEYPAIR(type) \ + (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \ + PSA_KEY_TYPE_ECC_KEYPAIR_BASE) +#define PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(type) \ + (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \ + PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) + +/** The type of PSA elliptic curve identifiers. */ +typedef uint16_t psa_ecc_curve_t; +/** Extract the curve from an elliptic curve key type. */ +#define PSA_KEY_TYPE_GET_CURVE(type) \ + ((psa_ecc_curve_t) (PSA_KEY_TYPE_IS_ECC(type) ? \ + ((type) & PSA_KEY_TYPE_ECC_CURVE_MASK) : \ + 0)) + +/* The encoding of curve identifiers is currently aligned with the + * TLS Supported Groups Registry (formerly known as the + * TLS EC Named Curve Registry) + * https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8 + * The values are defined by RFC 8422 and RFC 7027. */ +#define PSA_ECC_CURVE_SECT163K1 ((psa_ecc_curve_t) 0x0001) +#define PSA_ECC_CURVE_SECT163R1 ((psa_ecc_curve_t) 0x0002) +#define PSA_ECC_CURVE_SECT163R2 ((psa_ecc_curve_t) 0x0003) +#define PSA_ECC_CURVE_SECT193R1 ((psa_ecc_curve_t) 0x0004) +#define PSA_ECC_CURVE_SECT193R2 ((psa_ecc_curve_t) 0x0005) +#define PSA_ECC_CURVE_SECT233K1 ((psa_ecc_curve_t) 0x0006) +#define PSA_ECC_CURVE_SECT233R1 ((psa_ecc_curve_t) 0x0007) +#define PSA_ECC_CURVE_SECT239K1 ((psa_ecc_curve_t) 0x0008) +#define PSA_ECC_CURVE_SECT283K1 ((psa_ecc_curve_t) 0x0009) +#define PSA_ECC_CURVE_SECT283R1 ((psa_ecc_curve_t) 0x000a) +#define PSA_ECC_CURVE_SECT409K1 ((psa_ecc_curve_t) 0x000b) +#define PSA_ECC_CURVE_SECT409R1 ((psa_ecc_curve_t) 0x000c) +#define PSA_ECC_CURVE_SECT571K1 ((psa_ecc_curve_t) 0x000d) +#define PSA_ECC_CURVE_SECT571R1 ((psa_ecc_curve_t) 0x000e) +#define PSA_ECC_CURVE_SECP160K1 ((psa_ecc_curve_t) 0x000f) +#define PSA_ECC_CURVE_SECP160R1 ((psa_ecc_curve_t) 0x0010) +#define PSA_ECC_CURVE_SECP160R2 ((psa_ecc_curve_t) 0x0011) +#define PSA_ECC_CURVE_SECP192K1 ((psa_ecc_curve_t) 0x0012) +#define PSA_ECC_CURVE_SECP192R1 ((psa_ecc_curve_t) 0x0013) +#define PSA_ECC_CURVE_SECP224K1 ((psa_ecc_curve_t) 0x0014) +#define PSA_ECC_CURVE_SECP224R1 ((psa_ecc_curve_t) 0x0015) +#define PSA_ECC_CURVE_SECP256K1 ((psa_ecc_curve_t) 0x0016) +#define PSA_ECC_CURVE_SECP256R1 ((psa_ecc_curve_t) 0x0017) +#define PSA_ECC_CURVE_SECP384R1 ((psa_ecc_curve_t) 0x0018) +#define PSA_ECC_CURVE_SECP521R1 ((psa_ecc_curve_t) 0x0019) +#define PSA_ECC_CURVE_BRAINPOOL_P256R1 ((psa_ecc_curve_t) 0x001a) +#define PSA_ECC_CURVE_BRAINPOOL_P384R1 ((psa_ecc_curve_t) 0x001b) +#define PSA_ECC_CURVE_BRAINPOOL_P512R1 ((psa_ecc_curve_t) 0x001c) +#define PSA_ECC_CURVE_CURVE25519 ((psa_ecc_curve_t) 0x001d) +#define PSA_ECC_CURVE_CURVE448 ((psa_ecc_curve_t) 0x001e) + +/** The block size of a block cipher. + * + * \param type A cipher key type (value of type #psa_key_type_t). + * + * \return The block size for a block cipher, or 1 for a stream cipher. + * The return value is undefined if \p type is not a supported + * cipher key type. + * + * \note It is possible to build stream cipher algorithms on top of a block + * cipher, for example CTR mode (#PSA_ALG_CTR). + * This macro only takes the key type into account, so it cannot be + * used to determine the size of the data that #psa_cipher_update() + * might buffer for future processing in general. + * + * \note This macro returns a compile-time constant if its argument is one. + * + * \warning This macro may evaluate its argument multiple times. + */ +#define PSA_BLOCK_CIPHER_BLOCK_SIZE(type) \ + ( \ + (type) == PSA_KEY_TYPE_AES ? 16 : \ + (type) == PSA_KEY_TYPE_DES ? 8 : \ + (type) == PSA_KEY_TYPE_CAMELLIA ? 16 : \ + (type) == PSA_KEY_TYPE_ARC4 ? 1 : \ + 0) + +/** \brief Encoding of a cryptographic algorithm. + * + * For algorithms that can be applied to multiple key types, this type + * does not encode the key type. For example, for symmetric ciphers + * based on a block cipher, #psa_algorithm_t encodes the block cipher + * mode and the padding mode while the block cipher itself is encoded + * via #psa_key_type_t. + */ +typedef uint32_t psa_algorithm_t; + +#define PSA_ALG_VENDOR_FLAG ((psa_algorithm_t)0x80000000) +#define PSA_ALG_CATEGORY_MASK ((psa_algorithm_t)0x7f000000) +#define PSA_ALG_CATEGORY_HASH ((psa_algorithm_t)0x01000000) +#define PSA_ALG_CATEGORY_MAC ((psa_algorithm_t)0x02000000) +#define PSA_ALG_CATEGORY_CIPHER ((psa_algorithm_t)0x04000000) +#define PSA_ALG_CATEGORY_AEAD ((psa_algorithm_t)0x06000000) +#define PSA_ALG_CATEGORY_SIGN ((psa_algorithm_t)0x10000000) +#define PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION ((psa_algorithm_t)0x12000000) +#define PSA_ALG_CATEGORY_KEY_AGREEMENT ((psa_algorithm_t)0x22000000) +#define PSA_ALG_CATEGORY_KEY_DERIVATION ((psa_algorithm_t)0x30000000) +#define PSA_ALG_CATEGORY_KEY_SELECTION ((psa_algorithm_t)0x31000000) + +#define PSA_ALG_IS_VENDOR_DEFINED(alg) \ + (((alg) & PSA_ALG_VENDOR_FLAG) != 0) + +/** Whether the specified algorithm is a hash algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a hash algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_HASH(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_HASH) + +/** Whether the specified algorithm is a MAC algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a MAC algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_MAC(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_MAC) + +/** Whether the specified algorithm is a symmetric cipher algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a symmetric cipher algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_CIPHER(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_CIPHER) + +/** Whether the specified algorithm is an authenticated encryption + * with associated data (AEAD) algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is an AEAD algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_AEAD(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_AEAD) + +/** Whether the specified algorithm is a public-key signature algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a public-key signature algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_SIGN(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_SIGN) + +/** Whether the specified algorithm is a public-key encryption algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a public-key encryption algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_ASYMMETRIC_ENCRYPTION(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION) + +#define PSA_ALG_KEY_SELECTION_FLAG ((psa_algorithm_t)0x01000000) +/** Whether the specified algorithm is a key agreement algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a key agreement algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_KEY_AGREEMENT(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK & ~PSA_ALG_KEY_SELECTION_FLAG) == \ + PSA_ALG_CATEGORY_KEY_AGREEMENT) + +/** Whether the specified algorithm is a key derivation algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a key derivation algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_KEY_DERIVATION(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_DERIVATION) + +/** Whether the specified algorithm is a key selection algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a key selection algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_KEY_SELECTION(alg) \ + (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_SELECTION) + +#define PSA_ALG_HASH_MASK ((psa_algorithm_t)0x000000ff) +#define PSA_ALG_MD2 ((psa_algorithm_t)0x01000001) +#define PSA_ALG_MD4 ((psa_algorithm_t)0x01000002) +#define PSA_ALG_MD5 ((psa_algorithm_t)0x01000003) +#define PSA_ALG_RIPEMD160 ((psa_algorithm_t)0x01000004) +#define PSA_ALG_SHA_1 ((psa_algorithm_t)0x01000005) +/** SHA2-224 */ +#define PSA_ALG_SHA_224 ((psa_algorithm_t)0x01000008) +/** SHA2-256 */ +#define PSA_ALG_SHA_256 ((psa_algorithm_t)0x01000009) +/** SHA2-384 */ +#define PSA_ALG_SHA_384 ((psa_algorithm_t)0x0100000a) +/** SHA2-512 */ +#define PSA_ALG_SHA_512 ((psa_algorithm_t)0x0100000b) +/** SHA2-512/224 */ +#define PSA_ALG_SHA_512_224 ((psa_algorithm_t)0x0100000c) +/** SHA2-512/256 */ +#define PSA_ALG_SHA_512_256 ((psa_algorithm_t)0x0100000d) +/** SHA3-224 */ +#define PSA_ALG_SHA3_224 ((psa_algorithm_t)0x01000010) +/** SHA3-256 */ +#define PSA_ALG_SHA3_256 ((psa_algorithm_t)0x01000011) +/** SHA3-384 */ +#define PSA_ALG_SHA3_384 ((psa_algorithm_t)0x01000012) +/** SHA3-512 */ +#define PSA_ALG_SHA3_512 ((psa_algorithm_t)0x01000013) + +#define PSA_ALG_MAC_SUBCATEGORY_MASK ((psa_algorithm_t)0x00c00000) +#define PSA_ALG_HMAC_BASE ((psa_algorithm_t)0x02800000) +/** Macro to build an HMAC algorithm. + * + * For example, #PSA_ALG_HMAC(#PSA_ALG_SHA_256) is HMAC-SHA-256. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding HMAC algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_HMAC(hash_alg) \ + (PSA_ALG_HMAC_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) + +#define PSA_ALG_HMAC_GET_HASH(hmac_alg) \ + (PSA_ALG_CATEGORY_HASH | ((hmac_alg) & PSA_ALG_HASH_MASK)) + +/** Whether the specified algorithm is an HMAC algorithm. + * + * HMAC is a family of MAC algorithms that are based on a hash function. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is an HMAC algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_HMAC(alg) \ + (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \ + PSA_ALG_HMAC_BASE) + +/* In the encoding of a MAC algorithm, the bits corresponding to + * PSA_ALG_MAC_TRUNCATION_MASK encode the length to which the MAC is + * truncated. As an exception, the value 0 means the untruncated algorithm, + * whatever its length is. The length is encoded in 6 bits, so it can + * reach up to 63; the largest MAC is 64 bytes so its trivial truncation + * to full length is correctly encoded as 0 and any non-trivial truncation + * is correctly encoded as a value between 1 and 63. */ +#define PSA_ALG_MAC_TRUNCATION_MASK ((psa_algorithm_t)0x00003f00) +#define PSA_MAC_TRUNCATION_OFFSET 8 + +/** Macro to build a truncated MAC algorithm. + * + * A truncated MAC algorithm is identical to the corresponding MAC + * algorithm except that the MAC value for the truncated algorithm + * consists of only the first \p mac_length bytes of the MAC value + * for the untruncated algorithm. + * + * \note This macro may allow constructing algorithm identifiers that + * are not valid, either because the specified length is larger + * than the untruncated MAC or because the specified length is + * smaller than permitted by the implementation. + * + * \note It is implementation-defined whether a truncated MAC that + * is truncated to the same length as the MAC of the untruncated + * algorithm is considered identical to the untruncated algorithm + * for policy comparison purposes. + * + * \param alg A MAC algorithm identifier (value of type + * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p alg) + * is true). This may be a truncated or untruncated + * MAC algorithm. + * \param mac_length Desired length of the truncated MAC in bytes. + * This must be at most the full length of the MAC + * and must be at least an implementation-specified + * minimum. The implementation-specified minimum + * shall not be zero. + * + * \return The corresponding MAC algorithm with the specified + * length. + * \return Unspecified if \p alg is not a supported + * MAC algorithm or if \p mac_length is too small or + * too large for the specified MAC algorithm. + */ +#define PSA_ALG_TRUNCATED_MAC(alg, mac_length) \ + (((alg) & ~PSA_ALG_MAC_TRUNCATION_MASK) | \ + ((mac_length) << PSA_MAC_TRUNCATION_OFFSET & PSA_ALG_MAC_TRUNCATION_MASK)) + +/** Macro to build the base MAC algorithm corresponding to a truncated + * MAC algorithm. + * + * \param alg A MAC algorithm identifier (value of type + * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p alg) + * is true). This may be a truncated or untruncated + * MAC algorithm. + * + * \return The corresponding base MAC algorithm. + * \return Unspecified if \p alg is not a supported + * MAC algorithm. + */ +#define PSA_ALG_FULL_LENGTH_MAC(alg) \ + ((alg) & ~PSA_ALG_MAC_TRUNCATION_MASK) + +/** Length to which a MAC algorithm is truncated. + * + * \param alg A MAC algorithm identifier (value of type + * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p alg) + * is true). + * + * \return Length of the truncated MAC in bytes. + * \return 0 if \p alg is a non-truncated MAC algorithm. + * \return Unspecified if \p alg is not a supported + * MAC algorithm. + */ +#define PSA_MAC_TRUNCATED_LENGTH(alg) \ + (((alg) & PSA_ALG_MAC_TRUNCATION_MASK) >> PSA_MAC_TRUNCATION_OFFSET) + +#define PSA_ALG_CIPHER_MAC_BASE ((psa_algorithm_t)0x02c00000) +#define PSA_ALG_CBC_MAC ((psa_algorithm_t)0x02c00001) +#define PSA_ALG_CMAC ((psa_algorithm_t)0x02c00002) +#define PSA_ALG_GMAC ((psa_algorithm_t)0x02c00003) + +/** Whether the specified algorithm is a MAC algorithm based on a block cipher. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a MAC algorithm based on a block cipher, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier. + */ +#define PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) \ + (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \ + PSA_ALG_CIPHER_MAC_BASE) + +#define PSA_ALG_CIPHER_STREAM_FLAG ((psa_algorithm_t)0x00800000) +#define PSA_ALG_CIPHER_FROM_BLOCK_FLAG ((psa_algorithm_t)0x00400000) + +/** Whether the specified algorithm is a stream cipher. + * + * A stream cipher is a symmetric cipher that encrypts or decrypts messages + * by applying a bitwise-xor with a stream of bytes that is generated + * from a key. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \p alg is a stream cipher algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \p alg is not a supported + * algorithm identifier or if it is not a symmetric cipher algorithm. + */ +#define PSA_ALG_IS_STREAM_CIPHER(alg) \ + (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_CIPHER_STREAM_FLAG)) == \ + (PSA_ALG_CATEGORY_CIPHER | PSA_ALG_CIPHER_STREAM_FLAG)) + +/** The ARC4 stream cipher algorithm. + */ +#define PSA_ALG_ARC4 ((psa_algorithm_t)0x04800001) + +/** The CTR stream cipher mode. + * + * CTR is a stream cipher which is built from a block cipher. + * The underlying block cipher is determined by the key type. + * For example, to use AES-128-CTR, use this algorithm with + * a key of type #PSA_KEY_TYPE_AES and a length of 128 bits (16 bytes). + */ +#define PSA_ALG_CTR ((psa_algorithm_t)0x04c00001) + +#define PSA_ALG_CFB ((psa_algorithm_t)0x04c00002) + +#define PSA_ALG_OFB ((psa_algorithm_t)0x04c00003) + +/** The XTS cipher mode. + * + * XTS is a cipher mode which is built from a block cipher. It requires at + * least one full block of input, but beyond this minimum the input + * does not need to be a whole number of blocks. + */ +#define PSA_ALG_XTS ((psa_algorithm_t)0x044000ff) + +/** The CBC block cipher chaining mode, with no padding. + * + * The underlying block cipher is determined by the key type. + * + * This symmetric cipher mode can only be used with messages whose lengths + * are whole number of blocks for the chosen block cipher. + */ +#define PSA_ALG_CBC_NO_PADDING ((psa_algorithm_t)0x04600100) + +/** The CBC block cipher chaining mode with PKCS#7 padding. + * + * The underlying block cipher is determined by the key type. + * + * This is the padding method defined by PKCS#7 (RFC 2315) §10.3. + */ +#define PSA_ALG_CBC_PKCS7 ((psa_algorithm_t)0x04600101) + +#define PSA_ALG_CCM ((psa_algorithm_t)0x06001001) +#define PSA_ALG_GCM ((psa_algorithm_t)0x06001002) + +/* In the encoding of a AEAD algorithm, the bits corresponding to + * PSA_ALG_AEAD_TAG_LENGTH_MASK encode the length of the AEAD tag. + * The constants for default lengths follow this encoding. + */ +#define PSA_ALG_AEAD_TAG_LENGTH_MASK ((psa_algorithm_t)0x00003f00) +#define PSA_AEAD_TAG_LENGTH_OFFSET 8 + +/** Macro to build a shortened AEAD algorithm. + * + * A shortened AEAD algorithm is similar to the corresponding AEAD + * algorithm, but has an authentication tag that consists of fewer bytes. + * Depending on the algorithm, the tag length may affect the calculation + * of the ciphertext. + * + * \param alg A AEAD algorithm identifier (value of type + * #psa_algorithm_t such that #PSA_ALG_IS_AEAD(\p alg) + * is true). + * \param tag_length Desired length of the authentication tag in bytes. + * + * \return The corresponding AEAD algorithm with the specified + * length. + * \return Unspecified if \p alg is not a supported + * AEAD algorithm or if \p tag_length is not valid + * for the specified AEAD algorithm. + */ +#define PSA_ALG_AEAD_WITH_TAG_LENGTH(alg, tag_length) \ + (((alg) & ~PSA_ALG_AEAD_TAG_LENGTH_MASK) | \ + ((tag_length) << PSA_AEAD_TAG_LENGTH_OFFSET & \ + PSA_ALG_AEAD_TAG_LENGTH_MASK)) + +/** Calculate the corresponding AEAD algorithm with the default tag length. + * + * \param alg An AEAD algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(\p alg) is true). + * + * \return The corresponding AEAD algorithm with the default tag length + * for that algorithm. + */ +#define PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH(alg) \ + ( \ + PSA__ALG_AEAD_WITH_DEFAULT_TAG_LENGTH__CASE(alg, PSA_ALG_CCM) \ + PSA__ALG_AEAD_WITH_DEFAULT_TAG_LENGTH__CASE(alg, PSA_ALG_GCM) \ + 0) +#define PSA__ALG_AEAD_WITH_DEFAULT_TAG_LENGTH__CASE(alg, ref) \ + PSA_ALG_AEAD_WITH_TAG_LENGTH(alg, 0) == \ + PSA_ALG_AEAD_WITH_TAG_LENGTH(ref, 0) ? \ + ref : + +#define PSA_ALG_RSA_PKCS1V15_SIGN_BASE ((psa_algorithm_t)0x10020000) +/** RSA PKCS#1 v1.5 signature with hashing. + * + * This is the signature scheme defined by RFC 8017 + * (PKCS#1: RSA Cryptography Specifications) under the name + * RSASSA-PKCS1-v1_5. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding RSA PKCS#1 v1.5 signature algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_RSA_PKCS1V15_SIGN(hash_alg) \ + (PSA_ALG_RSA_PKCS1V15_SIGN_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +/** Raw PKCS#1 v1.5 signature. + * + * The input to this algorithm is the DigestInfo structure used by + * RFC 8017 (PKCS#1: RSA Cryptography Specifications), §9.2 + * steps 3–6. + */ +#define PSA_ALG_RSA_PKCS1V15_SIGN_RAW PSA_ALG_RSA_PKCS1V15_SIGN_BASE +#define PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PKCS1V15_SIGN_BASE) + +#define PSA_ALG_RSA_PSS_BASE ((psa_algorithm_t)0x10030000) +/** RSA PSS signature with hashing. + * + * This is the signature scheme defined by RFC 8017 + * (PKCS#1: RSA Cryptography Specifications) under the name + * RSASSA-PSS, with the message generation function MGF1, and with + * a salt length equal to the length of the hash. The specified + * hash algorithm is used to hash the input message, to create the + * salted hash, and for the mask generation. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding RSA PSS signature algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_RSA_PSS(hash_alg) \ + (PSA_ALG_RSA_PSS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +#define PSA_ALG_IS_RSA_PSS(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PSS_BASE) + +#define PSA_ALG_DSA_BASE ((psa_algorithm_t)0x10040000) +/** DSA signature with hashing. + * + * This is the signature scheme defined by FIPS 186-4, + * with a random per-message secret number (*k*). + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding DSA signature algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_DSA(hash_alg) \ + (PSA_ALG_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +#define PSA_ALG_DETERMINISTIC_DSA_BASE ((psa_algorithm_t)0x10050000) +#define PSA_ALG_DSA_DETERMINISTIC_FLAG ((psa_algorithm_t)0x00010000) +#define PSA_ALG_DETERMINISTIC_DSA(hash_alg) \ + (PSA_ALG_DETERMINISTIC_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +#define PSA_ALG_IS_DSA(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) == \ + PSA_ALG_DSA_BASE) +#define PSA_ALG_DSA_IS_DETERMINISTIC(alg) \ + (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0) +#define PSA_ALG_IS_DETERMINISTIC_DSA(alg) \ + (PSA_ALG_IS_DSA(alg) && PSA_ALG_DSA_IS_DETERMINISTIC(alg)) +#define PSA_ALG_IS_RANDOMIZED_DSA(alg) \ + (PSA_ALG_IS_DSA(alg) && !PSA_ALG_DSA_IS_DETERMINISTIC(alg)) + +#define PSA_ALG_ECDSA_BASE ((psa_algorithm_t)0x10060000) +/** ECDSA signature with hashing. + * + * This is the ECDSA signature scheme defined by ANSI X9.62, + * with a random per-message secret number (*k*). + * + * The representation of the signature as a byte string consists of + * the concatentation of the signature values *r* and *s*. Each of + * *r* and *s* is encoded as an *N*-octet string, where *N* is the length + * of the base point of the curve in octets. Each value is represented + * in big-endian order (most significant octet first). + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding ECDSA signature algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_ECDSA(hash_alg) \ + (PSA_ALG_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +/** ECDSA signature without hashing. + * + * This is the same signature scheme as #PSA_ALG_ECDSA(), but + * without specifying a hash algorithm. This algorithm may only be + * used to sign or verify a sequence of bytes that should be an + * already-calculated hash. Note that the input is padded with + * zeros on the left or truncated on the left as required to fit + * the curve size. + */ +#define PSA_ALG_ECDSA_ANY PSA_ALG_ECDSA_BASE +#define PSA_ALG_DETERMINISTIC_ECDSA_BASE ((psa_algorithm_t)0x10070000) +/** Deterministic ECDSA signature with hashing. + * + * This is the deterministic ECDSA signature scheme defined by RFC 6979. + * + * The representation of a signature is the same as with #PSA_ALG_ECDSA(). + * + * Note that when this algorithm is used for verification, signatures + * made with randomized ECDSA (#PSA_ALG_ECDSA(\p hash_alg)) with the + * same private key are accepted. In other words, + * #PSA_ALG_DETERMINISTIC_ECDSA(\p hash_alg) differs from + * #PSA_ALG_ECDSA(\p hash_alg) only for signature, not for verification. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding deterministic ECDSA signature + * algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_DETERMINISTIC_ECDSA(hash_alg) \ + (PSA_ALG_DETERMINISTIC_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +#define PSA_ALG_IS_ECDSA(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) == \ + PSA_ALG_ECDSA_BASE) +#define PSA_ALG_ECDSA_IS_DETERMINISTIC(alg) \ + (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0) +#define PSA_ALG_IS_DETERMINISTIC_ECDSA(alg) \ + (PSA_ALG_IS_ECDSA(alg) && PSA_ALG_ECDSA_IS_DETERMINISTIC(alg)) +#define PSA_ALG_IS_RANDOMIZED_ECDSA(alg) \ + (PSA_ALG_IS_ECDSA(alg) && !PSA_ALG_ECDSA_IS_DETERMINISTIC(alg)) + +/** Get the hash used by a hash-and-sign signature algorithm. + * + * A hash-and-sign algorithm is a signature algorithm which is + * composed of two phases: first a hashing phase which does not use + * the key and produces a hash of the input message, then a signing + * phase which only uses the hash and the key and not the message + * itself. + * + * \param alg A signature algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_SIGN(\p alg) is true). + * + * \return The underlying hash algorithm if \p alg is a hash-and-sign + * algorithm. + * \return 0 if \p alg is a signature algorithm that does not + * follow the hash-and-sign structure. + * \return Unspecified if \p alg is not a signature algorithm or + * if it is not supported by the implementation. + */ +#define PSA_ALG_SIGN_GET_HASH(alg) \ + (PSA_ALG_IS_RSA_PSS(alg) || PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) || \ + PSA_ALG_IS_DSA(alg) || PSA_ALG_IS_ECDSA(alg) ? \ + ((alg) & PSA_ALG_HASH_MASK) == 0 ? /*"raw" algorithm*/ 0 : \ + ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \ + 0) + +/** RSA PKCS#1 v1.5 encryption. + */ +#define PSA_ALG_RSA_PKCS1V15_CRYPT ((psa_algorithm_t)0x12020000) + +#define PSA_ALG_RSA_OAEP_BASE ((psa_algorithm_t)0x12030000) +/** RSA OAEP encryption. + * + * This is the encryption scheme defined by RFC 8017 + * (PKCS#1: RSA Cryptography Specifications) under the name + * RSAES-OAEP, with the message generation function MGF1. + * + * \param hash_alg The hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true) to use + * for MGF1. + * + * \return The corresponding RSA OAEP signature algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_RSA_OAEP(hash_alg) \ + (PSA_ALG_RSA_OAEP_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +#define PSA_ALG_IS_RSA_OAEP(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_OAEP_BASE) +#define PSA_ALG_RSA_OAEP_GET_HASH(alg) \ + (PSA_ALG_IS_RSA_OAEP(alg) ? \ + ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \ + 0) + +#define PSA_ALG_HKDF_BASE ((psa_algorithm_t)0x30000100) +/** Macro to build an HKDF algorithm. + * + * For example, `PSA_ALG_HKDF(PSA_ALG_SHA256)` is HKDF using HMAC-SHA-256. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding HKDF algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_HKDF(hash_alg) \ + (PSA_ALG_HKDF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) +/** Whether the specified algorithm is an HKDF algorithm. + * + * HKDF is a family of key derivation algorithms that are based on a hash + * function and the HMAC construction. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \c alg is an HKDF algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \c alg is not a supported + * key derivation algorithm identifier. + */ +#define PSA_ALG_IS_HKDF(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_BASE) +#define PSA_ALG_HKDF_GET_HASH(hkdf_alg) \ + (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) + +#define PSA_ALG_TLS12_PRF_BASE ((psa_algorithm_t)0x30000200) +/** Macro to build a TLS-1.2 PRF algorithm. + * + * TLS 1.2 uses a custom pseudorandom function (PRF) for key schedule, + * specified in Section 5 of RFC 5246. It is based on HMAC and can be + * used with either SHA-256 or SHA-384. + * + * For the application to TLS-1.2, the salt and label arguments passed + * to psa_key_derivation() are what's called 'seed' and 'label' in RFC 5246, + * respectively. For example, for TLS key expansion, the salt is the + * concatenation of ServerHello.Random + ClientHello.Random, + * while the label is "key expansion". + * + * For example, `PSA_ALG_TLS12_PRF(PSA_ALG_SHA256)` represents the + * TLS 1.2 PRF using HMAC-SHA-256. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding TLS-1.2 PRF algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_TLS12_PRF(hash_alg) \ + (PSA_ALG_TLS12_PRF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) + +/** Whether the specified algorithm is a TLS-1.2 PRF algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \c alg is a TLS-1.2 PRF algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \c alg is not a supported + * key derivation algorithm identifier. + */ +#define PSA_ALG_IS_TLS12_PRF(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PRF_BASE) +#define PSA_ALG_TLS12_PRF_GET_HASH(hkdf_alg) \ + (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) + +#define PSA_ALG_TLS12_PSK_TO_MS_BASE ((psa_algorithm_t)0x30000300) +/** Macro to build a TLS-1.2 PSK-to-MasterSecret algorithm. + * + * In a pure-PSK handshake in TLS 1.2, the master secret is derived + * from the PreSharedKey (PSK) through the application of padding + * (RFC 4279, Section 2) and the TLS-1.2 PRF (RFC 5246, Section 5). + * The latter is based on HMAC and can be used with either SHA-256 + * or SHA-384. + * + * For the application to TLS-1.2, the salt passed to psa_key_derivation() + * (and forwarded to the TLS-1.2 PRF) is the concatenation of the + * ClientHello.Random + ServerHello.Random, while the label is "master secret" + * or "extended master secret". + * + * For example, `PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA256)` represents the + * TLS-1.2 PSK to MasterSecret derivation PRF using HMAC-SHA-256. + * + * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p hash_alg) is true). + * + * \return The corresponding TLS-1.2 PSK to MS algorithm. + * \return Unspecified if \p alg is not a supported + * hash algorithm. + */ +#define PSA_ALG_TLS12_PSK_TO_MS(hash_alg) \ + (PSA_ALG_TLS12_PSK_TO_MS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) + +/** Whether the specified algorithm is a TLS-1.2 PSK to MS algorithm. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \c alg is a TLS-1.2 PSK to MS algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \c alg is not a supported + * key derivation algorithm identifier. + */ +#define PSA_ALG_IS_TLS12_PSK_TO_MS(alg) \ + (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PSK_TO_MS_BASE) +#define PSA_ALG_TLS12_PSK_TO_MS_GET_HASH(hkdf_alg) \ + (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) + +#define PSA_ALG_KEY_DERIVATION_MASK ((psa_algorithm_t)0x010fffff) + +/** Use a shared secret as is. + * + * Specify this algorithm as the selection component of a key agreement + * to use the raw result of the key agreement as key material. + * + * \warning The raw result of a key agreement algorithm such as finite-field + * Diffie-Hellman or elliptic curve Diffie-Hellman has biases and should + * not be used directly as key material. It can however be used as the secret + * input in a key derivation algorithm. + */ +#define PSA_ALG_SELECT_RAW ((psa_algorithm_t)0x31000001) + +#define PSA_ALG_KEY_AGREEMENT_GET_KDF(alg) \ + (((alg) & PSA_ALG_KEY_DERIVATION_MASK) | PSA_ALG_CATEGORY_KEY_DERIVATION) + +#define PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) \ + ((alg) & ~PSA_ALG_KEY_DERIVATION_MASK) + +#define PSA_ALG_FFDH_BASE ((psa_algorithm_t)0x22100000) +/** The Diffie-Hellman key agreement algorithm. + * + * This algorithm combines the finite-field Diffie-Hellman (DH) key + * agreement, also known as Diffie-Hellman-Merkle (DHM) key agreement, + * to produce a shared secret from a private key and the peer's + * public key, with a key selection or key derivation algorithm to produce + * one or more shared keys and other shared cryptographic material. + * + * The shared secret produced by key agreement and passed as input to the + * derivation or selection algorithm \p kdf_alg is the shared secret + * `g^{ab}` in big-endian format. + * It is `ceiling(m / 8)` bytes long where `m` is the size of the prime `p` + * in bits. + * + * \param kdf_alg A key derivation algorithm (\c PSA_ALG_XXX value such + * that #PSA_ALG_IS_KEY_DERIVATION(\p hash_alg) is true) + * or a key selection algorithm (\c PSA_ALG_XXX value such + * that #PSA_ALG_IS_KEY_SELECTION(\p hash_alg) is true). + * + * \return The Diffie-Hellman algorithm with the specified + * selection or derivation algorithm. + */ +#define PSA_ALG_FFDH(kdf_alg) \ + (PSA_ALG_FFDH_BASE | ((kdf_alg) & PSA_ALG_KEY_DERIVATION_MASK)) +/** Whether the specified algorithm is a finite field Diffie-Hellman algorithm. + * + * This includes every supported key selection or key agreement algorithm + * for the output of the Diffie-Hellman calculation. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \c alg is a finite field Diffie-Hellman algorithm, 0 otherwise. + * This macro may return either 0 or 1 if \c alg is not a supported + * key agreement algorithm identifier. + */ +#define PSA_ALG_IS_FFDH(alg) \ + (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_FFDH_BASE) + +#define PSA_ALG_ECDH_BASE ((psa_algorithm_t)0x22200000) +/** The elliptic curve Diffie-Hellman (ECDH) key agreement algorithm. + * + * This algorithm combines the elliptic curve Diffie-Hellman key + * agreement to produce a shared secret from a private key and the peer's + * public key, with a key selection or key derivation algorithm to produce + * one or more shared keys and other shared cryptographic material. + * + * The shared secret produced by key agreement and passed as input to the + * derivation or selection algorithm \p kdf_alg is the x-coordinate of + * the shared secret point. It is always `ceiling(m / 8)` bytes long where + * `m` is the bit size associated with the curve, i.e. the bit size of the + * order of the curve's coordinate field. When `m` is not a multiple of 8, + * the byte containing the most significant bit of the shared secret + * is padded with zero bits. The byte order is either little-endian + * or big-endian depending on the curve type. + * + * - For Montgomery curves (curve types `PSA_ECC_CURVE_CURVEXXX`), + * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` + * in little-endian byte order. + * The bit size is 448 for Curve448 and 255 for Curve25519. + * - For Weierstrass curves over prime fields (curve types + * `PSA_ECC_CURVE_SECPXXX` and `PSA_ECC_CURVE_BRAINPOOL_PXXX`), + * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` + * in big-endian byte order. + * The bit size is `m = ceiling(log_2(p))` for the field `F_p`. + * - For Weierstrass curves over binary fields (curve types + * `PSA_ECC_CURVE_SECTXXX`), + * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` + * in big-endian byte order. + * The bit size is `m` for the field `F_{2^m}`. + * + * \param kdf_alg A key derivation algorithm (\c PSA_ALG_XXX value such + * that #PSA_ALG_IS_KEY_DERIVATION(\p hash_alg) is true) + * or a selection algorithm (\c PSA_ALG_XXX value such + * that #PSA_ALG_IS_KEY_SELECTION(\p hash_alg) is true). + * + * \return The Diffie-Hellman algorithm with the specified + * selection or derivation algorithm. + */ +#define PSA_ALG_ECDH(kdf_alg) \ + (PSA_ALG_ECDH_BASE | ((kdf_alg) & PSA_ALG_KEY_DERIVATION_MASK)) +/** Whether the specified algorithm is an elliptic curve Diffie-Hellman + * algorithm. + * + * This includes every supported key selection or key agreement algorithm + * for the output of the Diffie-Hellman calculation. + * + * \param alg An algorithm identifier (value of type #psa_algorithm_t). + * + * \return 1 if \c alg is an elliptic curve Diffie-Hellman algorithm, + * 0 otherwise. + * This macro may return either 0 or 1 if \c alg is not a supported + * key agreement algorithm identifier. + */ +#define PSA_ALG_IS_ECDH(alg) \ + (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_ECDH_BASE) + +/**@}*/ + +/** \defgroup key_management Key management + * @{ + */ + +/** + * \brief Import a key in binary format. + * + * This function supports any output from psa_export_key(). Refer to the + * documentation of psa_export_public_key() for the format of public keys + * and to the documentation of psa_export_key() for the format for + * other key types. + * + * This specification supports a single format for each key type. + * Implementations may support other formats as long as the standard + * format is supported. Implementations that support other formats + * should ensure that the formats are clearly unambiguous so as to + * minimize the risk that an invalid input is accidentally interpreted + * according to a different format. + * + * \param key Slot where the key will be stored. This must be a + * valid slot for a key of the chosen type. It must + * be unoccupied. + * \param type Key type (a \c PSA_KEY_TYPE_XXX value). On a successful + * import, the key slot will contain a key of this type. + * \param[in] data Buffer containing the key data. The content of this + * buffer is interpreted according to \p type. It must + * contain the format described in the documentation + * of psa_export_key() or psa_export_public_key() for + * the chosen type. + * \param data_length Size of the \p data buffer in bytes. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_NOT_SUPPORTED + * The key type or key size is not supported, either by the + * implementation in general or in this particular slot. + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The key slot is invalid, + * or the key data is not correctly formatted. + * \retval #PSA_ERROR_OCCUPIED_SLOT + * There is already a key in the specified slot. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_INSUFFICIENT_STORAGE + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_STORAGE_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_import_key(psa_key_slot_t key, + psa_key_type_t type, + const uint8_t *data, + size_t data_length); + +/** + * \brief Destroy a key and restore the slot to its default state. + * + * This function destroys the content of the key slot from both volatile + * memory and, if applicable, non-volatile storage. Implementations shall + * make a best effort to ensure that any previous content of the slot is + * unrecoverable. + * + * This function also erases any metadata such as policies. It returns the + * specified slot to its default state. + * + * \param key The key slot to erase. + * + * \retval #PSA_SUCCESS + * The slot's content, if any, has been erased. + * \retval #PSA_ERROR_NOT_PERMITTED + * The slot holds content and cannot be erased because it is + * read-only, either due to a policy or due to physical restrictions. + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The specified slot number does not designate a valid slot. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * There was an failure in communication with the cryptoprocessor. + * The key material may still be present in the cryptoprocessor. + * \retval #PSA_ERROR_STORAGE_FAILURE + * The storage is corrupted. Implementations shall make a best effort + * to erase key material even in this stage, however applications + * should be aware that it may be impossible to guarantee that the + * key material is not recoverable in such cases. + * \retval #PSA_ERROR_TAMPERING_DETECTED + * An unexpected condition which is not a storage corruption or + * a communication failure occurred. The cryptoprocessor may have + * been compromised. + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_destroy_key(psa_key_slot_t key); + +/** + * \brief Get basic metadata about a key. + * + * \param key Slot whose content is queried. This must + * be an occupied key slot. + * \param[out] type On success, the key type (a \c PSA_KEY_TYPE_XXX value). + * This may be a null pointer, in which case the key type + * is not written. + * \param[out] bits On success, the key size in bits. + * This may be a null pointer, in which case the key size + * is not written. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_get_key_information(psa_key_slot_t key, + psa_key_type_t *type, + size_t *bits); + +/** + * \brief Export a key in binary format. + * + * The output of this function can be passed to psa_import_key() to + * create an equivalent object. + * + * If the implementation of psa_import_key() supports other formats + * beyond the format specified here, the output from psa_export_key() + * must use the representation specified here, not the original + * representation. + * + * For standard key types, the output format is as follows: + * + * - For symmetric keys (including MAC keys), the format is the + * raw bytes of the key. + * - For DES, the key data consists of 8 bytes. The parity bits must be + * correct. + * - For Triple-DES, the format is the concatenation of the + * two or three DES keys. + * - For RSA key pairs (#PSA_KEY_TYPE_RSA_KEYPAIR), the format + * is the non-encrypted DER encoding of the representation defined by + * PKCS\#1 (RFC 8017) as `RSAPrivateKey`, version 0. + * ``` + * RSAPrivateKey ::= SEQUENCE { + * version INTEGER, -- must be 0 + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p-1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER, -- (inverse of q) mod p + * } + * ``` + * - For DSA private keys (#PSA_KEY_TYPE_DSA_KEYPAIR), the format + * is the non-encrypted DER encoding of the representation used by + * OpenSSL and OpenSSH, whose structure is described in ASN.1 as follows: + * ``` + * DSAPrivateKey ::= SEQUENCE { + * version INTEGER, -- must be 0 + * prime INTEGER, -- p + * subprime INTEGER, -- q + * generator INTEGER, -- g + * public INTEGER, -- y + * private INTEGER, -- x + * } + * ``` + * - For elliptic curve key pairs (key types for which + * #PSA_KEY_TYPE_IS_ECC_KEYPAIR is true), the format is + * a representation of the private value as a `ceiling(m/8)`-byte string + * where `m` is the bit size associated with the curve, i.e. the bit size + * of the order of the curve's coordinate field. This byte string is + * in little-endian order for Montgomery curves (curve types + * `PSA_ECC_CURVE_CURVEXXX`), and in big-endian order for Weierstrass + * curves (curve types `PSA_ECC_CURVE_SECTXXX`, `PSA_ECC_CURVE_SECPXXX` + * and `PSA_ECC_CURVE_BRAINPOOL_PXXX`). + * This is the content of the `privateKey` field of the `ECPrivateKey` + * format defined by RFC 5915. + * - For public keys (key types for which #PSA_KEY_TYPE_IS_PUBLIC_KEY is + * true), the format is the same as for psa_export_public_key(). + * + * \param key Slot whose content is to be exported. This must + * be an occupied key slot. + * \param[out] data Buffer where the key data is to be written. + * \param data_size Size of the \p data buffer in bytes. + * \param[out] data_length On success, the number of bytes + * that make up the key data. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p data buffer is too small. You can determine a + * sufficient buffer size by calling + * #PSA_KEY_EXPORT_MAX_SIZE(\c type, \c bits) + * where \c type is the key type + * and \c bits is the key size in bits. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_export_key(psa_key_slot_t key, + uint8_t *data, + size_t data_size, + size_t *data_length); + +/** + * \brief Export a public key or the public part of a key pair in binary format. + * + * The output of this function can be passed to psa_import_key() to + * create an object that is equivalent to the public key. + * + * The format is the DER representation defined by RFC 5280 as + * `SubjectPublicKeyInfo`, with the `subjectPublicKey` format + * specified below. + * ``` + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING } + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL } + * ``` + * + * - For RSA public keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY), + * the `subjectPublicKey` format is defined by RFC 3279 §2.3.1 as + * `RSAPublicKey`, + * with the OID `rsaEncryption`, + * and with the parameters `NULL`. + * ``` + * pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) + * rsadsi(113549) pkcs(1) 1 } + * rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } + * + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER } -- e + * ``` + * - For DSA public keys (#PSA_KEY_TYPE_DSA_PUBLIC_KEY), + * the `subjectPublicKey` format is defined by RFC 3279 §2.3.2 as + * `DSAPublicKey`, + * with the OID `id-dsa`, + * and with the parameters `DSS-Parms`. + * ``` + * id-dsa OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 1 } + * + * Dss-Parms ::= SEQUENCE { + * p INTEGER, + * q INTEGER, + * g INTEGER } + * DSAPublicKey ::= INTEGER -- public key, Y + * ``` + * - For elliptic curve public keys (key types for which + * #PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY is true), + * the `subjectPublicKey` format is defined by RFC 3279 §2.3.5 as + * `ECPoint`, which contains the uncompressed + * representation defined by SEC1 §2.3.3. + * The OID is `id-ecPublicKey`, + * and the parameters must be given as a `namedCurve` OID as specified in + * RFC 5480 §2.1.1.1 or other applicable standards. + * ``` + * ansi-X9-62 OBJECT IDENTIFIER ::= + * { iso(1) member-body(2) us(840) 10045 } + * id-public-key-type OBJECT IDENTIFIER ::= { ansi-X9.62 2 } + * id-ecPublicKey OBJECT IDENTIFIER ::= { id-publicKeyType 1 } + * + * ECPoint ::= ... + * -- first 8 bits: 0x04; + * -- then x_P as a `ceiling(m/8)`-byte string, big endian; + * -- then y_P as a `ceiling(m/8)`-byte string, big endian; + * -- where `m` is the bit size associated with the curve, + * -- i.e. the bit size of `q` for a curve over `F_q`. + * + * EcpkParameters ::= CHOICE { -- other choices are not allowed + * namedCurve OBJECT IDENTIFIER } + * ``` + * + * \param key Slot whose content is to be exported. This must + * be an occupied key slot. + * \param[out] data Buffer where the key data is to be written. + * \param data_size Size of the \p data buffer in bytes. + * \param[out] data_length On success, the number of bytes + * that make up the key data. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The key is neither a public key nor a key pair. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p data buffer is too small. You can determine a + * sufficient buffer size by calling + * #PSA_KEY_EXPORT_MAX_SIZE(#PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(\c type), \c bits) + * where \c type is the key type + * and \c bits is the key size in bits. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_export_public_key(psa_key_slot_t key, + uint8_t *data, + size_t data_size, + size_t *data_length); + +/**@}*/ + +/** \defgroup policy Key policies + * @{ + */ + +/** \brief Encoding of permitted usage on a key. */ +typedef uint32_t psa_key_usage_t; + +/** Whether the key may be exported. + * + * A public key or the public part of a key pair may always be exported + * regardless of the value of this permission flag. + * + * If a key does not have export permission, implementations shall not + * allow the key to be exported in plain form from the cryptoprocessor, + * whether through psa_export_key() or through a proprietary interface. + * The key may however be exportable in a wrapped form, i.e. in a form + * where it is encrypted by another key. + */ +#define PSA_KEY_USAGE_EXPORT ((psa_key_usage_t)0x00000001) + +/** Whether the key may be used to encrypt a message. + * + * This flag allows the key to be used for a symmetric encryption operation, + * for an AEAD encryption-and-authentication operation, + * or for an asymmetric encryption operation, + * if otherwise permitted by the key's type and policy. + * + * For a key pair, this concerns the public key. + */ +#define PSA_KEY_USAGE_ENCRYPT ((psa_key_usage_t)0x00000100) + +/** Whether the key may be used to decrypt a message. + * + * This flag allows the key to be used for a symmetric decryption operation, + * for an AEAD decryption-and-verification operation, + * or for an asymmetric decryption operation, + * if otherwise permitted by the key's type and policy. + * + * For a key pair, this concerns the private key. + */ +#define PSA_KEY_USAGE_DECRYPT ((psa_key_usage_t)0x00000200) + +/** Whether the key may be used to sign a message. + * + * This flag allows the key to be used for a MAC calculation operation + * or for an asymmetric signature operation, + * if otherwise permitted by the key's type and policy. + * + * For a key pair, this concerns the private key. + */ +#define PSA_KEY_USAGE_SIGN ((psa_key_usage_t)0x00000400) + +/** Whether the key may be used to verify a message signature. + * + * This flag allows the key to be used for a MAC verification operation + * or for an asymmetric signature verification operation, + * if otherwise permitted by by the key's type and policy. + * + * For a key pair, this concerns the public key. + */ +#define PSA_KEY_USAGE_VERIFY ((psa_key_usage_t)0x00000800) + +/** Whether the key may be used to derive other keys. + */ +#define PSA_KEY_USAGE_DERIVE ((psa_key_usage_t)0x00001000) + +/** The type of the key policy data structure. + * + * This is an implementation-defined \c struct. Applications should not + * make any assumptions about the content of this structure except + * as directed by the documentation of a specific implementation. */ +typedef struct psa_key_policy_s psa_key_policy_t; + +/** \brief Initialize a key policy structure to a default that forbids all + * usage of the key. + * + * \param[out] policy The policy object to initialize. + */ +void psa_key_policy_init(psa_key_policy_t *policy); + +/** \brief Set the standard fields of a policy structure. + * + * Note that this function does not make any consistency check of the + * parameters. The values are only checked when applying the policy to + * a key slot with psa_set_key_policy(). + * + * \param[out] policy The policy object to modify. + * \param usage The permitted uses for the key. + * \param alg The algorithm that the key may be used for. + */ +void psa_key_policy_set_usage(psa_key_policy_t *policy, + psa_key_usage_t usage, + psa_algorithm_t alg); + +/** \brief Retrieve the usage field of a policy structure. + * + * \param[in] policy The policy object to query. + * + * \return The permitted uses for a key with this policy. + */ +psa_key_usage_t psa_key_policy_get_usage(const psa_key_policy_t *policy); + +/** \brief Retrieve the algorithm field of a policy structure. + * + * \param[in] policy The policy object to query. + * + * \return The permitted algorithm for a key with this policy. + */ +psa_algorithm_t psa_key_policy_get_algorithm(const psa_key_policy_t *policy); + +/** \brief Set the usage policy on a key slot. + * + * This function must be called on an empty key slot, before importing, + * generating or creating a key in the slot. Changing the policy of an + * existing key is not permitted. + * + * Implementations may set restrictions on supported key policies + * depending on the key type and the key slot. + * + * \param key The key slot whose policy is to be changed. + * \param[in] policy The policy object to query. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_OCCUPIED_SLOT + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_set_key_policy(psa_key_slot_t key, + const psa_key_policy_t *policy); + +/** \brief Get the usage policy for a key slot. + * + * \param key The key slot whose policy is being queried. + * \param[out] policy On success, the key's policy. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_get_key_policy(psa_key_slot_t key, + psa_key_policy_t *policy); + +/**@}*/ + +/** \defgroup persistence Key lifetime + * @{ + */ + +/** Encoding of key lifetimes. + */ +typedef uint32_t psa_key_lifetime_t; + +/** A volatile key slot retains its content as long as the application is + * running. It is guaranteed to be erased on a power reset. + */ +#define PSA_KEY_LIFETIME_VOLATILE ((psa_key_lifetime_t)0x00000000) + +/** A persistent key slot retains its content as long as it is not explicitly + * destroyed. + */ +#define PSA_KEY_LIFETIME_PERSISTENT ((psa_key_lifetime_t)0x00000001) + +/** A write-once key slot may not be modified once a key has been set. + * It will retain its content as long as the device remains operational. + */ +#define PSA_KEY_LIFETIME_WRITE_ONCE ((psa_key_lifetime_t)0x7fffffff) + +/** \brief Retrieve the lifetime of a key slot. + * + * The assignment of lifetimes to slots is implementation-dependent. + * + * \param key Slot to query. + * \param[out] lifetime On success, the lifetime value. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The key slot is invalid. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_get_key_lifetime(psa_key_slot_t key, + psa_key_lifetime_t *lifetime); + +/** \brief Change the lifetime of a key slot. + * + * Whether the lifetime of a key slot can be changed at all, and if so + * whether the lifetime of an occupied key slot can be changed, is + * implementation-dependent. + * + * When creating a persistent key, you must call this function before creating + * the key material with psa_import_key(), psa_generate_key() or + * psa_generator_import_key(). To open an existing persistent key, you must + * call this function with the correct lifetime value before using the slot + * for a cryptographic operation. Once a slot's lifetime has been set, + * the lifetime remains associated with the slot until a subsequent call to + * psa_set_key_lifetime(), until the key is wiped with psa_destroy_key or + * until the application terminates (or disconnects from the cryptography + * service, if the implementation offers such a possibility). + * + * \param key Slot whose lifetime is to be changed. + * \param lifetime The lifetime value to set for the given key slot. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The key slot is invalid, + * or the lifetime value is invalid. + * \retval #PSA_ERROR_NOT_SUPPORTED + * The implementation does not support the specified lifetime value, + * at least for the specified key slot. + * \retval #PSA_ERROR_OCCUPIED_SLOT + * The slot contains a key, and the implementation does not support + * changing the lifetime of an occupied slot. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_set_key_lifetime(psa_key_slot_t key, + psa_key_lifetime_t lifetime); + +/**@}*/ + +/** \defgroup hash Message digests + * @{ + */ + +/** The type of the state data structure for multipart hash operations. + * + * This is an implementation-defined \c struct. Applications should not + * make any assumptions about the content of this structure except + * as directed by the documentation of a specific implementation. */ +typedef struct psa_hash_operation_s psa_hash_operation_t; + +/** The size of the output of psa_hash_finish(), in bytes. + * + * This is also the hash size that psa_hash_verify() expects. + * + * \param alg A hash algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_HASH(\p alg) is true), or an HMAC algorithm + * (#PSA_ALG_HMAC(\c hash_alg) where \c hash_alg is a + * hash algorithm). + * + * \return The hash size for the specified hash algorithm. + * If the hash algorithm is not recognized, return 0. + * An implementation may return either 0 or the correct size + * for a hash algorithm that it recognizes, but does not support. + */ +#define PSA_HASH_SIZE(alg) \ + ( \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD2 ? 16 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD4 ? 16 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD5 ? 16 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_RIPEMD160 ? 20 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_1 ? 20 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_224 ? 28 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_256 ? 32 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_384 ? 48 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512 ? 64 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_224 ? 28 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_256 ? 32 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_224 ? 28 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_256 ? 32 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_384 ? 48 : \ + PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_512 ? 64 : \ + 0) + +/** Start a multipart hash operation. + * + * The sequence of operations to calculate a hash (message digest) + * is as follows: + * -# Allocate an operation object which will be passed to all the functions + * listed here. + * -# Call psa_hash_setup() to specify the algorithm. + * -# Call psa_hash_update() zero, one or more times, passing a fragment + * of the message each time. The hash that is calculated is the hash + * of the concatenation of these messages in order. + * -# To calculate the hash, call psa_hash_finish(). + * To compare the hash with an expected value, call psa_hash_verify(). + * + * The application may call psa_hash_abort() at any time after the operation + * has been initialized with psa_hash_setup(). + * + * After a successful call to psa_hash_setup(), the application must + * eventually terminate the operation. The following events terminate an + * operation: + * - A failed call to psa_hash_update(). + * - A call to psa_hash_finish(), psa_hash_verify() or psa_hash_abort(). + * + * \param[out] operation The operation object to use. + * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value + * such that #PSA_ALG_IS_HASH(\p alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not a hash algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_hash_setup(psa_hash_operation_t *operation, + psa_algorithm_t alg); + +/** Add a message fragment to a multipart hash operation. + * + * The application must call psa_hash_setup() before calling this function. + * + * If this function returns an error status, the operation becomes inactive. + * + * \param[in,out] operation Active hash operation. + * \param[in] input Buffer containing the message fragment to hash. + * \param input_length Size of the \p input buffer in bytes. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_hash_update(psa_hash_operation_t *operation, + const uint8_t *input, + size_t input_length); + +/** Finish the calculation of the hash of a message. + * + * The application must call psa_hash_setup() before calling this function. + * This function calculates the hash of the message formed by concatenating + * the inputs passed to preceding calls to psa_hash_update(). + * + * When this function returns, the operation becomes inactive. + * + * \warning Applications should not call this function if they expect + * a specific value for the hash. Call psa_hash_verify() instead. + * Beware that comparing integrity or authenticity data such as + * hash values with a function such as \c memcmp is risky + * because the time taken by the comparison may leak information + * about the hashed data which could allow an attacker to guess + * a valid hash and thereby bypass security controls. + * + * \param[in,out] operation Active hash operation. + * \param[out] hash Buffer where the hash is to be written. + * \param hash_size Size of the \p hash buffer in bytes. + * \param[out] hash_length On success, the number of bytes + * that make up the hash value. This is always + * #PSA_HASH_SIZE(\c alg) where \c alg is the + * hash algorithm that is calculated. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p hash buffer is too small. You can determine a + * sufficient buffer size by calling #PSA_HASH_SIZE(\c alg) + * where \c alg is the hash algorithm that is calculated. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_hash_finish(psa_hash_operation_t *operation, + uint8_t *hash, + size_t hash_size, + size_t *hash_length); + +/** Finish the calculation of the hash of a message and compare it with + * an expected value. + * + * The application must call psa_hash_setup() before calling this function. + * This function calculates the hash of the message formed by concatenating + * the inputs passed to preceding calls to psa_hash_update(). It then + * compares the calculated hash with the expected hash passed as a + * parameter to this function. + * + * When this function returns, the operation becomes inactive. + * + * \note Implementations shall make the best effort to ensure that the + * comparison between the actual hash and the expected hash is performed + * in constant time. + * + * \param[in,out] operation Active hash operation. + * \param[in] hash Buffer containing the expected hash value. + * \param hash_length Size of the \p hash buffer in bytes. + * + * \retval #PSA_SUCCESS + * The expected hash is identical to the actual hash of the message. + * \retval #PSA_ERROR_INVALID_SIGNATURE + * The hash of the message was calculated successfully, but it + * differs from the expected hash. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_hash_verify(psa_hash_operation_t *operation, + const uint8_t *hash, + size_t hash_length); + +/** Abort a hash operation. + * + * Aborting an operation frees all associated resources except for the + * \p operation structure itself. Once aborted, the operation object + * can be reused for another operation by calling + * psa_hash_setup() again. + * + * You may call this function any time after the operation object has + * been initialized by any of the following methods: + * - A call to psa_hash_setup(), whether it succeeds or not. + * - Initializing the \c struct to all-bits-zero. + * - Initializing the \c struct to logical zeros, e.g. + * `psa_hash_operation_t operation = {0}`. + * + * In particular, calling psa_hash_abort() after the operation has been + * terminated by a call to psa_hash_abort(), psa_hash_finish() or + * psa_hash_verify() is safe and has no effect. + * + * \param[in,out] operation Initialized hash operation. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BAD_STATE + * \p operation is not an active hash operation. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_hash_abort(psa_hash_operation_t *operation); + +/**@}*/ + +/** \defgroup MAC Message authentication codes + * @{ + */ + +/** The type of the state data structure for multipart MAC operations. + * + * This is an implementation-defined \c struct. Applications should not + * make any assumptions about the content of this structure except + * as directed by the documentation of a specific implementation. */ +typedef struct psa_mac_operation_s psa_mac_operation_t; + +/** Start a multipart MAC calculation operation. + * + * This function sets up the calculation of the MAC + * (message authentication code) of a byte string. + * To verify the MAC of a message against an + * expected value, use psa_mac_verify_setup() instead. + * + * The sequence of operations to calculate a MAC is as follows: + * -# Allocate an operation object which will be passed to all the functions + * listed here. + * -# Call psa_mac_sign_setup() to specify the algorithm and key. + * The key remains associated with the operation even if the content + * of the key slot changes. + * -# Call psa_mac_update() zero, one or more times, passing a fragment + * of the message each time. The MAC that is calculated is the MAC + * of the concatenation of these messages in order. + * -# At the end of the message, call psa_mac_sign_finish() to finish + * calculating the MAC value and retrieve it. + * + * The application may call psa_mac_abort() at any time after the operation + * has been initialized with psa_mac_sign_setup(). + * + * After a successful call to psa_mac_sign_setup(), the application must + * eventually terminate the operation through one of the following methods: + * - A failed call to psa_mac_update(). + * - A call to psa_mac_sign_finish() or psa_mac_abort(). + * + * \param[out] operation The operation object to use. + * \param key Slot containing the key to use for the operation. + * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value + * such that #PSA_ALG_IS_MAC(alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p key is not compatible with \p alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not a MAC algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg); + +/** Start a multipart MAC verification operation. + * + * This function sets up the verification of the MAC + * (message authentication code) of a byte string against an expected value. + * + * The sequence of operations to verify a MAC is as follows: + * -# Allocate an operation object which will be passed to all the functions + * listed here. + * -# Call psa_mac_verify_setup() to specify the algorithm and key. + * The key remains associated with the operation even if the content + * of the key slot changes. + * -# Call psa_mac_update() zero, one or more times, passing a fragment + * of the message each time. The MAC that is calculated is the MAC + * of the concatenation of these messages in order. + * -# At the end of the message, call psa_mac_verify_finish() to finish + * calculating the actual MAC of the message and verify it against + * the expected value. + * + * The application may call psa_mac_abort() at any time after the operation + * has been initialized with psa_mac_verify_setup(). + * + * After a successful call to psa_mac_verify_setup(), the application must + * eventually terminate the operation through one of the following methods: + * - A failed call to psa_mac_update(). + * - A call to psa_mac_verify_finish() or psa_mac_abort(). + * + * \param[out] operation The operation object to use. + * \param key Slot containing the key to use for the operation. + * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value + * such that #PSA_ALG_IS_MAC(\p alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \c key is not compatible with \c alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \c alg is not supported or is not a MAC algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg); + +/** Add a message fragment to a multipart MAC operation. + * + * The application must call psa_mac_sign_setup() or psa_mac_verify_setup() + * before calling this function. + * + * If this function returns an error status, the operation becomes inactive. + * + * \param[in,out] operation Active MAC operation. + * \param[in] input Buffer containing the message fragment to add to + * the MAC calculation. + * \param input_length Size of the \p input buffer in bytes. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_mac_update(psa_mac_operation_t *operation, + const uint8_t *input, + size_t input_length); + +/** Finish the calculation of the MAC of a message. + * + * The application must call psa_mac_sign_setup() before calling this function. + * This function calculates the MAC of the message formed by concatenating + * the inputs passed to preceding calls to psa_mac_update(). + * + * When this function returns, the operation becomes inactive. + * + * \warning Applications should not call this function if they expect + * a specific value for the MAC. Call psa_mac_verify_finish() instead. + * Beware that comparing integrity or authenticity data such as + * MAC values with a function such as \c memcmp is risky + * because the time taken by the comparison may leak information + * about the MAC value which could allow an attacker to guess + * a valid MAC and thereby bypass security controls. + * + * \param[in,out] operation Active MAC operation. + * \param[out] mac Buffer where the MAC value is to be written. + * \param mac_size Size of the \p mac buffer in bytes. + * \param[out] mac_length On success, the number of bytes + * that make up the MAC value. This is always + * #PSA_MAC_FINAL_SIZE(\c key_type, \c key_bits, \c alg) + * where \c key_type and \c key_bits are the type and + * bit-size respectively of the key and \c alg is the + * MAC algorithm that is calculated. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p mac buffer is too small. You can determine a + * sufficient buffer size by calling PSA_MAC_FINAL_SIZE(). + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation, + uint8_t *mac, + size_t mac_size, + size_t *mac_length); + +/** Finish the calculation of the MAC of a message and compare it with + * an expected value. + * + * The application must call psa_mac_verify_setup() before calling this function. + * This function calculates the MAC of the message formed by concatenating + * the inputs passed to preceding calls to psa_mac_update(). It then + * compares the calculated MAC with the expected MAC passed as a + * parameter to this function. + * + * When this function returns, the operation becomes inactive. + * + * \note Implementations shall make the best effort to ensure that the + * comparison between the actual MAC and the expected MAC is performed + * in constant time. + * + * \param[in,out] operation Active MAC operation. + * \param[in] mac Buffer containing the expected MAC value. + * \param mac_length Size of the \p mac buffer in bytes. + * + * \retval #PSA_SUCCESS + * The expected MAC is identical to the actual MAC of the message. + * \retval #PSA_ERROR_INVALID_SIGNATURE + * The MAC of the message was calculated successfully, but it + * differs from the expected MAC. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or already completed). + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation, + const uint8_t *mac, + size_t mac_length); + +/** Abort a MAC operation. + * + * Aborting an operation frees all associated resources except for the + * \p operation structure itself. Once aborted, the operation object + * can be reused for another operation by calling + * psa_mac_sign_setup() or psa_mac_verify_setup() again. + * + * You may call this function any time after the operation object has + * been initialized by any of the following methods: + * - A call to psa_mac_sign_setup() or psa_mac_verify_setup(), whether + * it succeeds or not. + * - Initializing the \c struct to all-bits-zero. + * - Initializing the \c struct to logical zeros, e.g. + * `psa_mac_operation_t operation = {0}`. + * + * In particular, calling psa_mac_abort() after the operation has been + * terminated by a call to psa_mac_abort(), psa_mac_sign_finish() or + * psa_mac_verify_finish() is safe and has no effect. + * + * \param[in,out] operation Initialized MAC operation. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BAD_STATE + * \p operation is not an active MAC operation. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_mac_abort(psa_mac_operation_t *operation); + +/**@}*/ + +/** \defgroup cipher Symmetric ciphers + * @{ + */ + +/** The type of the state data structure for multipart cipher operations. + * + * This is an implementation-defined \c struct. Applications should not + * make any assumptions about the content of this structure except + * as directed by the documentation of a specific implementation. */ +typedef struct psa_cipher_operation_s psa_cipher_operation_t; + +/** Set the key for a multipart symmetric encryption operation. + * + * The sequence of operations to encrypt a message with a symmetric cipher + * is as follows: + * -# Allocate an operation object which will be passed to all the functions + * listed here. + * -# Call psa_cipher_encrypt_setup() to specify the algorithm and key. + * The key remains associated with the operation even if the content + * of the key slot changes. + * -# Call either psa_cipher_generate_iv() or psa_cipher_set_iv() to + * generate or set the IV (initialization vector). You should use + * psa_cipher_generate_iv() unless the protocol you are implementing + * requires a specific IV value. + * -# Call psa_cipher_update() zero, one or more times, passing a fragment + * of the message each time. + * -# Call psa_cipher_finish(). + * + * The application may call psa_cipher_abort() at any time after the operation + * has been initialized with psa_cipher_encrypt_setup(). + * + * After a successful call to psa_cipher_encrypt_setup(), the application must + * eventually terminate the operation. The following events terminate an + * operation: + * - A failed call to psa_cipher_generate_iv(), psa_cipher_set_iv() + * or psa_cipher_update(). + * - A call to psa_cipher_finish() or psa_cipher_abort(). + * + * \param[out] operation The operation object to use. + * \param key Slot containing the key to use for the operation. + * \param alg The cipher algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_CIPHER(\p alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p key is not compatible with \p alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not a cipher algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg); + +/** Set the key for a multipart symmetric decryption operation. + * + * The sequence of operations to decrypt a message with a symmetric cipher + * is as follows: + * -# Allocate an operation object which will be passed to all the functions + * listed here. + * -# Call psa_cipher_decrypt_setup() to specify the algorithm and key. + * The key remains associated with the operation even if the content + * of the key slot changes. + * -# Call psa_cipher_update() with the IV (initialization vector) for the + * decryption. If the IV is prepended to the ciphertext, you can call + * psa_cipher_update() on a buffer containing the IV followed by the + * beginning of the message. + * -# Call psa_cipher_update() zero, one or more times, passing a fragment + * of the message each time. + * -# Call psa_cipher_finish(). + * + * The application may call psa_cipher_abort() at any time after the operation + * has been initialized with psa_cipher_decrypt_setup(). + * + * After a successful call to psa_cipher_decrypt_setup(), the application must + * eventually terminate the operation. The following events terminate an + * operation: + * - A failed call to psa_cipher_update(). + * - A call to psa_cipher_finish() or psa_cipher_abort(). + * + * \param[out] operation The operation object to use. + * \param key Slot containing the key to use for the operation. + * \param alg The cipher algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_CIPHER(\p alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p key is not compatible with \p alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not a cipher algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg); + +/** Generate an IV for a symmetric encryption operation. + * + * This function generates a random IV (initialization vector), nonce + * or initial counter value for the encryption operation as appropriate + * for the chosen algorithm, key type and key size. + * + * The application must call psa_cipher_encrypt_setup() before + * calling this function. + * + * If this function returns an error status, the operation becomes inactive. + * + * \param[in,out] operation Active cipher operation. + * \param[out] iv Buffer where the generated IV is to be written. + * \param iv_size Size of the \p iv buffer in bytes. + * \param[out] iv_length On success, the number of bytes of the + * generated IV. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or IV already set). + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p iv buffer is too small. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation, + unsigned char *iv, + size_t iv_size, + size_t *iv_length); + +/** Set the IV for a symmetric encryption or decryption operation. + * + * This function sets the random IV (initialization vector), nonce + * or initial counter value for the encryption or decryption operation. + * + * The application must call psa_cipher_encrypt_setup() before + * calling this function. + * + * If this function returns an error status, the operation becomes inactive. + * + * \note When encrypting, applications should use psa_cipher_generate_iv() + * instead of this function, unless implementing a protocol that requires + * a non-random IV. + * + * \param[in,out] operation Active cipher operation. + * \param[in] iv Buffer containing the IV to use. + * \param iv_length Size of the IV in bytes. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, or IV already set). + * \retval #PSA_ERROR_INVALID_ARGUMENT + * The size of \p iv is not acceptable for the chosen algorithm, + * or the chosen algorithm does not use an IV. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation, + const unsigned char *iv, + size_t iv_length); + +/** Encrypt or decrypt a message fragment in an active cipher operation. + * + * Before calling this function, you must: + * 1. Call either psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup(). + * The choice of setup function determines whether this function + * encrypts or decrypts its input. + * 2. If the algorithm requires an IV, call psa_cipher_generate_iv() + * (recommended when encrypting) or psa_cipher_set_iv(). + * + * If this function returns an error status, the operation becomes inactive. + * + * \param[in,out] operation Active cipher operation. + * \param[in] input Buffer containing the message fragment to + * encrypt or decrypt. + * \param input_length Size of the \p input buffer in bytes. + * \param[out] output Buffer where the output is to be written. + * \param output_size Size of the \p output buffer in bytes. + * \param[out] output_length On success, the number of bytes + * that make up the returned output. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, IV required but + * not set, or already completed). + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p output buffer is too small. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_cipher_update(psa_cipher_operation_t *operation, + const uint8_t *input, + size_t input_length, + unsigned char *output, + size_t output_size, + size_t *output_length); + +/** Finish encrypting or decrypting a message in a cipher operation. + * + * The application must call psa_cipher_encrypt_setup() or + * psa_cipher_decrypt_setup() before calling this function. The choice + * of setup function determines whether this function encrypts or + * decrypts its input. + * + * This function finishes the encryption or decryption of the message + * formed by concatenating the inputs passed to preceding calls to + * psa_cipher_update(). + * + * When this function returns, the operation becomes inactive. + * + * \param[in,out] operation Active cipher operation. + * \param[out] output Buffer where the output is to be written. + * \param output_size Size of the \p output buffer in bytes. + * \param[out] output_length On success, the number of bytes + * that make up the returned output. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_BAD_STATE + * The operation state is not valid (not started, IV required but + * not set, or already completed). + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p output buffer is too small. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation, + uint8_t *output, + size_t output_size, + size_t *output_length); + +/** Abort a cipher operation. + * + * Aborting an operation frees all associated resources except for the + * \p operation structure itself. Once aborted, the operation object + * can be reused for another operation by calling + * psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup() again. + * + * You may call this function any time after the operation object has + * been initialized by any of the following methods: + * - A call to psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup(), + * whether it succeeds or not. + * - Initializing the \c struct to all-bits-zero. + * - Initializing the \c struct to logical zeros, e.g. + * `psa_cipher_operation_t operation = {0}`. + * + * In particular, calling psa_cipher_abort() after the operation has been + * terminated by a call to psa_cipher_abort() or psa_cipher_finish() + * is safe and has no effect. + * + * \param[in,out] operation Initialized cipher operation. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BAD_STATE + * \p operation is not an active cipher operation. + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation); + +/**@}*/ + +/** \defgroup aead Authenticated encryption with associated data (AEAD) + * @{ + */ + +/** The tag size for an AEAD algorithm, in bytes. + * + * \param alg An AEAD algorithm + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(\p alg) is true). + * + * \return The tag size for the specified algorithm. + * If the AEAD algorithm does not have an identified + * tag that can be distinguished from the rest of + * the ciphertext, return 0. + * If the AEAD algorithm is not recognized, return 0. + * An implementation may return either 0 or a + * correct size for an AEAD algorithm that it + * recognizes, but does not support. + */ +#define PSA_AEAD_TAG_LENGTH(alg) \ + (PSA_ALG_IS_AEAD(alg) ? \ + (((alg) & PSA_ALG_AEAD_TAG_LENGTH_MASK) >> PSA_AEAD_TAG_LENGTH_OFFSET) : \ + 0) + +/** Process an authenticated encryption operation. + * + * \param key Slot containing the key to use. + * \param alg The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(\p alg) is true). + * \param[in] nonce Nonce or IV to use. + * \param nonce_length Size of the \p nonce buffer in bytes. + * \param[in] additional_data Additional data that will be authenticated + * but not encrypted. + * \param additional_data_length Size of \p additional_data in bytes. + * \param[in] plaintext Data that will be authenticated and + * encrypted. + * \param plaintext_length Size of \p plaintext in bytes. + * \param[out] ciphertext Output buffer for the authenticated and + * encrypted data. The additional data is not + * part of this output. For algorithms where the + * encrypted data and the authentication tag + * are defined as separate outputs, the + * authentication tag is appended to the + * encrypted data. + * \param ciphertext_size Size of the \p ciphertext buffer in bytes. + * This must be at least + * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\p alg, + * \p plaintext_length). + * \param[out] ciphertext_length On success, the size of the output + * in the \b ciphertext buffer. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p key is not compatible with \p alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not an AEAD algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_aead_encrypt(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *plaintext, + size_t plaintext_length, + uint8_t *ciphertext, + size_t ciphertext_size, + size_t *ciphertext_length); + +/** Process an authenticated decryption operation. + * + * \param key Slot containing the key to use. + * \param alg The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(\p alg) is true). + * \param[in] nonce Nonce or IV to use. + * \param nonce_length Size of the \p nonce buffer in bytes. + * \param[in] additional_data Additional data that has been authenticated + * but not encrypted. + * \param additional_data_length Size of \p additional_data in bytes. + * \param[in] ciphertext Data that has been authenticated and + * encrypted. For algorithms where the + * encrypted data and the authentication tag + * are defined as separate inputs, the buffer + * must contain the encrypted data followed + * by the authentication tag. + * \param ciphertext_length Size of \p ciphertext in bytes. + * \param[out] plaintext Output buffer for the decrypted data. + * \param plaintext_size Size of the \p plaintext buffer in bytes. + * This must be at least + * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\p alg, + * \p ciphertext_length). + * \param[out] plaintext_length On success, the size of the output + * in the \b plaintext buffer. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_INVALID_SIGNATURE + * The ciphertext is not authentic. + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p key is not compatible with \p alg. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \p alg is not supported or is not an AEAD algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_aead_decrypt(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *ciphertext, + size_t ciphertext_length, + uint8_t *plaintext, + size_t plaintext_size, + size_t *plaintext_length); + +/**@}*/ + +/** \defgroup asymmetric Asymmetric cryptography + * @{ + */ + +/** + * \brief ECDSA signature size for a given curve bit size + * + * \param curve_bits Curve size in bits. + * \return Signature size in bytes. + * + * \note This macro returns a compile-time constant if its argument is one. + */ +#define PSA_ECDSA_SIGNATURE_SIZE(curve_bits) \ + (PSA_BITS_TO_BYTES(curve_bits) * 2) + +/** + * \brief Sign a hash or short message with a private key. + * + * Note that to perform a hash-and-sign signature algorithm, you must + * first calculate the hash by calling psa_hash_setup(), psa_hash_update() + * and psa_hash_finish(). Then pass the resulting hash as the \p hash + * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg) + * to determine the hash algorithm to use. + * + * \param key Key slot containing an asymmetric key pair. + * \param alg A signature algorithm that is compatible with + * the type of \p key. + * \param[in] hash The hash or message to sign. + * \param hash_length Size of the \p hash buffer in bytes. + * \param[out] signature Buffer where the signature is to be written. + * \param signature_size Size of the \p signature buffer in bytes. + * \param[out] signature_length On success, the number of bytes + * that make up the returned signature value. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p signature buffer is too small. You can + * determine a sufficient buffer size by calling + * #PSA_ASYMMETRIC_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) + * where \c key_type and \c key_bits are the type and bit-size + * respectively of \p key. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_asymmetric_sign(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + uint8_t *signature, + size_t signature_size, + size_t *signature_length); + +/** + * \brief Verify the signature a hash or short message using a public key. + * + * Note that to perform a hash-and-sign signature algorithm, you must + * first calculate the hash by calling psa_hash_setup(), psa_hash_update() + * and psa_hash_finish(). Then pass the resulting hash as the \p hash + * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg) + * to determine the hash algorithm to use. + * + * \param key Key slot containing a public key or an + * asymmetric key pair. + * \param alg A signature algorithm that is compatible with + * the type of \p key. + * \param[in] hash The hash or message whose signature is to be + * verified. + * \param hash_length Size of the \p hash buffer in bytes. + * \param[in] signature Buffer containing the signature to verify. + * \param signature_length Size of the \p signature buffer in bytes. + * + * \retval #PSA_SUCCESS + * The signature is valid. + * \retval #PSA_ERROR_INVALID_SIGNATURE + * The calculation was perfomed successfully, but the passed + * signature is not a valid signature. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_asymmetric_verify(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + const uint8_t *signature, + size_t signature_length); + +#define PSA_RSA_MINIMUM_PADDING_SIZE(alg) \ + (PSA_ALG_IS_RSA_OAEP(alg) ? \ + 2 * PSA_HASH_FINAL_SIZE(PSA_ALG_RSA_OAEP_GET_HASH(alg)) + 1 : \ + 11 /*PKCS#1v1.5*/) + +/** + * \brief Encrypt a short message with a public key. + * + * \param key Key slot containing a public key or an + * asymmetric key pair. + * \param alg An asymmetric encryption algorithm that is + * compatible with the type of \p key. + * \param[in] input The message to encrypt. + * \param input_length Size of the \p input buffer in bytes. + * \param[in] salt A salt or label, if supported by the + * encryption algorithm. + * If the algorithm does not support a + * salt, pass \c NULL. + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass \c NULL. + * + * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported. + * \param salt_length Size of the \p salt buffer in bytes. + * If \p salt is \c NULL, pass 0. + * \param[out] output Buffer where the encrypted message is to + * be written. + * \param output_size Size of the \p output buffer in bytes. + * \param[out] output_length On success, the number of bytes + * that make up the returned output. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p output buffer is too small. You can + * determine a sufficient buffer size by calling + * #PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) + * where \c key_type and \c key_bits are the type and bit-size + * respectively of \p key. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_asymmetric_encrypt(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + const uint8_t *salt, + size_t salt_length, + uint8_t *output, + size_t output_size, + size_t *output_length); + +/** + * \brief Decrypt a short message with a private key. + * + * \param key Key slot containing an asymmetric key pair. + * \param alg An asymmetric encryption algorithm that is + * compatible with the type of \p key. + * \param[in] input The message to decrypt. + * \param input_length Size of the \p input buffer in bytes. + * \param[in] salt A salt or label, if supported by the + * encryption algorithm. + * If the algorithm does not support a + * salt, pass \c NULL. + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass \c NULL. + * + * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported. + * \param salt_length Size of the \p salt buffer in bytes. + * If \p salt is \c NULL, pass 0. + * \param[out] output Buffer where the decrypted message is to + * be written. + * \param output_size Size of the \c output buffer in bytes. + * \param[out] output_length On success, the number of bytes + * that make up the returned output. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_BUFFER_TOO_SMALL + * The size of the \p output buffer is too small. You can + * determine a sufficient buffer size by calling + * #PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) + * where \c key_type and \c key_bits are the type and bit-size + * respectively of \p key. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + * \retval #PSA_ERROR_INVALID_PADDING + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_asymmetric_decrypt(psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + const uint8_t *salt, + size_t salt_length, + uint8_t *output, + size_t output_size, + size_t *output_length); + +/**@}*/ + +/** \defgroup generators Generators + * @{ + */ + +/** The type of the state data structure for generators. + * + * Before calling any function on a generator, the application must + * initialize it by any of the following means: + * - Set the structure to all-bits-zero, for example: + * \code + * psa_crypto_generator_t generator; + * memset(&generator, 0, sizeof(generator)); + * \endcode + * - Initialize the structure to logical zero values, for example: + * \code + * psa_crypto_generator_t generator = {0}; + * \endcode + * - Initialize the structure to the initializer #PSA_CRYPTO_GENERATOR_INIT, + * for example: + * \code + * psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT; + * \endcode + * - Assign the result of the function psa_crypto_generator_init() + * to the structure, for example: + * \code + * psa_crypto_generator_t generator; + * generator = psa_crypto_generator_init(); + * \endcode + * + * This is an implementation-defined \c struct. Applications should not + * make any assumptions about the content of this structure except + * as directed by the documentation of a specific implementation. + */ +typedef struct psa_crypto_generator_s psa_crypto_generator_t; + +/** \def PSA_CRYPTO_GENERATOR_INIT + * + * This macro returns a suitable initializer for a generator object + * of type #psa_crypto_generator_t. + */ +#ifdef __DOXYGEN_ONLY__ +/* This is an example definition for documentation purposes. + * Implementations should define a suitable value in `crypto_struct.h`. + */ +#define PSA_CRYPTO_GENERATOR_INIT {0} +#endif + +/** Return an initial value for a generator object. + */ +static psa_crypto_generator_t psa_crypto_generator_init(void); + +/** Retrieve the current capacity of a generator. + * + * The capacity of a generator is the maximum number of bytes that it can + * return. Reading *N* bytes from a generator reduces its capacity by *N*. + * + * \param[in] generator The generator to query. + * \param[out] capacity On success, the capacity of the generator. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_BAD_STATE + * \retval PSA_ERROR_COMMUNICATION_FAILURE + */ +psa_status_t psa_get_generator_capacity(const psa_crypto_generator_t *generator, + size_t *capacity); + +/** Read some data from a generator. + * + * This function reads and returns a sequence of bytes from a generator. + * The data that is read is discarded from the generator. The generator's + * capacity is decreased by the number of bytes read. + * + * \param[in,out] generator The generator object to read from. + * \param[out] output Buffer where the generator output will be + * written. + * \param output_length Number of bytes to output. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_INSUFFICIENT_CAPACITY + * There were fewer than \p output_length bytes + * in the generator. Note that in this case, no + * output is written to the output buffer. + * The generator's capacity is set to 0, thus + * subsequent calls to this function will not + * succeed, even with a smaller output buffer. + * \retval PSA_ERROR_BAD_STATE + * \retval PSA_ERROR_INSUFFICIENT_MEMORY + * \retval PSA_ERROR_COMMUNICATION_FAILURE + * \retval PSA_ERROR_HARDWARE_FAILURE + * \retval PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_generator_read(psa_crypto_generator_t *generator, + uint8_t *output, + size_t output_length); + +/** Create a symmetric key from data read from a generator. + * + * This function reads a sequence of bytes from a generator and imports + * these bytes as a key. + * The data that is read is discarded from the generator. The generator's + * capacity is decreased by the number of bytes read. + * + * This function is equivalent to calling #psa_generator_read and + * passing the resulting output to #psa_import_key, but + * if the implementation provides an isolation boundary then + * the key material is not exposed outside the isolation boundary. + * + * \param key Slot where the key will be stored. This must be a + * valid slot for a key of the chosen type. It must + * be unoccupied. + * \param type Key type (a \c PSA_KEY_TYPE_XXX value). + * This must be a symmetric key type. + * \param bits Key size in bits. + * \param[in,out] generator The generator object to read from. + * + * \retval PSA_SUCCESS + * Success. + * \retval PSA_ERROR_INSUFFICIENT_CAPACITY + * There were fewer than \p output_length bytes + * in the generator. Note that in this case, no + * output is written to the output buffer. + * The generator's capacity is set to 0, thus + * subsequent calls to this function will not + * succeed, even with a smaller output buffer. + * \retval PSA_ERROR_NOT_SUPPORTED + * The key type or key size is not supported, either by the + * implementation in general or in this particular slot. + * \retval PSA_ERROR_BAD_STATE + * \retval PSA_ERROR_INVALID_ARGUMENT + * The key slot is invalid. + * \retval PSA_ERROR_OCCUPIED_SLOT + * There is already a key in the specified slot. + * \retval PSA_ERROR_INSUFFICIENT_MEMORY + * \retval PSA_ERROR_INSUFFICIENT_STORAGE + * \retval PSA_ERROR_COMMUNICATION_FAILURE + * \retval PSA_ERROR_HARDWARE_FAILURE + * \retval PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_generator_import_key(psa_key_slot_t key, + psa_key_type_t type, + size_t bits, + psa_crypto_generator_t *generator); + +/** Abort a generator. + * + * Once a generator has been aborted, its capacity is zero. + * Aborting a generator frees all associated resources except for the + * \c generator structure itself. + * + * This function may be called at any time as long as the generator + * object has been initialized to #PSA_CRYPTO_GENERATOR_INIT, to + * psa_crypto_generator_init() or a zero value. In particular, it is valid + * to call psa_generator_abort() twice, or to call psa_generator_abort() + * on a generator that has not been set up. + * + * Once aborted, the generator object may be called. + * + * \param[in,out] generator The generator to abort. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_BAD_STATE + * \retval PSA_ERROR_COMMUNICATION_FAILURE + * \retval PSA_ERROR_HARDWARE_FAILURE + * \retval PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_generator_abort(psa_crypto_generator_t *generator); + +/** Use the maximum possible capacity for a generator. + * + * Use this value as the capacity argument when setting up a generator + * to indicate that the generator should have the maximum possible capacity. + * The value of the maximum possible capacity depends on the generator + * algorithm. + */ +#define PSA_GENERATOR_UNBRIDLED_CAPACITY ((size_t)(-1)) + +/**@}*/ + +/** \defgroup derivation Key derivation + * @{ + */ + +/** Set up a key derivation operation. + * + * A key derivation algorithm takes three inputs: a secret input \p key and + * two non-secret inputs \p label and p salt. + * The result of this function is a byte generator which can + * be used to produce keys and other cryptographic material. + * + * The role of \p label and \p salt is as follows: + * - For HKDF (#PSA_ALG_HKDF), \p salt is the salt used in the "extract" step + * and \p label is the info string used in the "expand" step. + * + * \param[in,out] generator The generator object to set up. It must + * have been initialized to all-bits-zero, + * a logical zero (`{0}`), + * \c PSA_CRYPTO_GENERATOR_INIT or + * psa_crypto_generator_init(). + * \param key Slot containing the secret key to use. + * \param alg The key derivation algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_KEY_DERIVATION(\p alg) is true). + * \param[in] salt Salt to use. + * \param salt_length Size of the \p salt buffer in bytes. + * \param[in] label Label to use. + * \param label_length Size of the \p label buffer in bytes. + * \param capacity The maximum number of bytes that the + * generator will be able to provide. + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \c key is not compatible with \c alg, + * or \p capacity is too large for the specified algorithm and key. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \c alg is not supported or is not a key derivation algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_key_derivation(psa_crypto_generator_t *generator, + psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *salt, + size_t salt_length, + const uint8_t *label, + size_t label_length, + size_t capacity); + +/** Set up a key agreement operation. + * + * A key agreement algorithm takes two inputs: a private key \p private_key + * a public key \p peer_key. + * The result of this function is a byte generator which can + * be used to produce keys and other cryptographic material. + * + * The resulting generator always has the maximum capacity permitted by + * the algorithm. + * + * \param[in,out] generator The generator object to set up. It must + * have been initialized to all-bits-zero, + * a logical zero (`{0}`), + * \c PSA_CRYPTO_GENERATOR_INIT or + * psa_crypto_generator_init(). + * \param private_key Slot containing the private key to use. + * \param[in] peer_key Public key of the peer. It must be + * in the same format that psa_import_key() + * accepts. The standard formats for public + * keys are documented in the documentation + * of psa_export_public_key(). + * \param peer_key_length Size of \p peer_key in bytes. + * \param alg The key agreement algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_KEY_AGREEMENT(\p alg) is true). + * + * \retval #PSA_SUCCESS + * Success. + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \c private_key is not compatible with \c alg, + * or \p peer_key is not valid for \c alg or not compatible with + * \c private_key. + * \retval #PSA_ERROR_NOT_SUPPORTED + * \c alg is not supported or is not a key derivation algorithm. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +psa_status_t psa_key_agreement(psa_crypto_generator_t *generator, + psa_key_slot_t private_key, + const uint8_t *peer_key, + size_t peer_key_length, + psa_algorithm_t alg); + +/**@}*/ + +/** \defgroup random Random generation + * @{ + */ + +/** + * \brief Generate random bytes. + * + * \warning This function **can** fail! Callers MUST check the return status + * and MUST NOT use the content of the output buffer if the return + * status is not #PSA_SUCCESS. + * + * \note To generate a key, use psa_generate_key() instead. + * + * \param[out] output Output buffer for the generated data. + * \param output_size Number of bytes to generate and output. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_generate_random(uint8_t *output, + size_t output_size); + +/** Extra parameters for RSA key generation. + * + * You may pass a pointer to a structure of this type as the \c extra + * parameter to psa_generate_key(). + */ +typedef struct { + uint32_t e; /**< Public exponent value. Default: 65537. */ +} psa_generate_key_extra_rsa; + +/** + * \brief Generate a key or key pair. + * + * \param key Slot where the key will be stored. This must be a + * valid slot for a key of the chosen type. It must + * be unoccupied. + * \param type Key type (a \c PSA_KEY_TYPE_XXX value). + * \param bits Key size in bits. + * \param[in] extra Extra parameters for key generation. The + * interpretation of this parameter depends on + * \p type. All types support \c NULL to use + * default parameters. Implementation that support + * the generation of vendor-specific key types + * that allow extra parameters shall document + * the format of these extra parameters and + * the default values. For standard parameters, + * the meaning of \p extra is as follows: + * - For a symmetric key type (a type such + * that #PSA_KEY_TYPE_IS_ASYMMETRIC(\p type) is + * false), \p extra must be \c NULL. + * - For an elliptic curve key type (a type + * such that #PSA_KEY_TYPE_IS_ECC(\p type) is + * false), \p extra must be \c NULL. + * - For an RSA key (\p type is + * #PSA_KEY_TYPE_RSA_KEYPAIR), \p extra is an + * optional #psa_generate_key_extra_rsa structure + * specifying the public exponent. The + * default public exponent used when \p extra + * is \c NULL is 65537. + * \param extra_size Size of the buffer that \p extra + * points to, in bytes. Note that if \p extra is + * \c NULL then \p extra_size must be zero. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + * \retval #PSA_ERROR_BAD_STATE + * The library has not been previously initialized by psa_crypto_init(). + * It is implementation-dependent whether a failure to initialize + * results in this error code. + */ +psa_status_t psa_generate_key(psa_key_slot_t key, + psa_key_type_t type, + size_t bits, + const void *extra, + size_t extra_size); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +/* The file "crypto_sizes.h" contains definitions for size calculation + * macros whose definitions are implementation-specific. */ +#include "crypto_sizes.h" + +/* The file "crypto_struct.h" contains definitions for + * implementation-specific structs that are declared above. */ +#include "crypto_struct.h" + +/* The file "crypto_extra.h" contains vendor-specific definitions. This + * can include vendor-defined algorithms, extra functions, etc. */ +#include "crypto_extra.h" + +#endif /* PSA_CRYPTO_H */ diff --git a/features/mbedtls/inc/psa/crypto_driver.h b/features/mbedtls/inc/psa/crypto_driver.h new file mode 100644 index 00000000000..a52ecc427c1 --- /dev/null +++ b/features/mbedtls/inc/psa/crypto_driver.h @@ -0,0 +1,1787 @@ +/** + * \file psa/crypto_driver.h + * \brief Platform Security Architecture cryptographic driver module + * + * This file describes the PSA Crypto Driver Model, containing functions for + * driver developers to implement to enable hardware to be called in a + * standardized way by a PSA Cryptographic API implementation. The functions + * comprising the driver model, which driver authors implement, are not + * intended to be called by application developers. + */ + +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef PSA_CRYPTO_DRIVER_H +#define PSA_CRYPTO_DRIVER_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** The following types are redefinitions from the psa/crypto.h file. + * It is intended that these will be moved to a new common header file to + * avoid duplication. They are included here for expediency in publication. + */ +typedef uint32_t psa_status_t; +typedef uint32_t psa_algorithm_t; +typedef uint8_t psa_encrypt_or_decrypt_t; +typedef uint32_t psa_key_slot_t; +typedef uint32_t psa_key_type_t; +typedef uint32_t psa_key_usage_t; + +#define PSA_CRYPTO_DRIVER_ENCRYPT 1 +#define PSA_CRYPTO_DRIVER_DECRYPT 0 + +/** \defgroup opaque_mac Opaque Message Authentication Code + * Generation and authentication of Message Authentication Codes (MACs) using + * opaque keys can be done either as a single function call (via the + * `psa_drv_mac_opaque_generate_t` or `psa_drv_mac_opaque_verify_t` functions), or in + * parts using the following sequence: + * - `psa_drv_mac_opaque_setup_t` + * - `psa_drv_mac_opaque_update_t` + * - `psa_drv_mac_opaque_update_t` + * - ... + * - `psa_drv_mac_opaque_finish_t` or `psa_drv_mac_opaque_finish_verify_t` + * + * If a previously started Opaque MAC operation needs to be terminated, it + * should be done so by the `psa_drv_mac_opaque_abort_t`. Failure to do so may + * result in allocated resources not being freed or in other undefined + * behavior. + */ +/**@{*/ +/** \brief A function that starts a MAC operation for a PSA Crypto Driver + * implementation using an opaque key + * + * \param[in,out] p_context A structure that will contain the + * hardware-specific MAC context + * \param[in] key_slot The slot of the key to be used for the + * operation + * \param[in] algorithm The algorithm to be used to underly the MAC + * operation + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_mac_opaque_setup_t)(void *p_context, + psa_key_slot_t key_slot, + psa_algorithm_t algorithm); + +/** \brief A function that continues a previously started MAC operation using + * an opaque key + * + * \param[in,out] p_context A hardware-specific structure for the + * previously-established MAC operation to be + * continued + * \param[in] p_input A buffer containing the message to be appended + * to the MAC operation + * \param[in] input_length The size in bytes of the input message buffer + */ +typedef psa_status_t (*psa_drv_mac_opaque_update_t)(void *p_context, + const uint8_t *p_input, + size_t input_length); + +/** \brief a function that completes a previously started MAC operation by + * returning the resulting MAC using an opaque key + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started MAC operation to be + * finished + * \param[out] p_mac A buffer where the generated MAC will be + * placed + * \param[in] mac_size The size in bytes of the buffer that has been + * allocated for the `output` buffer + * \param[out] p_mac_length After completion, will contain the number of + * bytes placed in the `p_mac` buffer + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_mac_opaque_finish_t)(void *p_context, + uint8_t *p_mac, + size_t mac_size, + size_t *p_mac_length); + +/** \brief A function that completes a previously started MAC operation by + * comparing the resulting MAC against a known value using an opaque key + * + * \param[in,out] p_context A hardware-specific structure for the previously + * started MAC operation to be fiinished + * \param[in] p_mac The MAC value against which the resulting MAC will + * be compared against + * \param[in] mac_length The size in bytes of the value stored in `p_mac` + * + * \retval PSA_SUCCESS + * The operation completed successfully and the MACs matched each + * other + * \retval PSA_ERROR_INVALID_SIGNATURE + * The operation completed successfully, but the calculated MAC did + * not match the provided MAC + */ +typedef psa_status_t (*psa_drv_mac_opaque_finish_verify_t)(void *p_context, + const uint8_t *p_mac, + size_t mac_length); + +/** \brief A function that aborts a previous started opaque-key MAC operation + + * \param[in,out] p_context A hardware-specific structure for the previously + * started MAC operation to be aborted + */ +typedef psa_status_t (*psa_drv_mac_opaque_abort_t)(void *p_context); + +/** \brief A function that performs a MAC operation in one command and returns + * the calculated MAC using an opaque key + * + * \param[in] p_input A buffer containing the message to be MACed + * \param[in] input_length The size in bytes of `p_input` + * \param[in] key_slot The slot of the key to be used + * \param[in] alg The algorithm to be used to underlie the MAC + * operation + * \param[out] p_mac A buffer where the generated MAC will be + * placed + * \param[in] mac_size The size in bytes of the `p_mac` buffer + * \param[out] p_mac_length After completion, will contain the number of + * bytes placed in the `output` buffer + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_mac_opaque_generate_t)(const uint8_t *p_input, + size_t input_length, + psa_key_slot_t key_slot, + psa_algorithm_t alg, + uint8_t *p_mac, + size_t mac_size, + size_t *p_mac_length); + +/** \brief A function that performs an MAC operation in one command and + * compare the resulting MAC against a known value using an opaque key + * + * \param[in] p_input A buffer containing the message to be MACed + * \param[in] input_length The size in bytes of `input` + * \param[in] key_slot The slot of the key to be used + * \param[in] alg The algorithm to be used to underlie the MAC + * operation + * \param[in] p_mac The MAC value against which the resulting MAC will + * be compared against + * \param[in] mac_length The size in bytes of `mac` + * + * \retval PSA_SUCCESS + * The operation completed successfully and the MACs matched each + * other + * \retval PSA_ERROR_INVALID_SIGNATURE + * The operation completed successfully, but the calculated MAC did + * not match the provided MAC + */ +typedef psa_status_t (*psa_drv_mac_opaque_verify_t)(const uint8_t *p_input, + size_t input_length, + psa_key_slot_t key_slot, + psa_algorithm_t alg, + const uint8_t *p_mac, + size_t mac_length); + +/** \brief A struct containing all of the function pointers needed to + * implement MAC operations using opaque keys. + * + * PSA Crypto API implementations should populate the table as appropriate + * upon startup. + * + * If one of the functions is not implemented (such as + * `psa_drv_mac_opaque_generate_t`), it should be set to NULL. + * + * Driver implementers should ensure that they implement all of the functions + * that make sense for their hardware, and that they provide a full solution + * (for example, if they support `p_setup`, they should also support + * `p_update` and at least one of `p_finish` or `p_finish_verify`). + * + */ +typedef struct { + /**The size in bytes of the hardware-specific Opaque-MAC Context structure + */ + size_t context_size; + /** Function that performs the setup operation + */ + psa_drv_mac_opaque_setup_t *p_setup; + /** Function that performs the update operation + */ + psa_drv_mac_opaque_update_t *p_update; + /** Function that completes the operation + */ + psa_drv_mac_opaque_finish_t *p_finish; + /** Function that completed a MAC operation with a verify check + */ + psa_drv_mac_opaque_finish_verify_t *p_finish_verify; + /** Function that aborts a previoustly started operation + */ + psa_drv_mac_opaque_abort_t *p_abort; + /** Function that performs the MAC operation in one call + */ + psa_drv_mac_opaque_generate_t *p_mac; + /** Function that performs the MAC and verify operation in one call + */ + psa_drv_mac_opaque_verify_t *p_mac_verify; +} psa_drv_mac_opaque_t; +/**@}*/ + +/** \defgroup transparent_mac Transparent Message Authentication Code + * Generation and authentication of Message Authentication Codes (MACs) using + * transparent keys can be done either as a single function call (via the + * `psa_drv_mac_transparent_generate_t` or `psa_drv_mac_transparent_verify_t` + * functions), or in parts using the following sequence: + * - `psa_drv_mac_transparent_setup_t` + * - `psa_drv_mac_transparent_update_t` + * - `psa_drv_mac_transparent_update_t` + * - ... + * - `psa_drv_mac_transparent_finish_t` or `psa_drv_mac_transparent_finish_verify_t` + * + * If a previously started Transparent MAC operation needs to be terminated, it + * should be done so by the `psa_drv_mac_transparent_abort_t`. Failure to do so may + * result in allocated resources not being freed or in other undefined + * behavior. + * + */ +/**@{*/ + +/** \brief The hardware-specific transparent-key MAC context structure + * + * The contents of this structure are implementation dependent and are + * therefore not described here. + */ +typedef struct psa_drv_mac_transparent_context_s psa_drv_mac_transparent_context_t; + +/** \brief The function prototype for the setup operation of a + * transparent-key MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___setup + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying primitive, and `MAC_VARIANT` + * is the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in,out] p_context A structure that will contain the + * hardware-specific MAC context + * \param[in] p_key A buffer containing the cleartext key material + * to be used in the operation + * \param[in] key_length The size in bytes of the key material + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_mac_transparent_setup_t)(psa_drv_mac_transparent_context_t *p_context, + const uint8_t *p_key, + size_t key_length); + +/** \brief The function prototype for the update operation of a + * transparent-key MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___update + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` + * is the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously-established MAC operation to be + * continued + * \param[in] p_input A buffer containing the message to be appended + * to the MAC operation + * \param[in] input_length The size in bytes of the input message buffer + */ +typedef psa_status_t (*psa_drv_mac_transparent_update_t)(psa_drv_mac_transparent_context_t *p_context, + const uint8_t *p_input, + size_t input_length); + +/** \brief The function prototype for the finish operation of a + * transparent-key MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___finish + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` is + * the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started MAC operation to be + * finished + * \param[out] p_mac A buffer where the generated MAC will be placed + * \param[in] mac_length The size in bytes of the buffer that has been + * allocated for the `p_mac` buffer + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_mac_transparent_finish_t)(psa_drv_mac_transparent_context_t *p_context, + uint8_t *p_mac, + size_t mac_length); + +/** \brief The function prototype for the finish and verify operation of a + * transparent-key MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___finish_verify + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` is + * the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started MAC operation to be + * verified and finished + * \param[in] p_mac A buffer containing the MAC that will be used + * for verification + * \param[in] mac_length The size in bytes of the data in the `p_mac` + * buffer + * + * \retval PSA_SUCCESS + * The operation completed successfully and the comparison matched + */ +typedef psa_status_t (*psa_drv_mac_transparent_finish_verify_t)(psa_drv_mac_transparent_context_t *p_context, + const uint8_t *p_mac, + size_t mac_length); + +/** \brief The function prototype for the abort operation for a previously + * started transparent-key MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___abort + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` is + * the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started MAC operation to be + * aborted + * + */ +typedef psa_status_t (*psa_drv_mac_transparent_abort_t)(psa_drv_mac_transparent_context_t *p_context); + +/** \brief The function prototype for a one-shot operation of a transparent-key + * MAC operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent__ + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` is + * the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in] p_input A buffer containing the data to be MACed + * \param[in] input_length The length in bytes of the `p_input` data + * \param[in] p_key A buffer containing the key material to be used + * for the MAC operation + * \param[in] key_length The length in bytes of the `p_key` data + * \param[in] alg The algorithm to be performed + * \param[out] p_mac The buffer where the resulting MAC will be placed + * upon success + * \param[in] mac_length The length in bytes of the `p_mac` buffer + */ +typedef psa_status_t (*psa_drv_mac_transparent_t)(const uint8_t *p_input, + size_t input_length, + const uint8_t *p_key, + size_t key_length, + psa_algorithm_t alg, + uint8_t *p_mac, + size_t mac_length); + +/** \brief The function prototype for a one-shot operation of a transparent-key + * MAC Verify operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_mac_transparent___verify + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm, and `MAC_VARIANT` is + * the specific variant of a MAC operation (such as HMAC or CMAC) + * + * \param[in] p_input A buffer containing the data to be MACed + * \param[in] input_length The length in bytes of the `p_input` data + * \param[in] p_key A buffer containing the key material to be used + * for the MAC operation + * \param[in] key_length The length in bytes of the `p_key` data + * \param[in] alg The algorithm to be performed + * \param[in] p_mac The MAC data to be compared + * \param[in] mac_length The length in bytes of the `p_mac` buffer + * + * \retval PSA_SUCCESS + * The operation completed successfully and the comparison matched + */ +typedef psa_status_t (*psa_drv_mac_transparent_verify_t)(const uint8_t *p_input, + size_t input_length, + const uint8_t *p_key, + size_t key_length, + psa_algorithm_t alg, + const uint8_t *p_mac, + size_t mac_length); +/**@}*/ + +/** \defgroup opaque_cipher Opaque Symmetric Ciphers + * + * Encryption and Decryption using opaque keys in block modes other than ECB + * must be done in multiple parts, using the following flow: + * - `psa_drv_cipher_opaque_setup_t` + * - `psa_drv_cipher_opaque_set_iv_t` (optional depending upon block mode) + * - `psa_drv_cipher_opaque_update_t` + * - ... + * - `psa_drv_cipher_opaque_finish_t` + + * If a previously started Opaque Cipher operation needs to be terminated, it + * should be done so by the `psa_drv_cipher_opaque_abort_t`. Failure to do so may + * result in allocated resources not being freed or in other undefined + * behavior. + * + * In situations where a PSA Cryptographic API implementation is using a block + * mode not-supported by the underlying hardware or driver, it can construct + * the block mode itself, while calling the `psa_drv_cipher_opaque_ecb_t` function + * pointer for the cipher operations. + */ +/**@{*/ + +/** \brief A function pointer that provides the cipher setup function for + * opaque-key operations + * + * \param[in,out] p_context A structure that will contain the + * hardware-specific cipher context. + * \param[in] key_slot The slot of the key to be used for the + * operation + * \param[in] algorithm The algorithm to be used in the cipher + * operation + * \param[in] direction Indicates whether the operation is an encrypt + * or decrypt + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_NOT_SUPPORTED + */ +typedef psa_status_t (*psa_drv_cipher_opaque_setup_t)(void *p_context, + psa_key_slot_t key_slot, + psa_algorithm_t algorithm, + psa_encrypt_or_decrypt_t direction); + +/** \brief A function pointer that sets the initialization vector (if + * necessary) for an opaque cipher operation + * + * Rationale: The `psa_cipher_*` function in the PSA Cryptographic API has two + * IV functions: one to set the IV, and one to generate it internally. The + * generate function is not necessary for the drivers to implement as the PSA + * Crypto implementation can do the generation using its RNG features. + * + * \param[in,out] p_context A structure that contains the previously set up + * hardware-specific cipher context + * \param[in] p_iv A buffer containing the initialization vector + * \param[in] iv_length The size (in bytes) of the `p_iv` buffer + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_opaque_set_iv_t)(void *p_context, + const uint8_t *p_iv, + size_t iv_length); + +/** \brief A function that continues a previously started opaque-key cipher + * operation + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + * \param[in] p_input A buffer containing the data to be + * encrypted/decrypted + * \param[in] input_size The size in bytes of the buffer pointed to + * by `p_input` + * \param[out] p_output The caller-allocated buffer where the + * output will be placed + * \param[in] output_size The allocated size in bytes of the + * `p_output` buffer + * \param[out] p_output_length After completion, will contain the number + * of bytes placed in the `p_output` buffer + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_opaque_update_t)(void *p_context, + const uint8_t *p_input, + size_t input_size, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** \brief A function that completes a previously started opaque-key cipher + * operation + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + * \param[out] p_output The caller-allocated buffer where the output + * will be placed + * \param[in] output_size The allocated size in bytes of the `p_output` + * buffer + * \param[out] p_output_length After completion, will contain the number of + * bytes placed in the `p_output` buffer + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_opaque_finish_t)(void *p_context, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** \brief A function that aborts a previously started opaque-key cipher + * operation + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + */ +typedef psa_status_t (*psa_drv_cipher_opaque_abort_t)(void *p_context); + +/** \brief A function that performs the ECB block mode for opaque-key cipher + * operations + * + * Note: this function should only be used with implementations that do not + * provide a needed higher-level operation. + * + * \param[in] key_slot The slot of the key to be used for the operation + * \param[in] algorithm The algorithm to be used in the cipher operation + * \param[in] direction Indicates whether the operation is an encrypt or + * decrypt + * \param[in] p_input A buffer containing the data to be + * encrypted/decrypted + * \param[in] input_size The size in bytes of the buffer pointed to by + * `p_input` + * \param[out] p_output The caller-allocated buffer where the output will + * be placed + * \param[in] output_size The allocated size in bytes of the `p_output` + * buffer + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_NOT_SUPPORTED + */ +typedef psa_status_t (*psa_drv_cipher_opaque_ecb_t)(psa_key_slot_t key_slot, + psa_algorithm_t algorithm, + psa_encrypt_or_decrypt_t direction, + const uint8_t *p_input, + size_t input_size, + uint8_t *p_output, + size_t output_size); + +/** + * \brief A struct containing all of the function pointers needed to implement + * cipher operations using opaque keys. + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented (such as + * `psa_drv_cipher_opaque_ecb_t`), it should be set to NULL. + */ +typedef struct { + /** The size in bytes of the hardware-specific Opaque Cipher context + * structure + */ + size_t size; + /** Function that performs the setup operation */ + psa_drv_cipher_opaque_setup_t *p_setup; + /** Function that sets the IV (if necessary) */ + psa_drv_cipher_opaque_set_iv_t *p_set_iv; + /** Function that performs the update operation */ + psa_drv_cipher_opaque_update_t *p_update; + /** Function that completes the operation */ + psa_drv_cipher_opaque_finish_t *p_finish; + /** Function that aborts the operation */ + psa_drv_cipher_opaque_abort_t *p_abort; + /** Function that performs ECB mode for the cipher + * (Danger: ECB mode should not be used directly by clients of the PSA + * Crypto Client API) + */ + psa_drv_cipher_opaque_ecb_t *p_ecb; +} psa_drv_cipher_opaque_t; + +/**@}*/ + +/** \defgroup transparent_cipher Transparent Block Cipher + * Encryption and Decryption using transparent keys in block modes other than + * ECB must be done in multiple parts, using the following flow: + * - `psa_drv_cipher_transparent_setup_t` + * - `psa_drv_cipher_transparent_set_iv_t` (optional depending upon block mode) + * - `psa_drv_cipher_transparent_update_t` + * - ... + * - `psa_drv_cipher_transparent_finish_t` + + * If a previously started Transparent Cipher operation needs to be terminated, + * it should be done so by the `psa_drv_cipher_transparent_abort_t`. Failure to do + * so may result in allocated resources not being freed or in other undefined + * behavior. + */ +/**@{*/ + +/** \brief The hardware-specific transparent-key Cipher context structure + * + * The contents of this structure are implementation dependent and are + * therefore not described here. + */ +typedef struct psa_drv_cipher_transparent_context_s psa_drv_cipher_transparent_context_t; + +/** \brief The function prototype for the setup operation of transparent-key + * block cipher operations. + * Functions that implement the prototype should be named in the following + * conventions: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_setup__ + * ~~~~~~~~~~~~~ + * Where + * - `CIPHER_NAME` is the name of the underlying block cipher (i.e. AES or DES) + * - `MODE` is the block mode of the cipher operation (i.e. CBC or CTR) + * or for stream ciphers: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_setup_ + * ~~~~~~~~~~~~~ + * Where `CIPHER_NAME` is the name of a stream cipher (i.e. RC4) + * + * \param[in,out] p_context A structure that will contain the + * hardware-specific cipher context + * \param[in] direction Indicates if the operation is an encrypt or a + * decrypt + * \param[in] p_key_data A buffer containing the cleartext key material + * to be used in the operation + * \param[in] key_data_size The size in bytes of the key material + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_transparent_setup_t)(psa_drv_cipher_transparent_context_t *p_context, + psa_encrypt_or_decrypt_t direction, + const uint8_t *p_key_data, + size_t key_data_size); + +/** \brief The function prototype for the set initialization vector operation + * of transparent-key block cipher operations + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_set_iv__ + * ~~~~~~~~~~~~~ + * Where + * - `CIPHER_NAME` is the name of the underlying block cipher (i.e. AES or DES) + * - `MODE` is the block mode of the cipher operation (i.e. CBC or CTR) + * + * \param[in,out] p_context A structure that contains the previously setup + * hardware-specific cipher context + * \param[in] p_iv A buffer containing the initialization vecotr + * \param[in] iv_length The size in bytes of the contents of `p_iv` + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_transparent_set_iv_t)(psa_drv_cipher_transparent_context_t *p_context, + const uint8_t *p_iv, + size_t iv_length); + +/** \brief The function prototype for the update operation of transparent-key + * block cipher operations. + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_update__ + * ~~~~~~~~~~~~~ + * Where + * - `CIPHER_NAME` is the name of the underlying block cipher (i.e. AES or DES) + * - `MODE` is the block mode of the cipher operation (i.e. CBC or CTR) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + * \param[in] p_input A buffer containing the data to be + * encrypted or decrypted + * \param[in] input_size The size in bytes of the `p_input` buffer + * \param[out] p_output A caller-allocated buffer where the + * generated output will be placed + * \param[in] output_size The size in bytes of the `p_output` buffer + * \param[out] p_output_length After completion, will contain the number + * of bytes placed in the `p_output` buffer + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_transparent_update_t)(psa_drv_cipher_transparent_context_t *p_context, + const uint8_t *p_input, + size_t input_size, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** \brief The function prototype for the finish operation of transparent-key + * block cipher operations. + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_finish__ + * ~~~~~~~~~~~~~ + * Where + * - `CIPHER_NAME` is the name of the underlying block cipher (i.e. AES or DES) + * - `MODE` is the block mode of the cipher operation (i.e. CBC or CTR) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + * \param[out] p_output A caller-allocated buffer where the generated + * output will be placed + * \param[in] output_size The size in bytes of the `p_output` buffer + * \param[out] p_output_length After completion, will contain the number of + * bytes placed in the `p_output` buffer + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_transparent_finish_t)(psa_drv_cipher_transparent_context_t *p_context, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** \brief The function prototype for the abort operation of transparent-key + * block cipher operations. + * + * Functions that implement the following prototype should be named in the + * following convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_cipher_transparent_abort__ + * ~~~~~~~~~~~~~ + * Where + * - `CIPHER_NAME` is the name of the underlying block cipher (i.e. AES or DES) + * - `MODE` is the block mode of the cipher operation (i.e. CBC or CTR) + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started cipher operation + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_cipher_transparent_abort_t)(psa_drv_cipher_transparent_context_t *p_context); + +/**@}*/ + +/** \defgroup driver_digest Message Digests + * + * Generation and authentication of Message Digests (aka hashes) must be done + * in parts using the following sequence: + * - `psa_drv_hash_setup_t` + * - `psa_drv_hash_update_t` + * - ... + * - `psa_drv_hash_finish_t` + * + * If a previously started Message Digest operation needs to be terminated + * before the `psa_drv_hash_finish_t` operation is complete, it should be aborted + * by the `psa_drv_hash_abort_t`. Failure to do so may result in allocated + * resources not being freed or in other undefined behavior. + */ +/**@{*/ + +/** \brief The hardware-specific hash context structure + * + * The contents of this structure are implementation dependent and are + * therefore not described here + */ +typedef struct psa_drv_hash_context_s psa_drv_hash_context_t; + +/** \brief The function prototype for the start operation of a hash (message + * digest) operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_hash__setup + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying hash function + * + * \param[in,out] p_context A structure that will contain the + * hardware-specific hash context + * + * \retval PSA_SUCCESS Success. + */ +typedef psa_status_t (*psa_drv_hash_setup_t)(psa_drv_hash_context_t *p_context); + +/** \brief The function prototype for the update operation of a hash (message + * digest) operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_hash__update + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm + * + * \param[in,out] p_context A hardware-specific structure for the + * previously-established hash operation to be + * continued + * \param[in] p_input A buffer containing the message to be appended + * to the hash operation + * \param[in] input_length The size in bytes of the input message buffer + */ +typedef psa_status_t (*psa_drv_hash_update_t)(psa_drv_hash_context_t *p_context, + const uint8_t *p_input, + size_t input_length); + +/** \brief The prototype for the finish operation of a hash (message digest) + * operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_hash__finish + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm + * + * \param[in,out] p_context A hardware-specific structure for the + * previously started hash operation to be + * fiinished + * \param[out] p_output A buffer where the generated digest will be + * placed + * \param[in] output_size The size in bytes of the buffer that has been + * allocated for the `p_output` buffer + * \param[out] p_output_length The number of bytes placed in `p_output` after + * success + * + * \retval PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_hash_finish_t)(psa_drv_hash_context_t *p_context, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** \brief The function prototype for the abort operation of a hash (message + * digest) operation + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_hash__abort + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the underlying algorithm + * + * \param[in,out] p_context A hardware-specific structure for the previously + * started hash operation to be aborted + */ +typedef void (*psa_drv_hash_abort_t)(psa_drv_hash_context_t *p_context); + +/**@}*/ + + +/** \defgroup opaque_asymmetric Opaque Asymmetric Cryptography + * + * Since the amount of data that can (or should) be encrypted or signed using + * asymmetric keys is limited by the key size, asymmetric key operations using + * opaque keys must be done in single function calls. + */ +/**@{*/ + +/** + * \brief A function that signs a hash or short message with a private key + * + * \param[in] key_slot Key slot of an asymmetric key pair + * \param[in] alg A signature algorithm that is compatible + * with the type of `key` + * \param[in] p_hash The hash to sign + * \param[in] hash_length Size of the `p_hash` buffer in bytes + * \param[out] p_signature Buffer where the signature is to be written + * \param[in] signature_size Size of the `p_signature` buffer in bytes + * \param[out] p_signature_length On success, the number of bytes + * that make up the returned signature value + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_opaque_sign_t)(psa_key_slot_t key_slot, + psa_algorithm_t alg, + const uint8_t *p_hash, + size_t hash_length, + uint8_t *p_signature, + size_t signature_size, + size_t *p_signature_length); + +/** + * \brief A function that verifies the signature a hash or short message using + * an asymmetric public key + * + * \param[in] key_slot Key slot of a public key or an asymmetric key + * pair + * \param[in] alg A signature algorithm that is compatible with + * the type of `key` + * \param[in] p_hash The hash whose signature is to be verified + * \param[in] hash_length Size of the `p_hash` buffer in bytes + * \param[in] p_signature Buffer containing the signature to verify + * \param[in] signature_length Size of the `p_signature` buffer in bytes + * + * \retval PSA_SUCCESS + * The signature is valid. + */ +typedef psa_status_t (*psa_drv_asymmetric_opaque_verify_t)(psa_key_slot_t key_slot, + psa_algorithm_t alg, + const uint8_t *p_hash, + size_t hash_length, + const uint8_t *p_signature, + size_t signature_length); + +/** + * \brief A function that encrypts a short message with an asymmetric public + * key + * + * \param[in] key_slot Key slot of a public key or an asymmetric key + * pair + * \param[in] alg An asymmetric encryption algorithm that is + * compatible with the type of `key` + * \param[in] p_input The message to encrypt + * \param[in] input_length Size of the `p_input` buffer in bytes + * \param[in] p_salt A salt or label, if supported by the + * encryption algorithm + * If the algorithm does not support a + * salt, pass `NULL`. + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass `NULL`. + * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported. + * \param[in] salt_length Size of the `p_salt` buffer in bytes + * If `p_salt` is `NULL`, pass 0. + * \param[out] p_output Buffer where the encrypted message is to + * be written + * \param[in] output_size Size of the `p_output` buffer in bytes + * \param[out] p_output_length On success, the number of bytes that make up + * the returned output + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_opaque_encrypt_t)(psa_key_slot_t key_slot, + psa_algorithm_t alg, + const uint8_t *p_input, + size_t input_length, + const uint8_t *p_salt, + size_t salt_length, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** + * \brief Decrypt a short message with an asymmetric private key. + * + * \param[in] key_slot Key slot of an asymmetric key pair + * \param[in] alg An asymmetric encryption algorithm that is + * compatible with the type of `key` + * \param[in] p_input The message to decrypt + * \param[in] input_length Size of the `p_input` buffer in bytes + * \param[in] p_salt A salt or label, if supported by the + * encryption algorithm + * If the algorithm does not support a + * salt, pass `NULL`. + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass `NULL`. + * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported. + * \param[in] salt_length Size of the `p_salt` buffer in bytes + * If `p_salt` is `NULL`, pass 0. + * \param[out] p_output Buffer where the decrypted message is to + * be written + * \param[in] output_size Size of the `p_output` buffer in bytes + * \param[out] p_output_length On success, the number of bytes + * that make up the returned output + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_opaque_decrypt_t)(psa_key_slot_t key_slot, + psa_algorithm_t alg, + const uint8_t *p_input, + size_t input_length, + const uint8_t *p_salt, + size_t salt_length, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** + * \brief A struct containing all of the function pointers needed to implement + * asymmetric cryptographic operations using opaque keys. + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented, it should be set to NULL. + */ +typedef struct { + /** Function that performs the asymmetric sign operation */ + psa_drv_asymmetric_opaque_sign_t *p_sign; + /** Function that performs the asymmetric verify operation */ + psa_drv_asymmetric_opaque_verify_t *p_verify; + /** Function that performs the asymmetric encrypt operation */ + psa_drv_asymmetric_opaque_encrypt_t *p_encrypt; + /** Function that performs the asymmetric decrypt operation */ + psa_drv_asymmetric_opaque_decrypt_t *p_decrypt; +} psa_drv_asymmetric_opaque_t; + +/**@}*/ + +/** \defgroup transparent_asymmetric Transparent Asymmetric Cryptography + * + * Since the amount of data that can (or should) be encrypted or signed using + * asymmetric keys is limited by the key size, asymmetric key operations using + * transparent keys must be done in single function calls. + */ +/**@{*/ + + +/** + * \brief A function that signs a hash or short message with a transparent + * asymmetric private key + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_asymmetric__sign + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the signing algorithm + * + * \param[in] p_key A buffer containing the private key + * material + * \param[in] key_size The size in bytes of the `p_key` data + * \param[in] alg A signature algorithm that is compatible + * with the type of `p_key` + * \param[in] p_hash The hash or message to sign + * \param[in] hash_length Size of the `p_hash` buffer in bytes + * \param[out] p_signature Buffer where the signature is to be written + * \param[in] signature_size Size of the `p_signature` buffer in bytes + * \param[out] p_signature_length On success, the number of bytes + * that make up the returned signature value + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_transparent_sign_t)(const uint8_t *p_key, + size_t key_size, + psa_algorithm_t alg, + const uint8_t *p_hash, + size_t hash_length, + uint8_t *p_signature, + size_t signature_size, + size_t *p_signature_length); + +/** + * \brief A function that verifies the signature a hash or short message using + * a transparent asymmetric public key + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_asymmetric__verify + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the signing algorithm + * + * \param[in] p_key A buffer containing the public key material + * \param[in] key_size The size in bytes of the `p_key` data + * \param[in] alg A signature algorithm that is compatible with + * the type of `key` + * \param[in] p_hash The hash or message whose signature is to be + * verified + * \param[in] hash_length Size of the `p_hash` buffer in bytes + * \param[in] p_signature Buffer containing the signature to verify + * \param[in] signature_length Size of the `p_signature` buffer in bytes + * + * \retval PSA_SUCCESS + * The signature is valid. + */ +typedef psa_status_t (*psa_drv_asymmetric_transparent_verify_t)(const uint8_t *p_key, + size_t key_size, + psa_algorithm_t alg, + const uint8_t *p_hash, + size_t hash_length, + const uint8_t *p_signature, + size_t signature_length); + +/** + * \brief A function that encrypts a short message with a transparent + * asymmetric public key + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_asymmetric__encrypt + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the encryption algorithm + * + * \param[in] p_key A buffer containing the public key material + * \param[in] key_size The size in bytes of the `p_key` data + * \param[in] alg An asymmetric encryption algorithm that is + * compatible with the type of `key` + * \param[in] p_input The message to encrypt + * \param[in] input_length Size of the `p_input` buffer in bytes + * \param[in] p_salt A salt or label, if supported by the + * encryption algorithm + * If the algorithm does not support a + * salt, pass `NULL` + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass `NULL`. + * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported. + * \param[in] salt_length Size of the `p_salt` buffer in bytes + * If `p_salt` is `NULL`, pass 0. + * \param[out] p_output Buffer where the encrypted message is to + * be written + * \param[in] output_size Size of the `p_output` buffer in bytes + * \param[out] p_output_length On success, the number of bytes + * that make up the returned output + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_transparent_encrypt_t)(const uint8_t *p_key, + size_t key_size, + psa_algorithm_t alg, + const uint8_t *p_input, + size_t input_length, + const uint8_t *p_salt, + size_t salt_length, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** + * \brief Decrypt a short message with a transparent asymmetric private key + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_asymmetric__decrypt + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the encryption algorithm + * + * \param[in] p_key A buffer containing the private key material + * \param[in] key_size The size in bytes of the `p_key` data + * \param[in] alg An asymmetric encryption algorithm that is + * compatible with the type of `key` + * \param[in] p_input The message to decrypt + * \param[in] input_length Size of the `p_input` buffer in bytes + * \param[in] p_salt A salt or label, if supported by the + * encryption algorithm + * If the algorithm does not support a + * salt, pass `NULL`. + * If the algorithm supports an optional + * salt and you do not want to pass a salt, + * pass `NULL`. + * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is + * supported + * \param[in] salt_length Size of the `p_salt` buffer in bytes + * If `p_salt` is `NULL`, pass 0 + * \param[out] p_output Buffer where the decrypted message is to + * be written + * \param[in] output_size Size of the `p_output` buffer in bytes + * \param[out] p_output_length On success, the number of bytes + * that make up the returned output + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_asymmetric_transparent_decrypt_t)(const uint8_t *p_key, + size_t key_size, + psa_algorithm_t alg, + const uint8_t *p_input, + size_t input_length, + const uint8_t *p_salt, + size_t salt_length, + uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/**@}*/ + +/** \defgroup aead_opaque AEAD Opaque + * Authenticated Encryption with Additional Data (AEAD) operations with opaque + * keys must be done in one function call. While this creates a burden for + * implementers as there must be sufficient space in memory for the entire + * message, it prevents decrypted data from being made available before the + * authentication operation is complete and the data is known to be authentic. + */ +/**@{*/ + +/** \brief Process an authenticated encryption operation using an opaque key + * + * \param[in] key_slot Slot containing the key to use. + * \param[in] algorithm The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(`alg`) is true) + * \param[in] p_nonce Nonce or IV to use + * \param[in] nonce_length Size of the `p_nonce` buffer in bytes + * \param[in] p_additional_data Additional data that will be + * authenticated but not encrypted + * \param[in] additional_data_length Size of `p_additional_data` in bytes + * \param[in] p_plaintext Data that will be authenticated and + * encrypted + * \param[in] plaintext_length Size of `p_plaintext` in bytes + * \param[out] p_ciphertext Output buffer for the authenticated and + * encrypted data. The additional data is + * not part of this output. For algorithms + * where the encrypted data and the + * authentication tag are defined as + * separate outputs, the authentication + * tag is appended to the encrypted data. + * \param[in] ciphertext_size Size of the `p_ciphertext` buffer in + * bytes + * \param[out] p_ciphertext_length On success, the size of the output in + * the `p_ciphertext` buffer + * + * \retval #PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_aead_opaque_encrypt_t)(psa_key_slot_t key_slot, + psa_algorithm_t algorithm, + const uint8_t *p_nonce, + size_t nonce_length, + const uint8_t *p_additional_data, + size_t additional_data_length, + const uint8_t *p_plaintext, + size_t plaintext_length, + uint8_t *p_ciphertext, + size_t ciphertext_size, + size_t *p_ciphertext_length); + +/** Process an authenticated decryption operation using an opaque key + * + * \param[in] key_slot Slot containing the key to use + * \param[in] algorithm The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(`alg`) is true) + * \param[in] p_nonce Nonce or IV to use + * \param[in] nonce_length Size of the `p_nonce` buffer in bytes + * \param[in] p_additional_data Additional data that has been + * authenticated but not encrypted + * \param[in] additional_data_length Size of `p_additional_data` in bytes + * \param[in] p_ciphertext Data that has been authenticated and + * encrypted. + * For algorithms where the encrypted data + * and the authentication tag are defined + * as separate inputs, the buffer must + * contain the encrypted data followed by + * the authentication tag. + * \param[in] ciphertext_length Size of `p_ciphertext` in bytes + * \param[out] p_plaintext Output buffer for the decrypted data + * \param[in] plaintext_size Size of the `p_plaintext` buffer in + * bytes + * \param[out] p_plaintext_length On success, the size of the output in + * the `p_plaintext` buffer + * + * \retval #PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_aead_opaque_decrypt_t)(psa_key_slot_t key_slot, + psa_algorithm_t algorithm, + const uint8_t *p_nonce, + size_t nonce_length, + const uint8_t *p_additional_data, + size_t additional_data_length, + const uint8_t *p_ciphertext, + size_t ciphertext_length, + uint8_t *p_plaintext, + size_t plaintext_size, + size_t *p_plaintext_length); + +/** + * \brief A struct containing all of the function pointers needed to implement + * Authenticated Encryption with Additional Data operations using opaque keys + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented, it should be set to NULL. + */ +typedef struct { + /** Function that performs the AEAD encrypt operation */ + psa_drv_aead_opaque_encrypt_t *p_encrypt; + /** Function that performs the AEAD decrypt operation */ + psa_drv_aead_opaque_decrypt_t *p_decrypt; +} psa_drv_aead_opaque_t; +/**@}*/ + +/** \defgroup aead_transparent AEAD Transparent + * + * Authenticated Encryption with Additional Data (AEAD) operations with + * transparent keys must be done in one function call. While this creates a + * burden for implementers as there must be sufficient space in memory for the + * entire message, it prevents decrypted data from being made available before + * the authentication operation is complete and the data is known to be + * authentic. + */ +/**@{*/ + +/** Process an authenticated encryption operation using an opaque key. + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_aead__encrypt + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the AEAD algorithm + * + * \param[in] p_key A pointer to the key material + * \param[in] key_length The size in bytes of the key material + * \param[in] alg The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(`alg`) is true) + * \param[in] nonce Nonce or IV to use + * \param[in] nonce_length Size of the `nonce` buffer in bytes + * \param[in] additional_data Additional data that will be MACed + * but not encrypted. + * \param[in] additional_data_length Size of `additional_data` in bytes + * \param[in] plaintext Data that will be MACed and + * encrypted. + * \param[in] plaintext_length Size of `plaintext` in bytes + * \param[out] ciphertext Output buffer for the authenticated and + * encrypted data. The additional data is + * not part of this output. For algorithms + * where the encrypted data and the + * authentication tag are defined as + * separate outputs, the authentication + * tag is appended to the encrypted data. + * \param[in] ciphertext_size Size of the `ciphertext` buffer in + * bytes + * This must be at least + * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(`alg`, + * `plaintext_length`). + * \param[out] ciphertext_length On success, the size of the output in + * the `ciphertext` buffer + * + * \retval #PSA_SUCCESS + + */ +typedef psa_status_t (*psa_drv_aead_transparent_encrypt_t)(const uint8_t *p_key, + size_t key_length, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *plaintext, + size_t plaintext_length, + uint8_t *ciphertext, + size_t ciphertext_size, + size_t *ciphertext_length); + +/** Process an authenticated decryption operation using an opaque key. + * + * Functions that implement the prototype should be named in the following + * convention: + * ~~~~~~~~~~~~~{.c} + * psa_drv_aead__decrypt + * ~~~~~~~~~~~~~ + * Where `ALGO` is the name of the AEAD algorithm + * \param[in] p_key A pointer to the key material + * \param[in] key_length The size in bytes of the key material + * \param[in] alg The AEAD algorithm to compute + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(`alg`) is true) + * \param[in] nonce Nonce or IV to use + * \param[in] nonce_length Size of the `nonce` buffer in bytes + * \param[in] additional_data Additional data that has been MACed + * but not encrypted + * \param[in] additional_data_length Size of `additional_data` in bytes + * \param[in] ciphertext Data that has been MACed and + * encrypted + * For algorithms where the encrypted data + * and the authentication tag are defined + * as separate inputs, the buffer must + * contain the encrypted data followed by + * the authentication tag. + * \param[in] ciphertext_length Size of `ciphertext` in bytes + * \param[out] plaintext Output buffer for the decrypted data + * \param[in] plaintext_size Size of the `plaintext` buffer in + * bytes + * This must be at least + * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(`alg`, + * `ciphertext_length`). + * \param[out] plaintext_length On success, the size of the output + * in the \b plaintext buffer + * + * \retval #PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_aead_transparent_decrypt_t)(const uint8_t *p_key, + size_t key_length, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *ciphertext, + size_t ciphertext_length, + uint8_t *plaintext, + size_t plaintext_size, + size_t *plaintext_length); + +/**@}*/ + + +/** \defgroup driver_rng Entropy Generation + */ +/**@{*/ + +/** \brief A hardware-specific structure for a entropy providing hardware + */ +typedef struct psa_drv_entropy_context_s psa_drv_entropy_context_t; + +/** \brief Initialize an entropy driver + * + * + * \param[in,out] p_context A hardware-specific structure + * containing any context information for + * the implementation + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_entropy_init_t)(psa_drv_entropy_context_t *p_context); + +/** \brief Get a specified number of bits from the entropy source + * + * It retrives `buffer_size` bytes of data from the entropy source. The entropy + * source will always fill the provided buffer to its full size, however, most + * entropy sources have biases, and the actual amount of entropy contained in + * the buffer will be less than the number of bytes. + * The driver will return the actual number of bytes of entropy placed in the + * buffer in `p_received_entropy_bytes`. + * A PSA Crypto API implementation will likely feed the output of this function + * into a Digital Random Bit Generator (DRBG), and typically has a minimum + * amount of entropy that it needs. + * To accomplish this, the PSA Crypto implementation should be designed to call + * this function multiple times until it has received the required amount of + * entropy from the entropy source. + * + * \param[in,out] p_context A hardware-specific structure + * containing any context information + * for the implementation + * \param[out] p_buffer A caller-allocated buffer for the + * retrieved entropy to be placed in + * \param[in] buffer_size The allocated size of `p_buffer` + * \param[out] p_received_entropy_bits The amount of entropy (in bits) + * actually provided in `p_buffer` + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_entropy_get_bits_t)(psa_drv_entropy_context_t *p_context, + uint8_t *p_buffer, + uint32_t buffer_size, + uint32_t *p_received_entropy_bits); + +/** + * \brief A struct containing all of the function pointers needed to interface + * to an entropy source + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented, it should be set to NULL. + */ +typedef struct { + /** Function that performs initialization for the entropy source */ + psa_drv_entropy_init_t *p_init; + /** Function that performs the get_bits operation for the entropy source + */ + psa_drv_entropy_get_bits_t *p_get_bits; +} psa_drv_entropy_t; +/**@}*/ + +/** \defgroup driver_key_management Key Management + * Currently, key management is limited to importing keys in the clear, + * destroying keys, and exporting keys in the clear. + * Whether a key may be exported is determined by the key policies in place + * on the key slot. + */ +/**@{*/ + +/** \brief Import a key in binary format + * + * This function can support any output from psa_export_key(). Refer to the + * documentation of psa_export_key() for the format for each key type. + * + * \param[in] key_slot Slot where the key will be stored + * This must be a valid slot for a key of the chosen + * type. It must be unoccupied. + * \param[in] type Key type (a \c PSA_KEY_TYPE_XXX value) + * \param[in] algorithm Key algorithm (a \c PSA_ALG_XXX value) + * \param[in] usage The allowed uses of the key + * \param[in] p_data Buffer containing the key data + * \param[in] data_length Size of the `data` buffer in bytes + * + * \retval #PSA_SUCCESS + * Success. + */ +typedef psa_status_t (*psa_drv_opaque_import_key_t)(psa_key_slot_t key_slot, + psa_key_type_t type, + psa_algorithm_t algorithm, + psa_key_usage_t usage, + const uint8_t *p_data, + size_t data_length); + +/** + * \brief Destroy a key and restore the slot to its default state + * + * This function destroys the content of the key slot from both volatile + * memory and, if applicable, non-volatile storage. Implementations shall + * make a best effort to ensure that any previous content of the slot is + * unrecoverable. + * + * This function also erases any metadata such as policies. It returns the + * specified slot to its default state. + * + * \param[in] key_slot The key slot to erase. + * + * \retval #PSA_SUCCESS + * The slot's content, if any, has been erased. + */ +typedef psa_status_t (*psa_drv_destroy_key_t)(psa_key_slot_t key); + +/** + * \brief Export a key in binary format + * + * The output of this function can be passed to psa_import_key() to + * create an equivalent object. + * + * If a key is created with `psa_import_key()` and then exported with + * this function, it is not guaranteed that the resulting data is + * identical: the implementation may choose a different representation + * of the same key if the format permits it. + * + * For standard key types, the output format is as follows: + * + * - For symmetric keys (including MAC keys), the format is the + * raw bytes of the key. + * - For DES, the key data consists of 8 bytes. The parity bits must be + * correct. + * - For Triple-DES, the format is the concatenation of the + * two or three DES keys. + * - For RSA key pairs (#PSA_KEY_TYPE_RSA_KEYPAIR), the format + * is the non-encrypted DER representation defined by PKCS\#1 (RFC 8017) + * as RSAPrivateKey. + * - For RSA public keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY), the format + * is the DER representation defined by RFC 5280 as SubjectPublicKeyInfo. + * + * \param[in] key Slot whose content is to be exported. This must + * be an occupied key slot. + * \param[out] p_data Buffer where the key data is to be written. + * \param[in] data_size Size of the `p_data` buffer in bytes. + * \param[out] p_data_length On success, the number of bytes + * that make up the key data. + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_EMPTY_SLOT + * \retval #PSA_ERROR_NOT_PERMITTED + * \retval #PSA_ERROR_NOT_SUPPORTED + * \retval #PSA_ERROR_COMMUNICATION_FAILURE + * \retval #PSA_ERROR_HARDWARE_FAILURE + * \retval #PSA_ERROR_TAMPERING_DETECTED + */ +typedef psa_status_t (*psa_drv_export_key_t)(psa_key_slot_t key, + uint8_t *p_data, + size_t data_size, + size_t *p_data_length); + +/** + * \brief Export a public key or the public part of a key pair in binary format + * + * The output of this function can be passed to psa_import_key() to + * create an object that is equivalent to the public key. + * + * For standard key types, the output format is as follows: + * + * - For RSA keys (#PSA_KEY_TYPE_RSA_KEYPAIR or #PSA_KEY_TYPE_RSA_PUBLIC_KEY), + * the format is the DER representation of the public key defined by RFC 5280 + * as SubjectPublicKeyInfo. + * + * \param[in] key_slot Slot whose content is to be exported. This must + * be an occupied key slot. + * \param[out] p_data Buffer where the key data is to be written. + * \param[in] data_size Size of the `data` buffer in bytes. + * \param[out] p_data_length On success, the number of bytes + * that make up the key data. + * + * \retval #PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_export_public_key_t)(psa_key_slot_t key, + uint8_t *p_data, + size_t data_size, + size_t *p_data_length); + +/** + * \brief A struct containing all of the function pointers needed to for key + * management using opaque keys + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented, it should be set to NULL. + */ +typedef struct { + /** Function that performs the key import operation */ + psa_drv_opaque_import_key_t *p_import; + /** Function that performs the key destroy operation */ + psa_drv_destroy_key_t *p_destroy; + /** Function that performs the key export operation */ + psa_drv_export_key_t *p_export; + /** Function that perforsm the public key export operation */ + psa_drv_export_public_key_t *p_export_public; +} psa_drv_key_management_t; + +/**@}*/ + +/** \defgroup driver_derivation Key Derivation and Agreement + * Key derivation is the process of generating new key material using an + * existing key and additional parameters, iterating through a basic + * cryptographic function, such as a hash. + * Key agreement is a part of cryptographic protocols that allows two parties + * to agree on the same key value, but starting from different original key + * material. + * The flows are similar, and the PSA Crypto Driver Model uses the same functions + * for both of the flows. + * + * There are two different final functions for the flows, + * `psa_drv_key_derivation_derive` and `psa_drv_key_derivation_export`. + * `psa_drv_key_derivation_derive` is used when the key material should be placed + * in a slot on the hardware and not exposed to the caller. + * `psa_drv_key_derivation_export` is used when the key material should be returned + * to the PSA Cryptographic API implementation. + * + * Different key derivation algorithms require a different number of inputs. + * Instead of having an API that takes as input variable length arrays, which + * can be problemmatic to manage on embedded platforms, the inputs are passed + * to the driver via a function, `psa_drv_key_derivation_collateral`, that is + * called multiple times with different `collateral_id`s. Thus, for a key + * derivation algorithm that required 3 paramter inputs, the flow would look + * something like: + * ~~~~~~~~~~~~~{.c} + * psa_drv_key_derivation_setup(kdf_algorithm, source_key, dest_key_size_bytes); + * psa_drv_key_derivation_collateral(kdf_algorithm_collateral_id_0, + * p_collateral_0, + * collateral_0_size); + * psa_drv_key_derivation_collateral(kdf_algorithm_collateral_id_1, + * p_collateral_1, + * collateral_1_size); + * psa_drv_key_derivation_collateral(kdf_algorithm_collateral_id_2, + * p_collateral_2, + * collateral_2_size); + * psa_drv_key_derivation_derive(); + * ~~~~~~~~~~~~~ + * + * key agreement example: + * ~~~~~~~~~~~~~{.c} + * psa_drv_key_derivation_setup(alg, source_key. dest_key_size_bytes); + * psa_drv_key_derivation_collateral(DHE_PUBKEY, p_pubkey, pubkey_size); + * psa_drv_key_derivation_export(p_session_key, + * session_key_size, + * &session_key_length); + * ~~~~~~~~~~~~~ + */ +/**@{*/ + +/** \brief The hardware-specific key derivation context structure + * + * The contents of this structure are implementation dependent and are + * therefore not described here + */ +typedef struct psa_drv_key_derivation_context_s psa_drv_key_derivation_context_t; + +/** \brief Set up a key derivation operation by specifying the algorithm and + * the source key sot + * + * \param[in,out] p_context A hardware-specific structure containing any + * context information for the implementation + * \param[in] kdf_alg The algorithm to be used for the key derivation + * \param[in] souce_key The key to be used as the source material for the + * key derivation + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_key_derivation_setup_t)(psa_drv_key_derivation_context_t *p_context, + psa_algorithm_t kdf_alg, + psa_key_slot_t source_key); + +/** \brief Provide collateral (parameters) needed for a key derivation or key + * agreement operation + * + * Since many key derivation algorithms require multiple parameters, it is + * expeced that this function may be called multiple times for the same + * operation, each with a different algorithm-specific `collateral_id` + * + * \param[in,out] p_context A hardware-specific structure containing any + * context information for the implementation + * \param[in] collateral_id An ID for the collateral being provided + * \param[in] p_collateral A buffer containing the collateral data + * \param[in] collateral_size The size in bytes of the collateral + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_key_derivation_collateral_t)(psa_drv_key_derivation_context_t *p_context, + uint32_t collateral_id, + const uint8_t *p_collateral, + size_t collateral_size); + +/** \brief Perform the final key derivation step and place the generated key + * material in a slot + * \param[in,out] p_context A hardware-specific structure containing any + * context information for the implementation + * \param[in] dest_key The slot where the generated key material + * should be placed + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_key_derivation_derive_t)(psa_drv_key_derivation_context_t *p_context, + psa_key_slot_t dest_key); + +/** \brief Perform the final step of a key agreement and place the generated + * key material in a buffer + * + * \param[out] p_output Buffer in which to place the generated key + * material + * \param[in] output_size The size in bytes of `p_output` + * \param[out] p_output_length Upon success, contains the number of bytes of + * key material placed in `p_output` + * + * \retval PSA_SUCCESS + */ +typedef psa_status_t (*psa_drv_key_derivation_export_t)(uint8_t *p_output, + size_t output_size, + size_t *p_output_length); + +/** + * \brief A struct containing all of the function pointers needed to for key + * derivation and agreement + * + * PSA Crypto API implementations should populate instances of the table as + * appropriate upon startup. + * + * If one of the functions is not implemented, it should be set to NULL. + */ +typedef struct { + /** Function that performs the key derivation setup */ + psa_drv_key_derivation_setup_t *p_setup; + /** Function that sets the key derivation collateral */ + psa_drv_key_derivation_collateral_t *p_collateral; + /** Function that performs the final key derivation step */ + psa_drv_key_derivation_derive_t *p_derive; + /** Function that perforsm the final key derivation or agreement and + * exports the key */ + psa_drv_key_derivation_export_t *p_export; +} psa_drv_key_derivation_t; + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_DRIVER_H */ diff --git a/features/mbedtls/inc/psa/crypto_extra.h b/features/mbedtls/inc/psa/crypto_extra.h new file mode 100644 index 00000000000..7f08857942c --- /dev/null +++ b/features/mbedtls/inc/psa/crypto_extra.h @@ -0,0 +1,128 @@ +/** + * \file psa/crypto_extra.h + * + * \brief PSA cryptography module: Mbed TLS vendor extensions + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file is reserved for vendor-specific definitions. + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_EXTRA_H +#define PSA_CRYPTO_EXTRA_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* UID for secure storage seed */ +#define PSA_CRYPTO_ITS_RANDOM_SEED_UID 0xFFFFFF52 + +/** + * \brief Library deinitialization. + * + * This function clears all data associated with the PSA layer, + * including the whole key store. + * + * This is an Mbed TLS extension. + */ +void mbedtls_psa_crypto_free( void ); + + +/** + * \brief Inject an initial entropy seed for the random generator into + * secure storage. + * + * This function injects data to be used as a seed for the random generator + * used by the PSA Crypto implementation. On devices that lack a trusted + * entropy source (preferably a hardware random number generator), + * the Mbed PSA Crypto implementation uses this value to seed its + * random generator. + * + * On devices without a trusted entropy source, this function must be + * called exactly once in the lifetime of the device. On devices with + * a trusted entropy source, calling this function is optional. + * In all cases, this function may only be called before calling any + * other function in the PSA Crypto API, including psa_crypto_init(). + * + * When this function returns successfully, it populates a file in + * persistent storage. Once the file has been created, this function + * can no longer succeed. + * + * If any error occurs, this function does not change the system state. + * You can call this function again after correcting the reason for the + * error if possible. + * + * \warning This function **can** fail! Callers MUST check the return status. + * + * \warning If you use this function, you should use it as part of a + * factory provisioning process. The value of the injected seed + * is critical to the security of the device. It must be + * *secret*, *unpredictable* and (statistically) *unique per device*. + * You should be generate it randomly using a cryptographically + * secure random generator seeded from trusted entropy sources. + * You should transmit it securely to the device and ensure + * that its value is not leaked or stored anywhere beyond the + * needs of transmitting it from the point of generation to + * the call of this function, and erase all copies of the value + * once this function returns. + * + * This is an Mbed TLS extension. + * + * \note This function is only available on the following platforms: + * * If the compile-time options MBEDTLS_ENTROPY_NV_SEED and + * MBEDTLS_PSA_HAS_ITS_IO are both enabled. Note that you + * must provide compatible implementations of mbedtls_nv_seed_read + * and mbedtls_nv_seed_write. + * * In a client-server integration of PSA Cryptography, on the client side, + * if the server supports this feature. + * \param[in] seed Buffer containing the seed value to inject. + * \param[in] seed_size Size of the \p seed buffer. + * The size of the seed in bytes must be greater + * or equal to both #MBEDTLS_ENTROPY_MIN_PLATFORM + * and #MBEDTLS_ENTROPY_BLOCK_SIZE. + * It must be less or equal to + * #MBEDTLS_ENTROPY_MAX_SEED_SIZE. + * + * \retval #PSA_SUCCESS + * The seed value was injected successfully. The random generator + * of the PSA Crypto implementation is now ready for use. + * You may now call psa_crypto_init() and use the PSA Crypto + * implementation. + * \retval #PSA_ERROR_INVALID_ARGUMENT + * \p seed_size is out of range. + * \retval #PSA_ERROR_STORAGE_FAILURE + * \retval `PSA_ITS_ERROR_XXX` + * There was a failure reading or writing from storage. + * \retval #PSA_ERROR_NOT_PERMITTED + * The library has already been initialized. It is no longer + * possible to call this function. + */ +psa_status_t mbedtls_psa_inject_entropy(const unsigned char *seed, + size_t seed_size); + + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_EXTRA_H */ diff --git a/features/mbedtls/inc/psa/crypto_platform.h b/features/mbedtls/inc/psa/crypto_platform.h new file mode 100644 index 00000000000..9af320d1e9a --- /dev/null +++ b/features/mbedtls/inc/psa/crypto_platform.h @@ -0,0 +1,52 @@ +/** + * \file psa/crypto_platform.h + * + * \brief PSA cryptography module: Mbed TLS platfom definitions + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file contains platform-dependent type definitions. + * + * In implementations with isolation between the application and the + * cryptography module, implementers should take care to ensure that + * the definitions that are exposed to applications match what the + * module implements. + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_PLATFORM_H +#define PSA_CRYPTO_PLATFORM_H + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "../mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/* PSA requires several types which C99 provides in stdint.h. */ +#include + +/* Integral type representing a key slot number. */ +typedef uint16_t psa_key_slot_t; + +#endif /* PSA_CRYPTO_PLATFORM_H */ diff --git a/features/mbedtls/inc/psa/crypto_sizes.h b/features/mbedtls/inc/psa/crypto_sizes.h new file mode 100644 index 00000000000..7e179567367 --- /dev/null +++ b/features/mbedtls/inc/psa/crypto_sizes.h @@ -0,0 +1,527 @@ +/** + * \file psa/crypto_sizes.h + * + * \brief PSA cryptography module: Mbed TLS buffer size macros + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file contains the definitions of macros that are useful to + * compute buffer sizes. The signatures and semantics of these macros + * are standardized, but the definitions are not, because they depend on + * the available algorithms and, in some cases, on permitted tolerances + * on buffer sizes. + * + * In implementations with isolation between the application and the + * cryptography module, implementers should take care to ensure that + * the definitions that are exposed to applications match what the + * module implements. + * + * Macros that compute sizes whose values do not depend on the + * implementation are in crypto.h. + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_SIZES_H +#define PSA_CRYPTO_SIZES_H + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "../mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/** \def PSA_HASH_MAX_SIZE + * + * Maximum size of a hash. + * + * This macro must expand to a compile-time constant integer. This value + * should be the maximum size of a hash supported by the implementation, + * in bytes, and must be no smaller than this maximum. + */ +/* Note: for HMAC-SHA-3, the block size is 144 bytes for HMAC-SHA3-226, + * 136 bytes for HMAC-SHA3-256, 104 bytes for SHA3-384, 72 bytes for + * HMAC-SHA3-512. */ +#if defined(MBEDTLS_SHA512_C) +#define PSA_HASH_MAX_SIZE 64 +#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128 +#else +#define PSA_HASH_MAX_SIZE 32 +#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64 +#endif + +/** \def PSA_MAC_MAX_SIZE + * + * Maximum size of a MAC. + * + * This macro must expand to a compile-time constant integer. This value + * should be the maximum size of a MAC supported by the implementation, + * in bytes, and must be no smaller than this maximum. + */ +/* All non-HMAC MACs have a maximum size that's smaller than the + * minimum possible value of PSA_HASH_MAX_SIZE in this implementation. */ +/* Note that the encoding of truncated MAC algorithms limits this value + * to 64 bytes. + */ +#define PSA_MAC_MAX_SIZE PSA_HASH_MAX_SIZE + +/* The maximum size of an RSA key on this implementation, in bits. + * This is a vendor-specific macro. + * + * Mbed TLS does not set a hard limit on the size of RSA keys: any key + * whose parameters fit in a bignum is accepted. However large keys can + * induce a large memory usage and long computation times. Unlike other + * auxiliary macros in this file and in crypto.h, which reflect how the + * library is configured, this macro defines how the library is + * configured. This implementation refuses to import or generate an + * RSA key whose size is larger than the value defined here. + * + * Note that an implementation may set different size limits for different + * operations, and does not need to accept all key sizes up to the limit. */ +#define PSA_VENDOR_RSA_MAX_KEY_BITS 4096 + +/* The maximum size of an ECC key on this implementation, in bits. + * This is a vendor-specific macro. */ +#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 521 +#elif defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 512 +#elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 448 +#elif defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 384 +#elif defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 384 +#elif defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 +#elif defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 +#elif defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 +#elif defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 255 +#elif defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 224 +#elif defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 224 +#elif defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 192 +#elif defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 192 +#else +#define PSA_VENDOR_ECC_MAX_CURVE_BITS 0 +#endif + +/** \def PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN + * + * This macro returns the maximum length of the PSK supported + * by the TLS-1.2 PSK-to-MS key derivation. + * + * Quoting RFC 4279, Sect 5.3: + * TLS implementations supporting these ciphersuites MUST support + * arbitrary PSK identities up to 128 octets in length, and arbitrary + * PSKs up to 64 octets in length. Supporting longer identities and + * keys is RECOMMENDED. + * + * Therefore, no implementation should define a value smaller than 64 + * for #PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN. + */ +#define PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN 128 + +/** \def PSA_ASYMMETRIC_SIGNATURE_MAX_SIZE + * + * Maximum size of an asymmetric signature. + * + * This macro must expand to a compile-time constant integer. This value + * should be the maximum size of a MAC supported by the implementation, + * in bytes, and must be no smaller than this maximum. + */ +#define PSA_ASYMMETRIC_SIGNATURE_MAX_SIZE \ + PSA_BITS_TO_BYTES( \ + PSA_VENDOR_RSA_MAX_KEY_BITS > PSA_VENDOR_ECC_MAX_CURVE_BITS ? \ + PSA_VENDOR_RSA_MAX_KEY_BITS : \ + PSA_VENDOR_ECC_MAX_CURVE_BITS \ + ) + +/** The maximum size of a block cipher supported by the implementation. */ +#define PSA_MAX_BLOCK_CIPHER_BLOCK_SIZE 16 + +/** The size of the output of psa_mac_sign_finish(), in bytes. + * + * This is also the MAC size that psa_mac_verify_finish() expects. + * + * \param key_type The type of the MAC key. + * \param key_bits The size of the MAC key in bits. + * \param alg A MAC algorithm (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_MAC(alg) is true). + * + * \return The MAC size for the specified algorithm with + * the specified key parameters. + * \return 0 if the MAC algorithm is not recognized. + * \return Either 0 or the correct size for a MAC algorithm that + * the implementation recognizes, but does not support. + * \return Unspecified if the key parameters are not consistent + * with the algorithm. + */ +#define PSA_MAC_FINAL_SIZE(key_type, key_bits, alg) \ + ((alg) & PSA_ALG_MAC_TRUNCATION_MASK ? PSA_MAC_TRUNCATED_LENGTH(alg) : \ + PSA_ALG_IS_HMAC(alg) ? PSA_HASH_SIZE(PSA_ALG_HMAC_GET_HASH(alg)) : \ + PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) ? PSA_BLOCK_CIPHER_BLOCK_SIZE(key_type) : \ + ((void)(key_type), (void)(key_bits), 0)) + +/** The maximum size of the output of psa_aead_encrypt(), in bytes. + * + * If the size of the ciphertext buffer is at least this large, it is + * guaranteed that psa_aead_encrypt() will not fail due to an + * insufficient buffer size. Depending on the algorithm, the actual size of + * the ciphertext may be smaller. + * + * \param alg An AEAD algorithm + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(alg) is true). + * \param plaintext_length Size of the plaintext in bytes. + * + * \return The AEAD ciphertext size for the specified + * algorithm. + * If the AEAD algorithm is not recognized, return 0. + * An implementation may return either 0 or a + * correct size for an AEAD algorithm that it + * recognizes, but does not support. + */ +#define PSA_AEAD_ENCRYPT_OUTPUT_SIZE(alg, plaintext_length) \ + (PSA_AEAD_TAG_LENGTH(alg) != 0 ? \ + (plaintext_length) + PSA_AEAD_TAG_LENGTH(alg) : \ + 0) + +/** The maximum size of the output of psa_aead_decrypt(), in bytes. + * + * If the size of the plaintext buffer is at least this large, it is + * guaranteed that psa_aead_decrypt() will not fail due to an + * insufficient buffer size. Depending on the algorithm, the actual size of + * the plaintext may be smaller. + * + * \param alg An AEAD algorithm + * (\c PSA_ALG_XXX value such that + * #PSA_ALG_IS_AEAD(alg) is true). + * \param ciphertext_length Size of the plaintext in bytes. + * + * \return The AEAD ciphertext size for the specified + * algorithm. + * If the AEAD algorithm is not recognized, return 0. + * An implementation may return either 0 or a + * correct size for an AEAD algorithm that it + * recognizes, but does not support. + */ +#define PSA_AEAD_DECRYPT_OUTPUT_SIZE(alg, ciphertext_length) \ + (PSA_AEAD_TAG_LENGTH(alg) != 0 ? \ + (plaintext_length) - PSA_AEAD_TAG_LENGTH(alg) : \ + 0) + +/** Safe signature buffer size for psa_asymmetric_sign(). + * + * This macro returns a safe buffer size for a signature using a key + * of the specified type and size, with the specified algorithm. + * Note that the actual size of the signature may be smaller + * (some algorithms produce a variable-size signature). + * + * \warning This function may call its arguments multiple times or + * zero times, so you should not pass arguments that contain + * side effects. + * + * \param key_type An asymmetric key type (this may indifferently be a + * key pair type or a public key type). + * \param key_bits The size of the key in bits. + * \param alg The signature algorithm. + * + * \return If the parameters are valid and supported, return + * a buffer size in bytes that guarantees that + * psa_asymmetric_sign() will not fail with + * #PSA_ERROR_BUFFER_TOO_SMALL. + * If the parameters are a valid combination that is not supported + * by the implementation, this macro either shall return either a + * sensible size or 0. + * If the parameters are not valid, the + * return value is unspecified. + */ +#define PSA_ASYMMETRIC_SIGN_OUTPUT_SIZE(key_type, key_bits, alg) \ + (PSA_KEY_TYPE_IS_RSA(key_type) ? ((void)alg, PSA_BITS_TO_BYTES(key_bits)) : \ + PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_ECDSA_SIGNATURE_SIZE(key_bits) : \ + ((void)alg, 0)) + +/** Safe output buffer size for psa_asymmetric_encrypt(). + * + * This macro returns a safe buffer size for a ciphertext produced using + * a key of the specified type and size, with the specified algorithm. + * Note that the actual size of the ciphertext may be smaller, depending + * on the algorithm. + * + * \warning This function may call its arguments multiple times or + * zero times, so you should not pass arguments that contain + * side effects. + * + * \param key_type An asymmetric key type (this may indifferently be a + * key pair type or a public key type). + * \param key_bits The size of the key in bits. + * \param alg The signature algorithm. + * + * \return If the parameters are valid and supported, return + * a buffer size in bytes that guarantees that + * psa_asymmetric_encrypt() will not fail with + * #PSA_ERROR_BUFFER_TOO_SMALL. + * If the parameters are a valid combination that is not supported + * by the implementation, this macro either shall return either a + * sensible size or 0. + * If the parameters are not valid, the + * return value is unspecified. + */ +#define PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \ + (PSA_KEY_TYPE_IS_RSA(key_type) ? \ + ((void)alg, PSA_BITS_TO_BYTES(key_bits)) : \ + 0) + +/** Safe output buffer size for psa_asymmetric_decrypt(). + * + * This macro returns a safe buffer size for a ciphertext produced using + * a key of the specified type and size, with the specified algorithm. + * Note that the actual size of the ciphertext may be smaller, depending + * on the algorithm. + * + * \warning This function may call its arguments multiple times or + * zero times, so you should not pass arguments that contain + * side effects. + * + * \param key_type An asymmetric key type (this may indifferently be a + * key pair type or a public key type). + * \param key_bits The size of the key in bits. + * \param alg The signature algorithm. + * + * \return If the parameters are valid and supported, return + * a buffer size in bytes that guarantees that + * psa_asymmetric_decrypt() will not fail with + * #PSA_ERROR_BUFFER_TOO_SMALL. + * If the parameters are a valid combination that is not supported + * by the implementation, this macro either shall return either a + * sensible size or 0. + * If the parameters are not valid, the + * return value is unspecified. + */ +#define PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \ + (PSA_KEY_TYPE_IS_RSA(key_type) ? \ + PSA_BITS_TO_BYTES(key_bits) - PSA_RSA_MINIMUM_PADDING_SIZE(alg) : \ + 0) + +/* Maximum size of the ASN.1 encoding of an INTEGER with the specified + * number of bits. + * + * This definition assumes that bits <= 2^19 - 9 so that the length field + * is at most 3 bytes. The length of the encoding is the length of the + * bit string padded to a whole number of bytes plus: + * - 1 type byte; + * - 1 to 3 length bytes; + * - 0 to 1 bytes of leading 0 due to the sign bit. + */ +#define PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(bits) \ + ((bits) / 8 + 5) + +/* Maximum size of the export encoding of an RSA public key. + * Assumes that the public exponent is less than 2^32. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING } -- contains RSAPublicKey + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters NULL } + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER } -- e + * + * - 3 * 4 bytes of SEQUENCE overhead; + * - 1 + 1 + 9 bytes of algorithm (RSA OID); + * - 2 bytes of NULL; + * - 4 bytes of BIT STRING overhead; + * - n : INTEGER; + * - 7 bytes for the public exponent. + */ +#define PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) \ + (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) + 36) + +/* Maximum size of the export encoding of an RSA key pair. + * Assumes thatthe public exponent is less than 2^32 and that the size + * difference between the two primes is at most 1 bit. + * + * RSAPrivateKey ::= SEQUENCE { + * version Version, -- 0 + * modulus INTEGER, -- N-bit + * publicExponent INTEGER, -- 32-bit + * privateExponent INTEGER, -- N-bit + * prime1 INTEGER, -- N/2-bit + * prime2 INTEGER, -- N/2-bit + * exponent1 INTEGER, -- N/2-bit + * exponent2 INTEGER, -- N/2-bit + * coefficient INTEGER, -- N/2-bit + * } + * + * - 4 bytes of SEQUENCE overhead; + * - 3 bytes of version; + * - 7 half-size INTEGERs plus 2 full-size INTEGERs, + * overapproximated as 9 half-size INTEGERS; + * - 7 bytes for the public exponent. + */ +#define PSA_KEY_EXPORT_RSA_KEYPAIR_MAX_SIZE(key_bits) \ + (9 * PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE((key_bits) / 2 + 1) + 14) + +/* Maximum size of the export encoding of a DSA public key. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING } -- contains DSAPublicKey + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters Dss-Parms } -- SEQUENCE of 3 INTEGERs + * DSAPublicKey ::= INTEGER -- public key, Y + * + * - 3 * 4 bytes of SEQUENCE overhead; + * - 1 + 1 + 7 bytes of algorithm (DSA OID); + * - 4 bytes of BIT STRING overhead; + * - 3 full-size INTEGERs (p, g, y); + * - 1 + 1 + 32 bytes for 1 sub-size INTEGER (q <= 256 bits). + */ +#define PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) \ + (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3 + 59) + +/* Maximum size of the export encoding of a DSA key pair. + * + * DSAPrivateKey ::= SEQUENCE { + * version Version, -- 0 + * prime INTEGER, -- p + * subprime INTEGER, -- q + * generator INTEGER, -- g + * public INTEGER, -- y + * private INTEGER, -- x + * } + * + * - 4 bytes of SEQUENCE overhead; + * - 3 bytes of version; + * - 3 full-size INTEGERs (p, g, y); + * - 2 * (1 + 1 + 32) bytes for 2 sub-size INTEGERs (q, x <= 256 bits). + */ +#define PSA_KEY_EXPORT_DSA_KEYPAIR_MAX_SIZE(key_bits) \ + (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3 + 75) + +/* Maximum size of the export encoding of an ECC public key. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING } -- contains ECPoint + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters OBJECT IDENTIFIER } -- namedCurve + * ECPoint ::= ... + * -- first 8 bits: 0x04; + * -- then x_P as a `ceiling(m/8)`-byte string, big endian; + * -- then y_P as a `ceiling(m/8)`-byte string, big endian; + * -- where `m` is the bit size associated with the curve. + * + * - 2 * 4 bytes of SEQUENCE overhead; + * - 1 + 1 + 7 bytes of algorithm (id-ecPublicKey OID); + * - 1 + 1 + 12 bytes of namedCurve OID; + * - 4 bytes of BIT STRING overhead; + * - 1 byte + 2 * point size in ECPoint. + */ +#define PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) \ + (2 * PSA_BITS_TO_BYTES(key_bits) + 36) + +/* Maximum size of the export encoding of an ECC key pair. + * + * An ECC key pair is represented by the secret value. + */ +#define PSA_KEY_EXPORT_ECC_KEYPAIR_MAX_SIZE(key_bits) \ + (PSA_BITS_TO_BYTES(key_bits)) + +/** Safe output buffer size for psa_export_key() or psa_export_public_key(). + * + * This macro returns a compile-time constant if its arguments are + * compile-time constants. + * + * \warning This function may call its arguments multiple times or + * zero times, so you should not pass arguments that contain + * side effects. + * + * The following code illustrates how to allocate enough memory to export + * a key by querying the key type and size at runtime. + * \code{c} + * psa_key_type_t key_type; + * size_t key_bits; + * psa_status_t status; + * status = psa_get_key_information(key, &key_type, &key_bits); + * if (status != PSA_SUCCESS) handle_error(...); + * size_t buffer_size = PSA_KEY_EXPORT_MAX_SIZE(key_type, key_bits); + * unsigned char *buffer = malloc(buffer_size); + * if (buffer != NULL) handle_error(...); + * size_t buffer_length; + * status = psa_export_key(key, buffer, buffer_size, &buffer_length); + * if (status != PSA_SUCCESS) handle_error(...); + * \endcode + * + * For psa_export_public_key(), calculate the buffer size from the + * public key type. You can use the macro #PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR + * to convert a key pair type to the corresponding public key type. + * \code{c} + * psa_key_type_t key_type; + * size_t key_bits; + * psa_status_t status; + * status = psa_get_key_information(key, &key_type, &key_bits); + * if (status != PSA_SUCCESS) handle_error(...); + * psa_key_type_t public_key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEYPAIR(key_type); + * size_t buffer_size = PSA_KEY_EXPORT_MAX_SIZE(public_key_type, key_bits); + * unsigned char *buffer = malloc(buffer_size); + * if (buffer != NULL) handle_error(...); + * size_t buffer_length; + * status = psa_export_public_key(key, buffer, buffer_size, &buffer_length); + * if (status != PSA_SUCCESS) handle_error(...); + * \endcode + * + * \param key_type A supported key type. + * \param key_bits The size of the key in bits. + * + * \return If the parameters are valid and supported, return + * a buffer size in bytes that guarantees that + * psa_asymmetric_sign() will not fail with + * #PSA_ERROR_BUFFER_TOO_SMALL. + * If the parameters are a valid combination that is not supported + * by the implementation, this macro either shall return either a + * sensible size or 0. + * If the parameters are not valid, the + * return value is unspecified. + */ +#define PSA_KEY_EXPORT_MAX_SIZE(key_type, key_bits) \ + (PSA_KEY_TYPE_IS_UNSTRUCTURED(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \ + (key_type) == PSA_KEY_TYPE_RSA_KEYPAIR ? PSA_KEY_EXPORT_RSA_KEYPAIR_MAX_SIZE(key_bits) : \ + (key_type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \ + (key_type) == PSA_KEY_TYPE_DSA_KEYPAIR ? PSA_KEY_EXPORT_DSA_KEYPAIR_MAX_SIZE(key_bits) : \ + (key_type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY ? PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \ + PSA_KEY_TYPE_IS_ECC_KEYPAIR(key_type) ? PSA_KEY_EXPORT_ECC_KEYPAIR_MAX_SIZE(key_bits) : \ + PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \ + 0) + +#endif /* PSA_CRYPTO_SIZES_H */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/COMPONENT_NSPE/crypto_struct.h b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/COMPONENT_NSPE/crypto_struct.h new file mode 100644 index 00000000000..44a1a60572f --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/COMPONENT_NSPE/crypto_struct.h @@ -0,0 +1,211 @@ +/** + * \file psa/crypto_struct.h + * + * \brief PSA cryptography module: Mbed TLS structured type implementations + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file contains the definitions of some data structures with + * implementation-specific definitions. + * + * In implementations with isolation between the application and the + * cryptography module, it is expected that the front-end and the back-end + * would have different versions of this file. + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_STRUCT_H +#define PSA_CRYPTO_STRUCT_H + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "../mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/cipher.h" +#include "mbedtls/cmac.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md.h" +#include "mbedtls/md2.h" +#include "mbedtls/md4.h" +#include "mbedtls/md5.h" +#include "mbedtls/ripemd160.h" +#include "mbedtls/sha1.h" +#include "mbedtls/sha256.h" +#include "mbedtls/sha512.h" + +struct psa_hash_operation_s +{ + psa_algorithm_t alg; + union + { + unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ +#if defined(MBEDTLS_MD2_C) + mbedtls_md2_context md2; +#endif +#if defined(MBEDTLS_MD4_C) + mbedtls_md4_context md4; +#endif +#if defined(MBEDTLS_MD5_C) + mbedtls_md5_context md5; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + mbedtls_ripemd160_context ripemd160; +#endif +#if defined(MBEDTLS_SHA1_C) + mbedtls_sha1_context sha1; +#endif +#if defined(MBEDTLS_SHA256_C) + mbedtls_sha256_context sha256; +#endif +#if defined(MBEDTLS_SHA512_C) + mbedtls_sha512_context sha512; +#endif + } ctx; +}; + +#if defined(MBEDTLS_MD_C) +typedef struct +{ + /** The hash context. */ + struct psa_hash_operation_s hash_ctx; + /** The HMAC part of the context. */ + uint8_t opad[PSA_HMAC_MAX_HASH_BLOCK_SIZE]; +} psa_hmac_internal_data; +#endif /* MBEDTLS_MD_C */ + +struct psa_mac_operation_s +{ + psa_algorithm_t alg; + unsigned int key_set : 1; + unsigned int iv_required : 1; + unsigned int iv_set : 1; + unsigned int has_input : 1; + unsigned int is_sign : 1; + uint8_t mac_size; + union + { + unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ +#if defined(MBEDTLS_MD_C) + psa_hmac_internal_data hmac; +#endif +#if defined(MBEDTLS_CMAC_C) + mbedtls_cipher_context_t cmac; +#endif + } ctx; +}; + +struct psa_cipher_operation_s +{ + psa_algorithm_t alg; + unsigned int key_set : 1; + unsigned int iv_required : 1; + unsigned int iv_set : 1; + uint8_t iv_size; + uint8_t block_size; + union + { + mbedtls_cipher_context_t cipher; + } ctx; +}; + +#if defined(MBEDTLS_MD_C) +typedef struct +{ + uint8_t *info; + size_t info_length; + psa_hmac_internal_data hmac; + uint8_t prk[PSA_HASH_MAX_SIZE]; + uint8_t output_block[PSA_HASH_MAX_SIZE]; +#if PSA_HASH_MAX_SIZE > 0xff +#error "PSA_HASH_MAX_SIZE does not fit in uint8_t" +#endif + uint8_t offset_in_block; + uint8_t block_number; +} psa_hkdf_generator_t; +#endif /* MBEDTLS_MD_C */ + +#if defined(MBEDTLS_MD_C) +typedef struct psa_tls12_prf_generator_s +{ + /* The TLS 1.2 PRF uses the key for each HMAC iteration, + * hence we must store it for the lifetime of the generator. + * This is different from HKDF, where the key is only used + * in the extraction phase, but not during expansion. */ + unsigned char *key; + size_t key_len; + + /* `A(i) + seed` in the notation of RFC 5246, Sect. 5 */ + uint8_t *Ai_with_seed; + size_t Ai_with_seed_len; + + /* `HMAC_hash( prk, A(i) + seed )` in the notation of RFC 5246, Sect. 5. */ + uint8_t output_block[PSA_HASH_MAX_SIZE]; + +#if PSA_HASH_MAX_SIZE > 0xff +#error "PSA_HASH_MAX_SIZE does not fit in uint8_t" +#endif + + /* Indicates how many bytes in the current HMAC block have + * already been read by the user. */ + uint8_t offset_in_block; + + /* The 1-based number of the block. */ + uint8_t block_number; + +} psa_tls12_prf_generator_t; +#endif /* MBEDTLS_MD_C */ + +struct psa_crypto_generator_s +{ + psa_algorithm_t alg; + size_t capacity; + union + { + struct + { + uint8_t *data; + size_t size; + } buffer; +#if defined(MBEDTLS_MD_C) + psa_hkdf_generator_t hkdf; + psa_tls12_prf_generator_t tls12_prf; +#endif + } ctx; +}; + +#define PSA_CRYPTO_GENERATOR_INIT {0, 0, {{0, 0}}} +static inline struct psa_crypto_generator_s psa_crypto_generator_init( void ) +{ + const struct psa_crypto_generator_s v = PSA_CRYPTO_GENERATOR_INIT; + return( v ); +} + +struct psa_key_policy_s +{ + psa_key_usage_t usage; + psa_algorithm_t alg; +}; + +#endif /* PSA_CRYPTO_STRUCT_H */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto.c b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto.c new file mode 100644 index 00000000000..d100eb1fcb1 --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto.c @@ -0,0 +1,4479 @@ +/* + * PSA crypto layer on top of Mbed TLS crypto + */ +/* Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_PSA_CRYPTO_C) +/* + * In case MBEDTLS_PSA_CRYPTO_SPM is defined the code is built for SPM (Secure + * Partition Manager) integration which separate the code into two parts + * NSPE (Non-Secure Process Environment) and SPE (Secure Process Environment). + * In this mode an additional header file should be included. + */ +#if defined(MBEDTLS_PSA_CRYPTO_SPM) +/* + * PSA_CRYPTO_SECURE means that this file is compiled to the SPE side. + * some headers will be affected by this flag. + */ +#define PSA_CRYPTO_SECURE 1 +#include "crypto_spe.h" +#endif + +#include "psa/crypto.h" + +/* Include internal declarations that are useful for implementing persistently + * stored keys. */ +#include "psa_crypto_storage.h" + +#include +#include +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#define mbedtls_calloc calloc +#define mbedtls_free free +#endif + +#include "mbedtls/arc4.h" +#include "mbedtls/asn1.h" +#include "mbedtls/bignum.h" +#include "mbedtls/blowfish.h" +#include "mbedtls/camellia.h" +#include "mbedtls/cipher.h" +#include "mbedtls/ccm.h" +#include "mbedtls/cmac.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/des.h" +#include "mbedtls/ecdh.h" +#include "mbedtls/ecp.h" +#include "mbedtls/entropy.h" +#include "mbedtls/entropy_poll.h" +#include "mbedtls/error.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md2.h" +#include "mbedtls/md4.h" +#include "mbedtls/md5.h" +#include "mbedtls/md.h" +#include "mbedtls/md_internal.h" +#include "mbedtls/pk.h" +#include "mbedtls/pk_internal.h" +#include "mbedtls/ripemd160.h" +#include "mbedtls/rsa.h" +#include "mbedtls/sha1.h" +#include "mbedtls/sha256.h" +#include "mbedtls/sha512.h" +#include "mbedtls/xtea.h" + +#if ( defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_PSA_HAS_ITS_IO) ) +#include "psa_prot_internal_storage.h" +#endif + +#define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) ) + +/* Implementation that should never be optimized out by the compiler */ +static void mbedtls_zeroize( void *v, size_t n ) +{ + volatile unsigned char *p = v; while( n-- ) *p++ = 0; +} + +/* constant-time buffer comparison */ +static inline int safer_memcmp( const uint8_t *a, const uint8_t *b, size_t n ) +{ + size_t i; + unsigned char diff = 0; + + for( i = 0; i < n; i++ ) + diff |= a[i] ^ b[i]; + + return( diff ); +} + + + +/****************************************************************/ +/* Global data, support functions and library management */ +/****************************************************************/ + +/* Number of key slots (plus one because 0 is not used). + * The value is a compile-time constant for now, for simplicity. */ +#define PSA_KEY_SLOT_COUNT 32 + +typedef struct +{ + psa_key_type_t type; + psa_key_policy_t policy; + psa_key_lifetime_t lifetime; + union + { + struct raw_data + { + uint8_t *data; + size_t bytes; + } raw; +#if defined(MBEDTLS_RSA_C) + mbedtls_rsa_context *rsa; +#endif /* MBEDTLS_RSA_C */ +#if defined(MBEDTLS_ECP_C) + mbedtls_ecp_keypair *ecp; +#endif /* MBEDTLS_ECP_C */ + } data; +} key_slot_t; + +static int key_type_is_raw_bytes( psa_key_type_t type ) +{ + return( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) ); +} + +typedef struct +{ + int initialized; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + key_slot_t key_slots[PSA_KEY_SLOT_COUNT]; +} psa_global_data_t; + +static psa_global_data_t global_data; + +#define GUARD_MODULE_INITIALIZED \ + if( global_data.initialized == 0 ) \ + return( PSA_ERROR_BAD_STATE ); + +static psa_status_t mbedtls_to_psa_error( int ret ) +{ + /* If there's both a high-level code and low-level code, dispatch on + * the high-level code. */ + switch( ret < -0x7f ? - ( -ret & 0x7f80 ) : ret ) + { + case 0: + return( PSA_SUCCESS ); + + case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH: + case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH: + case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_AES_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_ASN1_OUT_OF_DATA: + case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG: + case MBEDTLS_ERR_ASN1_INVALID_LENGTH: + case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH: + case MBEDTLS_ERR_ASN1_INVALID_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_ASN1_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL: + return( PSA_ERROR_BUFFER_TOO_SMALL ); + + case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH: + case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH: + case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_CCM_BAD_INPUT: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_CCM_AUTH_FAILED: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_CIPHER_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_CIPHER_INVALID_PADDING: + return( PSA_ERROR_INVALID_PADDING ); + case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED: + return( PSA_ERROR_BAD_STATE ); + case MBEDTLS_ERR_CIPHER_AUTH_FAILED: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT: + return( PSA_ERROR_TAMPERING_DETECTED ); + case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED: + return( PSA_ERROR_INSUFFICIENT_ENTROPY ); + case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG: + case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR: + return( PSA_ERROR_INSUFFICIENT_ENTROPY ); + + case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_DES_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED: + case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE: + case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED: + return( PSA_ERROR_INSUFFICIENT_ENTROPY ); + + case MBEDTLS_ERR_GCM_AUTH_FAILED: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_GCM_BAD_INPUT: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED: + case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED: + case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_MD_BAD_INPUT_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MD_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_MD_FILE_IO_ERROR: + return( PSA_ERROR_STORAGE_FAILURE ); + case MBEDTLS_ERR_MD_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_MPI_FILE_IO_ERROR: + return( PSA_ERROR_STORAGE_FAILURE ); + case MBEDTLS_ERR_MPI_BAD_INPUT_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MPI_INVALID_CHARACTER: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL: + return( PSA_ERROR_BUFFER_TOO_SMALL ); + case MBEDTLS_ERR_MPI_NEGATIVE_VALUE: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_MPI_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + case MBEDTLS_ERR_PK_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_PK_TYPE_MISMATCH: + case MBEDTLS_ERR_PK_BAD_INPUT_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_PK_FILE_IO_ERROR: + return( PSA_ERROR_STORAGE_FAILURE ); + case MBEDTLS_ERR_PK_KEY_INVALID_VERSION: + case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_PK_PASSWORD_REQUIRED: + case MBEDTLS_ERR_PK_PASSWORD_MISMATCH: + return( PSA_ERROR_NOT_PERMITTED ); + case MBEDTLS_ERR_PK_INVALID_PUBKEY: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_PK_INVALID_ALG: + case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE: + case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_PK_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_RSA_BAD_INPUT_DATA: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_RSA_INVALID_PADDING: + return( PSA_ERROR_INVALID_PADDING ); + case MBEDTLS_ERR_RSA_KEY_GEN_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_RSA_PUBLIC_FAILED: + case MBEDTLS_ERR_RSA_PRIVATE_FAILED: + return( PSA_ERROR_TAMPERING_DETECTED ); + case MBEDTLS_ERR_RSA_VERIFY_FAILED: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE: + return( PSA_ERROR_BUFFER_TOO_SMALL ); + case MBEDTLS_ERR_RSA_RNG_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED: + case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED: + case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + case MBEDTLS_ERR_ECP_BAD_INPUT_DATA: + case MBEDTLS_ERR_ECP_INVALID_KEY: + return( PSA_ERROR_INVALID_ARGUMENT ); + case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL: + return( PSA_ERROR_BUFFER_TOO_SMALL ); + case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE: + return( PSA_ERROR_NOT_SUPPORTED ); + case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH: + case MBEDTLS_ERR_ECP_VERIFY_FAILED: + return( PSA_ERROR_INVALID_SIGNATURE ); + case MBEDTLS_ERR_ECP_ALLOC_FAILED: + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED: + return( PSA_ERROR_HARDWARE_FAILURE ); + + default: + return( PSA_ERROR_UNKNOWN_ERROR ); + } +} + + + + +/****************************************************************/ +/* Key management */ +/****************************************************************/ + +#if defined(MBEDTLS_ECP_C) +static psa_ecc_curve_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid ) +{ + switch( grpid ) + { + case MBEDTLS_ECP_DP_SECP192R1: + return( PSA_ECC_CURVE_SECP192R1 ); + case MBEDTLS_ECP_DP_SECP224R1: + return( PSA_ECC_CURVE_SECP224R1 ); + case MBEDTLS_ECP_DP_SECP256R1: + return( PSA_ECC_CURVE_SECP256R1 ); + case MBEDTLS_ECP_DP_SECP384R1: + return( PSA_ECC_CURVE_SECP384R1 ); + case MBEDTLS_ECP_DP_SECP521R1: + return( PSA_ECC_CURVE_SECP521R1 ); + case MBEDTLS_ECP_DP_BP256R1: + return( PSA_ECC_CURVE_BRAINPOOL_P256R1 ); + case MBEDTLS_ECP_DP_BP384R1: + return( PSA_ECC_CURVE_BRAINPOOL_P384R1 ); + case MBEDTLS_ECP_DP_BP512R1: + return( PSA_ECC_CURVE_BRAINPOOL_P512R1 ); + case MBEDTLS_ECP_DP_CURVE25519: + return( PSA_ECC_CURVE_CURVE25519 ); + case MBEDTLS_ECP_DP_SECP192K1: + return( PSA_ECC_CURVE_SECP192K1 ); + case MBEDTLS_ECP_DP_SECP224K1: + return( PSA_ECC_CURVE_SECP224K1 ); + case MBEDTLS_ECP_DP_SECP256K1: + return( PSA_ECC_CURVE_SECP256K1 ); + case MBEDTLS_ECP_DP_CURVE448: + return( PSA_ECC_CURVE_CURVE448 ); + default: + return( 0 ); + } +} + +static mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve ) +{ + switch( curve ) + { + case PSA_ECC_CURVE_SECP192R1: + return( MBEDTLS_ECP_DP_SECP192R1 ); + case PSA_ECC_CURVE_SECP224R1: + return( MBEDTLS_ECP_DP_SECP224R1 ); + case PSA_ECC_CURVE_SECP256R1: + return( MBEDTLS_ECP_DP_SECP256R1 ); + case PSA_ECC_CURVE_SECP384R1: + return( MBEDTLS_ECP_DP_SECP384R1 ); + case PSA_ECC_CURVE_SECP521R1: + return( MBEDTLS_ECP_DP_SECP521R1 ); + case PSA_ECC_CURVE_BRAINPOOL_P256R1: + return( MBEDTLS_ECP_DP_BP256R1 ); + case PSA_ECC_CURVE_BRAINPOOL_P384R1: + return( MBEDTLS_ECP_DP_BP384R1 ); + case PSA_ECC_CURVE_BRAINPOOL_P512R1: + return( MBEDTLS_ECP_DP_BP512R1 ); + case PSA_ECC_CURVE_CURVE25519: + return( MBEDTLS_ECP_DP_CURVE25519 ); + case PSA_ECC_CURVE_SECP192K1: + return( MBEDTLS_ECP_DP_SECP192K1 ); + case PSA_ECC_CURVE_SECP224K1: + return( MBEDTLS_ECP_DP_SECP224K1 ); + case PSA_ECC_CURVE_SECP256K1: + return( MBEDTLS_ECP_DP_SECP256K1 ); + case PSA_ECC_CURVE_CURVE448: + return( MBEDTLS_ECP_DP_CURVE448 ); + default: + return( MBEDTLS_ECP_DP_NONE ); + } +} +#endif /* defined(MBEDTLS_ECP_C) */ + +static psa_status_t prepare_raw_data_slot( psa_key_type_t type, + size_t bits, + struct raw_data *raw ) +{ + /* Check that the bit size is acceptable for the key type */ + switch( type ) + { + case PSA_KEY_TYPE_RAW_DATA: + if( bits == 0 ) + { + raw->bytes = 0; + raw->data = NULL; + return( PSA_SUCCESS ); + } + break; +#if defined(MBEDTLS_MD_C) + case PSA_KEY_TYPE_HMAC: +#endif + case PSA_KEY_TYPE_DERIVE: + break; +#if defined(MBEDTLS_AES_C) + case PSA_KEY_TYPE_AES: + if( bits != 128 && bits != 192 && bits != 256 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + break; +#endif +#if defined(MBEDTLS_CAMELLIA_C) + case PSA_KEY_TYPE_CAMELLIA: + if( bits != 128 && bits != 192 && bits != 256 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + break; +#endif +#if defined(MBEDTLS_DES_C) + case PSA_KEY_TYPE_DES: + if( bits != 64 && bits != 128 && bits != 192 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + break; +#endif +#if defined(MBEDTLS_ARC4_C) + case PSA_KEY_TYPE_ARC4: + if( bits < 8 || bits > 2048 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + break; +#endif + default: + return( PSA_ERROR_NOT_SUPPORTED ); + } + if( bits % 8 != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + /* Allocate memory for the key */ + raw->bytes = PSA_BITS_TO_BYTES( bits ); + raw->data = mbedtls_calloc( 1, raw->bytes ); + if( raw->data == NULL ) + { + raw->bytes = 0; + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + } + return( PSA_SUCCESS ); +} + +#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) +/* Mbed TLS doesn't support non-byte-aligned key sizes (i.e. key sizes + * that are not a multiple of 8) well. For example, there is only + * mbedtls_rsa_get_len(), which returns a number of bytes, and no + * way to return the exact bit size of a key. + * To keep things simple, reject non-byte-aligned key sizes. */ +static psa_status_t psa_check_rsa_key_byte_aligned( + const mbedtls_rsa_context *rsa ) +{ + mbedtls_mpi n; + psa_status_t status; + mbedtls_mpi_init( &n ); + status = mbedtls_to_psa_error( + mbedtls_rsa_export( rsa, &n, NULL, NULL, NULL, NULL ) ); + if( status == PSA_SUCCESS ) + { + if( mbedtls_mpi_bitlen( &n ) % 8 != 0 ) + status = PSA_ERROR_NOT_SUPPORTED; + } + mbedtls_mpi_free( &n ); + return( status ); +} + +static psa_status_t psa_import_rsa_key( mbedtls_pk_context *pk, + mbedtls_rsa_context **p_rsa ) +{ + if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_RSA ) + return( PSA_ERROR_INVALID_ARGUMENT ); + else + { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *pk ); + /* The size of an RSA key doesn't have to be a multiple of 8. + * Mbed TLS supports non-byte-aligned key sizes, but not well. + * For example, mbedtls_rsa_get_len() returns the key size in + * bytes, not in bits. */ + size_t bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( rsa ) ); + psa_status_t status; + if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS ) + return( PSA_ERROR_NOT_SUPPORTED ); + status = psa_check_rsa_key_byte_aligned( rsa ); + if( status != PSA_SUCCESS ) + return( status ); + *p_rsa = rsa; + return( PSA_SUCCESS ); + } +} +#endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) */ + +#if defined(MBEDTLS_ECP_C) && defined(MBEDTLS_PK_PARSE_C) +/* Import an elliptic curve parsed by the mbedtls pk module. */ +static psa_status_t psa_import_ecp_key( psa_ecc_curve_t expected_curve, + mbedtls_pk_context *pk, + mbedtls_ecp_keypair **p_ecp ) +{ + if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_ECKEY ) + return( PSA_ERROR_INVALID_ARGUMENT ); + else + { + mbedtls_ecp_keypair *ecp = mbedtls_pk_ec( *pk ); + psa_ecc_curve_t actual_curve = mbedtls_ecc_group_to_psa( ecp->grp.id ); + if( actual_curve != expected_curve ) + return( PSA_ERROR_INVALID_ARGUMENT ); + *p_ecp = ecp; + return( PSA_SUCCESS ); + } +} +#endif /* defined(MBEDTLS_ECP_C) && defined(MBEDTLS_PK_PARSE_C) */ + +#if defined(MBEDTLS_ECP_C) +/* Import a private key given as a byte string which is the private value + * in big-endian order. */ +static psa_status_t psa_import_ec_private_key( psa_ecc_curve_t curve, + const uint8_t *data, + size_t data_length, + mbedtls_ecp_keypair **p_ecp ) +{ + psa_status_t status = PSA_ERROR_TAMPERING_DETECTED; + mbedtls_ecp_keypair *ecp = NULL; + mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve ); + + *p_ecp = NULL; + ecp = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) ); + if( ecp == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + /* Load the group. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_group_load( &ecp->grp, grp_id ) ); + if( status != PSA_SUCCESS ) + goto exit; + /* Load the secret value. */ + status = mbedtls_to_psa_error( + mbedtls_mpi_read_binary( &ecp->d, data, data_length ) ); + if( status != PSA_SUCCESS ) + goto exit; + /* Validate the private key. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_check_privkey( &ecp->grp, &ecp->d ) ); + if( status != PSA_SUCCESS ) + goto exit; + /* Calculate the public key from the private key. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G, + mbedtls_ctr_drbg_random, &global_data.ctr_drbg ) ); + if( status != PSA_SUCCESS ) + goto exit; + + *p_ecp = ecp; + return( PSA_SUCCESS ); + +exit: + if( ecp != NULL ) + { + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + } + return( status ); +} +#endif /* defined(MBEDTLS_ECP_C) */ + +static psa_status_t psa_import_key_into_slot( key_slot_t *slot, + const uint8_t *data, + size_t data_length ) +{ + psa_status_t status = PSA_SUCCESS; + + if( key_type_is_raw_bytes( slot->type ) ) + { + /* Ensure that a bytes-to-bit conversion won't overflow. */ + if( data_length > SIZE_MAX / 8 ) + return( PSA_ERROR_NOT_SUPPORTED ); + status = prepare_raw_data_slot( slot->type, + PSA_BYTES_TO_BITS( data_length ), + &slot->data.raw ); + if( status != PSA_SUCCESS ) + return( status ); + if( data_length != 0 ) + memcpy( slot->data.raw.data, data, data_length ); + } + else +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC_KEYPAIR( slot->type ) ) + { + status = psa_import_ec_private_key( PSA_KEY_TYPE_GET_CURVE( slot->type ), + data, data_length, + &slot->data.ecp ); + if( status != PSA_SUCCESS ) + return( status ); + } + else +#endif /* MBEDTLS_ECP_C */ +#if defined(MBEDTLS_PK_PARSE_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) || + PSA_KEY_TYPE_IS_ECC( slot->type ) ) + { + int ret; + mbedtls_pk_context pk; + mbedtls_pk_init( &pk ); + + /* Parse the data. */ + if( PSA_KEY_TYPE_IS_KEYPAIR( slot->type ) ) + ret = mbedtls_pk_parse_key( &pk, data, data_length, NULL, 0 ); + else + ret = mbedtls_pk_parse_public_key( &pk, data, data_length ); + if( ret != 0 ) + return( mbedtls_to_psa_error( ret ) ); + + /* We have something that the pkparse module recognizes. + * If it has the expected type and passes any type-specific + * checks, store it. */ +#if defined(MBEDTLS_RSA_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + status = psa_import_rsa_key( &pk, &slot->data.rsa ); + else +#endif /* MBEDTLS_RSA_C */ +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC( slot->type ) ) + status = psa_import_ecp_key( PSA_KEY_TYPE_GET_CURVE( slot->type ), + &pk, &slot->data.ecp ); + else +#endif /* MBEDTLS_ECP_C */ + { + status = PSA_ERROR_NOT_SUPPORTED; + } + + /* Free the content of the pk object only on error. On success, + * the content of the object has been stored in the slot. */ + if( status != PSA_SUCCESS ) + { + mbedtls_pk_free( &pk ); + return( status ); + } + } + else +#endif /* defined(MBEDTLS_PK_PARSE_C) */ + { + return( PSA_ERROR_NOT_SUPPORTED ); + } + return( PSA_SUCCESS ); +} + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) +static psa_status_t psa_load_persistent_key_into_slot( psa_key_slot_t key, + key_slot_t *p_slot ) +{ + psa_status_t status = PSA_SUCCESS; + uint8_t *key_data = NULL; + size_t key_data_length = 0; + + status = psa_load_persistent_key( key, &( p_slot )->type, + &( p_slot )->policy, &key_data, + &key_data_length ); + if( status != PSA_SUCCESS ) + goto exit; + status = psa_import_key_into_slot( p_slot, + key_data, key_data_length ); +exit: + psa_free_persistent_key_data( key_data, key_data_length ); + return( status ); +} +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + +/* Retrieve a key slot, occupied or not. */ +static psa_status_t psa_get_key_slot( psa_key_slot_t key, + key_slot_t **p_slot ) +{ + GUARD_MODULE_INITIALIZED; + + /* 0 is not a valid slot number under any circumstance. This + * implementation provides slots number 1 to N where N is the + * number of available slots. */ + if( key == 0 || key > ARRAY_LENGTH( global_data.key_slots ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + *p_slot = &global_data.key_slots[key - 1]; + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + if( ( *p_slot )->lifetime == PSA_KEY_LIFETIME_PERSISTENT ) + { + /* There are two circumstances this can occur: the key material has + * not yet been created, or the key exists in storage but has not yet + * been loaded into memory. */ + if( ( *p_slot )->type == PSA_KEY_TYPE_NONE ) + { + psa_status_t status = PSA_SUCCESS; + status = psa_load_persistent_key_into_slot( key, *p_slot ); + if( status != PSA_ERROR_EMPTY_SLOT ) + return( status ); + } + } +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + + return( PSA_SUCCESS ); +} + +/* Retrieve an empty key slot (slot with no key data, but possibly + * with some metadata such as a policy). */ +static psa_status_t psa_get_empty_key_slot( psa_key_slot_t key, + key_slot_t **p_slot ) +{ + psa_status_t status; + key_slot_t *slot = NULL; + + *p_slot = NULL; + + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + if( slot->type != PSA_KEY_TYPE_NONE ) + return( PSA_ERROR_OCCUPIED_SLOT ); + + *p_slot = slot; + return( status ); +} + +/** Retrieve a slot which must contain a key. The key must have allow all the + * usage flags set in \p usage. If \p alg is nonzero, the key must allow + * operations with this algorithm. */ +static psa_status_t psa_get_key_from_slot( psa_key_slot_t key, + key_slot_t **p_slot, + psa_key_usage_t usage, + psa_algorithm_t alg ) +{ + psa_status_t status; + key_slot_t *slot = NULL; + + *p_slot = NULL; + + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + if( slot->type == PSA_KEY_TYPE_NONE ) + return( PSA_ERROR_EMPTY_SLOT ); + + /* Enforce that usage policy for the key slot contains all the flags + * required by the usage parameter. There is one exception: public + * keys can always be exported, so we treat public key objects as + * if they had the export flag. */ + if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->type ) ) + usage &= ~PSA_KEY_USAGE_EXPORT; + if( ( slot->policy.usage & usage ) != usage ) + return( PSA_ERROR_NOT_PERMITTED ); + if( alg != 0 && ( alg != slot->policy.alg ) ) + return( PSA_ERROR_NOT_PERMITTED ); + + *p_slot = slot; + return( PSA_SUCCESS ); +} + +static psa_status_t psa_remove_key_data_from_memory( key_slot_t *slot ) +{ + if( slot->type == PSA_KEY_TYPE_NONE ) + { + /* No key material to clean. */ + } + else if( key_type_is_raw_bytes( slot->type ) ) + { + mbedtls_free( slot->data.raw.data ); + } + else +#if defined(MBEDTLS_RSA_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + { + mbedtls_rsa_free( slot->data.rsa ); + mbedtls_free( slot->data.rsa ); + } + else +#endif /* defined(MBEDTLS_RSA_C) */ +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC( slot->type ) ) + { + mbedtls_ecp_keypair_free( slot->data.ecp ); + mbedtls_free( slot->data.ecp ); + } + else +#endif /* defined(MBEDTLS_ECP_C) */ + { + /* Shouldn't happen: the key type is not any type that we + * put in. */ + return( PSA_ERROR_TAMPERING_DETECTED ); + } + + return( PSA_SUCCESS ); +} + +psa_status_t psa_import_key( psa_key_slot_t key, + psa_key_type_t type, + const uint8_t *data, + size_t data_length ) +{ + key_slot_t *slot; + psa_status_t status; + + status = psa_get_empty_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + slot->type = type; + + status = psa_import_key_into_slot( slot, data, data_length ); + if( status != PSA_SUCCESS ) + { + slot->type = PSA_KEY_TYPE_NONE; + return( status ); + } + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + if( slot->lifetime == PSA_KEY_LIFETIME_PERSISTENT ) + { + /* Store in file location */ + status = psa_save_persistent_key( key, slot->type, &slot->policy, data, + data_length ); + if( status != PSA_SUCCESS ) + { + (void) psa_remove_key_data_from_memory( slot ); + slot->type = PSA_KEY_TYPE_NONE; + } + } +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + + return( status ); +} + +psa_status_t psa_destroy_key( psa_key_slot_t key ) +{ + key_slot_t *slot; + psa_status_t status = PSA_SUCCESS; + psa_status_t storage_status = PSA_SUCCESS; + + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + if( slot->lifetime == PSA_KEY_LIFETIME_PERSISTENT ) + { + storage_status = psa_destroy_persistent_key( key ); + } +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + status = psa_remove_key_data_from_memory( slot ); + /* Zeroize the slot to wipe metadata such as policies. */ + mbedtls_zeroize( slot, sizeof( *slot ) ); + if( status != PSA_SUCCESS ) + return( status ); + return( storage_status ); +} + +/* Return the size of the key in the given slot, in bits. */ +static size_t psa_get_key_bits( const key_slot_t *slot ) +{ + if( key_type_is_raw_bytes( slot->type ) ) + return( slot->data.raw.bytes * 8 ); +#if defined(MBEDTLS_RSA_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + return( PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( slot->data.rsa ) ) ); +#endif /* defined(MBEDTLS_RSA_C) */ +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC( slot->type ) ) + return( slot->data.ecp->grp.pbits ); +#endif /* defined(MBEDTLS_ECP_C) */ + /* Shouldn't happen except on an empty slot. */ + return( 0 ); +} + +psa_status_t psa_get_key_information( psa_key_slot_t key, + psa_key_type_t *type, + size_t *bits ) +{ + key_slot_t *slot; + psa_status_t status; + + if( type != NULL ) + *type = 0; + if( bits != NULL ) + *bits = 0; + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + if( slot->type == PSA_KEY_TYPE_NONE ) + return( PSA_ERROR_EMPTY_SLOT ); + if( type != NULL ) + *type = slot->type; + if( bits != NULL ) + *bits = psa_get_key_bits( slot ); + return( PSA_SUCCESS ); +} + +static psa_status_t psa_internal_export_key( key_slot_t *slot, + uint8_t *data, + size_t data_size, + size_t *data_length, + int export_public_key ) +{ + *data_length = 0; + + if( export_public_key && ! PSA_KEY_TYPE_IS_ASYMMETRIC( slot->type ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + if( key_type_is_raw_bytes( slot->type ) ) + { + if( slot->data.raw.bytes > data_size ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + if( data_size != 0 ) + { + memcpy( data, slot->data.raw.data, slot->data.raw.bytes ); + memset( data + slot->data.raw.bytes, 0, + data_size - slot->data.raw.bytes ); + } + *data_length = slot->data.raw.bytes; + return( PSA_SUCCESS ); + } +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC_KEYPAIR( slot->type ) && !export_public_key ) + { + psa_status_t status; + + size_t bytes = PSA_BITS_TO_BYTES( psa_get_key_bits( slot ) ); + if( bytes > data_size ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + status = mbedtls_to_psa_error( + mbedtls_mpi_write_binary( &slot->data.ecp->d, data, bytes ) ); + if( status != PSA_SUCCESS ) + return( status ); + memset( data + bytes, 0, data_size - bytes ); + *data_length = bytes; + return( PSA_SUCCESS ); + } +#endif + else + { +#if defined(MBEDTLS_PK_WRITE_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) || + PSA_KEY_TYPE_IS_ECC( slot->type ) ) + { + mbedtls_pk_context pk; + int ret; + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + { +#if defined(MBEDTLS_RSA_C) + mbedtls_pk_init( &pk ); + pk.pk_info = &mbedtls_rsa_info; + pk.pk_ctx = slot->data.rsa; +#else + return( PSA_ERROR_NOT_SUPPORTED ); +#endif + } + else + { +#if defined(MBEDTLS_ECP_C) + mbedtls_pk_init( &pk ); + pk.pk_info = &mbedtls_eckey_info; + pk.pk_ctx = slot->data.ecp; +#else + return( PSA_ERROR_NOT_SUPPORTED ); +#endif + } + if( export_public_key || PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->type ) ) + ret = mbedtls_pk_write_pubkey_der( &pk, data, data_size ); + else + ret = mbedtls_pk_write_key_der( &pk, data, data_size ); + if( ret < 0 ) + { + /* If data_size is 0 then data may be NULL and then the + * call to memset would have undefined behavior. */ + if( data_size != 0 ) + memset( data, 0, data_size ); + return( mbedtls_to_psa_error( ret ) ); + } + /* The mbedtls_pk_xxx functions write to the end of the buffer. + * Move the data to the beginning and erase remaining data + * at the original location. */ + if( 2 * (size_t) ret <= data_size ) + { + memcpy( data, data + data_size - ret, ret ); + memset( data + data_size - ret, 0, ret ); + } + else if( (size_t) ret < data_size ) + { + memmove( data, data + data_size - ret, ret ); + memset( data + ret, 0, data_size - ret ); + } + *data_length = ret; + return( PSA_SUCCESS ); + } + else +#endif /* defined(MBEDTLS_PK_WRITE_C) */ + { + /* This shouldn't happen in the reference implementation, but + it is valid for a special-purpose implementation to omit + support for exporting certain key types. */ + return( PSA_ERROR_NOT_SUPPORTED ); + } + } +} + +psa_status_t psa_export_key( psa_key_slot_t key, + uint8_t *data, + size_t data_size, + size_t *data_length ) +{ + key_slot_t *slot; + psa_status_t status; + + /* Set the key to empty now, so that even when there are errors, we always + * set data_length to a value between 0 and data_size. On error, setting + * the key to empty is a good choice because an empty key representation is + * unlikely to be accepted anywhere. */ + *data_length = 0; + + /* Export requires the EXPORT flag. There is an exception for public keys, + * which don't require any flag, but psa_get_key_from_slot takes + * care of this. */ + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_EXPORT, 0 ); + if( status != PSA_SUCCESS ) + return( status ); + return( psa_internal_export_key( slot, data, data_size, + data_length, 0 ) ); +} + +psa_status_t psa_export_public_key( psa_key_slot_t key, + uint8_t *data, + size_t data_size, + size_t *data_length ) +{ + key_slot_t *slot; + psa_status_t status; + + /* Set the key to empty now, so that even when there are errors, we always + * set data_length to a value between 0 and data_size. On error, setting + * the key to empty is a good choice because an empty key representation is + * unlikely to be accepted anywhere. */ + *data_length = 0; + + /* Exporting a public key doesn't require a usage flag. */ + status = psa_get_key_from_slot( key, &slot, 0, 0 ); + if( status != PSA_SUCCESS ) + return( status ); + return( psa_internal_export_key( slot, data, data_size, + data_length, 1 ) ); +} + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) +static psa_status_t psa_save_generated_persistent_key( psa_key_slot_t key, + key_slot_t *slot, + size_t bits ) +{ + psa_status_t status; + uint8_t *data; + size_t key_length; + size_t data_size = PSA_KEY_EXPORT_MAX_SIZE( slot->type, bits ); + data = mbedtls_calloc( 1, data_size ); + if( data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + /* Get key data in export format */ + status = psa_internal_export_key( slot, data, data_size, &key_length, 0 ); + if( status != PSA_SUCCESS ) + { + slot->type = PSA_KEY_TYPE_NONE; + goto exit; + } + /* Store in file location */ + status = psa_save_persistent_key( key, slot->type, &slot->policy, + data, key_length ); + if( status != PSA_SUCCESS ) + { + slot->type = PSA_KEY_TYPE_NONE; + } +exit: + mbedtls_zeroize( data, key_length ); + mbedtls_free( data ); + return( status ); +} +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + + + +/****************************************************************/ +/* Message digests */ +/****************************************************************/ + +static const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg ) +{ + switch( alg ) + { +#if defined(MBEDTLS_MD2_C) + case PSA_ALG_MD2: + return( &mbedtls_md2_info ); +#endif +#if defined(MBEDTLS_MD4_C) + case PSA_ALG_MD4: + return( &mbedtls_md4_info ); +#endif +#if defined(MBEDTLS_MD5_C) + case PSA_ALG_MD5: + return( &mbedtls_md5_info ); +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case PSA_ALG_RIPEMD160: + return( &mbedtls_ripemd160_info ); +#endif +#if defined(MBEDTLS_SHA1_C) + case PSA_ALG_SHA_1: + return( &mbedtls_sha1_info ); +#endif +#if defined(MBEDTLS_SHA256_C) + case PSA_ALG_SHA_224: + return( &mbedtls_sha224_info ); + case PSA_ALG_SHA_256: + return( &mbedtls_sha256_info ); +#endif +#if defined(MBEDTLS_SHA512_C) + case PSA_ALG_SHA_384: + return( &mbedtls_sha384_info ); + case PSA_ALG_SHA_512: + return( &mbedtls_sha512_info ); +#endif + default: + return( NULL ); + } +} + +psa_status_t psa_hash_abort( psa_hash_operation_t *operation ) +{ + switch( operation->alg ) + { + case 0: + /* The object has (apparently) been initialized but it is not + * in use. It's ok to call abort on such an object, and there's + * nothing to do. */ + break; +#if defined(MBEDTLS_MD2_C) + case PSA_ALG_MD2: + mbedtls_md2_free( &operation->ctx.md2 ); + break; +#endif +#if defined(MBEDTLS_MD4_C) + case PSA_ALG_MD4: + mbedtls_md4_free( &operation->ctx.md4 ); + break; +#endif +#if defined(MBEDTLS_MD5_C) + case PSA_ALG_MD5: + mbedtls_md5_free( &operation->ctx.md5 ); + break; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case PSA_ALG_RIPEMD160: + mbedtls_ripemd160_free( &operation->ctx.ripemd160 ); + break; +#endif +#if defined(MBEDTLS_SHA1_C) + case PSA_ALG_SHA_1: + mbedtls_sha1_free( &operation->ctx.sha1 ); + break; +#endif +#if defined(MBEDTLS_SHA256_C) + case PSA_ALG_SHA_224: + case PSA_ALG_SHA_256: + mbedtls_sha256_free( &operation->ctx.sha256 ); + break; +#endif +#if defined(MBEDTLS_SHA512_C) + case PSA_ALG_SHA_384: + case PSA_ALG_SHA_512: + mbedtls_sha512_free( &operation->ctx.sha512 ); + break; +#endif + default: + return( PSA_ERROR_BAD_STATE ); + } + operation->alg = 0; + return( PSA_SUCCESS ); +} + +psa_status_t psa_hash_setup( psa_hash_operation_t *operation, + psa_algorithm_t alg ) +{ + int ret; + operation->alg = 0; + switch( alg ) + { +#if defined(MBEDTLS_MD2_C) + case PSA_ALG_MD2: + mbedtls_md2_init( &operation->ctx.md2 ); + ret = mbedtls_md2_starts_ret( &operation->ctx.md2 ); + break; +#endif +#if defined(MBEDTLS_MD4_C) + case PSA_ALG_MD4: + mbedtls_md4_init( &operation->ctx.md4 ); + ret = mbedtls_md4_starts_ret( &operation->ctx.md4 ); + break; +#endif +#if defined(MBEDTLS_MD5_C) + case PSA_ALG_MD5: + mbedtls_md5_init( &operation->ctx.md5 ); + ret = mbedtls_md5_starts_ret( &operation->ctx.md5 ); + break; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case PSA_ALG_RIPEMD160: + mbedtls_ripemd160_init( &operation->ctx.ripemd160 ); + ret = mbedtls_ripemd160_starts_ret( &operation->ctx.ripemd160 ); + break; +#endif +#if defined(MBEDTLS_SHA1_C) + case PSA_ALG_SHA_1: + mbedtls_sha1_init( &operation->ctx.sha1 ); + ret = mbedtls_sha1_starts_ret( &operation->ctx.sha1 ); + break; +#endif +#if defined(MBEDTLS_SHA256_C) + case PSA_ALG_SHA_224: + mbedtls_sha256_init( &operation->ctx.sha256 ); + ret = mbedtls_sha256_starts_ret( &operation->ctx.sha256, 1 ); + break; + case PSA_ALG_SHA_256: + mbedtls_sha256_init( &operation->ctx.sha256 ); + ret = mbedtls_sha256_starts_ret( &operation->ctx.sha256, 0 ); + break; +#endif +#if defined(MBEDTLS_SHA512_C) + case PSA_ALG_SHA_384: + mbedtls_sha512_init( &operation->ctx.sha512 ); + ret = mbedtls_sha512_starts_ret( &operation->ctx.sha512, 1 ); + break; + case PSA_ALG_SHA_512: + mbedtls_sha512_init( &operation->ctx.sha512 ); + ret = mbedtls_sha512_starts_ret( &operation->ctx.sha512, 0 ); + break; +#endif + default: + return( PSA_ALG_IS_HASH( alg ) ? + PSA_ERROR_NOT_SUPPORTED : + PSA_ERROR_INVALID_ARGUMENT ); + } + if( ret == 0 ) + operation->alg = alg; + else + psa_hash_abort( operation ); + return( mbedtls_to_psa_error( ret ) ); +} + +psa_status_t psa_hash_update( psa_hash_operation_t *operation, + const uint8_t *input, + size_t input_length ) +{ + int ret; + + /* 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 ); + + switch( operation->alg ) + { +#if defined(MBEDTLS_MD2_C) + case PSA_ALG_MD2: + ret = mbedtls_md2_update_ret( &operation->ctx.md2, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_MD4_C) + case PSA_ALG_MD4: + ret = mbedtls_md4_update_ret( &operation->ctx.md4, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_MD5_C) + case PSA_ALG_MD5: + ret = mbedtls_md5_update_ret( &operation->ctx.md5, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case PSA_ALG_RIPEMD160: + ret = mbedtls_ripemd160_update_ret( &operation->ctx.ripemd160, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_SHA1_C) + case PSA_ALG_SHA_1: + ret = mbedtls_sha1_update_ret( &operation->ctx.sha1, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_SHA256_C) + case PSA_ALG_SHA_224: + case PSA_ALG_SHA_256: + ret = mbedtls_sha256_update_ret( &operation->ctx.sha256, + input, input_length ); + break; +#endif +#if defined(MBEDTLS_SHA512_C) + case PSA_ALG_SHA_384: + case PSA_ALG_SHA_512: + ret = mbedtls_sha512_update_ret( &operation->ctx.sha512, + input, input_length ); + break; +#endif + default: + ret = MBEDTLS_ERR_MD_BAD_INPUT_DATA; + break; + } + + if( ret != 0 ) + psa_hash_abort( operation ); + return( mbedtls_to_psa_error( ret ) ); +} + +psa_status_t psa_hash_finish( psa_hash_operation_t *operation, + uint8_t *hash, + size_t hash_size, + size_t *hash_length ) +{ + psa_status_t status; + int ret; + size_t actual_hash_length = PSA_HASH_SIZE( operation->alg ); + + /* Fill the output buffer with something that isn't a valid hash + * (barring an attack on the hash and deliberately-crafted input), + * in case the caller doesn't check the return status properly. */ + *hash_length = hash_size; + /* If hash_size is 0 then hash may be NULL and then the + * call to memset would have undefined behavior. */ + if( hash_size != 0 ) + memset( hash, '!', hash_size ); + + if( hash_size < actual_hash_length ) + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto exit; + } + + switch( operation->alg ) + { +#if defined(MBEDTLS_MD2_C) + case PSA_ALG_MD2: + ret = mbedtls_md2_finish_ret( &operation->ctx.md2, hash ); + break; +#endif +#if defined(MBEDTLS_MD4_C) + case PSA_ALG_MD4: + ret = mbedtls_md4_finish_ret( &operation->ctx.md4, hash ); + break; +#endif +#if defined(MBEDTLS_MD5_C) + case PSA_ALG_MD5: + ret = mbedtls_md5_finish_ret( &operation->ctx.md5, hash ); + break; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + case PSA_ALG_RIPEMD160: + ret = mbedtls_ripemd160_finish_ret( &operation->ctx.ripemd160, hash ); + break; +#endif +#if defined(MBEDTLS_SHA1_C) + case PSA_ALG_SHA_1: + ret = mbedtls_sha1_finish_ret( &operation->ctx.sha1, hash ); + break; +#endif +#if defined(MBEDTLS_SHA256_C) + case PSA_ALG_SHA_224: + case PSA_ALG_SHA_256: + ret = mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash ); + break; +#endif +#if defined(MBEDTLS_SHA512_C) + case PSA_ALG_SHA_384: + case PSA_ALG_SHA_512: + ret = mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash ); + break; +#endif + default: + ret = MBEDTLS_ERR_MD_BAD_INPUT_DATA; + break; + } + status = mbedtls_to_psa_error( ret ); + +exit: + if( status == PSA_SUCCESS ) + { + *hash_length = actual_hash_length; + return( psa_hash_abort( operation ) ); + } + else + { + psa_hash_abort( operation ); + return( status ); + } +} + +psa_status_t psa_hash_verify( psa_hash_operation_t *operation, + const uint8_t *hash, + size_t hash_length ) +{ + uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE]; + size_t actual_hash_length; + psa_status_t status = psa_hash_finish( operation, + actual_hash, sizeof( actual_hash ), + &actual_hash_length ); + if( status != PSA_SUCCESS ) + return( status ); + if( actual_hash_length != hash_length ) + return( PSA_ERROR_INVALID_SIGNATURE ); + if( safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 ) + return( PSA_ERROR_INVALID_SIGNATURE ); + return( PSA_SUCCESS ); +} + + + +/****************************************************************/ +/* MAC */ +/****************************************************************/ + +static const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa( + psa_algorithm_t alg, + psa_key_type_t key_type, + size_t key_bits, + mbedtls_cipher_id_t* cipher_id ) +{ + mbedtls_cipher_mode_t mode; + mbedtls_cipher_id_t cipher_id_tmp; + + if( PSA_ALG_IS_AEAD( alg ) ) + alg = PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 ); + + if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) ) + { + switch( alg ) + { + case PSA_ALG_ARC4: + mode = MBEDTLS_MODE_STREAM; + break; + case PSA_ALG_CTR: + mode = MBEDTLS_MODE_CTR; + break; + case PSA_ALG_CFB: + mode = MBEDTLS_MODE_CFB; + break; + case PSA_ALG_OFB: + mode = MBEDTLS_MODE_OFB; + break; + case PSA_ALG_CBC_NO_PADDING: + mode = MBEDTLS_MODE_CBC; + break; + case PSA_ALG_CBC_PKCS7: + mode = MBEDTLS_MODE_CBC; + break; + case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ): + mode = MBEDTLS_MODE_CCM; + break; + case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ): + mode = MBEDTLS_MODE_GCM; + break; + default: + return( NULL ); + } + } + else if( alg == PSA_ALG_CMAC ) + mode = MBEDTLS_MODE_ECB; + else if( alg == PSA_ALG_GMAC ) + mode = MBEDTLS_MODE_GCM; + else + return( NULL ); + + switch( key_type ) + { + case PSA_KEY_TYPE_AES: + cipher_id_tmp = MBEDTLS_CIPHER_ID_AES; + break; + case PSA_KEY_TYPE_DES: + /* key_bits is 64 for Single-DES, 128 for two-key Triple-DES, + * and 192 for three-key Triple-DES. */ + if( key_bits == 64 ) + cipher_id_tmp = MBEDTLS_CIPHER_ID_DES; + else + cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES; + /* mbedtls doesn't recognize two-key Triple-DES as an algorithm, + * but two-key Triple-DES is functionally three-key Triple-DES + * with K1=K3, so that's how we present it to mbedtls. */ + if( key_bits == 128 ) + key_bits = 192; + break; + case PSA_KEY_TYPE_CAMELLIA: + cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA; + break; + case PSA_KEY_TYPE_ARC4: + cipher_id_tmp = MBEDTLS_CIPHER_ID_ARC4; + break; + default: + return( NULL ); + } + if( cipher_id != NULL ) + *cipher_id = cipher_id_tmp; + + return( mbedtls_cipher_info_from_values( cipher_id_tmp, + (int) key_bits, mode ) ); +} + +#if defined(MBEDTLS_MD_C) +static size_t psa_get_hash_block_size( psa_algorithm_t alg ) +{ + switch( alg ) + { + case PSA_ALG_MD2: + return( 16 ); + case PSA_ALG_MD4: + return( 64 ); + case PSA_ALG_MD5: + return( 64 ); + case PSA_ALG_RIPEMD160: + return( 64 ); + case PSA_ALG_SHA_1: + return( 64 ); + case PSA_ALG_SHA_224: + return( 64 ); + case PSA_ALG_SHA_256: + return( 64 ); + case PSA_ALG_SHA_384: + return( 128 ); + case PSA_ALG_SHA_512: + return( 128 ); + default: + return( 0 ); + } +} +#endif /* MBEDTLS_MD_C */ + +/* Initialize the MAC operation structure. Once this function has been + * called, psa_mac_abort can run and will do the right thing. */ +static psa_status_t psa_mac_init( psa_mac_operation_t *operation, + psa_algorithm_t alg ) +{ + psa_status_t status = PSA_ERROR_NOT_SUPPORTED; + + operation->alg = alg; + operation->key_set = 0; + operation->iv_set = 0; + operation->iv_required = 0; + operation->has_input = 0; + operation->is_sign = 0; + +#if defined(MBEDTLS_CMAC_C) + if( alg == PSA_ALG_CMAC ) + { + operation->iv_required = 0; + mbedtls_cipher_init( &operation->ctx.cmac ); + status = PSA_SUCCESS; + } + else +#endif /* MBEDTLS_CMAC_C */ +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HMAC( operation->alg ) ) + { + /* We'll set up the hash operation later in psa_hmac_setup_internal. */ + operation->ctx.hmac.hash_ctx.alg = 0; + status = PSA_SUCCESS; + } + else +#endif /* MBEDTLS_MD_C */ + { + if( ! PSA_ALG_IS_MAC( alg ) ) + status = PSA_ERROR_INVALID_ARGUMENT; + } + + if( status != PSA_SUCCESS ) + memset( operation, 0, sizeof( *operation ) ); + return( status ); +} + +#if defined(MBEDTLS_MD_C) +static psa_status_t psa_hmac_abort_internal( psa_hmac_internal_data *hmac ) +{ + mbedtls_zeroize( hmac->opad, sizeof( hmac->opad ) ); + return( psa_hash_abort( &hmac->hash_ctx ) ); +} + +static void psa_hmac_init_internal( psa_hmac_internal_data *hmac ) +{ + /* Instances of psa_hash_operation_s can be initialized by zeroization. */ + memset( hmac, 0, sizeof( *hmac ) ); +} +#endif /* MBEDTLS_MD_C */ + +psa_status_t psa_mac_abort( psa_mac_operation_t *operation ) +{ + if( operation->alg == 0 ) + { + /* The object has (apparently) been initialized but it is not + * in use. It's ok to call abort on such an object, and there's + * nothing to do. */ + return( PSA_SUCCESS ); + } + else +#if defined(MBEDTLS_CMAC_C) + if( operation->alg == PSA_ALG_CMAC ) + { + mbedtls_cipher_free( &operation->ctx.cmac ); + } + else +#endif /* MBEDTLS_CMAC_C */ +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HMAC( operation->alg ) ) + { + psa_hmac_abort_internal( &operation->ctx.hmac ); + } + else +#endif /* MBEDTLS_MD_C */ + { + /* Sanity check (shouldn't happen: operation->alg should + * always have been initialized to a valid value). */ + goto bad_state; + } + + operation->alg = 0; + operation->key_set = 0; + operation->iv_set = 0; + operation->iv_required = 0; + operation->has_input = 0; + operation->is_sign = 0; + + return( PSA_SUCCESS ); + +bad_state: + /* If abort is called on an uninitialized object, we can't trust + * anything. Wipe the object in case it contains confidential data. + * This may result in a memory leak if a pointer gets overwritten, + * but it's too late to do anything about this. */ + memset( operation, 0, sizeof( *operation ) ); + return( PSA_ERROR_BAD_STATE ); +} + +#if defined(MBEDTLS_CMAC_C) +static int psa_cmac_setup( psa_mac_operation_t *operation, + size_t key_bits, + key_slot_t *slot, + const mbedtls_cipher_info_t *cipher_info ) +{ + int ret; + + operation->mac_size = cipher_info->block_size; + + ret = mbedtls_cipher_setup( &operation->ctx.cmac, cipher_info ); + if( ret != 0 ) + return( ret ); + + ret = mbedtls_cipher_cmac_starts( &operation->ctx.cmac, + slot->data.raw.data, + key_bits ); + return( ret ); +} +#endif /* MBEDTLS_CMAC_C */ + +#if defined(MBEDTLS_MD_C) +static psa_status_t psa_hmac_setup_internal( psa_hmac_internal_data *hmac, + const uint8_t *key, + size_t key_length, + psa_algorithm_t hash_alg ) +{ + unsigned char ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE]; + size_t i; + size_t hash_size = PSA_HASH_SIZE( hash_alg ); + size_t block_size = psa_get_hash_block_size( hash_alg ); + psa_status_t status; + + /* Sanity checks on block_size, to guarantee that there won't be a buffer + * overflow below. This should never trigger if the hash algorithm + * is implemented correctly. */ + /* The size checks against the ipad and opad buffers cannot be written + * `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )` + * because that triggers -Wlogical-op on GCC 7.3. */ + if( block_size > sizeof( ipad ) ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( block_size > sizeof( hmac->opad ) ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( block_size < hash_size ) + return( PSA_ERROR_NOT_SUPPORTED ); + + if( key_length > block_size ) + { + status = psa_hash_setup( &hmac->hash_ctx, hash_alg ); + if( status != PSA_SUCCESS ) + goto cleanup; + status = psa_hash_update( &hmac->hash_ctx, key, key_length ); + if( status != PSA_SUCCESS ) + goto cleanup; + status = psa_hash_finish( &hmac->hash_ctx, + ipad, sizeof( ipad ), &key_length ); + if( status != PSA_SUCCESS ) + goto cleanup; + } + /* A 0-length key is not commonly used in HMAC when used as a MAC, + * but it is permitted. It is common when HMAC is used in HKDF, for + * example. Don't call `memcpy` in the 0-length because `key` could be + * an invalid pointer which would make the behavior undefined. */ + else if( key_length != 0 ) + memcpy( ipad, key, key_length ); + + /* ipad contains the key followed by garbage. Xor and fill with 0x36 + * to create the ipad value. */ + for( i = 0; i < key_length; i++ ) + ipad[i] ^= 0x36; + memset( ipad + key_length, 0x36, block_size - key_length ); + + /* Copy the key material from ipad to opad, flipping the requisite bits, + * and filling the rest of opad with the requisite constant. */ + for( i = 0; i < key_length; i++ ) + hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C; + memset( hmac->opad + key_length, 0x5C, block_size - key_length ); + + status = psa_hash_setup( &hmac->hash_ctx, hash_alg ); + if( status != PSA_SUCCESS ) + goto cleanup; + + status = psa_hash_update( &hmac->hash_ctx, ipad, block_size ); + +cleanup: + mbedtls_zeroize( ipad, key_length ); + + return( status ); +} +#endif /* MBEDTLS_MD_C */ + +static psa_status_t psa_mac_setup( psa_mac_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg, + int is_sign ) +{ + psa_status_t status; + key_slot_t *slot; + size_t key_bits; + psa_key_usage_t usage = + is_sign ? PSA_KEY_USAGE_SIGN : PSA_KEY_USAGE_VERIFY; + unsigned char truncated = PSA_MAC_TRUNCATED_LENGTH( alg ); + psa_algorithm_t full_length_alg = PSA_ALG_FULL_LENGTH_MAC( alg ); + + status = psa_mac_init( operation, full_length_alg ); + if( status != PSA_SUCCESS ) + return( status ); + if( is_sign ) + operation->is_sign = 1; + + status = psa_get_key_from_slot( key, &slot, usage, alg ); + if( status != PSA_SUCCESS ) + goto exit; + key_bits = psa_get_key_bits( slot ); + +#if defined(MBEDTLS_CMAC_C) + if( full_length_alg == PSA_ALG_CMAC ) + { + const mbedtls_cipher_info_t *cipher_info = + mbedtls_cipher_info_from_psa( full_length_alg, + slot->type, key_bits, NULL ); + int ret; + if( cipher_info == NULL ) + { + status = PSA_ERROR_NOT_SUPPORTED; + goto exit; + } + operation->mac_size = cipher_info->block_size; + ret = psa_cmac_setup( operation, key_bits, slot, cipher_info ); + status = mbedtls_to_psa_error( ret ); + } + else +#endif /* MBEDTLS_CMAC_C */ +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HMAC( full_length_alg ) ) + { + psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH( alg ); + if( hash_alg == 0 ) + { + status = PSA_ERROR_NOT_SUPPORTED; + goto exit; + } + + operation->mac_size = PSA_HASH_SIZE( hash_alg ); + /* Sanity check. This shouldn't fail on a valid configuration. */ + if( operation->mac_size == 0 || + operation->mac_size > sizeof( operation->ctx.hmac.opad ) ) + { + status = PSA_ERROR_NOT_SUPPORTED; + goto exit; + } + + if( slot->type != PSA_KEY_TYPE_HMAC ) + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto exit; + } + + status = psa_hmac_setup_internal( &operation->ctx.hmac, + slot->data.raw.data, + slot->data.raw.bytes, + hash_alg ); + } + else +#endif /* MBEDTLS_MD_C */ + { + (void) key_bits; + status = PSA_ERROR_NOT_SUPPORTED; + } + + if( truncated == 0 ) + { + /* The "normal" case: untruncated algorithm. Nothing to do. */ + } + else if( truncated < 4 ) + { + /* A very short MAC is too short for security since it can be + * brute-forced. Ancient protocols with 32-bit MACs do exist, + * so we make this our minimum, even though 32 bits is still + * too small for security. */ + status = PSA_ERROR_NOT_SUPPORTED; + } + else if( truncated > operation->mac_size ) + { + /* It's impossible to "truncate" to a larger length. */ + status = PSA_ERROR_INVALID_ARGUMENT; + } + else + operation->mac_size = truncated; + +exit: + if( status != PSA_SUCCESS ) + { + psa_mac_abort( operation ); + } + else + { + operation->key_set = 1; + } + return( status ); +} + +psa_status_t psa_mac_sign_setup( psa_mac_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg ) +{ + return( psa_mac_setup( operation, key, alg, 1 ) ); +} + +psa_status_t psa_mac_verify_setup( psa_mac_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg ) +{ + return( psa_mac_setup( operation, key, alg, 0 ) ); +} + +psa_status_t psa_mac_update( psa_mac_operation_t *operation, + const uint8_t *input, + size_t input_length ) +{ + psa_status_t status = PSA_ERROR_BAD_STATE; + if( ! operation->key_set ) + goto cleanup; + if( operation->iv_required && ! operation->iv_set ) + goto cleanup; + operation->has_input = 1; + +#if defined(MBEDTLS_CMAC_C) + if( operation->alg == PSA_ALG_CMAC ) + { + int ret = mbedtls_cipher_cmac_update( &operation->ctx.cmac, + input, input_length ); + status = mbedtls_to_psa_error( ret ); + } + else +#endif /* MBEDTLS_CMAC_C */ +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HMAC( operation->alg ) ) + { + status = psa_hash_update( &operation->ctx.hmac.hash_ctx, input, + input_length ); + } + else +#endif /* MBEDTLS_MD_C */ + { + /* This shouldn't happen if `operation` was initialized by + * a setup function. */ + status = PSA_ERROR_BAD_STATE; + } + +cleanup: + if( status != PSA_SUCCESS ) + psa_mac_abort( operation ); + return( status ); +} + +#if defined(MBEDTLS_MD_C) +static psa_status_t psa_hmac_finish_internal( psa_hmac_internal_data *hmac, + uint8_t *mac, + size_t mac_size ) +{ + unsigned char tmp[MBEDTLS_MD_MAX_SIZE]; + psa_algorithm_t hash_alg = hmac->hash_ctx.alg; + size_t hash_size = 0; + size_t block_size = psa_get_hash_block_size( hash_alg ); + psa_status_t status; + + status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size ); + if( status != PSA_SUCCESS ) + return( status ); + /* From here on, tmp needs to be wiped. */ + + status = psa_hash_setup( &hmac->hash_ctx, hash_alg ); + if( status != PSA_SUCCESS ) + goto exit; + + status = psa_hash_update( &hmac->hash_ctx, hmac->opad, block_size ); + if( status != PSA_SUCCESS ) + goto exit; + + status = psa_hash_update( &hmac->hash_ctx, tmp, hash_size ); + if( status != PSA_SUCCESS ) + goto exit; + + status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size ); + if( status != PSA_SUCCESS ) + goto exit; + + memcpy( mac, tmp, mac_size ); + +exit: + mbedtls_zeroize( tmp, hash_size ); + return( status ); +} +#endif /* MBEDTLS_MD_C */ + +static psa_status_t psa_mac_finish_internal( psa_mac_operation_t *operation, + uint8_t *mac, + size_t mac_size ) +{ + if( ! operation->key_set ) + return( PSA_ERROR_BAD_STATE ); + if( operation->iv_required && ! operation->iv_set ) + return( PSA_ERROR_BAD_STATE ); + + if( mac_size < operation->mac_size ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + +#if defined(MBEDTLS_CMAC_C) + if( operation->alg == PSA_ALG_CMAC ) + { + uint8_t tmp[PSA_MAX_BLOCK_CIPHER_BLOCK_SIZE]; + int ret = mbedtls_cipher_cmac_finish( &operation->ctx.cmac, tmp ); + if( ret == 0 ) + memcpy( mac, tmp, operation->mac_size ); + mbedtls_zeroize( tmp, sizeof( tmp ) ); + return( mbedtls_to_psa_error( ret ) ); + } + else +#endif /* MBEDTLS_CMAC_C */ +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HMAC( operation->alg ) ) + { + return( psa_hmac_finish_internal( &operation->ctx.hmac, + mac, operation->mac_size ) ); + } + else +#endif /* MBEDTLS_MD_C */ + { + /* This shouldn't happen if `operation` was initialized by + * a setup function. */ + return( PSA_ERROR_BAD_STATE ); + } +} + +psa_status_t psa_mac_sign_finish( psa_mac_operation_t *operation, + uint8_t *mac, + size_t mac_size, + size_t *mac_length ) +{ + psa_status_t status; + + /* Fill the output buffer with something that isn't a valid mac + * (barring an attack on the mac and deliberately-crafted input), + * in case the caller doesn't check the return status properly. */ + *mac_length = mac_size; + /* If mac_size is 0 then mac may be NULL and then the + * call to memset would have undefined behavior. */ + if( mac_size != 0 ) + memset( mac, '!', mac_size ); + + if( ! operation->is_sign ) + { + status = PSA_ERROR_BAD_STATE; + goto cleanup; + } + + status = psa_mac_finish_internal( operation, mac, mac_size ); + +cleanup: + if( status == PSA_SUCCESS ) + { + status = psa_mac_abort( operation ); + if( status == PSA_SUCCESS ) + *mac_length = operation->mac_size; + else + memset( mac, '!', mac_size ); + } + else + psa_mac_abort( operation ); + return( status ); +} + +psa_status_t psa_mac_verify_finish( psa_mac_operation_t *operation, + const uint8_t *mac, + size_t mac_length ) +{ + uint8_t actual_mac[PSA_MAC_MAX_SIZE]; + psa_status_t status; + + if( operation->is_sign ) + { + status = PSA_ERROR_BAD_STATE; + goto cleanup; + } + if( operation->mac_size != mac_length ) + { + status = PSA_ERROR_INVALID_SIGNATURE; + goto cleanup; + } + + status = psa_mac_finish_internal( operation, + actual_mac, sizeof( actual_mac ) ); + + if( safer_memcmp( mac, actual_mac, mac_length ) != 0 ) + status = PSA_ERROR_INVALID_SIGNATURE; + +cleanup: + if( status == PSA_SUCCESS ) + status = psa_mac_abort( operation ); + else + psa_mac_abort( operation ); + + mbedtls_zeroize( actual_mac, sizeof( actual_mac ) ); + + return( status ); +} + + + +/****************************************************************/ +/* Asymmetric cryptography */ +/****************************************************************/ + +#if defined(MBEDTLS_RSA_C) +/* Decode the hash algorithm from alg and store the mbedtls encoding in + * md_alg. Verify that the hash length is acceptable. */ +static psa_status_t psa_rsa_decode_md_type( psa_algorithm_t alg, + size_t hash_length, + mbedtls_md_type_t *md_alg ) +{ + psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg ); + const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg ); + *md_alg = mbedtls_md_get_type( md_info ); + + /* The Mbed TLS RSA module uses an unsigned int for hash length + * parameters. Validate that it fits so that we don't risk an + * overflow later. */ +#if SIZE_MAX > UINT_MAX + if( hash_length > UINT_MAX ) + return( PSA_ERROR_INVALID_ARGUMENT ); +#endif + +#if defined(MBEDTLS_PKCS1_V15) + /* For PKCS#1 v1.5 signature, if using a hash, the hash length + * must be correct. */ + if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) && + alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW ) + { + if( md_info == NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( mbedtls_md_get_size( md_info ) != hash_length ) + return( PSA_ERROR_INVALID_ARGUMENT ); + } +#endif /* MBEDTLS_PKCS1_V15 */ + +#if defined(MBEDTLS_PKCS1_V21) + /* PSS requires a hash internally. */ + if( PSA_ALG_IS_RSA_PSS( alg ) ) + { + if( md_info == NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + } +#endif /* MBEDTLS_PKCS1_V21 */ + + return( PSA_SUCCESS ); +} + +static psa_status_t psa_rsa_sign( mbedtls_rsa_context *rsa, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + uint8_t *signature, + size_t signature_size, + size_t *signature_length ) +{ + psa_status_t status; + int ret; + mbedtls_md_type_t md_alg; + + status = psa_rsa_decode_md_type( alg, hash_length, &md_alg ); + if( status != PSA_SUCCESS ) + return( status ); + + if( signature_size < mbedtls_rsa_get_len( rsa ) ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + +#if defined(MBEDTLS_PKCS1_V15) + if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ) + { + mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15, + MBEDTLS_MD_NONE ); + ret = mbedtls_rsa_pkcs1_sign( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PRIVATE, + md_alg, + (unsigned int) hash_length, + hash, + signature ); + } + else +#endif /* MBEDTLS_PKCS1_V15 */ +#if defined(MBEDTLS_PKCS1_V21) + if( PSA_ALG_IS_RSA_PSS( alg ) ) + { + mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg ); + ret = mbedtls_rsa_rsassa_pss_sign( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PRIVATE, + MBEDTLS_MD_NONE, + (unsigned int) hash_length, + hash, + signature ); + } + else +#endif /* MBEDTLS_PKCS1_V21 */ + { + return( PSA_ERROR_INVALID_ARGUMENT ); + } + + if( ret == 0 ) + *signature_length = mbedtls_rsa_get_len( rsa ); + return( mbedtls_to_psa_error( ret ) ); +} + +static psa_status_t psa_rsa_verify( mbedtls_rsa_context *rsa, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + const uint8_t *signature, + size_t signature_length ) +{ + psa_status_t status; + int ret; + mbedtls_md_type_t md_alg; + + status = psa_rsa_decode_md_type( alg, hash_length, &md_alg ); + if( status != PSA_SUCCESS ) + return( status ); + + if( signature_length < mbedtls_rsa_get_len( rsa ) ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + +#if defined(MBEDTLS_PKCS1_V15) + if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ) + { + mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15, + MBEDTLS_MD_NONE ); + ret = mbedtls_rsa_pkcs1_verify( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PUBLIC, + md_alg, + (unsigned int) hash_length, + hash, + signature ); + } + else +#endif /* MBEDTLS_PKCS1_V15 */ +#if defined(MBEDTLS_PKCS1_V21) + if( PSA_ALG_IS_RSA_PSS( alg ) ) + { + mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg ); + ret = mbedtls_rsa_rsassa_pss_verify( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PUBLIC, + MBEDTLS_MD_NONE, + (unsigned int) hash_length, + hash, + signature ); + } + else +#endif /* MBEDTLS_PKCS1_V21 */ + { + return( PSA_ERROR_INVALID_ARGUMENT ); + } + + /* Mbed TLS distinguishes "invalid padding" from "valid padding but + * the rest of the signature is invalid". This has little use in + * practice and PSA doesn't report this distinction. */ + if( ret == MBEDTLS_ERR_RSA_INVALID_PADDING ) + return( PSA_ERROR_INVALID_SIGNATURE ); + return( mbedtls_to_psa_error( ret ) ); +} +#endif /* MBEDTLS_RSA_C */ + +#if defined(MBEDTLS_ECDSA_C) +/* `ecp` cannot be const because `ecp->grp` needs to be non-const + * for mbedtls_ecdsa_sign() and mbedtls_ecdsa_sign_det() + * (even though these functions don't modify it). */ +static psa_status_t psa_ecdsa_sign( mbedtls_ecp_keypair *ecp, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + uint8_t *signature, + size_t signature_size, + size_t *signature_length ) +{ + int ret; + mbedtls_mpi r, s; + size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits ); + mbedtls_mpi_init( &r ); + mbedtls_mpi_init( &s ); + + if( signature_size < 2 * curve_bytes ) + { + ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; + goto cleanup; + } + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + if( PSA_ALG_DSA_IS_DETERMINISTIC( alg ) ) + { + psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg ); + const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg ); + mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info ); + MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ecp->grp, &r, &s, &ecp->d, + hash, hash_length, + md_alg ) ); + } + else +#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ + { + (void) alg; + MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ecp->grp, &r, &s, &ecp->d, + hash, hash_length, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg ) ); + } + + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &r, + signature, + curve_bytes ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &s, + signature + curve_bytes, + curve_bytes ) ); + +cleanup: + mbedtls_mpi_free( &r ); + mbedtls_mpi_free( &s ); + if( ret == 0 ) + *signature_length = 2 * curve_bytes; + return( mbedtls_to_psa_error( ret ) ); +} + +static psa_status_t psa_ecdsa_verify( mbedtls_ecp_keypair *ecp, + const uint8_t *hash, + size_t hash_length, + const uint8_t *signature, + size_t signature_length ) +{ + int ret; + mbedtls_mpi r, s; + size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits ); + mbedtls_mpi_init( &r ); + mbedtls_mpi_init( &s ); + + if( signature_length != 2 * curve_bytes ) + return( PSA_ERROR_INVALID_SIGNATURE ); + + MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &r, + signature, + curve_bytes ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &s, + signature + curve_bytes, + curve_bytes ) ); + + ret = mbedtls_ecdsa_verify( &ecp->grp, hash, hash_length, + &ecp->Q, &r, &s ); + +cleanup: + mbedtls_mpi_free( &r ); + mbedtls_mpi_free( &s ); + return( mbedtls_to_psa_error( ret ) ); +} +#endif /* MBEDTLS_ECDSA_C */ + +psa_status_t psa_asymmetric_sign( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + uint8_t *signature, + size_t signature_size, + size_t *signature_length ) +{ + key_slot_t *slot; + psa_status_t status; + + *signature_length = signature_size; + + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_SIGN, alg ); + if( status != PSA_SUCCESS ) + goto exit; + if( ! PSA_KEY_TYPE_IS_KEYPAIR( slot->type ) ) + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto exit; + } + +#if defined(MBEDTLS_RSA_C) + if( slot->type == PSA_KEY_TYPE_RSA_KEYPAIR ) + { + status = psa_rsa_sign( slot->data.rsa, + alg, + hash, hash_length, + signature, signature_size, + signature_length ); + } + else +#endif /* defined(MBEDTLS_RSA_C) */ +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC( slot->type ) ) + { +#if defined(MBEDTLS_ECDSA_C) + if( +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + PSA_ALG_IS_ECDSA( alg ) +#else + PSA_ALG_IS_RANDOMIZED_ECDSA( alg ) +#endif + ) + status = psa_ecdsa_sign( slot->data.ecp, + alg, + hash, hash_length, + signature, signature_size, + signature_length ); + else +#endif /* defined(MBEDTLS_ECDSA_C) */ + { + status = PSA_ERROR_INVALID_ARGUMENT; + } + } + else +#endif /* defined(MBEDTLS_ECP_C) */ + { + status = PSA_ERROR_NOT_SUPPORTED; + } + +exit: + /* Fill the unused part of the output buffer (the whole buffer on error, + * the trailing part on success) with something that isn't a valid mac + * (barring an attack on the mac and deliberately-crafted input), + * in case the caller doesn't check the return status properly. */ + if( status == PSA_SUCCESS ) + memset( signature + *signature_length, '!', + signature_size - *signature_length ); + else if( signature_size != 0 ) + memset( signature, '!', signature_size ); + /* If signature_size is 0 then we have nothing to do. We must not call + * memset because signature may be NULL in this case. */ + return( status ); +} + +psa_status_t psa_asymmetric_verify( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + const uint8_t *signature, + size_t signature_length ) +{ + key_slot_t *slot; + psa_status_t status; + + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_VERIFY, alg ); + if( status != PSA_SUCCESS ) + return( status ); + +#if defined(MBEDTLS_RSA_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + { + return( psa_rsa_verify( slot->data.rsa, + alg, + hash, hash_length, + signature, signature_length ) ); + } + else +#endif /* defined(MBEDTLS_RSA_C) */ +#if defined(MBEDTLS_ECP_C) + if( PSA_KEY_TYPE_IS_ECC( slot->type ) ) + { +#if defined(MBEDTLS_ECDSA_C) + if( PSA_ALG_IS_ECDSA( alg ) ) + return( psa_ecdsa_verify( slot->data.ecp, + hash, hash_length, + signature, signature_length ) ); + else +#endif /* defined(MBEDTLS_ECDSA_C) */ + { + return( PSA_ERROR_INVALID_ARGUMENT ); + } + } + else +#endif /* defined(MBEDTLS_ECP_C) */ + { + return( PSA_ERROR_NOT_SUPPORTED ); + } +} + +#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21) +static void psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg, + mbedtls_rsa_context *rsa ) +{ + psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg ); + const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg ); + mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info ); + mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg ); +} +#endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21) */ + +psa_status_t psa_asymmetric_encrypt( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + const uint8_t *salt, + size_t salt_length, + uint8_t *output, + size_t output_size, + size_t *output_length ) +{ + key_slot_t *slot; + psa_status_t status; + + (void) input; + (void) input_length; + (void) salt; + (void) output; + (void) output_size; + + *output_length = 0; + + if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_ENCRYPT, alg ); + if( status != PSA_SUCCESS ) + return( status ); + if( ! ( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->type ) || + PSA_KEY_TYPE_IS_KEYPAIR( slot->type ) ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + +#if defined(MBEDTLS_RSA_C) + if( PSA_KEY_TYPE_IS_RSA( slot->type ) ) + { + mbedtls_rsa_context *rsa = slot->data.rsa; + int ret; + if( output_size < mbedtls_rsa_get_len( rsa ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); +#if defined(MBEDTLS_PKCS1_V15) + if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT ) + { + ret = mbedtls_rsa_pkcs1_encrypt( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PUBLIC, + input_length, + input, + output ); + } + else +#endif /* MBEDTLS_PKCS1_V15 */ +#if defined(MBEDTLS_PKCS1_V21) + if( PSA_ALG_IS_RSA_OAEP( alg ) ) + { + psa_rsa_oaep_set_padding_mode( alg, rsa ); + ret = mbedtls_rsa_rsaes_oaep_encrypt( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PUBLIC, + salt, salt_length, + input_length, + input, + output ); + } + else +#endif /* MBEDTLS_PKCS1_V21 */ + { + return( PSA_ERROR_INVALID_ARGUMENT ); + } + if( ret == 0 ) + *output_length = mbedtls_rsa_get_len( rsa ); + return( mbedtls_to_psa_error( ret ) ); + } + else +#endif /* defined(MBEDTLS_RSA_C) */ + { + return( PSA_ERROR_NOT_SUPPORTED ); + } +} + +psa_status_t psa_asymmetric_decrypt( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + const uint8_t *salt, + size_t salt_length, + uint8_t *output, + size_t output_size, + size_t *output_length ) +{ + key_slot_t *slot; + psa_status_t status; + + (void) input; + (void) input_length; + (void) salt; + (void) output; + (void) output_size; + + *output_length = 0; + + if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_DECRYPT, alg ); + if( status != PSA_SUCCESS ) + return( status ); + if( ! PSA_KEY_TYPE_IS_KEYPAIR( slot->type ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + +#if defined(MBEDTLS_RSA_C) + if( slot->type == PSA_KEY_TYPE_RSA_KEYPAIR ) + { + mbedtls_rsa_context *rsa = slot->data.rsa; + int ret; + + if( input_length != mbedtls_rsa_get_len( rsa ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + +#if defined(MBEDTLS_PKCS1_V15) + if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT ) + { + ret = mbedtls_rsa_pkcs1_decrypt( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PRIVATE, + output_length, + input, + output, + output_size ); + } + else +#endif /* MBEDTLS_PKCS1_V15 */ +#if defined(MBEDTLS_PKCS1_V21) + if( PSA_ALG_IS_RSA_OAEP( alg ) ) + { + psa_rsa_oaep_set_padding_mode( alg, rsa ); + ret = mbedtls_rsa_rsaes_oaep_decrypt( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + MBEDTLS_RSA_PRIVATE, + salt, salt_length, + output_length, + input, + output, + output_size ); + } + else +#endif /* MBEDTLS_PKCS1_V21 */ + { + return( PSA_ERROR_INVALID_ARGUMENT ); + } + + return( mbedtls_to_psa_error( ret ) ); + } + else +#endif /* defined(MBEDTLS_RSA_C) */ + { + return( PSA_ERROR_NOT_SUPPORTED ); + } +} + + + +/****************************************************************/ +/* Symmetric cryptography */ +/****************************************************************/ + +/* Initialize the cipher operation structure. Once this function has been + * called, psa_cipher_abort can run and will do the right thing. */ +static psa_status_t psa_cipher_init( psa_cipher_operation_t *operation, + psa_algorithm_t alg ) +{ + if( ! PSA_ALG_IS_CIPHER( alg ) ) + { + memset( operation, 0, sizeof( *operation ) ); + return( PSA_ERROR_INVALID_ARGUMENT ); + } + + operation->alg = alg; + operation->key_set = 0; + operation->iv_set = 0; + operation->iv_required = 1; + operation->iv_size = 0; + operation->block_size = 0; + mbedtls_cipher_init( &operation->ctx.cipher ); + return( PSA_SUCCESS ); +} + +static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg, + mbedtls_operation_t cipher_operation ) +{ + int ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE; + psa_status_t status; + key_slot_t *slot; + size_t key_bits; + const mbedtls_cipher_info_t *cipher_info = NULL; + psa_key_usage_t usage = ( cipher_operation == MBEDTLS_ENCRYPT ? + PSA_KEY_USAGE_ENCRYPT : + PSA_KEY_USAGE_DECRYPT ); + + status = psa_cipher_init( operation, alg ); + if( status != PSA_SUCCESS ) + return( status ); + + status = psa_get_key_from_slot( key, &slot, usage, alg); + if( status != PSA_SUCCESS ) + return( status ); + key_bits = psa_get_key_bits( slot ); + + cipher_info = mbedtls_cipher_info_from_psa( alg, slot->type, key_bits, NULL ); + if( cipher_info == NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + + ret = mbedtls_cipher_setup( &operation->ctx.cipher, cipher_info ); + if( ret != 0 ) + { + psa_cipher_abort( operation ); + return( mbedtls_to_psa_error( ret ) ); + } + +#if defined(MBEDTLS_DES_C) + if( slot->type == PSA_KEY_TYPE_DES && key_bits == 128 ) + { + /* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */ + unsigned char keys[24]; + memcpy( keys, slot->data.raw.data, 16 ); + memcpy( keys + 16, slot->data.raw.data, 8 ); + ret = mbedtls_cipher_setkey( &operation->ctx.cipher, + keys, + 192, cipher_operation ); + } + else +#endif + { + ret = mbedtls_cipher_setkey( &operation->ctx.cipher, + slot->data.raw.data, + (int) key_bits, cipher_operation ); + } + if( ret != 0 ) + { + psa_cipher_abort( operation ); + return( mbedtls_to_psa_error( ret ) ); + } + +#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) + switch( alg ) + { + case PSA_ALG_CBC_NO_PADDING: + ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher, + MBEDTLS_PADDING_NONE ); + break; + case PSA_ALG_CBC_PKCS7: + ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher, + MBEDTLS_PADDING_PKCS7 ); + break; + default: + /* The algorithm doesn't involve padding. */ + ret = 0; + break; + } + if( ret != 0 ) + { + psa_cipher_abort( operation ); + return( mbedtls_to_psa_error( ret ) ); + } +#endif //MBEDTLS_CIPHER_MODE_WITH_PADDING + + operation->key_set = 1; + operation->block_size = ( PSA_ALG_IS_STREAM_CIPHER( alg ) ? 1 : + PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->type ) ); + if( alg & PSA_ALG_CIPHER_FROM_BLOCK_FLAG ) + { + operation->iv_size = PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->type ); + } + + return( PSA_SUCCESS ); +} + +psa_status_t psa_cipher_encrypt_setup( psa_cipher_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg ) +{ + return( psa_cipher_setup( operation, key, alg, MBEDTLS_ENCRYPT ) ); +} + +psa_status_t psa_cipher_decrypt_setup( psa_cipher_operation_t *operation, + psa_key_slot_t key, + psa_algorithm_t alg ) +{ + return( psa_cipher_setup( operation, key, alg, MBEDTLS_DECRYPT ) ); +} + +psa_status_t psa_cipher_generate_iv( psa_cipher_operation_t *operation, + unsigned char *iv, + size_t iv_size, + size_t *iv_length ) +{ + psa_status_t status; + int ret; + if( operation->iv_set || ! operation->iv_required ) + { + status = PSA_ERROR_BAD_STATE; + goto exit; + } + if( iv_size < operation->iv_size ) + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto exit; + } + ret = mbedtls_ctr_drbg_random( &global_data.ctr_drbg, + iv, operation->iv_size ); + if( ret != 0 ) + { + status = mbedtls_to_psa_error( ret ); + goto exit; + } + + *iv_length = operation->iv_size; + status = psa_cipher_set_iv( operation, iv, *iv_length ); + +exit: + if( status != PSA_SUCCESS ) + psa_cipher_abort( operation ); + return( status ); +} + +psa_status_t psa_cipher_set_iv( psa_cipher_operation_t *operation, + const unsigned char *iv, + size_t iv_length ) +{ + psa_status_t status; + int ret; + if( operation->iv_set || ! operation->iv_required ) + { + status = PSA_ERROR_BAD_STATE; + goto exit; + } + if( iv_length != operation->iv_size ) + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto exit; + } + ret = mbedtls_cipher_set_iv( &operation->ctx.cipher, iv, iv_length ); + status = mbedtls_to_psa_error( ret ); +exit: + if( status == PSA_SUCCESS ) + operation->iv_set = 1; + else + psa_cipher_abort( operation ); + return( status ); +} + +psa_status_t psa_cipher_update( psa_cipher_operation_t *operation, + const uint8_t *input, + size_t input_length, + unsigned char *output, + size_t output_size, + size_t *output_length ) +{ + psa_status_t status; + int ret; + size_t expected_output_size; + if( ! PSA_ALG_IS_STREAM_CIPHER( operation->alg ) ) + { + /* Take the unprocessed partial block left over from previous + * update calls, if any, plus the input to this call. Remove + * the last partial block, if any. You get the data that will be + * output in this call. */ + expected_output_size = + ( operation->ctx.cipher.unprocessed_len + input_length ) + / operation->block_size * operation->block_size; + } + else + { + expected_output_size = input_length; + } + + if( output_size < expected_output_size ) + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto exit; + } + + ret = mbedtls_cipher_update( &operation->ctx.cipher, input, + input_length, output, output_length ); + status = mbedtls_to_psa_error( ret ); +exit: + if( status != PSA_SUCCESS ) + psa_cipher_abort( operation ); + return( status ); +} + +psa_status_t psa_cipher_finish( psa_cipher_operation_t *operation, + uint8_t *output, + size_t output_size, + size_t *output_length ) +{ + psa_status_t status = PSA_ERROR_UNKNOWN_ERROR; + int cipher_ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE; + uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH]; + + if( ! operation->key_set ) + { + status = PSA_ERROR_BAD_STATE; + goto error; + } + if( operation->iv_required && ! operation->iv_set ) + { + status = PSA_ERROR_BAD_STATE; + goto error; + } + + if( operation->ctx.cipher.operation == MBEDTLS_ENCRYPT && + operation->alg == PSA_ALG_CBC_NO_PADDING && + operation->ctx.cipher.unprocessed_len != 0 ) + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto error; + } + + cipher_ret = mbedtls_cipher_finish( &operation->ctx.cipher, + temp_output_buffer, + output_length ); + if( cipher_ret != 0 ) + { + status = mbedtls_to_psa_error( cipher_ret ); + goto error; + } + + if( *output_length == 0 ) + ; /* Nothing to copy. Note that output may be NULL in this case. */ + else if( output_size >= *output_length ) + memcpy( output, temp_output_buffer, *output_length ); + else + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto error; + } + + mbedtls_zeroize( temp_output_buffer, sizeof( temp_output_buffer ) ); + status = psa_cipher_abort( operation ); + + return( status ); + +error: + + *output_length = 0; + + mbedtls_zeroize( temp_output_buffer, sizeof( temp_output_buffer ) ); + (void) psa_cipher_abort( operation ); + + return( status ); +} + +psa_status_t psa_cipher_abort( psa_cipher_operation_t *operation ) +{ + if( operation->alg == 0 ) + { + /* The object has (apparently) been initialized but it is not + * in use. It's ok to call abort on such an object, and there's + * nothing to do. */ + return( PSA_SUCCESS ); + } + + /* Sanity check (shouldn't happen: operation->alg should + * always have been initialized to a valid value). */ + if( ! PSA_ALG_IS_CIPHER( operation->alg ) ) + return( PSA_ERROR_BAD_STATE ); + + mbedtls_cipher_free( &operation->ctx.cipher ); + + operation->alg = 0; + operation->key_set = 0; + operation->iv_set = 0; + operation->iv_size = 0; + operation->block_size = 0; + operation->iv_required = 0; + + return( PSA_SUCCESS ); +} + + + +/****************************************************************/ +/* Key Policy */ +/****************************************************************/ + +#if !defined(MBEDTLS_PSA_CRYPTO_SPM) +void psa_key_policy_init( psa_key_policy_t *policy ) +{ + memset( policy, 0, sizeof( *policy ) ); +} + +void psa_key_policy_set_usage( psa_key_policy_t *policy, + psa_key_usage_t usage, + psa_algorithm_t alg ) +{ + policy->usage = usage; + policy->alg = alg; +} + +psa_key_usage_t psa_key_policy_get_usage( const psa_key_policy_t *policy ) +{ + return( policy->usage ); +} + +psa_algorithm_t psa_key_policy_get_algorithm( const psa_key_policy_t *policy ) +{ + return( policy->alg ); +} +#endif /* !defined(MBEDTLS_PSA_CRYPTO_SPM) */ + +psa_status_t psa_set_key_policy( psa_key_slot_t key, + const psa_key_policy_t *policy ) +{ + key_slot_t *slot; + psa_status_t status; + + if( policy == NULL ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_empty_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + if( ( policy->usage & ~( PSA_KEY_USAGE_EXPORT | + PSA_KEY_USAGE_ENCRYPT | + PSA_KEY_USAGE_DECRYPT | + PSA_KEY_USAGE_SIGN | + PSA_KEY_USAGE_VERIFY | + PSA_KEY_USAGE_DERIVE ) ) != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + slot->policy = *policy; + + return( PSA_SUCCESS ); +} + +psa_status_t psa_get_key_policy( psa_key_slot_t key, + psa_key_policy_t *policy ) +{ + key_slot_t *slot; + psa_status_t status; + + if( policy == NULL ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + *policy = slot->policy; + + return( PSA_SUCCESS ); +} + + + +/****************************************************************/ +/* Key Lifetime */ +/****************************************************************/ + +psa_status_t psa_get_key_lifetime( psa_key_slot_t key, + psa_key_lifetime_t *lifetime ) +{ + key_slot_t *slot; + psa_status_t status; + + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + *lifetime = slot->lifetime; + + return( PSA_SUCCESS ); +} + +psa_status_t psa_set_key_lifetime( psa_key_slot_t key, + psa_key_lifetime_t lifetime ) +{ + key_slot_t *slot; + psa_status_t status; + + if( lifetime != PSA_KEY_LIFETIME_VOLATILE && + lifetime != PSA_KEY_LIFETIME_PERSISTENT && + lifetime != PSA_KEY_LIFETIME_WRITE_ONCE ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_empty_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + if( lifetime == PSA_KEY_LIFETIME_WRITE_ONCE ) + return( PSA_ERROR_NOT_SUPPORTED ); + +#if !defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + if( lifetime == PSA_KEY_LIFETIME_PERSISTENT ) + return( PSA_ERROR_NOT_SUPPORTED ); +#endif + + slot->lifetime = lifetime; + + return( PSA_SUCCESS ); +} + + + +/****************************************************************/ +/* AEAD */ +/****************************************************************/ + +typedef struct +{ + key_slot_t *slot; + const mbedtls_cipher_info_t *cipher_info; + union + { +#if defined(MBEDTLS_CCM_C) + mbedtls_ccm_context ccm; +#endif /* MBEDTLS_CCM_C */ +#if defined(MBEDTLS_GCM_C) + mbedtls_gcm_context gcm; +#endif /* MBEDTLS_GCM_C */ + } ctx; + psa_algorithm_t core_alg; + uint8_t full_tag_length; + uint8_t tag_length; +} aead_operation_t; + +static void psa_aead_abort( aead_operation_t *operation ) +{ + switch( operation->core_alg ) + { +#if defined(MBEDTLS_CCM_C) + case PSA_ALG_CCM: + mbedtls_ccm_free( &operation->ctx.ccm ); + break; +#endif /* MBEDTLS_CCM_C */ +#if defined(MBEDTLS_CCM_C) + case PSA_ALG_GCM: + mbedtls_gcm_free( &operation->ctx.gcm ); + break; +#endif /* MBEDTLS_GCM_C */ + } +} + +static psa_status_t psa_aead_setup( aead_operation_t *operation, + psa_key_slot_t key, + psa_key_usage_t usage, + psa_algorithm_t alg ) +{ + psa_status_t status; + size_t key_bits; + mbedtls_cipher_id_t cipher_id; + + status = psa_get_key_from_slot( key, &operation->slot, usage, alg ); + if( status != PSA_SUCCESS ) + return( status ); + + key_bits = psa_get_key_bits( operation->slot ); + + operation->cipher_info = + mbedtls_cipher_info_from_psa( alg, operation->slot->type, key_bits, + &cipher_id ); + if( operation->cipher_info == NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + + switch( PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 ) ) + { +#if defined(MBEDTLS_CCM_C) + case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ): + operation->core_alg = PSA_ALG_CCM; + operation->full_tag_length = 16; + if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->type ) != 16 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + mbedtls_ccm_init( &operation->ctx.ccm ); + status = mbedtls_to_psa_error( + mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id, + operation->slot->data.raw.data, + (unsigned int) key_bits ) ); + if( status != 0 ) + goto cleanup; + break; +#endif /* MBEDTLS_CCM_C */ + +#if defined(MBEDTLS_GCM_C) + case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ): + operation->core_alg = PSA_ALG_GCM; + operation->full_tag_length = 16; + if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->type ) != 16 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + mbedtls_gcm_init( &operation->ctx.gcm ); + status = mbedtls_to_psa_error( + mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id, + operation->slot->data.raw.data, + (unsigned int) key_bits ) ); + break; +#endif /* MBEDTLS_GCM_C */ + + default: + return( PSA_ERROR_NOT_SUPPORTED ); + } + + if( PSA_AEAD_TAG_LENGTH( alg ) > operation->full_tag_length ) + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto cleanup; + } + operation->tag_length = PSA_AEAD_TAG_LENGTH( alg ); + /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16. + * GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16. + * In both cases, mbedtls_xxx will validate the tag length below. */ + + return( PSA_SUCCESS ); + +cleanup: + psa_aead_abort( operation ); + return( status ); +} + +psa_status_t psa_aead_encrypt( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *plaintext, + size_t plaintext_length, + uint8_t *ciphertext, + size_t ciphertext_size, + size_t *ciphertext_length ) +{ + psa_status_t status; + aead_operation_t operation; + uint8_t *tag; + + *ciphertext_length = 0; + + status = psa_aead_setup( &operation, key, PSA_KEY_USAGE_ENCRYPT, alg ); + if( status != PSA_SUCCESS ) + return( status ); + + /* For all currently supported modes, the tag is at the end of the + * ciphertext. */ + if( ciphertext_size < ( plaintext_length + operation.tag_length ) ) + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto exit; + } + tag = ciphertext + plaintext_length; + + if( operation.core_alg == PSA_ALG_GCM ) + { + status = mbedtls_to_psa_error( + mbedtls_gcm_crypt_and_tag( &operation.ctx.gcm, + MBEDTLS_GCM_ENCRYPT, + plaintext_length, + nonce, nonce_length, + additional_data, additional_data_length, + plaintext, ciphertext, + operation.tag_length, tag ) ); + } + else if( operation.core_alg == PSA_ALG_CCM ) + { + status = mbedtls_to_psa_error( + mbedtls_ccm_encrypt_and_tag( &operation.ctx.ccm, + plaintext_length, + nonce, nonce_length, + additional_data, + additional_data_length, + plaintext, ciphertext, + tag, operation.tag_length ) ); + } + else + { + return( PSA_ERROR_NOT_SUPPORTED ); + } + + if( status != PSA_SUCCESS && ciphertext_size != 0 ) + memset( ciphertext, 0, ciphertext_size ); + +exit: + psa_aead_abort( &operation ); + if( status == PSA_SUCCESS ) + *ciphertext_length = plaintext_length + operation.tag_length; + return( status ); +} + +/* Locate the tag in a ciphertext buffer containing the encrypted data + * followed by the tag. Return the length of the part preceding the tag in + * *plaintext_length. This is the size of the plaintext in modes where + * the encrypted data has the same size as the plaintext, such as + * CCM and GCM. */ +static psa_status_t psa_aead_unpadded_locate_tag( size_t tag_length, + const uint8_t *ciphertext, + size_t ciphertext_length, + size_t plaintext_size, + const uint8_t **p_tag ) +{ + size_t payload_length; + if( tag_length > ciphertext_length ) + return( PSA_ERROR_INVALID_ARGUMENT ); + payload_length = ciphertext_length - tag_length; + if( payload_length > plaintext_size ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + *p_tag = ciphertext + payload_length; + return( PSA_SUCCESS ); +} + +psa_status_t psa_aead_decrypt( psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *nonce, + size_t nonce_length, + const uint8_t *additional_data, + size_t additional_data_length, + const uint8_t *ciphertext, + size_t ciphertext_length, + uint8_t *plaintext, + size_t plaintext_size, + size_t *plaintext_length ) +{ + psa_status_t status; + aead_operation_t operation; + const uint8_t *tag = NULL; + + *plaintext_length = 0; + + status = psa_aead_setup( &operation, key, PSA_KEY_USAGE_DECRYPT, alg ); + if( status != PSA_SUCCESS ) + return( status ); + + if( operation.core_alg == PSA_ALG_GCM ) + { + status = psa_aead_unpadded_locate_tag( operation.tag_length, + ciphertext, ciphertext_length, + plaintext_size, &tag ); + if( status != PSA_SUCCESS ) + goto exit; + + status = mbedtls_to_psa_error( + mbedtls_gcm_auth_decrypt( &operation.ctx.gcm, + ciphertext_length - operation.tag_length, + nonce, nonce_length, + additional_data, + additional_data_length, + tag, operation.tag_length, + ciphertext, plaintext ) ); + } + else if( operation.core_alg == PSA_ALG_CCM ) + { + status = psa_aead_unpadded_locate_tag( operation.tag_length, + ciphertext, ciphertext_length, + plaintext_size, &tag ); + if( status != PSA_SUCCESS ) + goto exit; + + status = mbedtls_to_psa_error( + mbedtls_ccm_auth_decrypt( &operation.ctx.ccm, + ciphertext_length - operation.tag_length, + nonce, nonce_length, + additional_data, + additional_data_length, + ciphertext, plaintext, + tag, operation.tag_length ) ); + } + else + { + return( PSA_ERROR_NOT_SUPPORTED ); + } + + if( status != PSA_SUCCESS && plaintext_size != 0 ) + memset( plaintext, 0, plaintext_size ); + +exit: + psa_aead_abort( &operation ); + if( status == PSA_SUCCESS ) + *plaintext_length = ciphertext_length - operation.tag_length; + return( status ); +} + + + +/****************************************************************/ +/* Generators */ +/****************************************************************/ + +psa_status_t psa_generator_abort( psa_crypto_generator_t *generator ) +{ + psa_status_t status = PSA_SUCCESS; + if( generator->alg == 0 ) + { + /* The object has (apparently) been initialized but it is not + * in use. It's ok to call abort on such an object, and there's + * nothing to do. */ + } + else + if( generator->alg == PSA_ALG_SELECT_RAW ) + { + if( generator->ctx.buffer.data != NULL ) + { + mbedtls_zeroize( generator->ctx.buffer.data, + generator->ctx.buffer.size ); + mbedtls_free( generator->ctx.buffer.data ); + } + } + else +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HKDF( generator->alg ) ) + { + mbedtls_free( generator->ctx.hkdf.info ); + status = psa_hmac_abort_internal( &generator->ctx.hkdf.hmac ); + } + else if( PSA_ALG_IS_TLS12_PRF( generator->alg ) || + /* TLS-1.2 PSK-to-MS KDF uses the same generator as TLS-1.2 PRF */ + PSA_ALG_IS_TLS12_PSK_TO_MS( generator->alg ) ) + { + if( generator->ctx.tls12_prf.key != NULL ) + { + mbedtls_zeroize( generator->ctx.tls12_prf.key, + generator->ctx.tls12_prf.key_len ); + mbedtls_free( generator->ctx.tls12_prf.key ); + } + + if( generator->ctx.tls12_prf.Ai_with_seed != NULL ) + { + mbedtls_zeroize( generator->ctx.tls12_prf.Ai_with_seed, + generator->ctx.tls12_prf.Ai_with_seed_len ); + mbedtls_free( generator->ctx.tls12_prf.Ai_with_seed ); + } + } + else +#endif /* MBEDTLS_MD_C */ + { + status = PSA_ERROR_BAD_STATE; + } + memset( generator, 0, sizeof( *generator ) ); + return( status ); +} + + +psa_status_t psa_get_generator_capacity(const psa_crypto_generator_t *generator, + size_t *capacity) +{ + *capacity = generator->capacity; + return( PSA_SUCCESS ); +} + +#if defined(MBEDTLS_MD_C) +/* Read some bytes from an HKDF-based generator. This performs a chunk + * of the expand phase of the HKDF algorithm. */ +static psa_status_t psa_generator_hkdf_read( psa_hkdf_generator_t *hkdf, + psa_algorithm_t hash_alg, + uint8_t *output, + size_t output_length ) +{ + uint8_t hash_length = PSA_HASH_SIZE( hash_alg ); + psa_status_t status; + + while( output_length != 0 ) + { + /* Copy what remains of the current block */ + uint8_t n = hash_length - hkdf->offset_in_block; + if( n > output_length ) + n = (uint8_t) output_length; + memcpy( output, hkdf->output_block + hkdf->offset_in_block, n ); + output += n; + output_length -= n; + hkdf->offset_in_block += n; + if( output_length == 0 ) + break; + /* We can't be wanting more output after block 0xff, otherwise + * the capacity check in psa_generator_read() would have + * prevented this call. It could happen only if the generator + * object was corrupted or if this function is called directly + * inside the library. */ + if( hkdf->block_number == 0xff ) + return( PSA_ERROR_BAD_STATE ); + + /* We need a new block */ + ++hkdf->block_number; + hkdf->offset_in_block = 0; + status = psa_hmac_setup_internal( &hkdf->hmac, + hkdf->prk, hash_length, + hash_alg ); + if( status != PSA_SUCCESS ) + return( status ); + if( hkdf->block_number != 1 ) + { + status = psa_hash_update( &hkdf->hmac.hash_ctx, + hkdf->output_block, + hash_length ); + if( status != PSA_SUCCESS ) + return( status ); + } + status = psa_hash_update( &hkdf->hmac.hash_ctx, + hkdf->info, + hkdf->info_length ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_hash_update( &hkdf->hmac.hash_ctx, + &hkdf->block_number, 1 ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_hmac_finish_internal( &hkdf->hmac, + hkdf->output_block, + sizeof( hkdf->output_block ) ); + if( status != PSA_SUCCESS ) + return( status ); + } + + return( PSA_SUCCESS ); +} + +static psa_status_t psa_generator_tls12_prf_generate_next_block( + psa_tls12_prf_generator_t *tls12_prf, + psa_algorithm_t alg ) +{ + psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg ); + uint8_t hash_length = PSA_HASH_SIZE( hash_alg ); + psa_hmac_internal_data hmac; + psa_status_t status, cleanup_status; + + unsigned char *Ai; + size_t Ai_len; + + /* We can't be wanting more output after block 0xff, otherwise + * the capacity check in psa_generator_read() would have + * prevented this call. It could happen only if the generator + * object was corrupted or if this function is called directly + * inside the library. */ + if( tls12_prf->block_number == 0xff ) + return( PSA_ERROR_BAD_STATE ); + + /* We need a new block */ + ++tls12_prf->block_number; + tls12_prf->offset_in_block = 0; + + /* Recall the definition of the TLS-1.2-PRF from RFC 5246: + * + * PRF(secret, label, seed) = P_(secret, label + seed) + * + * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + + * HMAC_hash(secret, A(2) + seed) + + * HMAC_hash(secret, A(3) + seed) + ... + * + * A(0) = seed + * A(i) = HMAC_hash( secret, A(i-1) ) + * + * The `psa_tls12_prf_generator` structures saves the block + * `HMAC_hash(secret, A(i) + seed)` from which the output + * is currently extracted as `output_block`, while + * `A(i) + seed` is stored in `Ai_with_seed`. + * + * Generating a new block means recalculating `Ai_with_seed` + * from the A(i)-part of it, and afterwards recalculating + * `output_block`. + * + * A(0) is computed at setup time. + * + */ + + psa_hmac_init_internal( &hmac ); + + /* We must distinguish the calculation of A(1) from those + * of A(2) and higher, because A(0)=seed has a different + * length than the other A(i). */ + if( tls12_prf->block_number == 1 ) + { + Ai = tls12_prf->Ai_with_seed + hash_length; + Ai_len = tls12_prf->Ai_with_seed_len - hash_length; + } + else + { + Ai = tls12_prf->Ai_with_seed; + Ai_len = hash_length; + } + + /* Compute A(i+1) = HMAC_hash(secret, A(i)) */ + status = psa_hmac_setup_internal( &hmac, + tls12_prf->key, + tls12_prf->key_len, + hash_alg ); + if( status != PSA_SUCCESS ) + goto cleanup; + + status = psa_hash_update( &hmac.hash_ctx, + Ai, Ai_len ); + if( status != PSA_SUCCESS ) + goto cleanup; + + status = psa_hmac_finish_internal( &hmac, + tls12_prf->Ai_with_seed, + hash_length ); + if( status != PSA_SUCCESS ) + goto cleanup; + + /* Compute the next block `HMAC_hash(secret, A(i+1) + seed)`. */ + status = psa_hmac_setup_internal( &hmac, + tls12_prf->key, + tls12_prf->key_len, + hash_alg ); + if( status != PSA_SUCCESS ) + goto cleanup; + + status = psa_hash_update( &hmac.hash_ctx, + tls12_prf->Ai_with_seed, + tls12_prf->Ai_with_seed_len ); + if( status != PSA_SUCCESS ) + goto cleanup; + + status = psa_hmac_finish_internal( &hmac, + tls12_prf->output_block, + hash_length ); + if( status != PSA_SUCCESS ) + goto cleanup; + +cleanup: + + cleanup_status = psa_hmac_abort_internal( &hmac ); + if( status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS ) + status = cleanup_status; + + return( status ); +} + +/* Read some bytes from an TLS-1.2-PRF-based generator. + * See Section 5 of RFC 5246. */ +static psa_status_t psa_generator_tls12_prf_read( + psa_tls12_prf_generator_t *tls12_prf, + psa_algorithm_t alg, + uint8_t *output, + size_t output_length ) +{ + psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg ); + uint8_t hash_length = PSA_HASH_SIZE( hash_alg ); + psa_status_t status; + + while( output_length != 0 ) + { + /* Copy what remains of the current block */ + uint8_t n = hash_length - tls12_prf->offset_in_block; + + /* Check if we have fully processed the current block. */ + if( n == 0 ) + { + status = psa_generator_tls12_prf_generate_next_block( tls12_prf, + alg ); + if( status != PSA_SUCCESS ) + return( status ); + + continue; + } + + if( n > output_length ) + n = (uint8_t) output_length; + memcpy( output, tls12_prf->output_block + tls12_prf->offset_in_block, + n ); + output += n; + output_length -= n; + tls12_prf->offset_in_block += n; + } + + return( PSA_SUCCESS ); +} +#endif /* MBEDTLS_MD_C */ + +psa_status_t psa_generator_read( psa_crypto_generator_t *generator, + uint8_t *output, + size_t output_length ) +{ + psa_status_t status; + + if( output_length > generator->capacity ) + { + generator->capacity = 0; + /* Go through the error path to wipe all confidential data now + * that the generator object is useless. */ + status = PSA_ERROR_INSUFFICIENT_CAPACITY; + goto exit; + } + if( output_length == 0 && + generator->capacity == 0 && generator->alg == 0 ) + { + /* Edge case: this is a blank or finished generator, and 0 + * bytes were requested. The right error in this case could + * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return + * INSUFFICIENT_CAPACITY, which is right for a finished + * generator, for consistency with the case when + * output_length > 0. */ + return( PSA_ERROR_INSUFFICIENT_CAPACITY ); + } + generator->capacity -= output_length; + + if( generator->alg == PSA_ALG_SELECT_RAW ) + { + /* Initially, the capacity of a selection generator is always + * the size of the buffer, i.e. `generator->ctx.buffer.size`, + * abbreviated in this comment as `size`. When the remaining + * capacity is `c`, the next bytes to serve start `c` bytes + * from the end of the buffer, i.e. `size - c` from the + * beginning of the buffer. Since `generator->capacity` was just + * decremented above, we need to serve the bytes from + * `size - generator->capacity - output_length` to + * `size - generator->capacity`. */ + size_t offset = + generator->ctx.buffer.size - generator->capacity - output_length; + memcpy( output, generator->ctx.buffer.data + offset, output_length ); + status = PSA_SUCCESS; + } + else +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HKDF( generator->alg ) ) + { + psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( generator->alg ); + status = psa_generator_hkdf_read( &generator->ctx.hkdf, hash_alg, + output, output_length ); + } + else if( PSA_ALG_IS_TLS12_PRF( generator->alg ) || + PSA_ALG_IS_TLS12_PSK_TO_MS( generator->alg ) ) + { + status = psa_generator_tls12_prf_read( &generator->ctx.tls12_prf, + generator->alg, output, + output_length ); + } + else +#endif /* MBEDTLS_MD_C */ + { + return( PSA_ERROR_BAD_STATE ); + } + +exit: + if( status != PSA_SUCCESS ) + { + psa_generator_abort( generator ); + memset( output, '!', output_length ); + } + return( status ); +} + +#if defined(MBEDTLS_DES_C) +static void psa_des_set_key_parity( uint8_t *data, size_t data_size ) +{ + if( data_size >= 8 ) + mbedtls_des_key_set_parity( data ); + if( data_size >= 16 ) + mbedtls_des_key_set_parity( data + 8 ); + if( data_size >= 24 ) + mbedtls_des_key_set_parity( data + 16 ); +} +#endif /* MBEDTLS_DES_C */ + +psa_status_t psa_generator_import_key( psa_key_slot_t key, + psa_key_type_t type, + size_t bits, + psa_crypto_generator_t *generator ) +{ + uint8_t *data = NULL; + size_t bytes = PSA_BITS_TO_BYTES( bits ); + psa_status_t status; + + if( ! key_type_is_raw_bytes( type ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + if( bits % 8 != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + data = mbedtls_calloc( 1, bytes ); + if( data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + status = psa_generator_read( generator, data, bytes ); + if( status != PSA_SUCCESS ) + goto exit; +#if defined(MBEDTLS_DES_C) + if( type == PSA_KEY_TYPE_DES ) + psa_des_set_key_parity( data, bytes ); +#endif /* MBEDTLS_DES_C */ + status = psa_import_key( key, type, data, bytes ); + +exit: + mbedtls_free( data ); + return( status ); +} + + + +/****************************************************************/ +/* Key derivation */ +/****************************************************************/ + +#if defined(MBEDTLS_MD_C) +/* Set up an HKDF-based generator. This is exactly the extract phase + * of the HKDF algorithm. + * + * Note that if this function fails, you must call psa_generator_abort() + * to potentially free embedded data structures and wipe confidential data. + */ +static psa_status_t psa_generator_hkdf_setup( psa_hkdf_generator_t *hkdf, + const uint8_t *secret, + size_t secret_length, + psa_algorithm_t hash_alg, + const uint8_t *salt, + size_t salt_length, + const uint8_t *label, + size_t label_length ) +{ + psa_status_t status; + status = psa_hmac_setup_internal( &hkdf->hmac, + salt, salt_length, + PSA_ALG_HMAC_GET_HASH( hash_alg ) ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_hash_update( &hkdf->hmac.hash_ctx, secret, secret_length ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_hmac_finish_internal( &hkdf->hmac, + hkdf->prk, + sizeof( hkdf->prk ) ); + if( status != PSA_SUCCESS ) + return( status ); + hkdf->offset_in_block = PSA_HASH_SIZE( hash_alg ); + hkdf->block_number = 0; + hkdf->info_length = label_length; + if( label_length != 0 ) + { + hkdf->info = mbedtls_calloc( 1, label_length ); + if( hkdf->info == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + memcpy( hkdf->info, label, label_length ); + } + return( PSA_SUCCESS ); +} +#endif /* MBEDTLS_MD_C */ + +#if defined(MBEDTLS_MD_C) +/* Set up a TLS-1.2-prf-based generator (see RFC 5246, Section 5). + * + * Note that if this function fails, you must call psa_generator_abort() + * to potentially free embedded data structures and wipe confidential data. + */ +static psa_status_t psa_generator_tls12_prf_setup( + psa_tls12_prf_generator_t *tls12_prf, + const unsigned char *key, + size_t key_len, + psa_algorithm_t hash_alg, + const uint8_t *salt, + size_t salt_length, + const uint8_t *label, + size_t label_length ) +{ + uint8_t hash_length = PSA_HASH_SIZE( hash_alg ); + size_t Ai_with_seed_len = hash_length + salt_length + label_length; + int overflow; + + tls12_prf->key = mbedtls_calloc( 1, key_len ); + if( tls12_prf->key == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + tls12_prf->key_len = key_len; + memcpy( tls12_prf->key, key, key_len ); + + overflow = ( salt_length + label_length < salt_length ) || + ( salt_length + label_length + hash_length < hash_length ); + if( overflow ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + tls12_prf->Ai_with_seed = mbedtls_calloc( 1, Ai_with_seed_len ); + if( tls12_prf->Ai_with_seed == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + tls12_prf->Ai_with_seed_len = Ai_with_seed_len; + + /* Write `label + seed' at the end of the `A(i) + seed` buffer, + * leaving the initial `hash_length` bytes unspecified for now. */ + if( label_length != 0 ) + { + memcpy( tls12_prf->Ai_with_seed + hash_length, + label, label_length ); + } + + if( salt_length != 0 ) + { + memcpy( tls12_prf->Ai_with_seed + hash_length + label_length, + salt, salt_length ); + } + + /* The first block gets generated when + * psa_generator_read() is called. */ + tls12_prf->block_number = 0; + tls12_prf->offset_in_block = hash_length; + + return( PSA_SUCCESS ); +} + +/* Set up a TLS-1.2-PSK-to-MS-based generator. */ +static psa_status_t psa_generator_tls12_psk_to_ms_setup( + psa_tls12_prf_generator_t *tls12_prf, + const unsigned char *psk, + size_t psk_len, + psa_algorithm_t hash_alg, + const uint8_t *salt, + size_t salt_length, + const uint8_t *label, + size_t label_length ) +{ + psa_status_t status; + unsigned char pms[ 4 + 2 * PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN ]; + + if( psk_len > PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + /* Quoting RFC 4279, Section 2: + * + * The premaster secret is formed as follows: if the PSK is N octets + * long, concatenate a uint16 with the value N, N zero octets, a second + * uint16 with the value N, and the PSK itself. + */ + + pms[0] = ( psk_len >> 8 ) & 0xff; + pms[1] = ( psk_len >> 0 ) & 0xff; + memset( pms + 2, 0, psk_len ); + pms[2 + psk_len + 0] = pms[0]; + pms[2 + psk_len + 1] = pms[1]; + memcpy( pms + 4 + psk_len, psk, psk_len ); + + status = psa_generator_tls12_prf_setup( tls12_prf, + pms, 4 + 2 * psk_len, + hash_alg, + salt, salt_length, + label, label_length ); + + mbedtls_zeroize( pms, sizeof( pms ) ); + return( status ); +} +#endif /* MBEDTLS_MD_C */ + +/* Note that if this function fails, you must call psa_generator_abort() + * to potentially free embedded data structures and wipe confidential data. + */ +static psa_status_t psa_key_derivation_internal( + psa_crypto_generator_t *generator, + const uint8_t *secret, size_t secret_length, + psa_algorithm_t alg, + const uint8_t *salt, size_t salt_length, + const uint8_t *label, size_t label_length, + size_t capacity ) +{ + psa_status_t status; + size_t max_capacity; + + /* Set generator->alg even on failure so that abort knows what to do. */ + generator->alg = alg; + + if( alg == PSA_ALG_SELECT_RAW ) + { + (void) salt; + if( salt_length != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + (void) label; + if( label_length != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + generator->ctx.buffer.data = mbedtls_calloc( 1, secret_length ); + if( generator->ctx.buffer.data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + memcpy( generator->ctx.buffer.data, secret, secret_length ); + generator->ctx.buffer.size = secret_length; + max_capacity = secret_length; + status = PSA_SUCCESS; + } + else +#if defined(MBEDTLS_MD_C) + if( PSA_ALG_IS_HKDF( alg ) ) + { + psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg ); + size_t hash_size = PSA_HASH_SIZE( hash_alg ); + if( hash_size == 0 ) + return( PSA_ERROR_NOT_SUPPORTED ); + max_capacity = 255 * hash_size; + status = psa_generator_hkdf_setup( &generator->ctx.hkdf, + secret, secret_length, + hash_alg, + salt, salt_length, + label, label_length ); + } + /* TLS-1.2 PRF and TLS-1.2 PSK-to-MS are very similar, so share code. */ + else if( PSA_ALG_IS_TLS12_PRF( alg ) || + PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) ) + { + psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg ); + size_t hash_size = PSA_HASH_SIZE( hash_alg ); + + /* TLS-1.2 PRF supports only SHA-256 and SHA-384. */ + if( hash_alg != PSA_ALG_SHA_256 && + hash_alg != PSA_ALG_SHA_384 ) + { + return( PSA_ERROR_NOT_SUPPORTED ); + } + + max_capacity = 255 * hash_size; + + if( PSA_ALG_IS_TLS12_PRF( alg ) ) + { + status = psa_generator_tls12_prf_setup( &generator->ctx.tls12_prf, + secret, secret_length, + hash_alg, salt, salt_length, + label, label_length ); + } + else + { + status = psa_generator_tls12_psk_to_ms_setup( + &generator->ctx.tls12_prf, + secret, secret_length, + hash_alg, salt, salt_length, + label, label_length ); + } + } + else +#endif + { + return( PSA_ERROR_NOT_SUPPORTED ); + } + + if( status != PSA_SUCCESS ) + return( status ); + + if( capacity <= max_capacity ) + generator->capacity = capacity; + else if( capacity == PSA_GENERATOR_UNBRIDLED_CAPACITY ) + generator->capacity = max_capacity; + else + return( PSA_ERROR_INVALID_ARGUMENT ); + + return( PSA_SUCCESS ); +} + +psa_status_t psa_key_derivation( psa_crypto_generator_t *generator, + psa_key_slot_t key, + psa_algorithm_t alg, + const uint8_t *salt, + size_t salt_length, + const uint8_t *label, + size_t label_length, + size_t capacity ) +{ + key_slot_t *slot; + psa_status_t status; + + if( generator->alg != 0 ) + return( PSA_ERROR_BAD_STATE ); + + /* Make sure that alg is a key derivation algorithm. This prevents + * key selection algorithms, which psa_key_derivation_internal + * accepts for the sake of key agreement. */ + if( ! PSA_ALG_IS_KEY_DERIVATION( alg ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_key_from_slot( key, &slot, PSA_KEY_USAGE_DERIVE, alg ); + if( status != PSA_SUCCESS ) + return( status ); + + if( slot->type != PSA_KEY_TYPE_DERIVE ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_key_derivation_internal( generator, + slot->data.raw.data, + slot->data.raw.bytes, + alg, + salt, salt_length, + label, label_length, + capacity ); + if( status != PSA_SUCCESS ) + psa_generator_abort( generator ); + return( status ); +} + + + +/****************************************************************/ +/* Key agreement */ +/****************************************************************/ + +#if defined(MBEDTLS_ECDH_C) +static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key, + size_t peer_key_length, + const mbedtls_ecp_keypair *our_key, + uint8_t *shared_secret, + size_t shared_secret_size, + size_t *shared_secret_length ) +{ + mbedtls_pk_context pk; + mbedtls_ecp_keypair *their_key = NULL; + mbedtls_ecdh_context ecdh; + int ret; + mbedtls_ecdh_init( &ecdh ); + mbedtls_pk_init( &pk ); + + ret = mbedtls_pk_parse_public_key( &pk, peer_key, peer_key_length ); + if( ret != 0 ) + goto exit; + switch( mbedtls_pk_get_type( &pk ) ) + { + case MBEDTLS_PK_ECKEY: + case MBEDTLS_PK_ECKEY_DH: + break; + default: + ret = MBEDTLS_ERR_ECP_INVALID_KEY; + goto exit; + } + their_key = mbedtls_pk_ec( pk ); + if( their_key->grp.id != our_key->grp.id ) + { + ret = MBEDTLS_ERR_ECP_INVALID_KEY; + goto exit; + } + + ret = mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ); + if( ret != 0 ) + goto exit; + ret = mbedtls_ecdh_get_params( &ecdh, our_key, MBEDTLS_ECDH_OURS ); + if( ret != 0 ) + goto exit; + + ret = mbedtls_ecdh_calc_secret( &ecdh, + shared_secret_length, + shared_secret, shared_secret_size, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg ); + +exit: + mbedtls_pk_free( &pk ); + mbedtls_ecdh_free( &ecdh ); + return( mbedtls_to_psa_error( ret ) ); +} +#endif /* MBEDTLS_ECDH_C */ + +#define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES + +/* Note that if this function fails, you must call psa_generator_abort() + * to potentially free embedded data structures and wipe confidential data. + */ +static psa_status_t psa_key_agreement_internal( psa_crypto_generator_t *generator, + key_slot_t *private_key, + const uint8_t *peer_key, + size_t peer_key_length, + psa_algorithm_t alg ) +{ + psa_status_t status; + uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE]; + size_t shared_secret_length = 0; + + /* Step 1: run the secret agreement algorithm to generate the shared + * secret. */ + switch( PSA_ALG_KEY_AGREEMENT_GET_BASE( alg ) ) + { +#if defined(MBEDTLS_ECDH_C) + case PSA_ALG_ECDH_BASE: + if( ! PSA_KEY_TYPE_IS_ECC_KEYPAIR( private_key->type ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + status = psa_key_agreement_ecdh( peer_key, peer_key_length, + private_key->data.ecp, + shared_secret, + sizeof( shared_secret ), + &shared_secret_length ); + break; +#endif /* MBEDTLS_ECDH_C */ + default: + (void) private_key; + (void) peer_key; + (void) peer_key_length; + return( PSA_ERROR_NOT_SUPPORTED ); + } + if( status != PSA_SUCCESS ) + goto exit; + + /* Step 2: set up the key derivation to generate key material from + * the shared secret. */ + status = psa_key_derivation_internal( generator, + shared_secret, shared_secret_length, + PSA_ALG_KEY_AGREEMENT_GET_KDF( alg ), + NULL, 0, NULL, 0, + PSA_GENERATOR_UNBRIDLED_CAPACITY ); +exit: + mbedtls_zeroize( shared_secret, shared_secret_length ); + return( status ); +} + +psa_status_t psa_key_agreement( psa_crypto_generator_t *generator, + psa_key_slot_t private_key, + const uint8_t *peer_key, + size_t peer_key_length, + psa_algorithm_t alg ) +{ + key_slot_t *slot; + psa_status_t status; + if( ! PSA_ALG_IS_KEY_AGREEMENT( alg ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + status = psa_get_key_from_slot( private_key, &slot, + PSA_KEY_USAGE_DERIVE, alg ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_key_agreement_internal( generator, + slot, + peer_key, peer_key_length, + alg ); + if( status != PSA_SUCCESS ) + psa_generator_abort( generator ); + return( status ); +} + + + +/****************************************************************/ +/* Random generation */ +/****************************************************************/ + +psa_status_t psa_generate_random( uint8_t *output, + size_t output_size ) +{ + int ret; + GUARD_MODULE_INITIALIZED; + + ret = mbedtls_ctr_drbg_random( &global_data.ctr_drbg, output, output_size ); + return( mbedtls_to_psa_error( ret ) ); +} + +#if ( defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_PSA_HAS_ITS_IO) ) + +/* Support function for error conversion between psa_its error codes to psa crypto */ +static psa_status_t its_to_psa_error( psa_its_status_t ret ) +{ + switch( ret ) + { + case PSA_ITS_SUCCESS: + return( PSA_SUCCESS ); + + case PSA_ITS_ERROR_KEY_NOT_FOUND: + return( PSA_ERROR_EMPTY_SLOT ); + + case PSA_ITS_ERROR_STORAGE_FAILURE: + return( PSA_ERROR_STORAGE_FAILURE ); + + case PSA_ITS_ERROR_INSUFFICIENT_SPACE: + return( PSA_ERROR_INSUFFICIENT_STORAGE ); + + case PSA_ITS_ERROR_INVALID_KEY: + case PSA_PS_ERROR_OFFSET_INVALID: + case PSA_ITS_ERROR_INCORRECT_SIZE: + case PSA_ITS_ERROR_BAD_POINTER: + return( PSA_ERROR_INVALID_ARGUMENT ); + + case PSA_ITS_ERROR_FLAGS_NOT_SUPPORTED: + return( PSA_ERROR_NOT_SUPPORTED ); + + case PSA_ITS_ERROR_WRITE_ONCE: + return( PSA_ERROR_OCCUPIED_SLOT ); + + default: + return( PSA_ERROR_UNKNOWN_ERROR ); + } +} + +psa_status_t mbedtls_psa_inject_entropy( const unsigned char *seed, + size_t seed_size ) +{ + psa_status_t status; + psa_its_status_t its_status; + struct psa_its_info_t p_info; + if( global_data.initialized ) + return( PSA_ERROR_NOT_PERMITTED ); + + if( ( ( seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM ) || + ( seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE ) ) || + ( seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + its_status = psa_its_get_info( PSA_CRYPTO_ITS_RANDOM_SEED_UID, &p_info ); + status = its_to_psa_error( its_status ); + + if( PSA_ITS_ERROR_KEY_NOT_FOUND == its_status ) /* No seed exists */ + { + its_status = psa_its_set( PSA_CRYPTO_ITS_RANDOM_SEED_UID, seed_size, seed, 0 ); + status = its_to_psa_error( its_status ); + } + else if( PSA_ITS_SUCCESS == its_status ) + { + /* You should not be here. Seed needs to be injected only once */ + status = PSA_ERROR_NOT_PERMITTED; + } + return( status ); +} +#endif + +psa_status_t psa_generate_key( psa_key_slot_t key, + psa_key_type_t type, + size_t bits, + const void *extra, + size_t extra_size ) +{ + key_slot_t *slot; + psa_status_t status; + + if( extra == NULL && extra_size != 0 ) + return( PSA_ERROR_INVALID_ARGUMENT ); + + status = psa_get_empty_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + return( status ); + + if( key_type_is_raw_bytes( type ) ) + { + status = prepare_raw_data_slot( type, bits, &slot->data.raw ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_generate_random( slot->data.raw.data, + slot->data.raw.bytes ); + if( status != PSA_SUCCESS ) + { + mbedtls_free( slot->data.raw.data ); + return( status ); + } +#if defined(MBEDTLS_DES_C) + if( type == PSA_KEY_TYPE_DES ) + psa_des_set_key_parity( slot->data.raw.data, + slot->data.raw.bytes ); +#endif /* MBEDTLS_DES_C */ + } + else + +#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME) + if ( type == PSA_KEY_TYPE_RSA_KEYPAIR ) + { + mbedtls_rsa_context *rsa; + int ret; + int exponent = 65537; + if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS ) + return( PSA_ERROR_NOT_SUPPORTED ); + /* Accept only byte-aligned keys, for the same reasons as + * in psa_import_rsa_key(). */ + if( bits % 8 != 0 ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( extra != NULL ) + { + const psa_generate_key_extra_rsa *p = extra; + if( extra_size != sizeof( *p ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); +#if INT_MAX < 0xffffffff + /* Check that the uint32_t value passed by the caller fits + * in the range supported by this implementation. */ + if( p->e > INT_MAX ) + return( PSA_ERROR_NOT_SUPPORTED ); +#endif + exponent = p->e; + } + rsa = mbedtls_calloc( 1, sizeof( *rsa ) ); + if( rsa == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + mbedtls_rsa_init( rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE ); + ret = mbedtls_rsa_gen_key( rsa, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg, + (unsigned int) bits, + exponent ); + if( ret != 0 ) + { + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + return( mbedtls_to_psa_error( ret ) ); + } + slot->data.rsa = rsa; + } + else +#endif /* MBEDTLS_RSA_C && MBEDTLS_GENPRIME */ + +#if defined(MBEDTLS_ECP_C) + if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEYPAIR( type ) ) + { + psa_ecc_curve_t curve = PSA_KEY_TYPE_GET_CURVE( type ); + mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve ); + const mbedtls_ecp_curve_info *curve_info = + mbedtls_ecp_curve_info_from_grp_id( grp_id ); + mbedtls_ecp_keypair *ecp; + int ret; + if( extra != NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( grp_id == MBEDTLS_ECP_DP_NONE || curve_info == NULL ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( curve_info->bit_size != bits ) + return( PSA_ERROR_INVALID_ARGUMENT ); + ecp = mbedtls_calloc( 1, sizeof( *ecp ) ); + if( ecp == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + mbedtls_ecp_keypair_init( ecp ); + ret = mbedtls_ecp_gen_key( grp_id, ecp, + mbedtls_ctr_drbg_random, + &global_data.ctr_drbg ); + if( ret != 0 ) + { + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + return( mbedtls_to_psa_error( ret ) ); + } + slot->data.ecp = ecp; + } + else +#endif /* MBEDTLS_ECP_C */ + + return( PSA_ERROR_NOT_SUPPORTED ); + + slot->type = type; + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + if( slot->lifetime == PSA_KEY_LIFETIME_PERSISTENT ) + { + return( psa_save_generated_persistent_key( key, slot, bits ) ); + } +#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ + + return( status ); +} + + +/****************************************************************/ +/* Module setup */ +/****************************************************************/ + +void mbedtls_psa_crypto_free( void ) +{ + psa_key_slot_t key; + key_slot_t *slot; + psa_status_t status; + + for( key = 1; key <= PSA_KEY_SLOT_COUNT; key++ ) + { + status = psa_get_key_slot( key, &slot ); + if( status != PSA_SUCCESS ) + continue; + psa_remove_key_data_from_memory( slot ); + /* Zeroize the slot to wipe metadata such as policies. */ + mbedtls_zeroize( slot, sizeof( *slot ) ); + } + mbedtls_ctr_drbg_free( &global_data.ctr_drbg ); + mbedtls_entropy_free( &global_data.entropy ); + mbedtls_zeroize( &global_data, sizeof( global_data ) ); +} + +psa_status_t psa_crypto_init( void ) +{ + int ret; + const unsigned char drbg_seed[] = "PSA"; + + if( global_data.initialized != 0 ) + return( PSA_SUCCESS ); + + mbedtls_zeroize( &global_data, sizeof( global_data ) ); + mbedtls_entropy_init( &global_data.entropy ); + mbedtls_ctr_drbg_init( &global_data.ctr_drbg ); + + ret = mbedtls_ctr_drbg_seed( &global_data.ctr_drbg, + mbedtls_entropy_func, + &global_data.entropy, + drbg_seed, sizeof( drbg_seed ) - 1 ); + if( ret != 0 ) + goto exit; + + global_data.initialized = 1; + +exit: + if( ret != 0 ) + mbedtls_psa_crypto_free( ); + return( mbedtls_to_psa_error( ret ) ); +} + +#endif /* MBEDTLS_PSA_CRYPTO_C */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.c b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.c new file mode 100644 index 00000000000..0a5805b62b4 --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.c @@ -0,0 +1,219 @@ +/* + * PSA persistent key storage + */ +/* Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) + +#include +#include + +#include "psa/crypto.h" +#include "psa_crypto_storage.h" +#include "psa_crypto_storage_backend.h" +#include "mbedtls/platform_util.h" + +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#define mbedtls_calloc calloc +#define mbedtls_free free +#endif + +/* + * 32-bit integer manipulation macros (little endian) + */ +#ifndef GET_UINT32_LE +#define GET_UINT32_LE(n,b,i) \ +{ \ + (n) = ( (uint32_t) (b)[(i) ] ) \ + | ( (uint32_t) (b)[(i) + 1] << 8 ) \ + | ( (uint32_t) (b)[(i) + 2] << 16 ) \ + | ( (uint32_t) (b)[(i) + 3] << 24 ); \ +} +#endif + +#ifndef PUT_UINT32_LE +#define PUT_UINT32_LE(n,b,i) \ +{ \ + (b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \ + (b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \ + (b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \ + (b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \ +} +#endif + +/** + * Persistent key storage magic header. + */ +#define PSA_KEY_STORAGE_MAGIC_HEADER "PSA\0KEY" +#define PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH ( sizeof( PSA_KEY_STORAGE_MAGIC_HEADER ) ) + +typedef struct { + uint8_t magic[PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH]; + uint8_t version[4]; + uint8_t type[sizeof( psa_key_type_t )]; + uint8_t policy[sizeof( psa_key_policy_t )]; + uint8_t data_len[4]; + uint8_t key_data[]; +} psa_persistent_key_storage_format; + +void psa_format_key_data_for_storage( const uint8_t *data, + const size_t data_length, + const psa_key_type_t type, + const psa_key_policy_t *policy, + uint8_t *storage_data ) +{ + psa_persistent_key_storage_format *storage_format = + (psa_persistent_key_storage_format *) storage_data; + + memcpy( storage_format->magic, PSA_KEY_STORAGE_MAGIC_HEADER, PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH ); + PUT_UINT32_LE(0, storage_format->version, 0); + PUT_UINT32_LE(type, storage_format->type, 0); + PUT_UINT32_LE(policy->usage, storage_format->policy, 0); + PUT_UINT32_LE(policy->alg, storage_format->policy, sizeof( uint32_t )); + PUT_UINT32_LE(data_length, storage_format->data_len, 0); + memcpy( storage_format->key_data, data, data_length ); +} + +static psa_status_t check_magic_header( const uint8_t *data ) +{ + if( memcmp( data, PSA_KEY_STORAGE_MAGIC_HEADER, + PSA_KEY_STORAGE_MAGIC_HEADER_LENGTH ) != 0 ) + return( PSA_ERROR_STORAGE_FAILURE ); + return( PSA_SUCCESS ); +} + +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_key_type_t *type, + psa_key_policy_t *policy ) +{ + psa_status_t status; + const psa_persistent_key_storage_format *storage_format = + (const psa_persistent_key_storage_format *)storage_data; + uint32_t version; + + if( storage_data_length < sizeof(*storage_format) ) + return( PSA_ERROR_STORAGE_FAILURE ); + + status = check_magic_header( storage_data ); + if( status != PSA_SUCCESS ) + return( status ); + + GET_UINT32_LE(version, storage_format->version, 0); + if( version != 0 ) + return( PSA_ERROR_STORAGE_FAILURE ); + + GET_UINT32_LE(*key_data_length, storage_format->data_len, 0); + if( *key_data_length > ( storage_data_length - sizeof(*storage_format) ) || + *key_data_length > PSA_CRYPTO_MAX_STORAGE_SIZE ) + return( PSA_ERROR_STORAGE_FAILURE ); + + *key_data = mbedtls_calloc( 1, *key_data_length ); + if( *key_data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + GET_UINT32_LE(*type, storage_format->type, 0); + GET_UINT32_LE(policy->usage, storage_format->policy, 0); + GET_UINT32_LE(policy->alg, storage_format->policy, sizeof( uint32_t )); + + memcpy( *key_data, storage_format->key_data, *key_data_length ); + + return( PSA_SUCCESS ); +} + +psa_status_t psa_save_persistent_key( const psa_key_slot_t key, + const psa_key_type_t type, + const psa_key_policy_t *policy, + const uint8_t *data, + const size_t data_length ) +{ + size_t storage_data_length; + uint8_t *storage_data; + psa_status_t status; + + if( data_length > PSA_CRYPTO_MAX_STORAGE_SIZE ) + return PSA_ERROR_INSUFFICIENT_STORAGE; + storage_data_length = data_length + sizeof( psa_persistent_key_storage_format ); + + storage_data = mbedtls_calloc( 1, storage_data_length ); + if( storage_data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + psa_format_key_data_for_storage( data, data_length, type, policy, + storage_data ); + + status = psa_crypto_storage_store( key, + storage_data, storage_data_length ); + + mbedtls_free( storage_data ); + + return( status ); +} + +void psa_free_persistent_key_data( uint8_t *key_data, size_t key_data_length ) +{ + if( key_data != NULL ) + { + mbedtls_platform_zeroize( key_data, key_data_length ); + } + mbedtls_free( key_data ); +} + +psa_status_t psa_load_persistent_key( psa_key_slot_t key, + psa_key_type_t *type, + psa_key_policy_t *policy, + uint8_t **data, + size_t *data_length ) +{ + psa_status_t status = PSA_SUCCESS; + uint8_t *loaded_data; + size_t storage_data_length = 0; + + status = psa_crypto_storage_get_data_length( key, &storage_data_length ); + if( status != PSA_SUCCESS ) + return( status ); + + loaded_data = mbedtls_calloc( 1, storage_data_length ); + + if( loaded_data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + + status = psa_crypto_storage_load( key, loaded_data, storage_data_length ); + if( status != PSA_SUCCESS ) + goto exit; + + status = psa_parse_key_data_from_storage( loaded_data, storage_data_length, + data, data_length, type, policy ); + +exit: + mbedtls_free( loaded_data ); + return( status ); +} + +#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.h b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.h new file mode 100644 index 00000000000..167b0db0586 --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage.h @@ -0,0 +1,177 @@ +/** + * \file psa_crypto_storage.h + * + * \brief PSA cryptography module: Mbed TLS key storage + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_STORAGE_H +#define PSA_CRYPTO_STORAGE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +#include "psa/crypto.h" +#include + +/* Limit the maximum key size to 30kB (just in case someone tries to + * inadvertently store an obscene amount of data) */ +#define PSA_CRYPTO_MAX_STORAGE_SIZE ( 30 * 1024 ) + +/** + * \brief Format key data and metadata and save to a location for given key + * slot. + * + * This function formats the key data and metadata and saves it to a + * persistent storage backend. The storage location corresponding to the + * key slot must be empty, otherwise this function will fail. This function + * should be called after psa_import_key_into_slot() to ensure the + * persistent key is not saved into a storage location corresponding to an + * already occupied non-persistent key, as well as validating the key data. + * + * + * \param key Slot number of the key to be stored. This must be a + * valid slot for a key of the chosen type. This should be + * an occupied key slot with an unoccupied corresponding + * storage location. + * \param type Key type (a \c PSA_KEY_TYPE_XXX value). + * \param[in] policy The key policy to save. + * \param[in] data Buffer containing the key data. + * \param data_length The number of bytes that make up the key data. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_INSUFFICIENT_STORAGE + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_save_persistent_key( const psa_key_slot_t key, + const psa_key_type_t type, + const psa_key_policy_t *policy, + const uint8_t *data, + const size_t data_length ); + +/** + * \brief Parses key data and metadata and load persistent key for given + * key slot number. + * + * This function reads from a storage backend, parses the key data and + * metadata and writes them to the appropriate output parameters. + * + * Note: This function allocates a buffer and returns a pointer to it through + * the data parameter. psa_free_persistent_key_data() must be called after + * this function to zeroize and free this buffer, regardless of whether this + * function succeeds or fails. + * + * \param key Slot number whose content is to be loaded. This + * must be an unoccupied key slot with an occupied + * corresponding storage location. The key slot + * lifetime must be set to persistent. + * \param[out] type On success, the key type (a \c PSA_KEY_TYPE_XXX + * value). + * \param[out] policy On success, the key's policy. + * \param[out] data Pointer to an allocated key data buffer on return. + * \param[out] data_length The number of bytes that make up the key data. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_INSUFFICIENT_MEMORY + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_load_persistent_key( psa_key_slot_t key, + psa_key_type_t *type, + psa_key_policy_t *policy, + uint8_t **data, + size_t *data_length ); + +/** + * \brief Remove persistent data for the given key slot number. + * + * \param key Slot number whose content is to be removed + * from persistent storage. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_destroy_persistent_key( const psa_key_slot_t key ); + +/** + * \brief Zeroizes and frees the given buffer. + * + * This function must be called at some point after psa_load_persistent_key() + * to zeroize and free the memory allocated to the buffer in that function. + * + * \param key_data Buffer for the key data. + * \param key_data_length Size of the key data buffer. + * + */ +void psa_free_persistent_key_data( uint8_t *key_data, size_t key_data_length ); + +/** + * \brief Formats key data and metadata for persistent storage + * + * \param[in] data Buffer for the key data. + * \param data_length Length of the key data buffer. + * \param type Key type (a \c PSA_KEY_TYPE_XXX value). + * \param policy The key policy. + * \param[out] storage_data Output buffer for the formatted data. + * + */ +void psa_format_key_data_for_storage( const uint8_t *data, + const size_t data_length, + const psa_key_type_t type, + const psa_key_policy_t *policy, + uint8_t *storage_data ); + +/** + * \brief Parses persistent storage data into key data and metadata + * + * \param[in] storage_data Buffer for the storage data. + * \param storage_data_length Length of the storage data buffer + * \param[out] key_data On output, pointer to a newly allocated buffer + * containing the key data. This must be freed + * using psa_free_persistent_key_data() + * \param[out] key_data_length Length of the key data buffer + * \param[out] type Key type (a \c PSA_KEY_TYPE_XXX value). + * \param[out] policy The key policy. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_INSUFFICIENT_STORAGE + * \retval PSA_ERROR_INSUFFICIENT_MEMORY + * \retval PSA_ERROR_STORAGE_FAILURE + */ +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_key_type_t *type, + psa_key_policy_t *policy ); + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_STORAGE_H */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_backend.h b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_backend.h new file mode 100644 index 00000000000..3ca9a1d74fc --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_backend.h @@ -0,0 +1,112 @@ +/** + * \file psa_crypto_storage_backend.h + * + * \brief PSA cryptography module: Mbed TLS key storage backend + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_STORAGE_BACKEND_H +#define PSA_CRYPTO_STORAGE_BACKEND_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +#include "psa/crypto.h" +#include "psa_crypto_storage.h" +#include + +/** + * \brief Load persistent data for the given key slot number. + * + * This function reads data from a storage backend and returns the data in a + * buffer. + * + * \param key Slot number whose content is to be loaded. This must + * be a key slot whose lifetime is set to persistent. + * \param[out] data Buffer where the data is to be written. + * \param data_size Size of the \c data buffer in bytes. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_crypto_storage_load( const psa_key_slot_t key, uint8_t *data, + size_t data_size ); + +/** + * \brief Store persistent data for the given key slot number. + * + * This function stores the given data buffer to a persistent storage. + * + * \param key Slot number whose content is to be stored. + * \param[in] data Buffer containing the data to be stored. + * \param data_length The number of bytes + * that make up the data. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_INSUFFICIENT_STORAGE + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_crypto_storage_store( const psa_key_slot_t key, + const uint8_t *data, + size_t data_length ); + +/** + * \brief Checks if persistent data is stored for the given key slot number + * + * This function checks if any key data or metadata exists for the key slot in + * the persistent storage. + * + * \param key Slot number whose content is to be checked. + * + * \retval 0 + * No persistent data present for slot number + * \retval 1 + * Persistent data present for slot number + */ +int psa_is_key_present_in_storage( const psa_key_slot_t key ); + +/** + * \brief Get data length for given key slot number. + * + * \param key Slot number whose stored data length is to be obtained. + * \param[out] data_length The number of bytes + * that make up the data. + * + * \retval PSA_SUCCESS + * \retval PSA_ERROR_STORAGE_FAILURE + */ +psa_status_t psa_crypto_storage_get_data_length( const psa_key_slot_t key, + size_t *data_length ); + + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_STORAGE_H */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_file.c b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_file.c new file mode 100644 index 00000000000..03c711af306 --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_file.c @@ -0,0 +1,218 @@ +/* + * PSA file storage backend for persistent keys + */ +/* Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_FILE_C) + +#include + +#include "psa/crypto.h" +#include "psa_crypto_storage_backend.h" +#include "mbedtls/platform_util.h" + +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#define mbedtls_snprintf snprintf +#endif + +/* This option sets where files are to be stored. If this is left unset, + * the files by default will be stored in the same location as the program, + * which may not be desired or possible. */ +#if !defined(CRYPTO_STORAGE_FILE_LOCATION) +#define CRYPTO_STORAGE_FILE_LOCATION "" +#endif + +enum { MAX_LOCATION_LEN = sizeof(CRYPTO_STORAGE_FILE_LOCATION) + 40 }; + +static void key_slot_to_location( const psa_key_slot_t key, + char *location, + size_t location_size ) +{ + mbedtls_snprintf( location, location_size, + CRYPTO_STORAGE_FILE_LOCATION "psa_key_slot_%d", key ); +} + +psa_status_t psa_crypto_storage_load( const psa_key_slot_t key, uint8_t *data, + size_t data_size ) +{ + psa_status_t status = PSA_SUCCESS; + FILE *file; + size_t num_read; + char slot_location[MAX_LOCATION_LEN]; + + key_slot_to_location( key, slot_location, MAX_LOCATION_LEN ); + file = fopen( slot_location, "rb" ); + if( file == NULL ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + num_read = fread( data, 1, data_size, file ); + if( num_read != data_size ) + status = PSA_ERROR_STORAGE_FAILURE; + +exit: + if( file != NULL ) + fclose( file ); + return( status ); +} + +int psa_is_key_present_in_storage( const psa_key_slot_t key ) +{ + char slot_location[MAX_LOCATION_LEN]; + FILE *file; + + key_slot_to_location( key, slot_location, MAX_LOCATION_LEN ); + + file = fopen( slot_location, "r" ); + if( file == NULL ) + { + /* File doesn't exist */ + return( 0 ); + } + + fclose( file ); + return( 1 ); +} + +psa_status_t psa_crypto_storage_store( const psa_key_slot_t key, + const uint8_t *data, + size_t data_length ) +{ + psa_status_t status = PSA_SUCCESS; + int ret; + size_t num_written; + char slot_location[MAX_LOCATION_LEN]; + FILE *file; + /* The storage location corresponding to "key slot 0" is used as a + * temporary location in order to make the apparition of the actual slot + * file atomic. 0 is not a valid key slot number, so this should not + * affect actual keys. */ + const char *temp_location = CRYPTO_STORAGE_FILE_LOCATION "psa_key_slot_0"; + + key_slot_to_location( key, slot_location, MAX_LOCATION_LEN ); + + if( psa_is_key_present_in_storage( key ) == 1 ) + return( PSA_ERROR_OCCUPIED_SLOT ); + + file = fopen( temp_location, "wb" ); + if( file == NULL ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + + num_written = fwrite( data, 1, data_length, file ); + if( num_written != data_length ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + + ret = fclose( file ); + file = NULL; + if( ret != 0 ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + + if( rename( temp_location, slot_location ) != 0 ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + +exit: + if( file != NULL ) + fclose( file ); + remove( temp_location ); + return( status ); +} + +psa_status_t psa_destroy_persistent_key( const psa_key_slot_t key ) +{ + FILE *file; + char slot_location[MAX_LOCATION_LEN]; + + key_slot_to_location( key, slot_location, MAX_LOCATION_LEN ); + + /* Only try remove the file if it exists */ + file = fopen( slot_location, "rb" ); + if( file != NULL ) + { + fclose( file ); + + if( remove( slot_location ) != 0 ) + return( PSA_ERROR_STORAGE_FAILURE ); + } + return( PSA_SUCCESS ); +} + +psa_status_t psa_crypto_storage_get_data_length( const psa_key_slot_t key, + size_t *data_length ) +{ + psa_status_t status = PSA_SUCCESS; + FILE *file; + long file_size; + char slot_location[MAX_LOCATION_LEN]; + + key_slot_to_location( key, slot_location, MAX_LOCATION_LEN ); + + file = fopen( slot_location, "rb" ); + if( file == NULL ) + return( PSA_ERROR_EMPTY_SLOT ); + + if( fseek( file, 0, SEEK_END ) != 0 ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + + file_size = ftell( file ); + + if( file_size < 0 ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + +#if LONG_MAX > SIZE_MAX + if( (unsigned long) file_size > SIZE_MAX ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } +#endif + *data_length = (size_t) file_size; + +exit: + fclose( file ); + return( status ); +} + +#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_FILE_C */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_its.c b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_its.c new file mode 100644 index 00000000000..29394b5d89c --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/psa_crypto_storage_its.c @@ -0,0 +1,184 @@ +/* + * PSA storage backend for persistent keys using psa_its APIs. + */ +/* Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C) + +#include "psa/crypto.h" +#include "psa_crypto_storage_backend.h" +#include "psa_prot_internal_storage.h" + +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#endif + +static psa_status_t its_to_psa_error( psa_its_status_t ret ) +{ + switch( ret ) + { + case PSA_ITS_SUCCESS: + return( PSA_SUCCESS ); + + case PSA_ITS_ERROR_KEY_NOT_FOUND: + return( PSA_ERROR_EMPTY_SLOT ); + + case PSA_ITS_ERROR_STORAGE_FAILURE: + return( PSA_ERROR_STORAGE_FAILURE ); + + case PSA_ITS_ERROR_INSUFFICIENT_SPACE: + return( PSA_ERROR_INSUFFICIENT_STORAGE ); + + case PSA_ITS_ERROR_INVALID_KEY: + case PSA_PS_ERROR_OFFSET_INVALID: + case PSA_ITS_ERROR_INCORRECT_SIZE: + case PSA_ITS_ERROR_BAD_POINTER: + return( PSA_ERROR_INVALID_ARGUMENT ); + + case PSA_ITS_ERROR_FLAGS_NOT_SUPPORTED: + return( PSA_ERROR_NOT_SUPPORTED ); + + case PSA_ITS_ERROR_WRITE_ONCE: + return( PSA_ERROR_OCCUPIED_SLOT ); + + default: + return( PSA_ERROR_UNKNOWN_ERROR ); + } +} + +static uint32_t psa_its_identifier_of_slot( psa_key_slot_t key ) +{ + return( key ); +} + +psa_status_t psa_crypto_storage_load( const psa_key_slot_t key, uint8_t *data, + size_t data_size ) +{ + psa_its_status_t ret; + psa_status_t status; + uint32_t data_identifier = psa_its_identifier_of_slot( key ); + struct psa_its_info_t data_identifier_info; + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + status = its_to_psa_error( ret ); + if( status != PSA_SUCCESS ) + return( status ); + + ret = psa_its_get( data_identifier, 0, data_size, data ); + status = its_to_psa_error( ret ); + + return( status ); +} + +int psa_is_key_present_in_storage( const psa_key_slot_t key ) +{ + psa_its_status_t ret; + uint32_t data_identifier = psa_its_identifier_of_slot( key ); + struct psa_its_info_t data_identifier_info; + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + + if( ret == PSA_ITS_ERROR_KEY_NOT_FOUND ) + return( 0 ); + return( 1 ); +} + +psa_status_t psa_crypto_storage_store( const psa_key_slot_t key, + const uint8_t *data, + size_t data_length ) +{ + psa_its_status_t ret; + psa_status_t status; + uint32_t data_identifier = psa_its_identifier_of_slot( key ); + struct psa_its_info_t data_identifier_info; + + if( psa_is_key_present_in_storage( key ) == 1 ) + return( PSA_ERROR_OCCUPIED_SLOT ); + + ret = psa_its_set( data_identifier, data_length, data, 0 ); + status = its_to_psa_error( ret ); + if( status != PSA_SUCCESS ) + { + return( PSA_ERROR_STORAGE_FAILURE ); + } + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + status = its_to_psa_error( ret ); + if( status != PSA_SUCCESS ) + { + goto exit; + } + + if( data_identifier_info.size != data_length ) + { + status = PSA_ERROR_STORAGE_FAILURE; + goto exit; + } + +exit: + if( status != PSA_SUCCESS ) + psa_its_remove( data_identifier ); + return( status ); +} + +psa_status_t psa_destroy_persistent_key( const psa_key_slot_t key ) +{ + psa_its_status_t ret; + uint32_t data_identifier = psa_its_identifier_of_slot( key ); + struct psa_its_info_t data_identifier_info; + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + if( ret == PSA_ITS_ERROR_KEY_NOT_FOUND ) + return( PSA_SUCCESS ); + + if( psa_its_remove( data_identifier ) != PSA_ITS_SUCCESS ) + return( PSA_ERROR_STORAGE_FAILURE ); + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + if( ret != PSA_ITS_ERROR_KEY_NOT_FOUND ) + return( PSA_ERROR_STORAGE_FAILURE ); + + return( PSA_SUCCESS ); +} + +psa_status_t psa_crypto_storage_get_data_length( const psa_key_slot_t key, + size_t *data_length ) +{ + psa_its_status_t ret; + psa_status_t status; + uint32_t data_identifier = psa_its_identifier_of_slot( key ); + struct psa_its_info_t data_identifier_info; + + ret = psa_its_get_info( data_identifier, &data_identifier_info ); + status = its_to_psa_error( ret ); + if( status != PSA_SUCCESS ) + return( status ); + + *data_length = (size_t) data_identifier_info.size; + + return( PSA_SUCCESS ); +} + +#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C */ diff --git a/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_SPE/crypto_struct_spe.h b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_SPE/crypto_struct_spe.h new file mode 100644 index 00000000000..44a1a60572f --- /dev/null +++ b/features/mbedtls/mbed-crypto/platform/TARGET_PSA/COMPONENT_SPE/crypto_struct_spe.h @@ -0,0 +1,211 @@ +/** + * \file psa/crypto_struct.h + * + * \brief PSA cryptography module: Mbed TLS structured type implementations + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file contains the definitions of some data structures with + * implementation-specific definitions. + * + * In implementations with isolation between the application and the + * cryptography module, it is expected that the front-end and the back-end + * would have different versions of this file. + */ +/* + * Copyright (C) 2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef PSA_CRYPTO_STRUCT_H +#define PSA_CRYPTO_STRUCT_H + +/* Include the Mbed TLS configuration file, the way Mbed TLS does it + * in each of its header files. */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "../mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/cipher.h" +#include "mbedtls/cmac.h" +#include "mbedtls/gcm.h" +#include "mbedtls/md.h" +#include "mbedtls/md2.h" +#include "mbedtls/md4.h" +#include "mbedtls/md5.h" +#include "mbedtls/ripemd160.h" +#include "mbedtls/sha1.h" +#include "mbedtls/sha256.h" +#include "mbedtls/sha512.h" + +struct psa_hash_operation_s +{ + psa_algorithm_t alg; + union + { + unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ +#if defined(MBEDTLS_MD2_C) + mbedtls_md2_context md2; +#endif +#if defined(MBEDTLS_MD4_C) + mbedtls_md4_context md4; +#endif +#if defined(MBEDTLS_MD5_C) + mbedtls_md5_context md5; +#endif +#if defined(MBEDTLS_RIPEMD160_C) + mbedtls_ripemd160_context ripemd160; +#endif +#if defined(MBEDTLS_SHA1_C) + mbedtls_sha1_context sha1; +#endif +#if defined(MBEDTLS_SHA256_C) + mbedtls_sha256_context sha256; +#endif +#if defined(MBEDTLS_SHA512_C) + mbedtls_sha512_context sha512; +#endif + } ctx; +}; + +#if defined(MBEDTLS_MD_C) +typedef struct +{ + /** The hash context. */ + struct psa_hash_operation_s hash_ctx; + /** The HMAC part of the context. */ + uint8_t opad[PSA_HMAC_MAX_HASH_BLOCK_SIZE]; +} psa_hmac_internal_data; +#endif /* MBEDTLS_MD_C */ + +struct psa_mac_operation_s +{ + psa_algorithm_t alg; + unsigned int key_set : 1; + unsigned int iv_required : 1; + unsigned int iv_set : 1; + unsigned int has_input : 1; + unsigned int is_sign : 1; + uint8_t mac_size; + union + { + unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ +#if defined(MBEDTLS_MD_C) + psa_hmac_internal_data hmac; +#endif +#if defined(MBEDTLS_CMAC_C) + mbedtls_cipher_context_t cmac; +#endif + } ctx; +}; + +struct psa_cipher_operation_s +{ + psa_algorithm_t alg; + unsigned int key_set : 1; + unsigned int iv_required : 1; + unsigned int iv_set : 1; + uint8_t iv_size; + uint8_t block_size; + union + { + mbedtls_cipher_context_t cipher; + } ctx; +}; + +#if defined(MBEDTLS_MD_C) +typedef struct +{ + uint8_t *info; + size_t info_length; + psa_hmac_internal_data hmac; + uint8_t prk[PSA_HASH_MAX_SIZE]; + uint8_t output_block[PSA_HASH_MAX_SIZE]; +#if PSA_HASH_MAX_SIZE > 0xff +#error "PSA_HASH_MAX_SIZE does not fit in uint8_t" +#endif + uint8_t offset_in_block; + uint8_t block_number; +} psa_hkdf_generator_t; +#endif /* MBEDTLS_MD_C */ + +#if defined(MBEDTLS_MD_C) +typedef struct psa_tls12_prf_generator_s +{ + /* The TLS 1.2 PRF uses the key for each HMAC iteration, + * hence we must store it for the lifetime of the generator. + * This is different from HKDF, where the key is only used + * in the extraction phase, but not during expansion. */ + unsigned char *key; + size_t key_len; + + /* `A(i) + seed` in the notation of RFC 5246, Sect. 5 */ + uint8_t *Ai_with_seed; + size_t Ai_with_seed_len; + + /* `HMAC_hash( prk, A(i) + seed )` in the notation of RFC 5246, Sect. 5. */ + uint8_t output_block[PSA_HASH_MAX_SIZE]; + +#if PSA_HASH_MAX_SIZE > 0xff +#error "PSA_HASH_MAX_SIZE does not fit in uint8_t" +#endif + + /* Indicates how many bytes in the current HMAC block have + * already been read by the user. */ + uint8_t offset_in_block; + + /* The 1-based number of the block. */ + uint8_t block_number; + +} psa_tls12_prf_generator_t; +#endif /* MBEDTLS_MD_C */ + +struct psa_crypto_generator_s +{ + psa_algorithm_t alg; + size_t capacity; + union + { + struct + { + uint8_t *data; + size_t size; + } buffer; +#if defined(MBEDTLS_MD_C) + psa_hkdf_generator_t hkdf; + psa_tls12_prf_generator_t tls12_prf; +#endif + } ctx; +}; + +#define PSA_CRYPTO_GENERATOR_INIT {0, 0, {{0, 0}}} +static inline struct psa_crypto_generator_s psa_crypto_generator_init( void ) +{ + const struct psa_crypto_generator_s v = PSA_CRYPTO_GENERATOR_INIT; + return( v ); +} + +struct psa_key_policy_s +{ + psa_key_usage_t usage; + psa_algorithm_t alg; +}; + +#endif /* PSA_CRYPTO_STRUCT_H */ diff --git a/features/mbedtls/src/Makefile b/features/mbedtls/src/Makefile index 430c5988123..f01b1a15026 100644 --- a/features/mbedtls/src/Makefile +++ b/features/mbedtls/src/Makefile @@ -63,6 +63,13 @@ DLEXT = dylib endif endif + +ifdef USE_CRYPTO_SUBMODULE +# Look in crypto for libmbedcrypto. +LOCAL_LDFLAGS += -L../crypto/library +LOCAL_CFLAGS += -I../crypto/include +CRYPTO := ../crypto/library/ +else OBJS_CRYPTO= aes.o aesni.o arc4.o \ aria.o asn1parse.o asn1write.o \ base64.o bignum.o blowfish.o \ @@ -85,6 +92,8 @@ OBJS_CRYPTO= aes.o aesni.o arc4.o \ sha1.o sha256.o sha512.o \ threading.o timing.o version.o \ version_features.o xtea.o +CRYPTO := +endif OBJS_X509= certs.o pkcs11.o x509.o \ x509_create.o x509_crl.o x509_crt.o \ @@ -148,7 +157,7 @@ ifneq ($(APPLE_BUILD),0) endif endif -libmbedx509.$(SOEXT_X509): $(OBJS_X509) libmbedcrypto.so +libmbedx509.$(SOEXT_X509): $(OBJS_X509) $(CRYPTO)libmbedcrypto.so echo " LD $@" $(CC) -shared -Wl,-soname,$@ -L. -lmbedcrypto $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509) @@ -165,6 +174,10 @@ libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll $(CC) -shared -Wl,-soname,$@ -Wl,--out-implib,$@.a -o $@ $(OBJS_X509) -lws2_32 -lwinmm -lgdi32 -L. -lmbedcrypto -static-libgcc $(LOCAL_LDFLAGS) $(LDFLAGS) # crypto +ifdef USE_CRYPTO_SUBMODULE +libmbedcrypto.%: + $(MAKE) CRYPTO_INCLUDES:="-I../../include -I../include" -C ../crypto/library $@ +else libmbedcrypto.a: $(OBJS_CRYPTO) echo " AR $@" $(AR) $(ARFLAGS) $@ $(OBJS_CRYPTO) @@ -190,6 +203,7 @@ libmbedcrypto.dylib: $(OBJS_CRYPTO) libmbedcrypto.dll: $(OBJS_CRYPTO) echo " LD $@" $(CC) -shared -Wl,-soname,$@ -Wl,--out-implib,$@.a -o $@ $(OBJS_CRYPTO) -lws2_32 -lwinmm -lgdi32 -static-libgcc $(LOCAL_LDFLAGS) $(LDFLAGS) +endif .c.o: echo " CC $<" diff --git a/features/mbedtls/src/aes.c b/features/mbedtls/src/aes.c index 5c939bba479..3de571e6933 100644 --- a/features/mbedtls/src/aes.c +++ b/features/mbedtls/src/aes.c @@ -36,6 +36,7 @@ #include #include "mbedtls/aes.h" +#include "mbedtls/platform.h" #include "mbedtls/platform_util.h" #if defined(MBEDTLS_PADLOCK_C) #include "mbedtls/padlock.h" @@ -1142,11 +1143,11 @@ int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, unsigned char prev_tweak[16]; unsigned char tmp[16]; - /* Sectors must be at least 16 bytes. */ + /* Data units must be at least 16 bytes long. */ if( length < 16 ) return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; - /* NIST SP 80-38E disallows data units larger than 2**20 blocks. */ + /* NIST SP 800-38E disallows data units larger than 2**20 blocks. */ if( length > ( 1 << 20 ) * 16 ) return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; @@ -1757,7 +1758,7 @@ int mbedtls_aes_self_test( int verbose ) * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ - if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 ) + if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192 ) { mbedtls_printf( "skipped\n" ); continue; @@ -1821,7 +1822,7 @@ int mbedtls_aes_self_test( int verbose ) * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ - if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 ) + if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192 ) { mbedtls_printf( "skipped\n" ); continue; @@ -1886,7 +1887,7 @@ int mbedtls_aes_self_test( int verbose ) * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ - if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 ) + if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192 ) { mbedtls_printf( "skipped\n" ); continue; @@ -1949,7 +1950,7 @@ int mbedtls_aes_self_test( int verbose ) * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ - if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 ) + if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192 ) { mbedtls_printf( "skipped\n" ); continue; diff --git a/features/mbedtls/src/asn1write.c b/features/mbedtls/src/asn1write.c index 72acdf30122..d617de5b076 100644 --- a/features/mbedtls/src/asn1write.c +++ b/features/mbedtls/src/asn1write.c @@ -257,34 +257,37 @@ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val ) return( (int) len ); } -int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start, - const char *text, size_t text_len ) +int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start, int tag, + const char *text, size_t text_len ) { int ret; size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, - (const unsigned char *) text, text_len ) ); + (const unsigned char *) text, text_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_PRINTABLE_STRING ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, tag ) ); return( (int) len ); } -int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start, - const char *text, size_t text_len ) +int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ) { - int ret; - size_t len = 0; - - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, - (const unsigned char *) text, text_len ) ); + return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_UTF8_STRING, text, text_len) ); +} - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_IA5_STRING ) ); +int mbedtls_asn1_write_printable_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ) +{ + return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_PRINTABLE_STRING, text, text_len) ); +} - return( (int) len ); +int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ) +{ + return( mbedtls_asn1_write_tagged_string(p, start, MBEDTLS_ASN1_IA5_STRING, text, text_len) ); } int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start, diff --git a/features/mbedtls/src/bignum.c b/features/mbedtls/src/bignum.c index 423e375fd19..ae5e7cfa0c6 100644 --- a/features/mbedtls/src/bignum.c +++ b/features/mbedtls/src/bignum.c @@ -2056,12 +2056,12 @@ static int mpi_check_small_factors( const mbedtls_mpi *X ) /* * Miller-Rabin pseudo-primality test (HAC 4.24) */ -static int mpi_miller_rabin( const mbedtls_mpi *X, +static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count; - size_t i, j, k, n, s; + size_t i, j, k, s; mbedtls_mpi W, R, T, A, RR; mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A ); @@ -2077,27 +2077,12 @@ static int mpi_miller_rabin( const mbedtls_mpi *X, MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) ); i = mbedtls_mpi_bitlen( X ); - /* - * HAC, table 4.4 - */ - n = ( ( i >= 1300 ) ? 2 : ( i >= 850 ) ? 3 : - ( i >= 650 ) ? 4 : ( i >= 350 ) ? 8 : - ( i >= 250 ) ? 12 : ( i >= 150 ) ? 18 : 27 ); - for( i = 0; i < n; i++ ) + for( i = 0; i < rounds; i++ ) { /* * pick a random A, 1 < A < |X| - 1 */ - MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) ); - - if( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 ) - { - j = mbedtls_mpi_bitlen( &A ) - mbedtls_mpi_bitlen( &W ); - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j + 1 ) ); - } - A.p[0] |= 3; - count = 0; do { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) ); @@ -2105,7 +2090,7 @@ static int mpi_miller_rabin( const mbedtls_mpi *X, j = mbedtls_mpi_bitlen( &A ); k = mbedtls_mpi_bitlen( &W ); if (j > k) { - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j - k ) ); + A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1; } if (count++ > 30) { @@ -2160,9 +2145,9 @@ static int mpi_miller_rabin( const mbedtls_mpi *X, /* * Pseudo-primality test: small factors, then Miller-Rabin */ -int mbedtls_mpi_is_prime( const mbedtls_mpi *X, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) +int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) { int ret; mbedtls_mpi XX; @@ -2186,17 +2171,34 @@ int mbedtls_mpi_is_prime( const mbedtls_mpi *X, return( ret ); } - return( mpi_miller_rabin( &XX, f_rng, p_rng ) ); + return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) ); } +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +/* + * Pseudo-primality test, error probability 2^-80 + */ +int mbedtls_mpi_is_prime( const mbedtls_mpi *X, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) +{ + /* + * In the past our key generation aimed for an error rate of at most + * 2^-80. Since this function is deprecated, aim for the same certainty + * here as well. + */ + return mbedtls_mpi_is_prime_ext( X, 40, f_rng, p_rng ); +} +#endif + /* * Prime number generation * - * If dh_flag is 0 and nbits is at least 1024, then the procedure - * follows the RSA probably-prime generation method of FIPS 186-4. - * NB. FIPS 186-4 only allows the specific bit lengths of 1024 and 1536. + * To generate an RSA key in a way recommended by FIPS 186-4, both primes must + * be either 1024 bits or 1536 bits long, and flags must contain + * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR. */ -int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, +int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { @@ -2209,6 +2211,7 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, #endif int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE; size_t k, n; + int rounds; mbedtls_mpi_uint r; mbedtls_mpi Y; @@ -2219,6 +2222,27 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, n = BITS_TO_LIMBS( nbits ); + if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR ) == 0 ) + { + /* + * 2^-80 error probability, number of rounds chosen per HAC, table 4.4 + */ + rounds = ( ( nbits >= 1300 ) ? 2 : ( nbits >= 850 ) ? 3 : + ( nbits >= 650 ) ? 4 : ( nbits >= 350 ) ? 8 : + ( nbits >= 250 ) ? 12 : ( nbits >= 150 ) ? 18 : 27 ); + } + else + { + /* + * 2^-100 error probability, number of rounds computed based on HAC, + * fact 4.48 + */ + rounds = ( ( nbits >= 1450 ) ? 4 : ( nbits >= 1150 ) ? 5 : + ( nbits >= 1000 ) ? 6 : ( nbits >= 850 ) ? 7 : + ( nbits >= 750 ) ? 8 : ( nbits >= 500 ) ? 13 : + ( nbits >= 250 ) ? 28 : ( nbits >= 150 ) ? 40 : 51 ); + } + while( 1 ) { MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) ); @@ -2229,9 +2253,9 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, if( k > nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, k - nbits ) ); X->p[0] |= 1; - if( dh_flag == 0 ) + if( ( flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH ) == 0 ) { - ret = mbedtls_mpi_is_prime( X, f_rng, p_rng ); + ret = mbedtls_mpi_is_prime_ext( X, rounds, f_rng, p_rng ); if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) goto cleanup; @@ -2264,8 +2288,10 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag, */ if( ( ret = mpi_check_small_factors( X ) ) == 0 && ( ret = mpi_check_small_factors( &Y ) ) == 0 && - ( ret = mpi_miller_rabin( X, f_rng, p_rng ) ) == 0 && - ( ret = mpi_miller_rabin( &Y, f_rng, p_rng ) ) == 0 ) + ( ret = mpi_miller_rabin( X, rounds, f_rng, p_rng ) ) + == 0 && + ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng ) ) + == 0 ) goto cleanup; if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) diff --git a/features/mbedtls/src/certs.c b/features/mbedtls/src/certs.c index f1379b8cb1e..ff0f11e923c 100644 --- a/features/mbedtls/src/certs.c +++ b/features/mbedtls/src/certs.c @@ -218,12 +218,13 @@ const size_t mbedtls_test_ca_key_rsa_len = sizeof( mbedtls_test_ca_key_rsa ); const char mbedtls_test_ca_pwd_rsa[] = "PolarSSLTest"; const size_t mbedtls_test_ca_pwd_rsa_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1; +/* tests/data_files/server2.crt */ const char mbedtls_test_srv_crt_rsa[] = "-----BEGIN CERTIFICATE-----\r\n" "MIIDNzCCAh+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" -"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" +"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" "MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA0MQswCQYDVQQGEwJOTDERMA8G\r\n" -"A1UEChMIUG9sYXJTU0wxEjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" +"A1UECgwIUG9sYXJTU0wxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcN\r\n" "AQEBBQADggEPADCCAQoCggEBAMFNo93nzR3RBNdJcriZrA545Do8Ss86ExbQWuTN\r\n" "owCIp+4ea5anUrSQ7y1yej4kmvy2NKwk9XfgJmSMnLAofaHa6ozmyRyWvP7BBFKz\r\n" "NtSj+uGxdtiQwWG0ZlI2oiZTqqt0Xgd9GYLbKtgfoNkNHC1JZvdbJXNG6AuKT2kM\r\n" @@ -231,16 +232,17 @@ const char mbedtls_test_srv_crt_rsa[] = "hYvai0Re4hjGYi/HZo36Xdh98yeJKQHFkA4/J/EwyEoO79bex8cna8cFPXrEAjya\r\n" "HT4P6DSYW8tzS1KW2BGiLICIaTla0w+w3lkvEcf36hIBMJcCAwEAAaNNMEswCQYD\r\n" "VR0TBAIwADAdBgNVHQ4EFgQUpQXoZLjc32APUBJNYKhkr02LQ5MwHwYDVR0jBBgw\r\n" -"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAJxnXClY\r\n" -"oHkbp70cqBrsGXLybA74czbO5RdLEgFs7rHVS9r+c293luS/KdliLScZqAzYVylw\r\n" -"UfRWvKMoWhHYKp3dEIS4xTXk6/5zXxhv9Rw8SGc8qn6vITHk1S1mPevtekgasY5Y\r\n" -"iWQuM3h4YVlRH3HHEMAD1TnAexfXHHDFQGe+Bd1iAbz1/sH9H8l4StwX6egvTK3M\r\n" -"wXRwkKkvjKaEDA9ATbZx0mI8LGsxSuCqe9r9dyjmttd47J1p1Rulz3CLzaRcVIuS\r\n" -"RRQfaD8neM9c1S/iJ/amTVqJxA1KOdOS5780WhPfSArA+g4qAmSjelc3p4wWpha8\r\n" -"zhuYwjVuX6JHG0c=\r\n" +"FoAUtFrkpbPe0lL2udWmlQ/rPrzH/f8wDQYJKoZIhvcNAQEFBQADggEBAAFzC0rF\r\n" +"y6De8WMcdgQrEw3AhBHFjzqnxZw1ene4IBSC7lTw8rBSy3jOWQdPUWn+0y/pCeeF\r\n" +"kti6sevFdl1hLemGtd4q+T9TKEKGg3ND4ARfB5AUZZ9uEHq8WBkiwus5clGS17Qd\r\n" +"dS/TOisB59tQruLx1E1bPLtBKyqk4koC5WAULJwfpswGSyWJTpYwIpxcWE3D2tBu\r\n" +"UB6MZfXZFzWmWEOyKbeoXjXe8GBCGgHLywvYDsGQ36HSGtEsAvR2QaTLSxWYcfk1\r\n" +"fbDn4jSWkb4yZy1r01UEigFQtONieGwRFaUqEcFJHJvEEGVgh9keaVlOj2vrwf5r\r\n" +"4mN4lW7gLdenN6g=\r\n" "-----END CERTIFICATE-----\r\n"; const size_t mbedtls_test_srv_crt_rsa_len = sizeof( mbedtls_test_srv_crt_rsa ); +/* tests/data_files/server2.key */ const char mbedtls_test_srv_key_rsa[] = "-----BEGIN RSA PRIVATE KEY-----\r\n" "MIIEpAIBAAKCAQEAwU2j3efNHdEE10lyuJmsDnjkOjxKzzoTFtBa5M2jAIin7h5r\r\n" @@ -271,11 +273,12 @@ const char mbedtls_test_srv_key_rsa[] = "-----END RSA PRIVATE KEY-----\r\n"; const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa ); +/* tests/data_files/cli-rsa-sha256.crt */ const char mbedtls_test_cli_crt_rsa[] = "-----BEGIN CERTIFICATE-----\r\n" -"MIIDhTCCAm2gAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" +"MIIDPzCCAiegAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" -"MTcwNTA1MTMwNzU5WhcNMjcwNTA2MTMwNzU5WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n" +"MTEwMjEyMTQ0NDA2WhcNMjEwMjEyMTQ0NDA2WjA8MQswCQYDVQQGEwJOTDERMA8G\r\n" "A1UECgwIUG9sYXJTU0wxGjAYBgNVBAMMEVBvbGFyU1NMIENsaWVudCAyMIIBIjAN\r\n" "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6f\r\n" "M60Nj4o8VmXl3ETZzGaFB9X4J7BKNdBjngpuG7fa8H6r7gwQk4ZJGDTzqCrSV/Uu\r\n" @@ -283,18 +286,18 @@ const char mbedtls_test_cli_crt_rsa[] = "MjDV0/YI0FZPRo7yX/k9Z5GIMC5Cst99++UMd//sMcB4j7/Cf8qtbCHWjdmLao5v\r\n" "4Jv4EFbMs44TFeY0BGbH7vk2DmqV9gmaBmf0ZXH4yqSxJeD+PIs1BGe64E92hfx/\r\n" "/DZrtenNLQNiTrM9AM+vdqBpVoNq0qjU51Bx5rU2BXcFbXvI5MT9TNUhXwIDAQAB\r\n" -"o4GSMIGPMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITBjBgNVHSMEXDBa\r\n" -"gBS0WuSls97SUva51aaVD+s+vMf9/6E/pD0wOzELMAkGA1UEBhMCTkwxETAPBgNV\r\n" -"BAoMCFBvbGFyU1NMMRkwFwYDVQQDDBBQb2xhclNTTCBUZXN0IENBggEAMAkGA1Ud\r\n" -"EwQCMAAwDQYJKoZIhvcNAQELBQADggEBAC7yO786NvcHpK8UovKIG9cB32oSQQom\r\n" -"LoR0eHDRzdqEkoq7yGZufHFiRAAzbMqJfogRtxlrWAeB4y/jGaMBV25IbFOIcH2W\r\n" -"iCEaMMbG+VQLKNvuC63kmw/Zewc9ThM6Pa1Hcy0axT0faf1B/U01j0FIcw/6mTfK\r\n" -"D8w48OIwc1yr0JtutCVjig5DC0yznGMt32RyseOLcUe+lfq005v2PAiCozr5X8rE\r\n" -"ofGZpiM2NqRPePgYy+Vc75Zk28xkRQq1ncprgQb3S4vTsZdScpM9hLf+eMlrgqlj\r\n" -"c5PLSkXBeLE5+fedkyfTaLxxQlgCpuoOhKBm04/R1pWNzUHyqagjO9Q=\r\n" +"o00wSzAJBgNVHRMEAjAAMB0GA1UdDgQWBBRxoQBzckAvVHZeM/xSj7zx3WtGITAf\r\n" +"BgNVHSMEGDAWgBS0WuSls97SUva51aaVD+s+vMf9/zANBgkqhkiG9w0BAQsFAAOC\r\n" +"AQEAlHabem2Tu69VUN7EipwnQn1dIHdgvT5i+iQHpSxY1crPnBbAeSdAXwsVEqLQ\r\n" +"gOOIAQD5VIITNuoGgo4i+4OpNh9u7ZkpRHla+/swsfrFWRRbBNP5Bcu74AGLstwU\r\n" +"zM8gIkBiyfM1Q1qDQISV9trlCG6O8vh8dp/rbI3rfzo99BOHXgFCrzXjCuW4vDsF\r\n" +"r+Dao26bX3sJ6UnEWg1H3o2x6PpUcvQ36h71/bz4TEbbUUEpe02V4QWuL+wrhHJL\r\n" +"U7o3SVE3Og7jPF8sat0a50YUWhwEFI256m02KAXLg89ueUyYKEr6rNwhcvXJpvU9\r\n" +"giIVvd0Sbjjnn7NC4VDbcXV8vw==\r\n" "-----END CERTIFICATE-----\r\n"; const size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa ); +/* tests/data_files/cli-rsa.key */ const char mbedtls_test_cli_key_rsa[] = "-----BEGIN RSA PRIVATE KEY-----\r\n" "MIIEpAIBAAKCAQEAyHTEzLn5tXnpRdkUYLB9u5Pyax6fM60Nj4o8VmXl3ETZzGaF\r\n" diff --git a/features/mbedtls/src/cipher.c b/features/mbedtls/src/cipher.c index 7ae6c4ac5d1..1cc0beb2887 100644 --- a/features/mbedtls/src/cipher.c +++ b/features/mbedtls/src/cipher.c @@ -58,6 +58,11 @@ #include "mbedtls/cmac.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#include "mbedtls/psa_util.h" +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else @@ -71,7 +76,8 @@ * a non-zero value. * This is currently only used by GCM and ChaCha20+Poly1305. */ -static int mbedtls_constant_time_memcmp( const void *v1, const void *v2, size_t len ) +static int mbedtls_constant_time_memcmp( const void *v1, const void *v2, + size_t len ) { const unsigned char *p1 = (const unsigned char*) v1; const unsigned char *p2 = (const unsigned char*) v2; @@ -108,7 +114,8 @@ const int *mbedtls_cipher_list( void ) return( mbedtls_cipher_supported ); } -const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ) +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( + const mbedtls_cipher_type_t cipher_type ) { const mbedtls_cipher_definition_t *def; @@ -119,7 +126,8 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher return( NULL ); } -const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ) +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( + const char *cipher_name ) { const mbedtls_cipher_definition_t *def; @@ -133,9 +141,10 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher return( NULL ); } -const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, - int key_bitlen, - const mbedtls_cipher_mode_t mode ) +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( + const mbedtls_cipher_id_t cipher_id, + int key_bitlen, + const mbedtls_cipher_mode_t mode ) { const mbedtls_cipher_definition_t *def; @@ -158,6 +167,29 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) if( ctx == NULL ) return; +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + if( ctx->cipher_ctx != NULL ) + { + mbedtls_cipher_context_psa * const cipher_psa = + (mbedtls_cipher_context_psa *) ctx->cipher_ctx; + + if( cipher_psa->slot_state == MBEDTLS_CIPHER_PSA_KEY_OWNED ) + { + /* xxx_free() doesn't allow to return failures. */ + (void) psa_destroy_key( cipher_psa->slot ); + } + + mbedtls_platform_zeroize( cipher_psa, sizeof( *cipher_psa ) ); + mbedtls_free( cipher_psa ); + } + + mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); + return; + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_CMAC_C) if( ctx->cmac_ctx ) { @@ -173,7 +205,8 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ) mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) ); } -int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info ) +int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, + const mbedtls_cipher_info_t *cipher_info ) { if( NULL == cipher_info || NULL == ctx ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); @@ -199,11 +232,118 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_in return( 0 ); } -int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key, - int key_bitlen, const mbedtls_operation_t operation ) +#if defined(MBEDTLS_USE_PSA_CRYPTO) +int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx, + const mbedtls_cipher_info_t *cipher_info, + size_t taglen ) { - if( NULL == ctx || NULL == ctx->cipher_info ) + psa_algorithm_t alg; + mbedtls_cipher_context_psa *cipher_psa; + + if( NULL == cipher_info || NULL == ctx ) + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + + /* Check that the underlying cipher mode and cipher type are + * supported by the underlying PSA Crypto implementation. */ + alg = mbedtls_psa_translate_cipher_mode( cipher_info->mode, taglen ); + if( alg == 0 ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + if( mbedtls_psa_translate_cipher_type( cipher_info->type ) == 0 ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + + memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) ); + + cipher_psa = mbedtls_calloc( 1, sizeof(mbedtls_cipher_context_psa ) ); + if( cipher_psa == NULL ) + return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED ); + cipher_psa->alg = alg; + ctx->cipher_ctx = cipher_psa; + ctx->cipher_info = cipher_info; + ctx->psa_enabled = 1; + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + +int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, + const unsigned char *key, + int key_bitlen, + const mbedtls_operation_t operation ) +{ + if( NULL == ctx || NULL == ctx->cipher_info || + NULL == ctx->cipher_ctx ) + { + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + } + + if( operation != MBEDTLS_DECRYPT && + operation != MBEDTLS_ENCRYPT ) + { return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + } + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + mbedtls_cipher_context_psa * const cipher_psa = + (mbedtls_cipher_context_psa *) ctx->cipher_ctx; + + size_t const key_bytelen = ( (size_t) key_bitlen + 7 ) / 8; + + psa_status_t status; + psa_key_type_t key_type; + psa_key_usage_t key_usage; + psa_key_policy_t key_policy; + + /* PSA Crypto API only accepts byte-aligned keys. */ + if( key_bitlen % 8 != 0 ) + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + + /* Don't allow keys to be set multiple times. */ + if( cipher_psa->slot_state != MBEDTLS_CIPHER_PSA_KEY_UNSET ) + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + + /* Find a fresh key slot to use. */ + status = mbedtls_psa_get_free_key_slot( &cipher_psa->slot ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + /* Indicate that we own the key slot and need to + * destroy it in mbedtls_cipher_free(). */ + cipher_psa->slot_state = MBEDTLS_CIPHER_PSA_KEY_OWNED; + + /* From that point on, the responsibility for destroying the + * key slot is on mbedtls_cipher_free(). This includes the case + * where the policy setup or key import below fail, as + * mbedtls_cipher_free() needs to be called in any case. */ + + /* Setup policy for the new key slot. */ + psa_key_policy_init( &key_policy ); + + /* Mbed TLS' cipher layer doesn't enforce the mode of operation + * (encrypt vs. decrypt): it is possible to setup a key for encryption + * and use it for AEAD decryption. Until tests relying on this + * are changed, allow any usage in PSA. */ + /* key_usage = mbedtls_psa_translate_cipher_operation( operation ); */ + key_usage = PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT; + psa_key_policy_set_usage( &key_policy, key_usage, cipher_psa->alg ); + status = psa_set_key_policy( cipher_psa->slot, &key_policy ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + /* Populate new key slot. */ + key_type = mbedtls_psa_translate_cipher_type( + ctx->cipher_info->type ); + if( key_type == 0 ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + status = psa_import_key( cipher_psa->slot, + key_type, key, key_bytelen ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + ctx->key_bitlen = key_bitlen; + ctx->operation = operation; + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 && (int) ctx->cipher_info->key_bitlen != key_bitlen ) @@ -223,12 +363,13 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k MBEDTLS_MODE_CTR == ctx->cipher_info->mode ) { return ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key, - ctx->key_bitlen ); + ctx->key_bitlen ); } if( MBEDTLS_DECRYPT == operation ) return ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key, - ctx->key_bitlen ); + ctx->key_bitlen ); + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } @@ -237,10 +378,24 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, const unsigned char *iv, size_t iv_len ) { size_t actual_iv_size; - - if( NULL == ctx || NULL == ctx->cipher_info || NULL == iv ) + if( NULL == ctx || NULL == ctx->cipher_info ) + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + else if( NULL == iv && iv_len != 0 ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + + if( NULL == iv && iv_len == 0 ) + ctx->iv_size = 0; + /* avoid buffer overflow in ctx->iv */ if( iv_len > MBEDTLS_MAX_IV_LENGTH ) return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); @@ -268,8 +423,11 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, } #endif - memcpy( ctx->iv, iv, actual_iv_size ); - ctx->iv_size = actual_iv_size; + if ( actual_iv_size != 0 ) + { + memcpy( ctx->iv, iv, actual_iv_size ); + ctx->iv_size = actual_iv_size; + } return( 0 ); } @@ -279,6 +437,15 @@ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ) if( NULL == ctx || NULL == ctx->cipher_info ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* We don't support resetting PSA-based + * cipher contexts, yet. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + ctx->unprocessed_len = 0; return( 0 ); @@ -291,6 +458,16 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, if( NULL == ctx || NULL == ctx->cipher_info ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { @@ -335,6 +512,16 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + *olen = 0; block_size = mbedtls_cipher_get_block_size( ctx ); @@ -741,6 +928,16 @@ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, if( NULL == ctx || NULL == ctx->cipher_info || NULL == olen ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + *olen = 0; if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode || @@ -823,7 +1020,8 @@ int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, } #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) -int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode ) +int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, + mbedtls_cipher_padding_t mode ) { if( NULL == ctx || MBEDTLS_MODE_CBC != ctx->cipher_info->mode ) @@ -831,6 +1029,19 @@ int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_ciph return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto knows about CBC padding + * schemes, we currently don't make them + * accessible through the cipher layer. */ + if( mode != MBEDTLS_PADDING_NONE ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + switch( mode ) { #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) @@ -880,9 +1091,22 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, if( MBEDTLS_ENCRYPT != ctx->operation ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) - return mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, tag, tag_len ); + return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, + tag, tag_len ) ); #endif #if defined(MBEDTLS_CHACHAPOLY_C) @@ -892,8 +1116,8 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, if ( tag_len != 16U ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); - return mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx, - tag ); + return( mbedtls_chachapoly_finish( + (mbedtls_chachapoly_context*) ctx->cipher_ctx, tag ) ); } #endif @@ -912,14 +1136,25 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* While PSA Crypto has an API for multipart + * operations, we currently don't make it + * accessible through the cipher layer. */ + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { if( tag_len > sizeof( check_tag ) ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); - if( 0 != ( ret = mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx, - check_tag, tag_len ) ) ) + if( 0 != ( ret = mbedtls_gcm_finish( + (mbedtls_gcm_context *) ctx->cipher_ctx, + check_tag, tag_len ) ) ) { return( ret ); } @@ -939,8 +1174,8 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, if ( tag_len != sizeof( check_tag ) ) return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); - ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx, - check_tag ); + ret = mbedtls_chachapoly_finish( + (mbedtls_chachapoly_context*) ctx->cipher_ctx, check_tag ); if ( ret != 0 ) { return( ret ); @@ -969,16 +1204,76 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, int ret; size_t finish_olen; +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* As in the non-PSA case, we don't check that + * a key has been set. If not, the key slot will + * still be in its default state of 0, which is + * guaranteed to be invalid, hence the PSA-call + * below will gracefully fail. */ + mbedtls_cipher_context_psa * const cipher_psa = + (mbedtls_cipher_context_psa *) ctx->cipher_ctx; + + psa_status_t status; + psa_cipher_operation_t cipher_op; + size_t part_len; + + if( ctx->operation == MBEDTLS_DECRYPT ) + { + status = psa_cipher_decrypt_setup( &cipher_op, + cipher_psa->slot, + cipher_psa->alg ); + } + else if( ctx->operation == MBEDTLS_ENCRYPT ) + { + status = psa_cipher_encrypt_setup( &cipher_op, + cipher_psa->slot, + cipher_psa->alg ); + } + else + return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA ); + + /* In the following, we can immediately return on an error, + * because the PSA Crypto API guarantees that cipher operations + * are terminated by unsuccessful calls to psa_cipher_update(), + * and by any call to psa_cipher_finish(). */ + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + status = psa_cipher_set_iv( &cipher_op, iv, iv_len ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + status = psa_cipher_update( &cipher_op, + input, ilen, + output, ilen, olen ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + status = psa_cipher_finish( &cipher_op, + output + *olen, ilen - *olen, + &part_len ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + *olen += part_len; + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 ) return( ret ); if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 ) return( ret ); - if( ( ret = mbedtls_cipher_update( ctx, input, ilen, output, olen ) ) != 0 ) + if( ( ret = mbedtls_cipher_update( ctx, input, ilen, + output, olen ) ) != 0 ) return( ret ); - if( ( ret = mbedtls_cipher_finish( ctx, output + *olen, &finish_olen ) ) != 0 ) + if( ( ret = mbedtls_cipher_finish( ctx, output + *olen, + &finish_olen ) ) != 0 ) return( ret ); *olen += finish_olen; @@ -997,13 +1292,45 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen, unsigned char *tag, size_t tag_len ) { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* As in the non-PSA case, we don't check that + * a key has been set. If not, the key slot will + * still be in its default state of 0, which is + * guaranteed to be invalid, hence the PSA-call + * below will gracefully fail. */ + mbedtls_cipher_context_psa * const cipher_psa = + (mbedtls_cipher_context_psa *) ctx->cipher_ctx; + + psa_status_t status; + + /* PSA Crypto API always writes the authentication tag + * at the end of the encrypted message. */ + if( tag != output + ilen ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + + status = psa_aead_encrypt( cipher_psa->slot, + cipher_psa->alg, + iv, iv_len, + ad, ad_len, + input, ilen, + output, ilen + tag_len, olen ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + *olen -= tag_len; + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { *olen = ilen; - return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT, ilen, - iv, iv_len, ad, ad_len, input, output, - tag_len, tag ) ); + return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT, + ilen, iv, iv_len, ad, ad_len, + input, output, tag_len, tag ) ); } #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_CCM_C) @@ -1044,6 +1371,39 @@ int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen, const unsigned char *tag, size_t tag_len ) { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ctx->psa_enabled == 1 ) + { + /* As in the non-PSA case, we don't check that + * a key has been set. If not, the key slot will + * still be in its default state of 0, which is + * guaranteed to be invalid, hence the PSA-call + * below will gracefully fail. */ + mbedtls_cipher_context_psa * const cipher_psa = + (mbedtls_cipher_context_psa *) ctx->cipher_ctx; + + psa_status_t status; + + /* PSA Crypto API always writes the authentication tag + * at the end of the encrypted message. */ + if( tag != input + ilen ) + return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ); + + status = psa_aead_decrypt( cipher_psa->slot, + cipher_psa->alg, + iv, iv_len, + ad, ad_len, + input, ilen + tag_len, + output, ilen, olen ); + if( status == PSA_ERROR_INVALID_SIGNATURE ) + return( MBEDTLS_ERR_CIPHER_AUTH_FAILED ); + else if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED ); + + return( 0 ); + } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_GCM_C) if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode ) { diff --git a/features/mbedtls/src/cipher_wrap.c b/features/mbedtls/src/cipher_wrap.c index 893490acc83..d4538ed7b32 100644 --- a/features/mbedtls/src/cipher_wrap.c +++ b/features/mbedtls/src/cipher_wrap.c @@ -258,7 +258,7 @@ static const mbedtls_cipher_info_t aes_128_ecb_info = { MBEDTLS_MODE_ECB, 128, "AES-128-ECB", - 16, + 0, 0, 16, &aes_info @@ -269,7 +269,7 @@ static const mbedtls_cipher_info_t aes_192_ecb_info = { MBEDTLS_MODE_ECB, 192, "AES-192-ECB", - 16, + 0, 0, 16, &aes_info @@ -280,7 +280,7 @@ static const mbedtls_cipher_info_t aes_256_ecb_info = { MBEDTLS_MODE_ECB, 256, "AES-256-ECB", - 16, + 0, 0, 16, &aes_info @@ -2266,7 +2266,8 @@ const mbedtls_cipher_definition_t mbedtls_cipher_definitions[] = { MBEDTLS_CIPHER_NONE, NULL } }; -#define NUM_CIPHERS sizeof mbedtls_cipher_definitions / sizeof mbedtls_cipher_definitions[0] +#define NUM_CIPHERS ( sizeof(mbedtls_cipher_definitions) / \ + sizeof(mbedtls_cipher_definitions[0]) ) int mbedtls_cipher_supported[NUM_CIPHERS]; #endif /* MBEDTLS_CIPHER_C */ diff --git a/features/mbedtls/src/ctr_drbg.c b/features/mbedtls/src/ctr_drbg.c index d0e5ba862d2..fead18f7238 100644 --- a/features/mbedtls/src/ctr_drbg.c +++ b/features/mbedtls/src/ctr_drbg.c @@ -66,6 +66,18 @@ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx ) * Non-public function wrapped by mbedtls_ctr_drbg_seed(). Necessary to allow * NIST tests to succeed (which require known length fixed entropy) */ +/* CTR_DRBG_Instantiate with derivation function (SP 800-90A §10.2.1.3.2) + * mbedtls_ctr_drbg_seed_entropy_len(ctx, f_entropy, p_entropy, + * custom, len, entropy_len) + * implements + * CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string, + * security_strength) -> initial_working_state + * with inputs + * custom[:len] = nonce || personalization_string + * where entropy_input comes from f_entropy for entropy_len bytes + * and with outputs + * ctx = initial_working_state + */ int mbedtls_ctr_drbg_seed_entropy_len( mbedtls_ctr_drbg_context *ctx, int (*f_entropy)(void *, unsigned char *, size_t), @@ -256,6 +268,14 @@ static int block_cipher_df( unsigned char *output, return( ret ); } +/* CTR_DRBG_Update (SP 800-90A §10.2.1.2) + * ctr_drbg_update_internal(ctx, provided_data) + * implements + * CTR_DRBG_Update(provided_data, Key, V) + * with inputs and outputs + * ctx->aes_ctx = Key + * ctx->counter = V + */ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx, const unsigned char data[MBEDTLS_CTR_DRBG_SEEDLEN] ) { @@ -301,6 +321,18 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx, return( 0 ); } +/* CTR_DRBG_Instantiate with derivation function (SP 800-90A §10.2.1.3.2) + * mbedtls_ctr_drbg_update(ctx, additional, add_len) + * implements + * CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string, + * security_strength) -> initial_working_state + * with inputs + * ctx->counter = all-bits-0 + * ctx->aes_ctx = context from all-bits-0 key + * additional[:add_len] = entropy_input || nonce || personalization_string + * and with outputs + * ctx = initial_working_state + */ void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t add_len ) { @@ -318,6 +350,18 @@ void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx, } } +/* CTR_DRBG_Reseed with derivation function (SP 800-90A §10.2.1.4.2) + * mbedtls_ctr_drbg_reseed(ctx, additional, len) + * implements + * CTR_DRBG_Reseed(working_state, entropy_input, additional_input) + * -> new_working_state + * with inputs + * ctx contains working_state + * additional[:len] = additional_input + * and entropy_input comes from calling ctx->f_entropy + * and with output + * ctx contains new_working_state + */ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx, const unsigned char *additional, size_t len ) { @@ -371,6 +415,25 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx, return( 0 ); } +/* CTR_DRBG_Generate with derivation function (SP 800-90A §10.2.1.5.2) + * mbedtls_ctr_drbg_random_with_add(ctx, output, output_len, additional, add_len) + * implements + * CTR_DRBG_Reseed(working_state, entropy_input, additional[:add_len]) + * -> working_state_after_reseed + * if required, then + * CTR_DRBG_Generate(working_state_after_reseed, + * requested_number_of_bits, additional_input) + * -> status, returned_bits, new_working_state + * with inputs + * ctx contains working_state + * requested_number_of_bits = 8 * output_len + * additional[:add_len] = additional_input + * and entropy_input comes from calling ctx->f_entropy + * and with outputs + * status = SUCCESS (this function does the reseed internally) + * returned_bits = output[:output_len] + * ctx contains new_working_state + */ int mbedtls_ctr_drbg_random_with_add( void *p_rng, unsigned char *output, size_t output_len, const unsigned char *additional, size_t add_len ) diff --git a/features/mbedtls/src/ecdh.c b/features/mbedtls/src/ecdh.c index 61380b69366..e6ae99994e1 100644 --- a/features/mbedtls/src/ecdh.c +++ b/features/mbedtls/src/ecdh.c @@ -40,36 +40,62 @@ #if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) /* - * Generate public key: simple wrapper around mbedtls_ecp_gen_keypair + * Generate public key (restartable version) + * + * Note: this internal function relies on its caller preserving the value of + * the output parameter 'd' across continuation calls. This would not be + * acceptable for a public function but is OK here as we control call sites. + */ +static int ecdh_gen_public_restartable( mbedtls_ecp_group *grp, + mbedtls_mpi *d, mbedtls_ecp_point *Q, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) +{ + int ret; + + /* If multiplication is in progress, we already generated a privkey */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx == NULL || rs_ctx->rsm == NULL ) +#endif + MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) ); + + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, Q, d, &grp->G, + f_rng, p_rng, rs_ctx ) ); + +cleanup: + return( ret ); +} + +/* + * Generate public key */ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { - return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng ); + return( ecdh_gen_public_restartable( grp, d, Q, f_rng, p_rng, NULL ) ); } -#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */ +#endif /* !MBEDTLS_ECDH_GEN_PUBLIC_ALT */ #if !defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) /* * Compute shared secret (SEC1 3.3.1) */ -int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, +static int ecdh_compute_shared_restartable( mbedtls_ecp_group *grp, + mbedtls_mpi *z, const mbedtls_ecp_point *Q, const mbedtls_mpi *d, int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) + void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret; mbedtls_ecp_point P; mbedtls_ecp_point_init( &P ); - /* - * Make sure Q is a valid pubkey before using it - */ - MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) ); - - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &P, d, Q, f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &P, d, Q, + f_rng, p_rng, rs_ctx ) ); if( mbedtls_ecp_is_zero( &P ) ) { @@ -84,14 +110,39 @@ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, return( ret ); } -#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */ + +/* + * Compute shared secret (SEC1 3.3.1) + */ +int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, + const mbedtls_ecp_point *Q, const mbedtls_mpi *d, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) +{ + return( ecdh_compute_shared_restartable( grp, z, Q, d, + f_rng, p_rng, NULL ) ); +} +#endif /* !MBEDTLS_ECDH_COMPUTE_SHARED_ALT */ /* * Initialize context */ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx ) { - memset( ctx, 0, sizeof( mbedtls_ecdh_context ) ); + mbedtls_ecp_group_init( &ctx->grp ); + mbedtls_mpi_init( &ctx->d ); + mbedtls_ecp_point_init( &ctx->Q ); + mbedtls_ecp_point_init( &ctx->Qp ); + mbedtls_mpi_init( &ctx->z ); + ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED; + mbedtls_ecp_point_init( &ctx->Vi ); + mbedtls_ecp_point_init( &ctx->Vf ); + mbedtls_mpi_init( &ctx->_d ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + ctx->restart_enabled = 0; + mbedtls_ecp_restart_init( &ctx->rs ); +#endif } /* @@ -103,14 +154,28 @@ void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ) return; mbedtls_ecp_group_free( &ctx->grp ); + mbedtls_mpi_free( &ctx->d ); mbedtls_ecp_point_free( &ctx->Q ); mbedtls_ecp_point_free( &ctx->Qp ); + mbedtls_mpi_free( &ctx->z ); mbedtls_ecp_point_free( &ctx->Vi ); mbedtls_ecp_point_free( &ctx->Vf ); - mbedtls_mpi_free( &ctx->d ); - mbedtls_mpi_free( &ctx->z ); mbedtls_mpi_free( &ctx->_d ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + mbedtls_ecp_restart_free( &ctx->rs ); +#endif +} + +#if defined(MBEDTLS_ECP_RESTARTABLE) +/* + * Enable restartable operations for context + */ +void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx ) +{ + ctx->restart_enabled = 1; } +#endif /* * Setup and write the ServerKeyExhange parameters (RFC 4492) @@ -126,13 +191,28 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, { int ret; size_t grp_len, pt_len; +#if defined(MBEDTLS_ECP_RESTARTABLE) + mbedtls_ecp_restart_ctx *rs_ctx = NULL; +#endif if( ctx == NULL || ctx->grp.pbits == 0 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); - if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ) - != 0 ) +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ctx->restart_enabled ) + rs_ctx = &ctx->rs; +#endif + + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q, + f_rng, p_rng, rs_ctx ) ) != 0 ) + return( ret ); +#else + if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, + f_rng, p_rng ) ) != 0 ) return( ret ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ if( ( ret = mbedtls_ecp_tls_write_group( &ctx->grp, &grp_len, buf, blen ) ) != 0 ) @@ -142,7 +222,7 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, blen -= grp_len; if( ( ret = mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, ctx->point_format, - &pt_len, buf, blen ) ) != 0 ) + &pt_len, buf, blen ) ) != 0 ) return( ret ); *olen = grp_len + pt_len; @@ -206,13 +286,27 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, void *p_rng ) { int ret; +#if defined(MBEDTLS_ECP_RESTARTABLE) + mbedtls_ecp_restart_ctx *rs_ctx = NULL; +#endif if( ctx == NULL || ctx->grp.pbits == 0 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); - if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ) - != 0 ) +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ctx->restart_enabled ) + rs_ctx = &ctx->rs; +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q, + f_rng, p_rng, rs_ctx ) ) != 0 ) return( ret ); +#else + if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q, + f_rng, p_rng ) ) != 0 ) + return( ret ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ return mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, ctx->point_format, olen, buf, blen ); @@ -248,15 +342,31 @@ int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, void *p_rng ) { int ret; +#if defined(MBEDTLS_ECP_RESTARTABLE) + mbedtls_ecp_restart_ctx *rs_ctx = NULL; +#endif - if( ctx == NULL ) + if( ctx == NULL || ctx->grp.pbits == 0 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); - if( ( ret = mbedtls_ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp, &ctx->d, - f_rng, p_rng ) ) != 0 ) +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ctx->restart_enabled ) + rs_ctx = &ctx->rs; +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ( ret = ecdh_compute_shared_restartable( &ctx->grp, + &ctx->z, &ctx->Qp, &ctx->d, f_rng, p_rng, rs_ctx ) ) != 0 ) + { + return( ret ); + } +#else + if( ( ret = mbedtls_ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp, + &ctx->d, f_rng, p_rng ) ) != 0 ) { return( ret ); } +#endif /* MBEDTLS_ECP_RESTARTABLE */ if( mbedtls_mpi_size( &ctx->z ) > blen ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); diff --git a/features/mbedtls/src/ecdsa.c b/features/mbedtls/src/ecdsa.c index 17a88bdd29f..a62c14cbe0a 100644 --- a/features/mbedtls/src/ecdsa.c +++ b/features/mbedtls/src/ecdsa.c @@ -42,6 +42,178 @@ #include "mbedtls/hmac_drbg.h" #endif +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#include +#define mbedtls_calloc calloc +#define mbedtls_free free +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) + +/* + * Sub-context for ecdsa_verify() + */ +struct mbedtls_ecdsa_restart_ver +{ + mbedtls_mpi u1, u2; /* intermediate values */ + enum { /* what to do next? */ + ecdsa_ver_init = 0, /* getting started */ + ecdsa_ver_muladd, /* muladd step */ + } state; +}; + +/* + * Init verify restart sub-context + */ +static void ecdsa_restart_ver_init( mbedtls_ecdsa_restart_ver_ctx *ctx ) +{ + mbedtls_mpi_init( &ctx->u1 ); + mbedtls_mpi_init( &ctx->u2 ); + ctx->state = ecdsa_ver_init; +} + +/* + * Free the components of a verify restart sub-context + */ +static void ecdsa_restart_ver_free( mbedtls_ecdsa_restart_ver_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_mpi_free( &ctx->u1 ); + mbedtls_mpi_free( &ctx->u2 ); + + ecdsa_restart_ver_init( ctx ); +} + +/* + * Sub-context for ecdsa_sign() + */ +struct mbedtls_ecdsa_restart_sig +{ + int sign_tries; + int key_tries; + mbedtls_mpi k; /* per-signature random */ + mbedtls_mpi r; /* r value */ + enum { /* what to do next? */ + ecdsa_sig_init = 0, /* getting started */ + ecdsa_sig_mul, /* doing ecp_mul() */ + ecdsa_sig_modn, /* mod N computations */ + } state; +}; + +/* + * Init verify sign sub-context + */ +static void ecdsa_restart_sig_init( mbedtls_ecdsa_restart_sig_ctx *ctx ) +{ + ctx->sign_tries = 0; + ctx->key_tries = 0; + mbedtls_mpi_init( &ctx->k ); + mbedtls_mpi_init( &ctx->r ); + ctx->state = ecdsa_sig_init; +} + +/* + * Free the components of a sign restart sub-context + */ +static void ecdsa_restart_sig_free( mbedtls_ecdsa_restart_sig_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_mpi_free( &ctx->k ); + mbedtls_mpi_free( &ctx->r ); +} + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) +/* + * Sub-context for ecdsa_sign_det() + */ +struct mbedtls_ecdsa_restart_det +{ + mbedtls_hmac_drbg_context rng_ctx; /* DRBG state */ + enum { /* what to do next? */ + ecdsa_det_init = 0, /* getting started */ + ecdsa_det_sign, /* make signature */ + } state; +}; + +/* + * Init verify sign_det sub-context + */ +static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx ) +{ + mbedtls_hmac_drbg_init( &ctx->rng_ctx ); + ctx->state = ecdsa_det_init; +} + +/* + * Free the components of a sign_det restart sub-context + */ +static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_hmac_drbg_free( &ctx->rng_ctx ); + + ecdsa_restart_det_init( ctx ); +} +#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ + +#define ECDSA_RS_ECP &rs_ctx->ecp + +/* Utility macro for checking and updating ops budget */ +#define ECDSA_BUDGET( ops ) \ + MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, &rs_ctx->ecp, ops ) ); + +/* Call this when entering a function that needs its own sub-context */ +#define ECDSA_RS_ENTER( SUB ) do { \ + /* reset ops count for this call if top-level */ \ + if( rs_ctx != NULL && rs_ctx->ecp.depth++ == 0 ) \ + rs_ctx->ecp.ops_done = 0; \ + \ + /* set up our own sub-context if needed */ \ + if( mbedtls_ecp_restart_is_enabled() && \ + rs_ctx != NULL && rs_ctx->SUB == NULL ) \ + { \ + rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \ + if( rs_ctx->SUB == NULL ) \ + return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \ + \ + ecdsa_restart_## SUB ##_init( rs_ctx->SUB ); \ + } \ +} while( 0 ) + +/* Call this when leaving a function that needs its own sub-context */ +#define ECDSA_RS_LEAVE( SUB ) do { \ + /* clear our sub-context when not in progress (done or error) */ \ + if( rs_ctx != NULL && rs_ctx->SUB != NULL && \ + ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \ + { \ + ecdsa_restart_## SUB ##_free( rs_ctx->SUB ); \ + mbedtls_free( rs_ctx->SUB ); \ + rs_ctx->SUB = NULL; \ + } \ + \ + if( rs_ctx != NULL ) \ + rs_ctx->ecp.depth--; \ +} while( 0 ) + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +#define ECDSA_RS_ECP NULL + +#define ECDSA_BUDGET( ops ) /* no-op; for compatibility */ + +#define ECDSA_RS_ENTER( SUB ) (void) rs_ctx +#define ECDSA_RS_LEAVE( SUB ) (void) rs_ctx + +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /* * Derive a suitable integer for group grp from a buffer of length len * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3 @@ -70,13 +242,17 @@ static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x, * Compute ECDSA signature of a hashed message (SEC1 4.1.3) * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message) */ -int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, +static int ecdsa_sign_restartable( mbedtls_ecp_group *grp, + mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, - int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_ecdsa_restart_ctx *rs_ctx ) { - int ret, key_tries, sign_tries, blind_tries; + int ret, key_tries, sign_tries; + int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; + mbedtls_mpi *pk = &k, *pr = r; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) @@ -89,26 +265,72 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); - sign_tries = 0; + ECDSA_RS_ENTER( sig ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->sig != NULL ) + { + /* redirect to our context */ + p_sign_tries = &rs_ctx->sig->sign_tries; + p_key_tries = &rs_ctx->sig->key_tries; + pk = &rs_ctx->sig->k; + pr = &rs_ctx->sig->r; + + /* jump to current step */ + if( rs_ctx->sig->state == ecdsa_sig_mul ) + goto mul; + if( rs_ctx->sig->state == ecdsa_sig_modn ) + goto modn; + } +#endif /* MBEDTLS_ECP_RESTARTABLE */ + + *p_sign_tries = 0; do { + if( *p_sign_tries++ > 10 ) + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } + /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ - key_tries = 0; + *p_key_tries = 0; do { - MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) ); - - if( key_tries++ > 10 ) + if( *p_key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } + + MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->sig != NULL ) + rs_ctx->sig->state = ecdsa_sig_mul; + +mul: +#endif + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G, + f_rng, p_rng, ECDSA_RS_ECP ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) ); } - while( mbedtls_mpi_cmp_int( r, 0 ) == 0 ); + while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->sig != NULL ) + rs_ctx->sig->state = ecdsa_sig_modn; + +modn: +#endif + /* + * Accounting for everything up to the end of the loop + * (step 6, but checking now avoids saving e and t) + */ + ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 ); /* * Step 5: derive MPI from hashed message @@ -119,57 +341,60 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ - blind_tries = 0; - do - { - size_t n_size = ( grp->nbits + 7 ) / 8; - MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) ); - - /* See mbedtls_ecp_gen_keypair() */ - if( ++blind_tries > 30 ) - return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); - } - while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 || - mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 ); + MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ - MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); - - if( sign_tries++ > 10 ) - { - ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; - goto cleanup; - } } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->sig != NULL ) + mbedtls_mpi_copy( r, pr ); +#endif + cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); + ECDSA_RS_LEAVE( sig ); + return( ret ); } -#endif /* MBEDTLS_ECDSA_SIGN_ALT */ + +/* + * Compute ECDSA signature of a hashed message + */ +int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, + const mbedtls_mpi *d, const unsigned char *buf, size_t blen, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, + f_rng, p_rng, NULL ) ); +} +#endif /* !MBEDTLS_ECDSA_SIGN_ALT */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /* * Deterministic signature wrapper */ -int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, +static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, + mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, - mbedtls_md_type_t md_alg ) + mbedtls_md_type_t md_alg, + mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; + mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; @@ -181,21 +406,58 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); + ECDSA_RS_ENTER( det ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->det != NULL ) + { + /* redirect to our context */ + p_rng = &rs_ctx->det->rng_ctx; + + /* jump to current step */ + if( rs_ctx->det->state == ecdsa_det_sign ) + goto sign; + } +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); - mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len ); + mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->det != NULL ) + rs_ctx->det->state = ecdsa_det_sign; +sign: +#endif +#if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, - mbedtls_hmac_drbg_random, &rng_ctx ); + mbedtls_hmac_drbg_random, p_rng ); +#else + ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, + mbedtls_hmac_drbg_random, p_rng, rs_ctx ); +#endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); + ECDSA_RS_LEAVE( det ); + return( ret ); } + +/* + * Deterministic signature wrapper + */ +int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, + const mbedtls_mpi *d, const unsigned char *buf, size_t blen, + mbedtls_md_type_t md_alg ) +{ + return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) ); +} #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #if !defined(MBEDTLS_ECDSA_VERIFY_ALT) @@ -203,21 +465,40 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi * Verify ECDSA signature of hashed message (SEC1 4.1.4) * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message) */ -int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, - const unsigned char *buf, size_t blen, - const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s) +static int ecdsa_verify_restartable( mbedtls_ecp_group *grp, + const unsigned char *buf, size_t blen, + const mbedtls_ecp_point *Q, + const mbedtls_mpi *r, const mbedtls_mpi *s, + mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi e, s_inv, u1, u2; mbedtls_ecp_point R; + mbedtls_mpi *pu1 = &u1, *pu2 = &u2; mbedtls_ecp_point_init( &R ); - mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 ); + mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); + mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 ); /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); + ECDSA_RS_ENTER( ver ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ver != NULL ) + { + /* redirect to our context */ + pu1 = &rs_ctx->ver->u1; + pu2 = &rs_ctx->ver->u2; + + /* jump to current step */ + if( rs_ctx->ver->state == ecdsa_ver_muladd ) + goto muladd; + } +#endif /* MBEDTLS_ECP_RESTARTABLE */ + /* * Step 1: make sure r and s are in range 1..n-1 */ @@ -228,11 +509,6 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, goto cleanup; } - /* - * Additional precaution: make sure Q is valid - */ - MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) ); - /* * Step 3: derive MPI from hashed message */ @@ -241,21 +517,27 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, /* * Step 4: u1 = e / s mod n, u2 = r / s mod n */ + ECDSA_BUDGET( MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2 ); + MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u1, &e, &s_inv ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u1, &u1, &grp->N ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu1, &e, &s_inv ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu1, pu1, &grp->N ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u2, r, &s_inv ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u2, &u2, &grp->N ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu2, r, &s_inv ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu2, pu2, &grp->N ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ver != NULL ) + rs_ctx->ver->state = ecdsa_ver_muladd; + +muladd: +#endif /* * Step 5: R = u1 G + u2 Q - * - * Since we're not using any secret data, no need to pass a RNG to - * mbedtls_ecp_mul() for countermesures. */ - MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, &R, &u1, &grp->G, &u2, Q ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_muladd_restartable( grp, + &R, pu1, &grp->G, pu2, Q, ECDSA_RS_ECP ) ); if( mbedtls_ecp_is_zero( &R ) ) { @@ -280,11 +562,24 @@ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, cleanup: mbedtls_ecp_point_free( &R ); - mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 ); + mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); + mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 ); + + ECDSA_RS_LEAVE( ver ); return( ret ); } -#endif /* MBEDTLS_ECDSA_VERIFY_ALT */ + +/* + * Verify ECDSA signature of hashed message + */ +int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, + const unsigned char *buf, size_t blen, + const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s) +{ + return( ecdsa_verify_restartable( grp, buf, blen, Q, r, s, NULL ) ); +} +#endif /* !MBEDTLS_ECDSA_VERIFY_ALT */ /* * Convert a signature (given by context) to ASN.1 @@ -313,11 +608,13 @@ static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s, /* * Compute and write signature */ -int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, +int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, + mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) + void *p_rng, + mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi r, s; @@ -329,14 +626,19 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t (void) f_rng; (void) p_rng; - MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d, - hash, hlen, md_alg ) ); + MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d, + hash, hlen, md_alg, rs_ctx ) ); #else (void) md_alg; +#if defined(MBEDTLS_ECDSA_SIGN_ALT) MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); -#endif +#else + MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d, + hash, hlen, f_rng, p_rng, rs_ctx ) ); +#endif /* MBEDTLS_ECDSA_SIGN_ALT */ +#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); @@ -347,7 +649,20 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t return( ret ); } -#if ! defined(MBEDTLS_DEPRECATED_REMOVED) && \ +/* + * Compute and write signature + */ +int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hlen, + unsigned char *sig, size_t *slen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) +{ + return( mbedtls_ecdsa_write_signature_restartable( + ctx, md_alg, hash, hlen, sig, slen, f_rng, p_rng, NULL ) ); +} + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) && \ defined(MBEDTLS_ECDSA_DETERMINISTIC) int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, @@ -365,6 +680,18 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ) +{ + return( mbedtls_ecdsa_read_signature_restartable( + ctx, hash, hlen, sig, slen, NULL ) ); +} + +/* + * Restartable read and check signature + */ +int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, + const unsigned char *hash, size_t hlen, + const unsigned char *sig, size_t slen, + mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; unsigned char *p = (unsigned char *) sig; @@ -395,10 +722,15 @@ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } - +#if defined(MBEDTLS_ECDSA_VERIFY_ALT) if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen, - &ctx->Q, &r, &s ) ) != 0 ) + &ctx->Q, &r, &s ) ) != 0 ) + goto cleanup; +#else + if( ( ret = ecdsa_verify_restartable( &ctx->grp, hash, hlen, + &ctx->Q, &r, &s, rs_ctx ) ) != 0 ) goto cleanup; +#endif /* MBEDTLS_ECDSA_VERIFY_ALT */ /* At this point we know that the buffer starts with a valid signature. * Return 0 if the buffer just contains the signature, and a specific @@ -423,7 +755,7 @@ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, return( mbedtls_ecp_group_load( &ctx->grp, gid ) || mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); } -#endif /* MBEDTLS_ECDSA_GENKEY_ALT */ +#endif /* !MBEDTLS_ECDSA_GENKEY_ALT */ /* * Set context from an mbedtls_ecp_keypair @@ -458,4 +790,42 @@ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ) mbedtls_ecp_keypair_free( ctx ); } +#if defined(MBEDTLS_ECP_RESTARTABLE) +/* + * Initialize a restart context + */ +void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ) +{ + mbedtls_ecp_restart_init( &ctx->ecp ); + + ctx->ver = NULL; + ctx->sig = NULL; +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + ctx->det = NULL; +#endif +} + +/* + * Free the components of a restart context + */ +void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ) +{ + mbedtls_ecp_restart_free( &ctx->ecp ); + + ecdsa_restart_ver_free( ctx->ver ); + mbedtls_free( ctx->ver ); + ctx->ver = NULL; + + ecdsa_restart_sig_free( ctx->sig ); + mbedtls_free( ctx->sig ); + ctx->sig = NULL; + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + ecdsa_restart_det_free( ctx->det ); + mbedtls_free( ctx->det ); + ctx->det = NULL; +#endif +} +#endif /* MBEDTLS_ECP_RESTARTABLE */ + #endif /* MBEDTLS_ECDSA_C */ diff --git a/features/mbedtls/src/ecp.c b/features/mbedtls/src/ecp.c index 9e2c085bb6d..de5725c7007 100644 --- a/features/mbedtls/src/ecp.c +++ b/features/mbedtls/src/ecp.c @@ -82,6 +82,230 @@ static unsigned long add_count, dbl_count, mul_count; #endif +#if defined(MBEDTLS_ECP_RESTARTABLE) +/* + * Maximum number of "basic operations" to be done in a row. + * + * Default value 0 means that ECC operations will not yield. + * Note that regardless of the value of ecp_max_ops, always at + * least one step is performed before yielding. + * + * Setting ecp_max_ops=1 can be suitable for testing purposes + * as it will interrupt computation at all possible points. + */ +static unsigned ecp_max_ops = 0; + +/* + * Set ecp_max_ops + */ +void mbedtls_ecp_set_max_ops( unsigned max_ops ) +{ + ecp_max_ops = max_ops; +} + +/* + * Check if restart is enabled + */ +int mbedtls_ecp_restart_is_enabled( void ) +{ + return( ecp_max_ops != 0 ); +} + +/* + * Restart sub-context for ecp_mul_comb() + */ +struct mbedtls_ecp_restart_mul +{ + mbedtls_ecp_point R; /* current intermediate result */ + size_t i; /* current index in various loops, 0 outside */ + mbedtls_ecp_point *T; /* table for precomputed points */ + unsigned char T_size; /* number of points in table T */ + enum { /* what were we doing last time we returned? */ + ecp_rsm_init = 0, /* nothing so far, dummy initial state */ + ecp_rsm_pre_dbl, /* precompute 2^n multiples */ + ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */ + ecp_rsm_pre_add, /* precompute remaining points by adding */ + ecp_rsm_pre_norm_add, /* normalize all precomputed points */ + ecp_rsm_comb_core, /* ecp_mul_comb_core() */ + ecp_rsm_final_norm, /* do the final normalization */ + } state; +}; + +/* + * Init restart_mul sub-context + */ +static void ecp_restart_rsm_init( mbedtls_ecp_restart_mul_ctx *ctx ) +{ + mbedtls_ecp_point_init( &ctx->R ); + ctx->i = 0; + ctx->T = NULL; + ctx->T_size = 0; + ctx->state = ecp_rsm_init; +} + +/* + * Free the components of a restart_mul sub-context + */ +static void ecp_restart_rsm_free( mbedtls_ecp_restart_mul_ctx *ctx ) +{ + unsigned char i; + + if( ctx == NULL ) + return; + + mbedtls_ecp_point_free( &ctx->R ); + + if( ctx->T != NULL ) + { + for( i = 0; i < ctx->T_size; i++ ) + mbedtls_ecp_point_free( ctx->T + i ); + mbedtls_free( ctx->T ); + } + + ecp_restart_rsm_init( ctx ); +} + +/* + * Restart context for ecp_muladd() + */ +struct mbedtls_ecp_restart_muladd +{ + mbedtls_ecp_point mP; /* mP value */ + mbedtls_ecp_point R; /* R intermediate result */ + enum { /* what should we do next? */ + ecp_rsma_mul1 = 0, /* first multiplication */ + ecp_rsma_mul2, /* second multiplication */ + ecp_rsma_add, /* addition */ + ecp_rsma_norm, /* normalization */ + } state; +}; + +/* + * Init restart_muladd sub-context + */ +static void ecp_restart_ma_init( mbedtls_ecp_restart_muladd_ctx *ctx ) +{ + mbedtls_ecp_point_init( &ctx->mP ); + mbedtls_ecp_point_init( &ctx->R ); + ctx->state = ecp_rsma_mul1; +} + +/* + * Free the components of a restart_muladd sub-context + */ +static void ecp_restart_ma_free( mbedtls_ecp_restart_muladd_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_ecp_point_free( &ctx->mP ); + mbedtls_ecp_point_free( &ctx->R ); + + ecp_restart_ma_init( ctx ); +} + +/* + * Initialize a restart context + */ +void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx ) +{ + ctx->ops_done = 0; + ctx->depth = 0; + ctx->rsm = NULL; + ctx->ma = NULL; +} + +/* + * Free the components of a restart context + */ +void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + ecp_restart_rsm_free( ctx->rsm ); + mbedtls_free( ctx->rsm ); + + ecp_restart_ma_free( ctx->ma ); + mbedtls_free( ctx->ma ); + + mbedtls_ecp_restart_init( ctx ); +} + +/* + * Check if we can do the next step + */ +int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, + mbedtls_ecp_restart_ctx *rs_ctx, + unsigned ops ) +{ + if( rs_ctx != NULL && ecp_max_ops != 0 ) + { + /* scale depending on curve size: the chosen reference is 256-bit, + * and multiplication is quadratic. Round to the closest integer. */ + if( grp->pbits >= 512 ) + ops *= 4; + else if( grp->pbits >= 384 ) + ops *= 2; + + /* Avoid infinite loops: always allow first step. + * Because of that, however, it's not generally true + * that ops_done <= ecp_max_ops, so the check + * ops_done > ecp_max_ops below is mandatory. */ + if( ( rs_ctx->ops_done != 0 ) && + ( rs_ctx->ops_done > ecp_max_ops || + ops > ecp_max_ops - rs_ctx->ops_done ) ) + { + return( MBEDTLS_ERR_ECP_IN_PROGRESS ); + } + + /* update running count */ + rs_ctx->ops_done += ops; + } + + return( 0 ); +} + +/* Call this when entering a function that needs its own sub-context */ +#define ECP_RS_ENTER( SUB ) do { \ + /* reset ops count for this call if top-level */ \ + if( rs_ctx != NULL && rs_ctx->depth++ == 0 ) \ + rs_ctx->ops_done = 0; \ + \ + /* set up our own sub-context if needed */ \ + if( mbedtls_ecp_restart_is_enabled() && \ + rs_ctx != NULL && rs_ctx->SUB == NULL ) \ + { \ + rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \ + if( rs_ctx->SUB == NULL ) \ + return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \ + \ + ecp_restart_## SUB ##_init( rs_ctx->SUB ); \ + } \ +} while( 0 ) + +/* Call this when leaving a function that needs its own sub-context */ +#define ECP_RS_LEAVE( SUB ) do { \ + /* clear our sub-context when not in progress (done or error) */ \ + if( rs_ctx != NULL && rs_ctx->SUB != NULL && \ + ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \ + { \ + ecp_restart_## SUB ##_free( rs_ctx->SUB ); \ + mbedtls_free( rs_ctx->SUB ); \ + rs_ctx->SUB = NULL; \ + } \ + \ + if( rs_ctx != NULL ) \ + rs_ctx->depth--; \ +} while( 0 ) + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +#define ECP_RS_ENTER( sub ) (void) rs_ctx; +#define ECP_RS_LEAVE( sub ) (void) rs_ctx; + +#endif /* MBEDTLS_ECP_RESTARTABLE */ + #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ @@ -289,7 +513,21 @@ void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ) if( grp == NULL ) return; - memset( grp, 0, sizeof( mbedtls_ecp_group ) ); + grp->id = MBEDTLS_ECP_DP_NONE; + mbedtls_mpi_init( &grp->P ); + mbedtls_mpi_init( &grp->A ); + mbedtls_mpi_init( &grp->B ); + mbedtls_ecp_point_init( &grp->G ); + mbedtls_mpi_init( &grp->N ); + grp->pbits = 0; + grp->nbits = 0; + grp->h = 0; + grp->modp = NULL; + grp->t_pre = NULL; + grp->t_post = NULL; + grp->t_data = NULL; + grp->T = NULL; + grp->T_size = 0; } /* @@ -752,11 +990,10 @@ static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p return( 0 ); #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_normalize_jac( grp, pt ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_normalize_jac( grp, pt ) ); #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */ + mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi ); /* @@ -796,32 +1033,33 @@ static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p * Cost: 1N(t) := 1I + (6t - 3)M + 1S */ static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp, - mbedtls_ecp_point *T[], size_t t_len ) + mbedtls_ecp_point *T[], size_t T_size ) { int ret; size_t i; mbedtls_mpi *c, u, Zi, ZZi; - if( t_len < 2 ) + if( T_size < 2 ) return( ecp_normalize_jac( grp, *T ) ); #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_normalize_jac_many(grp, T, t_len); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_normalize_jac_many( grp, T, T_size ) ); #endif - if( ( c = mbedtls_calloc( t_len, sizeof( mbedtls_mpi ) ) ) == NULL ) + if( ( c = mbedtls_calloc( T_size, sizeof( mbedtls_mpi ) ) ) == NULL ) return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); + for( i = 0; i < T_size; i++ ) + mbedtls_mpi_init( &c[i] ); + mbedtls_mpi_init( &u ); mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi ); /* * c[i] = Z_0 * ... * Z_i */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &c[0], &T[0]->Z ) ); - for( i = 1; i < t_len; i++ ) + for( i = 1; i < T_size; i++ ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &c[i], &c[i-1], &T[i]->Z ) ); MOD_MUL( c[i] ); @@ -830,9 +1068,9 @@ static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp, /* * u = 1 / (Z_0 * ... * Z_n) mod P */ - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[t_len-1], &grp->P ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[T_size-1], &grp->P ) ); - for( i = t_len - 1; ; i-- ) + for( i = T_size - 1; ; i-- ) { /* * Zi = 1 / Z_i mod p @@ -872,7 +1110,7 @@ static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp, cleanup: mbedtls_mpi_free( &u ); mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi ); - for( i = 0; i < t_len; i++ ) + for( i = 0; i < T_size; i++ ) mbedtls_mpi_free( &c[i] ); mbedtls_free( c ); @@ -929,10 +1167,8 @@ static int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, #endif #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_double_jac( grp, R, P ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_double_jac( grp, R, P ) ); #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */ mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U ); @@ -1027,10 +1263,8 @@ static int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, #endif #if defined(MBEDTLS_ECP_ADD_MIXED_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_add_mixed( grp, R, P, Q ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_add_mixed( grp, R, P, Q ) ); #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */ /* @@ -1114,10 +1348,8 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p int count = 0; #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_randomize_jac( grp, pt, f_rng, p_rng ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_randomize_jac( grp, pt, f_rng, p_rng ) ); #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */ p_size = ( grp->pbits + 7 ) / 8; @@ -1173,11 +1405,38 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p * modified version that provides resistance to SPA by avoiding zero * digits in the representation as in [3]. We modify the method further by * requiring that all K_i be odd, which has the small cost that our - * representation uses one more K_i, due to carries. + * representation uses one more K_i, due to carries, but saves on the size of + * the precomputed table. + * + * Summary of the comb method and its modifications: + * + * - The goal is to compute m*P for some w*d-bit integer m. + * + * - The basic comb method splits m into the w-bit integers + * x[0] .. x[d-1] where x[i] consists of the bits in m whose + * index has residue i modulo d, and computes m * P as + * S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where + * S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P. + * + * - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by + * .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] .., + * thereby successively converting it into a form where all summands + * are nonzero, at the cost of negative summands. This is the basic idea of [3]. * - * Also, for the sake of compactness, only the seven low-order bits of x[i] - * are used to represent K_i, and the msb of x[i] encodes the the sign (s_i in - * the paper): it is set if and only if if s_i == -1; + * - More generally, even if x[i+1] != 0, we can first transform the sum as + * .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] .., + * and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]]. + * Performing and iterating this procedure for those x[i] that are even + * (keeping track of carry), we can transform the original sum into one of the form + * S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]] + * with all x'[i] odd. It is therefore only necessary to know S at odd indices, + * which is why we are only computing half of it in the first place in + * ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb. + * + * - For the sake of compactness, only the seven low-order bits of x[i] + * are used to represent its absolute value (K_i in the paper), and the msb + * of x[i] encodes the sign (s_i in the paper): it is set if and only if + * if s_i == -1; * * Calling conventions: * - x is an array of size d + 1 @@ -1186,8 +1445,8 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d * (the result will be incorrect if these assumptions are not satisfied) */ -static void ecp_comb_fixed( unsigned char x[], size_t d, - unsigned char w, const mbedtls_mpi *m ) +static void ecp_comb_recode_core( unsigned char x[], size_t d, + unsigned char w, const mbedtls_mpi *m ) { size_t i, j; unsigned char c, cc, adjust; @@ -1217,70 +1476,178 @@ static void ecp_comb_fixed( unsigned char x[], size_t d, } /* - * Precompute points for the comb method + * Precompute points for the adapted comb method * - * If i = i_{w-1} ... i_1 is the binary representation of i, then - * T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P + * Assumption: T must be able to hold 2^{w - 1} elements. * - * T must be able to hold 2^{w - 1} elements + * Operation: If i = i_{w-1} ... i_1 is the binary representation of i, + * sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P. * * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1) + * + * Note: Even comb values (those where P would be omitted from the + * sum defining T[i] above) are not needed in our adaption + * the comb method. See ecp_comb_recode_core(). + * + * This function currently works in four steps: + * (1) [dbl] Computation of intermediate T[i] for 2-power values of i + * (2) [norm_dbl] Normalization of coordinates of these T[i] + * (3) [add] Computation of all T[i] + * (4) [norm_add] Normalization of all T[i] + * + * Step 1 can be interrupted but not the others; together with the final + * coordinate normalization they are the largest steps done at once, depending + * on the window size. Here are operation counts for P-256: + * + * step (2) (3) (4) + * w = 5 142 165 208 + * w = 4 136 77 160 + * w = 3 130 33 136 + * w = 2 124 11 124 + * + * So if ECC operations are blocking for too long even with a low max_ops + * value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order + * to minimize maximum blocking time. */ static int ecp_precompute_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point T[], const mbedtls_ecp_point *P, - unsigned char w, size_t d ) + unsigned char w, size_t d, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret; - unsigned char i, k; - size_t j; + unsigned char i; + size_t j = 0; + const unsigned char T_size = 1U << ( w - 1 ); mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1]; +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + { + if( rs_ctx->rsm->state == ecp_rsm_pre_dbl ) + goto dbl; + if( rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl ) + goto norm_dbl; + if( rs_ctx->rsm->state == ecp_rsm_pre_add ) + goto add; + if( rs_ctx->rsm->state == ecp_rsm_pre_norm_add ) + goto norm_add; + } +#else + (void) rs_ctx; +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + { + rs_ctx->rsm->state = ecp_rsm_pre_dbl; + + /* initial state for the loop */ + rs_ctx->rsm->i = 0; + } + +dbl: +#endif /* * Set T[0] = P and * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value) */ MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &T[0], P ) ); - k = 0; - for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 ) +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0 ) + j = rs_ctx->rsm->i; + else +#endif + j = 0; + + for( ; j < d * ( w - 1 ); j++ ) { + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL ); + + i = 1U << ( j / d ); cur = T + i; - MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) ); - for( j = 0; j < d; j++ ) - MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) ); - TT[k++] = cur; + if( j % d == 0 ) + MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) ); + + MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) ); } - MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl; + +norm_dbl: +#endif + /* + * Normalize current elements in T. As T has holes, + * use an auxiliary array of pointers to elements in T. + */ + j = 0; + for( i = 1; i < T_size; i <<= 1 ) + TT[j++] = T + i; + + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 ); + MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + rs_ctx->rsm->state = ecp_rsm_pre_add; + +add: +#endif /* * Compute the remaining ones using the minimal number of additions * Be careful to update T[2^l] only after using it! */ - k = 0; - for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 ) + MBEDTLS_ECP_BUDGET( ( T_size - 1 ) * MBEDTLS_ECP_OPS_ADD ); + + for( i = 1; i < T_size; i <<= 1 ) { j = i; while( j-- ) - { MBEDTLS_MPI_CHK( ecp_add_mixed( grp, &T[i + j], &T[j], &T[i] ) ); - TT[k++] = &T[i + j]; - } } - MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + rs_ctx->rsm->state = ecp_rsm_pre_norm_add; + +norm_add: +#endif + /* + * Normalize final elements in T. Even though there are no holes now, we + * still need the auxiliary array for homogeneity with the previous + * call. Also, skip T[0] which is already normalised, being a copy of P. + */ + for( j = 0; j + 1 < T_size; j++ ) + TT[j] = T + j + 1; + + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 ); + + MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) ); cleanup: +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL && + ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + { + if( rs_ctx->rsm->state == ecp_rsm_pre_dbl ) + rs_ctx->rsm->i = j; + } +#endif return( ret ); } /* * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ] + * + * See ecp_comb_recode_core() for background */ static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, - const mbedtls_ecp_point T[], unsigned char t_len, + const mbedtls_ecp_point T[], unsigned char T_size, unsigned char i ) { int ret; @@ -1290,7 +1657,7 @@ static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, ii = ( i & 0x7Fu ) >> 1; /* Read the whole table to thwart cache-based timing attacks */ - for( j = 0; j < t_len; j++ ) + for( j = 0; j < T_size; j++ ) { MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->X, &T[j].X, j == ii ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->Y, &T[j].Y, j == ii ) ); @@ -1310,10 +1677,11 @@ static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * Cost: d A + d D + 1 R */ static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R, - const mbedtls_ecp_point T[], unsigned char t_len, + const mbedtls_ecp_point T[], unsigned char T_size, const unsigned char x[], size_t d, int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) + void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret; mbedtls_ecp_point Txi; @@ -1321,17 +1689,42 @@ static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R mbedtls_ecp_point_init( &Txi ); - /* Start with a non-zero point and randomize its coordinates */ - i = d; - MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, t_len, x[i] ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) ); - if( f_rng != 0 ) - MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) ); +#if !defined(MBEDTLS_ECP_RESTARTABLE) + (void) rs_ctx; +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL && + rs_ctx->rsm->state != ecp_rsm_comb_core ) + { + rs_ctx->rsm->i = 0; + rs_ctx->rsm->state = ecp_rsm_comb_core; + } - while( i-- != 0 ) + /* new 'if' instead of nested for the sake of the 'else' branch */ + if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0 ) { + /* restore current index (R already pointing to rs_ctx->rsm->R) */ + i = rs_ctx->rsm->i; + } + else +#endif + { + /* Start with a non-zero point and randomize its coordinates */ + i = d; + MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, T_size, x[i] ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) ); + if( f_rng != 0 ) + MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) ); + } + + while( i != 0 ) + { + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD ); + --i; + MBEDTLS_MPI_CHK( ecp_double_jac( grp, R, R ) ); - MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, t_len, x[i] ) ); + MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, T_size, x[i] ) ); MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, R, &Txi ) ); } @@ -1339,32 +1732,130 @@ static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R mbedtls_ecp_point_free( &Txi ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL && + ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + { + rs_ctx->rsm->i = i; + /* no need to save R, already pointing to rs_ctx->rsm->R */ + } +#endif + return( ret ); } /* - * Multiplication using the comb method, - * for curves in short Weierstrass form - */ -static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, - const mbedtls_mpi *m, const mbedtls_ecp_point *P, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) + * Recode the scalar to get constant-time comb multiplication + * + * As the actual scalar recoding needs an odd scalar as a starting point, + * this wrapper ensures that by replacing m by N - m if necessary, and + * informs the caller that the result of multiplication will be negated. + * + * This works because we only support large prime order for Short Weierstrass + * curves, so N is always odd hence either m or N - m is. + * + * See ecp_comb_recode_core() for background. + */ +static int ecp_comb_recode_scalar( const mbedtls_ecp_group *grp, + const mbedtls_mpi *m, + unsigned char k[COMB_MAX_D + 1], + size_t d, + unsigned char w, + unsigned char *parity_trick ) { int ret; - unsigned char w, m_is_odd, p_eq_g, pre_len, i; - size_t d; - unsigned char k[COMB_MAX_D + 1]; - mbedtls_ecp_point *T; mbedtls_mpi M, mm; mbedtls_mpi_init( &M ); mbedtls_mpi_init( &mm ); - /* we need N to be odd to trnaform m in an odd number, check now */ + /* N is always odd (see above), just make extra sure */ if( mbedtls_mpi_get_bit( &grp->N, 0 ) != 1 ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); + /* do we need the parity trick? */ + *parity_trick = ( mbedtls_mpi_get_bit( m, 0 ) == 0 ); + + /* execute parity fix in constant time */ + MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, *parity_trick ) ); + + /* actual scalar recoding */ + ecp_comb_recode_core( k, d, w, &M ); + +cleanup: + mbedtls_mpi_free( &mm ); + mbedtls_mpi_free( &M ); + + return( ret ); +} + +/* + * Perform comb multiplication (for short Weierstrass curves) + * once the auxiliary table has been pre-computed. + * + * Scalar recoding may use a parity trick that makes us compute -m * P, + * if that is the case we'll need to recover m * P at the end. + */ +static int ecp_mul_comb_after_precomp( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, + const mbedtls_mpi *m, + const mbedtls_ecp_point *T, + unsigned char T_size, + unsigned char w, + size_t d, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) +{ + int ret; + unsigned char parity_trick; + unsigned char k[COMB_MAX_D + 1]; + mbedtls_ecp_point *RR = R; + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + { + RR = &rs_ctx->rsm->R; + + if( rs_ctx->rsm->state == ecp_rsm_final_norm ) + goto final_norm; + } +#endif + + MBEDTLS_MPI_CHK( ecp_comb_recode_scalar( grp, m, k, d, w, + &parity_trick ) ); + MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, RR, T, T_size, k, d, + f_rng, p_rng, rs_ctx ) ); + MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, RR, parity_trick ) ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + rs_ctx->rsm->state = ecp_rsm_final_norm; + +final_norm: +#endif + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); + MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, RR ) ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, RR ) ); +#endif + +cleanup: + return( ret ); +} + +/* + * Pick window size based on curve size and whether we optimize for base point + */ +static unsigned char ecp_pick_window_size( const mbedtls_ecp_group *grp, + unsigned char p_eq_g ) +{ + unsigned char w; + /* * Minimize the number of multiplications, that is minimize * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w ) @@ -1377,14 +1868,8 @@ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * Just adding one avoids upping the cost of the first mul too much, * and the memory cost too. */ -#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1 - p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 && - mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 ); if( p_eq_g ) w++; -#else - p_eq_g = 0; -#endif /* * Make sure w is within bounds. @@ -1395,75 +1880,140 @@ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, if( w >= grp->nbits ) w = 2; - /* Other sizes that depend on w */ - pre_len = 1U << ( w - 1 ); + return( w ); +} + +/* + * Multiplication using the comb method - for curves in short Weierstrass form + * + * This function is mainly responsible for administrative work: + * - managing the restart context if enabled + * - managing the table of precomputed points (passed between the below two + * functions): allocation, computation, ownership tranfer, freeing. + * + * It delegates the actual arithmetic work to: + * ecp_precompute_comb() and ecp_mul_comb_with_precomp() + * + * See comments on ecp_comb_recode_core() regarding the computation strategy. + */ +static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) +{ + int ret; + unsigned char w, p_eq_g, i; + size_t d; + unsigned char T_size, T_ok; + mbedtls_ecp_point *T; + + ECP_RS_ENTER( rsm ); + + /* Is P the base point ? */ +#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1 + p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 && + mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 ); +#else + p_eq_g = 0; +#endif + + /* Pick window size and deduce related sizes */ + w = ecp_pick_window_size( grp, p_eq_g ); + T_size = 1U << ( w - 1 ); d = ( grp->nbits + w - 1 ) / w; - /* - * Prepare precomputed points: if P == G we want to - * use grp->T if already initialized, or initialize it. - */ - T = p_eq_g ? grp->T : NULL; + /* Pre-computed table: do we have it already for the base point? */ + if( p_eq_g && grp->T != NULL ) + { + /* second pointer to the same table, will be deleted on exit */ + T = grp->T; + T_ok = 1; + } + else +#if defined(MBEDTLS_ECP_RESTARTABLE) + /* Pre-computed table: do we have one in progress? complete? */ + if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->T != NULL ) + { + /* transfer ownership of T from rsm to local function */ + T = rs_ctx->rsm->T; + rs_ctx->rsm->T = NULL; + rs_ctx->rsm->T_size = 0; - if( T == NULL ) + /* This effectively jumps to the call to mul_comb_after_precomp() */ + T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core; + } + else +#endif + /* Allocate table if we didn't have any */ { - T = mbedtls_calloc( pre_len, sizeof( mbedtls_ecp_point ) ); + T = mbedtls_calloc( T_size, sizeof( mbedtls_ecp_point ) ); if( T == NULL ) { ret = MBEDTLS_ERR_ECP_ALLOC_FAILED; goto cleanup; } - MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d ) ); + for( i = 0; i < T_size; i++ ) + mbedtls_ecp_point_init( &T[i] ); + + T_ok = 0; + } + + /* Compute table (or finish computing it) if not done already */ + if( !T_ok ) + { + MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d, rs_ctx ) ); if( p_eq_g ) { + /* almost transfer ownership of T to the group, but keep a copy of + * the pointer to use for calling the next function more easily */ grp->T = T; - grp->T_size = pre_len; + grp->T_size = T_size; } } - /* - * Make sure M is odd (M = m or M = N - m, since N is odd) - * using the fact that m * P = - (N - m) * P - */ - m_is_odd = ( mbedtls_mpi_get_bit( m, 0 ) == 1 ); - MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, ! m_is_odd ) ); + /* Actual comb multiplication using precomputed points */ + MBEDTLS_MPI_CHK( ecp_mul_comb_after_precomp( grp, R, m, + T, T_size, w, d, + f_rng, p_rng, rs_ctx ) ); - /* - * Go for comb multiplication, R = M * P - */ - ecp_comb_fixed( k, d, w, &M ); - MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, R, T, pre_len, k, d, f_rng, p_rng ) ); +cleanup: - /* - * Now get m * P from M * P and normalize it - */ - MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, ! m_is_odd ) ); - MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) ); + /* does T belong to the group? */ + if( T == grp->T ) + T = NULL; -cleanup: + /* does T belong to the restart context? */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T != NULL ) + { + /* transfer ownership of T from local function to rsm */ + rs_ctx->rsm->T_size = T_size; + rs_ctx->rsm->T = T; + T = NULL; + } +#endif - /* There are two cases where T is not stored in grp: - * - P != G - * - An intermediate operation failed before setting grp->T - * In either case, T must be freed. - */ - if( T != NULL && T != grp->T ) + /* did T belong to us? then let's destroy it! */ + if( T != NULL ) { - for( i = 0; i < pre_len; i++ ) + for( i = 0; i < T_size; i++ ) mbedtls_ecp_point_free( &T[i] ); mbedtls_free( T ); } - mbedtls_mpi_free( &M ); - mbedtls_mpi_free( &mm ); - + /* don't free R while in progress in case R == P */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) +#endif + /* prevent caller from using invalid value */ if( ret != 0 ) mbedtls_ecp_point_free( R ); + ECP_RS_LEAVE( rsm ); + return( ret ); } @@ -1487,10 +2037,8 @@ static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P int ret; #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_normalize_mxz( grp, P ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_normalize_mxz( grp, P ) ); #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) ); @@ -1518,10 +2066,8 @@ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P int count = 0; #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng ); #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */ p_size = ( grp->pbits + 7 ) / 8; @@ -1573,10 +2119,8 @@ static int ecp_double_add_mxz( const mbedtls_ecp_group *grp, mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB; #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) - if ( mbedtls_internal_ecp_grp_capable( grp ) ) - { - return mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ); - } + if( mbedtls_internal_ecp_grp_capable( grp ) ) + return( mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ) ); #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */ mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B ); @@ -1673,54 +2217,77 @@ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, #endif /* ECP_MONTGOMERY */ /* - * Multiplication R = m * P + * Restartable multiplication R = m * P */ -int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, +int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, - int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; #if defined(MBEDTLS_ECP_INTERNAL_ALT) char is_grp_capable = 0; #endif - /* Common sanity checks */ - if( mbedtls_mpi_cmp_int( &P->Z, 1 ) != 0 ) - return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); - - if( ( ret = mbedtls_ecp_check_privkey( grp, m ) ) != 0 || - ( ret = mbedtls_ecp_check_pubkey( grp, P ) ) != 0 ) - return( ret ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + /* reset ops count for this call if top-level */ + if( rs_ctx != NULL && rs_ctx->depth++ == 0 ) + rs_ctx->ops_done = 0; +#endif #if defined(MBEDTLS_ECP_INTERNAL_ALT) - if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) - { + if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) ) MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); +#endif /* MBEDTLS_ECP_INTERNAL_ALT */ + +#if defined(MBEDTLS_ECP_RESTARTABLE) + /* skip argument check when restarting */ + if( rs_ctx == NULL || rs_ctx->rsm == NULL ) +#endif + { + /* check_privkey is free */ + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_CHK ); + + /* Common sanity checks */ + MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( grp, m ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, P ) ); } -#endif /* MBEDTLS_ECP_INTERNAL_ALT */ + ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; #if defined(ECP_MONTGOMERY) if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY ) - ret = ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ); - + MBEDTLS_MPI_CHK( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) ); #endif #if defined(ECP_SHORTWEIERSTRASS) if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS ) - ret = ecp_mul_comb( grp, R, m, P, f_rng, p_rng ); - + MBEDTLS_MPI_CHK( ecp_mul_comb( grp, R, m, P, f_rng, p_rng, rs_ctx ) ); #endif -#if defined(MBEDTLS_ECP_INTERNAL_ALT) + cleanup: - if ( is_grp_capable ) - { +#if defined(MBEDTLS_ECP_INTERNAL_ALT) + if( is_grp_capable ) mbedtls_internal_ecp_free( grp ); - } - #endif /* MBEDTLS_ECP_INTERNAL_ALT */ + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL ) + rs_ctx->depth--; +#endif + return( ret ); } +/* + * Multiplication R = m * P + */ +int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + return( mbedtls_ecp_mul_restartable( grp, R, m, P, f_rng, p_rng, NULL ) ); +} + #if defined(ECP_SHORTWEIERSTRASS) /* * Check that an affine point is valid as a public key, @@ -1778,7 +2345,8 @@ static int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_ static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, - const mbedtls_ecp_point *P ) + const mbedtls_ecp_point *P, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret; @@ -1794,7 +2362,8 @@ static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp, } else { - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, R, m, P, + NULL, NULL, rs_ctx ) ); } cleanup: @@ -1802,15 +2371,19 @@ static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp, } /* - * Linear combination + * Restartable linear combination * NOT constant-time */ -int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, +int mbedtls_ecp_muladd_restartable( + mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, - const mbedtls_mpi *n, const mbedtls_ecp_point *Q ) + const mbedtls_mpi *n, const mbedtls_ecp_point *Q, + mbedtls_ecp_restart_ctx *rs_ctx ) { int ret; mbedtls_ecp_point mP; + mbedtls_ecp_point *pmP = &mP; + mbedtls_ecp_point *pR = R; #if defined(MBEDTLS_ECP_INTERNAL_ALT) char is_grp_capable = 0; #endif @@ -1820,33 +2393,83 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, mbedtls_ecp_point_init( &mP ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, &mP, m, P ) ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R, n, Q ) ); - #if defined(MBEDTLS_ECP_INTERNAL_ALT) - if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) - { + if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) ) MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); - } - #endif /* MBEDTLS_ECP_INTERNAL_ALT */ - MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, &mP, R ) ); - MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) ); -cleanup: + ECP_RS_ENTER( ma ); -#if defined(MBEDTLS_ECP_INTERNAL_ALT) - if ( is_grp_capable ) +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ma != NULL ) { - mbedtls_internal_ecp_free( grp ); + /* redirect intermediate results to restart context */ + pmP = &rs_ctx->ma->mP; + pR = &rs_ctx->ma->R; + + /* jump to next operation */ + if( rs_ctx->ma->state == ecp_rsma_mul2 ) + goto mul2; + if( rs_ctx->ma->state == ecp_rsma_add ) + goto add; + if( rs_ctx->ma->state == ecp_rsma_norm ) + goto norm; } +#endif /* MBEDTLS_ECP_RESTARTABLE */ + + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pmP, m, P, rs_ctx ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ma != NULL ) + rs_ctx->ma->state = ecp_rsma_mul2; +mul2: +#endif + MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pR, n, Q, rs_ctx ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ma != NULL ) + rs_ctx->ma->state = ecp_rsma_add; + +add: +#endif + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_ADD ); + MBEDTLS_MPI_CHK( ecp_add_mixed( grp, pR, pmP, pR ) ); +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ma != NULL ) + rs_ctx->ma->state = ecp_rsma_norm; + +norm: +#endif + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); + MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, pR ) ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->ma != NULL ) + MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, pR ) ); +#endif + +cleanup: +#if defined(MBEDTLS_ECP_INTERNAL_ALT) + if( is_grp_capable ) + mbedtls_internal_ecp_free( grp ); #endif /* MBEDTLS_ECP_INTERNAL_ALT */ + mbedtls_ecp_point_free( &mP ); + ECP_RS_LEAVE( ma ); + return( ret ); } +/* + * Linear combination + * NOT constant-time + */ +int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + const mbedtls_mpi *n, const mbedtls_ecp_point *Q ) +{ + return( mbedtls_ecp_muladd_restartable( grp, R, m, P, n, Q, NULL ) ); +} #if defined(ECP_MONTGOMERY) /* @@ -1921,15 +2544,14 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi * } /* - * Generate a keypair with configurable base point + * Generate a private key */ -int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, - const mbedtls_ecp_point *G, - mbedtls_mpi *d, mbedtls_ecp_point *Q, +int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, + mbedtls_mpi *d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { - int ret; + int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; size_t n_size = ( grp->nbits + 7 ) / 8; #if defined(ECP_MONTGOMERY) @@ -1958,8 +2580,8 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); } } - else #endif /* ECP_MONTGOMERY */ + #if defined(ECP_SHORTWEIERSTRASS) if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS ) { @@ -1993,15 +2615,28 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ); } - else #endif /* ECP_SHORTWEIERSTRASS */ - return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); cleanup: - if( ret != 0 ) - return( ret ); + return( ret ); +} + +/* + * Generate a keypair with configurable base point + */ +int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, + const mbedtls_ecp_point *G, + mbedtls_mpi *d, mbedtls_ecp_point *Q, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) +{ + int ret; + + MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) ); - return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) ); +cleanup: + return( ret ); } /* diff --git a/features/mbedtls/src/error.c b/features/mbedtls/src/error.c index 6c88689190b..eabee9e21b7 100644 --- a/features/mbedtls/src/error.c +++ b/features/mbedtls/src/error.c @@ -165,6 +165,10 @@ #include "mbedtls/pkcs5.h" #endif +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#endif + #if defined(MBEDTLS_POLY1305_C) #include "mbedtls/poly1305.h" #endif @@ -289,6 +293,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "ECP - The buffer contains a valid signature followed by more data" ); if( use_ret == -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED) ) mbedtls_snprintf( buf, buflen, "ECP - The ECP hardware accelerator failed" ); + if( use_ret == -(MBEDTLS_ERR_ECP_IN_PROGRESS) ) + mbedtls_snprintf( buf, buflen, "ECP - Operation in progress, call again with the same parameters to continue" ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) @@ -517,6 +523,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "SSL - The asynchronous operation is not completed yet" ); if( use_ret == -(MBEDTLS_ERR_SSL_EARLY_MESSAGE) ) mbedtls_snprintf( buf, buflen, "SSL - Internal-only message signaling that a message arrived early" ); + if( use_ret == -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) ) + mbedtls_snprintf( buf, buflen, "SSL - A cryptographic operation is in progress. Try again later" ); #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) @@ -823,6 +831,13 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" ); #endif /* MBEDTLS_PADLOCK_C */ +#if defined(MBEDTLS_PLATFORM_C) + if( use_ret == -(MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED) ) + mbedtls_snprintf( buf, buflen, "PLATFORM - Hardware accelerator failed" ); + if( use_ret == -(MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED) ) + mbedtls_snprintf( buf, buflen, "PLATFORM - The requested feature is not supported by the platform" ); +#endif /* MBEDTLS_PLATFORM_C */ + #if defined(MBEDTLS_POLY1305_C) if( use_ret == -(MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA) ) mbedtls_snprintf( buf, buflen, "POLY1305 - Invalid input parameter(s)" ); diff --git a/features/mbedtls/src/gcm.c b/features/mbedtls/src/gcm.c index 57b027933dd..c486ef765d2 100644 --- a/features/mbedtls/src/gcm.c +++ b/features/mbedtls/src/gcm.c @@ -48,9 +48,8 @@ #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #include "mbedtls/aes.h" -#if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" -#else +#if !defined(MBEDTLS_PLATFORM_C) #include #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ @@ -764,7 +763,7 @@ int mbedtls_gcm_self_test( int verbose ) * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ - if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && key_len == 192 ) + if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && key_len == 192 ) { mbedtls_printf( "skipped\n" ); break; diff --git a/features/mbedtls/src/pk.c b/features/mbedtls/src/pk.c index f05b139e3f3..989ed095b2e 100644 --- a/features/mbedtls/src/pk.c +++ b/features/mbedtls/src/pk.c @@ -41,6 +41,10 @@ #include "mbedtls/ecdsa.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "mbedtls/psa_util.h" +#endif + #include #include @@ -69,6 +73,34 @@ void mbedtls_pk_free( mbedtls_pk_context *ctx ) mbedtls_platform_zeroize( ctx, sizeof( mbedtls_pk_context ) ); } +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/* + * Initialize a restart context + */ +void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx ) +{ + ctx->pk_info = NULL; + ctx->rs_ctx = NULL; +} + +/* + * Free the components of a restart context + */ +void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx ) +{ + if( ctx == NULL || ctx->pk_info == NULL || + ctx->pk_info->rs_free_func == NULL ) + { + return; + } + + ctx->pk_info->rs_free_func( ctx->rs_ctx ); + + ctx->pk_info = NULL; + ctx->rs_ctx = NULL; +} +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + /* * Get pk_info structure from type */ @@ -111,6 +143,38 @@ int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info ) return( 0 ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/* + * Initialise a PSA-wrapping context + */ +int mbedtls_pk_setup_opaque( mbedtls_pk_context *ctx, const psa_key_slot_t key ) +{ + const mbedtls_pk_info_t * const info = &mbedtls_pk_opaque_info; + psa_key_slot_t *pk_ctx; + psa_key_type_t type; + + if( ctx == NULL || ctx->pk_info != NULL ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + if( PSA_SUCCESS != psa_get_key_information( key, &type, NULL ) ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + /* Current implementation of can_do() relies on this. */ + if( ! PSA_KEY_TYPE_IS_ECC_KEYPAIR( type ) ) + return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ; + + if( ( ctx->pk_ctx = info->ctx_alloc_func() ) == NULL ) + return( MBEDTLS_ERR_PK_ALLOC_FAILED ); + + ctx->pk_info = info; + + pk_ctx = (psa_key_slot_t *) ctx->pk_ctx; + *pk_ctx = key; + + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) /* * Initialize an RSA-alt context @@ -171,17 +235,66 @@ static inline int pk_hashlen_helper( mbedtls_md_type_t md_alg, size_t *hash_len return( 0 ); } +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* - * Verify a signature + * Helper to set up a restart context if needed */ -int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, +static int pk_restart_setup( mbedtls_pk_restart_ctx *ctx, + const mbedtls_pk_info_t *info ) +{ + /* Don't do anything if already set up or invalid */ + if( ctx == NULL || ctx->pk_info != NULL ) + return( 0 ); + + /* Should never happen when we're called */ + if( info->rs_alloc_func == NULL || info->rs_free_func == NULL ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + if( ( ctx->rs_ctx = info->rs_alloc_func() ) == NULL ) + return( MBEDTLS_ERR_PK_ALLOC_FAILED ); + + ctx->pk_info = info; + + return( 0 ); +} +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +/* + * Verify a signature (restartable) + */ +int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, - const unsigned char *sig, size_t sig_len ) + const unsigned char *sig, size_t sig_len, + mbedtls_pk_restart_ctx *rs_ctx ) { if( ctx == NULL || ctx->pk_info == NULL || pk_hashlen_helper( md_alg, &hash_len ) != 0 ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /* optimization: use non-restartable version if restart disabled */ + if( rs_ctx != NULL && + mbedtls_ecp_restart_is_enabled() && + ctx->pk_info->verify_rs_func != NULL ) + { + int ret; + + if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 ) + return( ret ); + + ret = ctx->pk_info->verify_rs_func( ctx->pk_ctx, + md_alg, hash, hash_len, sig, sig_len, rs_ctx->rs_ctx ); + + if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) + mbedtls_pk_restart_free( rs_ctx ); + + return( ret ); + } +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + (void) rs_ctx; +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + if( ctx->pk_info->verify_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); @@ -189,6 +302,17 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, sig, sig_len ) ); } +/* + * Verify a signature + */ +int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len ) +{ + return( mbedtls_pk_verify_restartable( ctx, md_alg, hash, hash_len, + sig, sig_len, NULL ) ); +} + /* * Verify a signature with options */ @@ -248,17 +372,42 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options, } /* - * Make a signature + * Make a signature (restartable) */ -int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, +int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, unsigned char *sig, size_t *sig_len, - int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_pk_restart_ctx *rs_ctx ) { if( ctx == NULL || ctx->pk_info == NULL || pk_hashlen_helper( md_alg, &hash_len ) != 0 ) return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /* optimization: use non-restartable version if restart disabled */ + if( rs_ctx != NULL && + mbedtls_ecp_restart_is_enabled() && + ctx->pk_info->sign_rs_func != NULL ) + { + int ret; + + if( ( ret = pk_restart_setup( rs_ctx, ctx->pk_info ) ) != 0 ) + return( ret ); + + ret = ctx->pk_info->sign_rs_func( ctx->pk_ctx, md_alg, + hash, hash_len, sig, sig_len, f_rng, p_rng, rs_ctx->rs_ctx ); + + if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) + mbedtls_pk_restart_free( rs_ctx ); + + return( ret ); + } +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + (void) rs_ctx; +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + if( ctx->pk_info->sign_func == NULL ) return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); @@ -266,6 +415,18 @@ int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, sig, sig_len, f_rng, p_rng ) ); } +/* + * Make a signature + */ +int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + return( mbedtls_pk_sign_restartable( ctx, md_alg, hash, hash_len, + sig, sig_len, f_rng, p_rng, NULL ) ); +} + /* * Decrypt message */ @@ -308,12 +469,14 @@ int mbedtls_pk_encrypt( mbedtls_pk_context *ctx, int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv ) { if( pub == NULL || pub->pk_info == NULL || - prv == NULL || prv->pk_info == NULL || - prv->pk_info->check_pair_func == NULL ) + prv == NULL || prv->pk_info == NULL ) { return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); } + if( prv->pk_info->check_pair_func == NULL ) + return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); + if( prv->pk_info->type == MBEDTLS_PK_RSA_ALT ) { if( pub->pk_info->type != MBEDTLS_PK_RSA ) @@ -376,4 +539,65 @@ 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 private keys. + */ +int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk, + psa_key_slot_t *slot, + psa_algorithm_t hash_alg ) +{ +#if !defined(MBEDTLS_ECP_C) + return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); +#else + psa_key_slot_t key; + const mbedtls_ecp_keypair *ec; + unsigned char d[MBEDTLS_ECP_MAX_BYTES]; + size_t d_len; + psa_ecc_curve_t curve_id; + psa_key_type_t key_type; + psa_key_policy_t policy; + int ret; + + /* export the private key material in the format PSA wants */ + if( mbedtls_pk_get_type( pk ) != MBEDTLS_PK_ECKEY ) + return( MBEDTLS_ERR_PK_TYPE_MISMATCH ); + + ec = mbedtls_pk_ec( *pk ); + d_len = ( ec->grp.nbits + 7 ) / 8; + if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 ) + return( ret ); + + curve_id = mbedtls_ecp_curve_info_from_grp_id( ec->grp.id )->tls_id; + + /* find a free key slot */ + if( PSA_SUCCESS != mbedtls_psa_get_free_key_slot( &key ) ) + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + + /* set policy */ + psa_key_policy_init( &policy ); + psa_key_policy_set_usage( &policy, PSA_KEY_USAGE_SIGN, + PSA_ALG_ECDSA(hash_alg) ); + if( PSA_SUCCESS != psa_set_key_policy( key, &policy ) ) + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + + /* import private key in slot */ + key_type = PSA_KEY_TYPE_ECC_KEYPAIR(curve_id); + if( PSA_SUCCESS != psa_import_key( key, key_type, d, d_len ) ) + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + + /* remember slot number to be destroyed later by caller */ + *slot = key; + + /* make PK context wrap the key slot */ + mbedtls_pk_free( pk ); + mbedtls_pk_init( pk ); + + return( mbedtls_pk_setup_opaque( pk, key ) ); +#endif /* MBEDTLS_ECP_C */ +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_PK_C */ diff --git a/features/mbedtls/src/pk_wrap.c b/features/mbedtls/src/pk_wrap.c index 2c7d2d79b82..6aacba856d5 100644 --- a/features/mbedtls/src/pk_wrap.c +++ b/features/mbedtls/src/pk_wrap.c @@ -41,10 +41,20 @@ #include "mbedtls/ecdsa.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "mbedtls/asn1write.h" +#endif + #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) #include "mbedtls/platform_util.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#include "mbedtls/psa_util.h" +#include "mbedtls/asn1.h" +#endif + #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else @@ -190,11 +200,19 @@ const mbedtls_pk_info_t mbedtls_rsa_info = { rsa_can_do, rsa_verify_wrap, rsa_sign_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif rsa_decrypt_wrap, rsa_encrypt_wrap, rsa_check_pair_wrap, rsa_alloc_wrap, rsa_free_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif rsa_debug, }; #endif /* MBEDTLS_RSA_C */ @@ -262,6 +280,110 @@ static int eckey_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, return( ret ); } +#if defined(MBEDTLS_ECP_RESTARTABLE) +/* Forward declarations */ +static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + void *rs_ctx ); + +static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + void *rs_ctx ); + +/* + * Restart context for ECDSA operations with ECKEY context + * + * We need to store an actual ECDSA context, as we need to pass the same to + * the underlying ecdsa function, so we can't create it on the fly every time. + */ +typedef struct +{ + mbedtls_ecdsa_restart_ctx ecdsa_rs; + mbedtls_ecdsa_context ecdsa_ctx; +} eckey_restart_ctx; + +static void *eckey_rs_alloc( void ) +{ + eckey_restart_ctx *rs_ctx; + + void *ctx = mbedtls_calloc( 1, sizeof( eckey_restart_ctx ) ); + + if( ctx != NULL ) + { + rs_ctx = ctx; + mbedtls_ecdsa_restart_init( &rs_ctx->ecdsa_rs ); + mbedtls_ecdsa_init( &rs_ctx->ecdsa_ctx ); + } + + return( ctx ); +} + +static void eckey_rs_free( void *ctx ) +{ + eckey_restart_ctx *rs_ctx; + + if( ctx == NULL) + return; + + rs_ctx = ctx; + mbedtls_ecdsa_restart_free( &rs_ctx->ecdsa_rs ); + mbedtls_ecdsa_free( &rs_ctx->ecdsa_ctx ); + + mbedtls_free( ctx ); +} + +static int eckey_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + void *rs_ctx ) +{ + int ret; + eckey_restart_ctx *rs = rs_ctx; + + /* Should never happen */ + if( rs == NULL ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + /* set up our own sub-context if needed (that is, on first run) */ + if( rs->ecdsa_ctx.grp.pbits == 0 ) + MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) ); + + MBEDTLS_MPI_CHK( ecdsa_verify_rs_wrap( &rs->ecdsa_ctx, + md_alg, hash, hash_len, + sig, sig_len, &rs->ecdsa_rs ) ); + +cleanup: + return( ret ); +} + +static int eckey_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + void *rs_ctx ) +{ + int ret; + eckey_restart_ctx *rs = rs_ctx; + + /* Should never happen */ + if( rs == NULL ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + /* set up our own sub-context if needed (that is, on first run) */ + if( rs->ecdsa_ctx.grp.pbits == 0 ) + MBEDTLS_MPI_CHK( mbedtls_ecdsa_from_keypair( &rs->ecdsa_ctx, ctx ) ); + + MBEDTLS_MPI_CHK( ecdsa_sign_rs_wrap( &rs->ecdsa_ctx, md_alg, + hash, hash_len, sig, sig_len, + f_rng, p_rng, &rs->ecdsa_rs ) ); + +cleanup: + return( ret ); +} +#endif /* MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_ECDSA_C */ static int eckey_check_pair( const void *pub, const void *prv ) @@ -301,15 +423,23 @@ const mbedtls_pk_info_t mbedtls_eckey_info = { #if defined(MBEDTLS_ECDSA_C) eckey_verify_wrap, eckey_sign_wrap, -#else +#if defined(MBEDTLS_ECP_RESTARTABLE) + eckey_verify_rs_wrap, + eckey_sign_rs_wrap, +#endif +#else /* MBEDTLS_ECDSA_C */ NULL, NULL, -#endif +#endif /* MBEDTLS_ECDSA_C */ NULL, NULL, eckey_check_pair, eckey_alloc_wrap, eckey_free_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + eckey_rs_alloc, + eckey_rs_free, +#endif eckey_debug, }; @@ -329,11 +459,19 @@ const mbedtls_pk_info_t mbedtls_eckeydh_info = { eckeydh_can_do, NULL, NULL, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif NULL, NULL, eckey_check_pair, eckey_alloc_wrap, /* Same underlying key structure */ eckey_free_wrap, /* Same underlying key structure */ +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif eckey_debug, /* Same underlying key structure */ }; #endif /* MBEDTLS_ECP_C */ @@ -344,6 +482,154 @@ static int ecdsa_can_do( mbedtls_pk_type_t type ) return( type == MBEDTLS_PK_ECDSA ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/* + * An ASN.1 encoded signature is a sequence of two ASN.1 integers. Parse one of + * those integers and convert it to the fixed-length encoding expected by PSA. + */ +static int extract_ecdsa_sig_int( unsigned char **from, const unsigned char *end, + unsigned char *to, size_t to_len ) +{ + int ret; + size_t unpadded_len, padding_len; + + if( ( ret = mbedtls_asn1_get_tag( from, end, &unpadded_len, + MBEDTLS_ASN1_INTEGER ) ) != 0 ) + { + return( ret ); + } + + while( unpadded_len > 0 && **from == 0x00 ) + { + ( *from )++; + unpadded_len--; + } + + if( unpadded_len > to_len || unpadded_len == 0 ) + return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); + + padding_len = to_len - unpadded_len; + memset( to, 0x00, padding_len ); + memcpy( to + padding_len, *from, unpadded_len ); + ( *from ) += unpadded_len; + + return( 0 ); +} + +/* + * Convert a signature from an ASN.1 sequence of two integers + * to a raw {r,s} buffer. Note: the provided sig buffer must be at least + * twice as big as int_size. + */ +static int extract_ecdsa_sig( unsigned char **p, const unsigned char *end, + unsigned char *sig, size_t int_size ) +{ + int ret; + size_t tmp_size; + + if( ( ret = mbedtls_asn1_get_tag( p, end, &tmp_size, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) + return( ret ); + + /* Extract r */ + if( ( ret = extract_ecdsa_sig_int( p, end, sig, int_size ) ) != 0 ) + return( ret ); + /* Extract s */ + if( ( ret = extract_ecdsa_sig_int( p, end, sig + int_size, int_size ) ) != 0 ) + return( ret ); + + return( 0 ); +} + +static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len ) +{ + int ret; + psa_key_slot_t key_slot; + psa_key_policy_t policy; + psa_key_type_t psa_type; + mbedtls_pk_context key; + int key_len; + /* see ECP_PUB_DER_MAX_BYTES in pkwrite.c */ + unsigned char buf[30 + 2 * MBEDTLS_ECP_MAX_BYTES]; + unsigned char *p = (unsigned char*) sig; + mbedtls_pk_info_t pk_info = mbedtls_eckey_info; + psa_algorithm_t psa_sig_md, psa_md; + psa_ecc_curve_t curve = mbedtls_psa_translate_ecc_group( + ( (mbedtls_ecdsa_context *) ctx )->grp.id ); + const size_t signature_part_size = ( ( (mbedtls_ecdsa_context *) ctx )->grp.nbits + 7 ) / 8; + + if( curve == 0 ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + /* mbedlts_pk_write_pubkey_der() expects a full PK context, + * re-construct one to make it happy */ + key.pk_info = &pk_info; + key.pk_ctx = ctx; + key_len = mbedtls_pk_write_pubkey_der( &key, buf, sizeof( buf ) ); + if( key_len <= 0 ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + if( ( ret = mbedtls_psa_get_free_key_slot( &key_slot ) ) != PSA_SUCCESS ) + return( mbedtls_psa_err_translate_pk( ret ) ); + + psa_md = mbedtls_psa_translate_md( md_alg ); + if( psa_md == 0 ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + psa_sig_md = PSA_ALG_ECDSA( psa_md ); + psa_type = PSA_KEY_TYPE_ECC_PUBLIC_KEY( curve ); + + psa_key_policy_init( &policy ); + psa_key_policy_set_usage( &policy, PSA_KEY_USAGE_VERIFY, psa_sig_md ); + if( ( ret = psa_set_key_policy( key_slot, &policy ) ) != PSA_SUCCESS ) + { + ret = mbedtls_psa_err_translate_pk( ret ); + goto cleanup; + } + + if( psa_import_key( key_slot, psa_type, buf + sizeof( buf ) - key_len, key_len ) + != PSA_SUCCESS ) + { + ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA; + goto cleanup; + } + + /* We don't need the exported key anymore and can + * reuse its buffer for signature extraction. */ + if( 2 * signature_part_size > sizeof( buf ) ) + { + ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA; + goto cleanup; + } + + if( ( ret = extract_ecdsa_sig( &p, sig + sig_len, buf, + signature_part_size ) ) != 0 ) + { + goto cleanup; + } + + if( psa_asymmetric_verify( key_slot, psa_sig_md, + hash, hash_len, + buf, 2 * signature_part_size ) + != PSA_SUCCESS ) + { + ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; + goto cleanup; + } + + if( p != sig + sig_len ) + { + ret = MBEDTLS_ERR_PK_SIG_LEN_MISMATCH; + goto cleanup; + } + ret = 0; + +cleanup: + psa_destroy_key( key_slot ); + return( ret ); +} +#else /* MBEDTLS_USE_PSA_CRYPTO */ static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len ) @@ -359,6 +645,7 @@ static int ecdsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, return( ret ); } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hash_len, @@ -369,6 +656,40 @@ static int ecdsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng ) ); } +#if defined(MBEDTLS_ECP_RESTARTABLE) +static int ecdsa_verify_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + void *rs_ctx ) +{ + int ret; + ((void) md_alg); + + ret = mbedtls_ecdsa_read_signature_restartable( + (mbedtls_ecdsa_context *) ctx, + hash, hash_len, sig, sig_len, + (mbedtls_ecdsa_restart_ctx *) rs_ctx ); + + if( ret == MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH ) + return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); + + return( ret ); +} + +static int ecdsa_sign_rs_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + void *rs_ctx ) +{ + return( mbedtls_ecdsa_write_signature_restartable( + (mbedtls_ecdsa_context *) ctx, + md_alg, hash, hash_len, sig, sig_len, f_rng, p_rng, + (mbedtls_ecdsa_restart_ctx *) rs_ctx ) ); + +} +#endif /* MBEDTLS_ECP_RESTARTABLE */ + static void *ecdsa_alloc_wrap( void ) { void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_context ) ); @@ -385,6 +706,24 @@ static void ecdsa_free_wrap( void *ctx ) mbedtls_free( ctx ); } +#if defined(MBEDTLS_ECP_RESTARTABLE) +static void *ecdsa_rs_alloc( void ) +{ + void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ecdsa_restart_ctx ) ); + + if( ctx != NULL ) + mbedtls_ecdsa_restart_init( ctx ); + + return( ctx ); +} + +static void ecdsa_rs_free( void *ctx ) +{ + mbedtls_ecdsa_restart_free( ctx ); + mbedtls_free( ctx ); +} +#endif /* MBEDTLS_ECP_RESTARTABLE */ + const mbedtls_pk_info_t mbedtls_ecdsa_info = { MBEDTLS_PK_ECDSA, "ECDSA", @@ -392,11 +731,19 @@ const mbedtls_pk_info_t mbedtls_ecdsa_info = { ecdsa_can_do, ecdsa_verify_wrap, ecdsa_sign_wrap, +#if defined(MBEDTLS_ECP_RESTARTABLE) + ecdsa_verify_rs_wrap, + ecdsa_sign_rs_wrap, +#endif NULL, NULL, eckey_check_pair, /* Compatible key structures */ ecdsa_alloc_wrap, ecdsa_free_wrap, +#if defined(MBEDTLS_ECP_RESTARTABLE) + ecdsa_rs_alloc, + ecdsa_rs_free, +#endif eckey_debug, /* Compatible key structures */ }; #endif /* MBEDTLS_ECDSA_C */ @@ -506,6 +853,10 @@ const mbedtls_pk_info_t mbedtls_rsa_alt_info = { rsa_alt_can_do, NULL, rsa_alt_sign_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif rsa_alt_decrypt_wrap, NULL, #if defined(MBEDTLS_RSA_C) @@ -515,9 +866,191 @@ const mbedtls_pk_info_t mbedtls_rsa_alt_info = { #endif rsa_alt_alloc_wrap, rsa_alt_free_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, + NULL, +#endif NULL, }; #endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ +#if defined(MBEDTLS_USE_PSA_CRYPTO) + +static void *pk_opaque_alloc_wrap( void ) +{ + void *ctx = mbedtls_calloc( 1, sizeof( psa_key_slot_t ) ); + + /* no _init() function to call, an calloc() already zeroized */ + + return( ctx ); +} + +static void pk_opaque_free_wrap( void *ctx ) +{ + mbedtls_platform_zeroize( ctx, sizeof( psa_key_slot_t ) ); + mbedtls_free( ctx ); +} + +static size_t pk_opaque_get_bitlen( const void *ctx ) +{ + const psa_key_slot_t *key = (const psa_key_slot_t *) ctx; + size_t bits; + + if( PSA_SUCCESS != psa_get_key_information( *key, NULL, &bits ) ) + return( 0 ); + + return( bits ); +} + +static int pk_opaque_can_do( mbedtls_pk_type_t type ) +{ + /* For now opaque PSA keys can only wrap ECC keypairs, + * as checked by setup_psa(). + * Also, ECKEY_DH does not really make sense with the current API. */ + return( type == MBEDTLS_PK_ECKEY || + type == MBEDTLS_PK_ECDSA ); +} + +/* + * Simultaneously convert and move raw MPI from the beginning of a buffer + * to an ASN.1 MPI at the end of the buffer. + * See also mbedtls_asn1_write_mpi(). + * + * p: pointer to the end of the output buffer + * start: start of the output buffer, and also of the mpi to write at the end + * n_len: length of the mpi to read from start + */ +static int asn1_write_mpibuf( unsigned char **p, unsigned char *start, + size_t n_len ) +{ + int ret; + size_t len = 0; + + if( (size_t)( *p - start ) < n_len ) + return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); + + len = n_len; + *p -= len; + memmove( *p, start, len ); + + /* ASN.1 DER encoding requires minimal length, so skip leading 0s. + * Neither r nor s should be 0, but as a failsafe measure, still detect + * that rather than overflowing the buffer in case of a PSA error. */ + while( len > 0 && **p == 0x00 ) + { + ++(*p); + --len; + } + + /* this is only reached if the signature was invalid */ + if( len == 0 ) + return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); + + /* if the msb is 1, ASN.1 requires that we prepend a 0. + * Neither r nor s can be 0, so we can assume len > 0 at all times. */ + if( **p & 0x80 ) + { + if( *p - start < 1 ) + return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); + + *--(*p) = 0x00; + len += 1; + } + + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, + MBEDTLS_ASN1_INTEGER ) ); + + return( (int) len ); +} + +/* Transcode signature from PSA format to ASN.1 sequence. + * See ecdsa_signature_to_asn1 in ecdsa.c, but with byte buffers instead of + * MPIs, and in-place. + * + * [in/out] sig: the signature pre- and post-transcoding + * [in/out] sig_len: signature length pre- and post-transcoding + * [int] buf_len: the available size the in/out buffer + */ +static int pk_ecdsa_sig_asn1_from_psa( unsigned char *sig, size_t *sig_len, + size_t buf_len ) +{ + int ret; + size_t len = 0; + const size_t rs_len = *sig_len / 2; + unsigned char *p = sig + buf_len; + + MBEDTLS_ASN1_CHK_ADD( len, asn1_write_mpibuf( &p, sig + rs_len, rs_len ) ); + MBEDTLS_ASN1_CHK_ADD( len, asn1_write_mpibuf( &p, sig, rs_len ) ); + + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, sig, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, sig, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); + + memmove( sig, p, len ); + *sig_len = len; + + return( 0 ); +} + +static int pk_opaque_sign_wrap( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + const psa_key_slot_t *key = (const psa_key_slot_t *) ctx; + psa_algorithm_t alg = PSA_ALG_ECDSA( mbedtls_psa_translate_md( md_alg ) ); + size_t bits, buf_len; + psa_status_t status; + + /* PSA has its own RNG */ + (void) f_rng; + (void) p_rng; + + /* PSA needs an output buffer of known size, but our API doesn't provide + * that information. Assume that the buffer is large enough for a + * maximal-length signature with that key (otherwise the application is + * buggy anyway). */ + status = psa_get_key_information( *key, NULL, &bits ); + if( status != PSA_SUCCESS ) + return( mbedtls_psa_err_translate_pk( status ) ); + + buf_len = MBEDTLS_ECDSA_MAX_SIG_LEN( bits ); + + /* make the signature */ + status = psa_asymmetric_sign( *key, alg, hash, hash_len, + sig, buf_len, sig_len ); + if( status != PSA_SUCCESS ) + return( mbedtls_psa_err_translate_pk( status ) ); + + /* transcode it to ASN.1 sequence */ + return( pk_ecdsa_sig_asn1_from_psa( sig, sig_len, buf_len ) ); +} + +const mbedtls_pk_info_t mbedtls_pk_opaque_info = { + MBEDTLS_PK_OPAQUE, + "Opaque", + pk_opaque_get_bitlen, + pk_opaque_can_do, + NULL, /* verify - will be done later */ + pk_opaque_sign_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, /* restartable verify - not relevant */ + NULL, /* restartable sign - not relevant */ +#endif + NULL, /* decrypt - will be done later */ + NULL, /* encrypt - will be done later */ + NULL, /* check_pair - could be done later or left NULL */ + pk_opaque_alloc_wrap, + pk_opaque_free_wrap, +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + NULL, /* restart alloc - not relevant */ + NULL, /* restart free - not relevant */ +#endif + NULL, /* debug - could be done later, or even left NULL */ +}; + +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + #endif /* MBEDTLS_PK_C */ diff --git a/features/mbedtls/src/pkparse.c b/features/mbedtls/src/pkparse.c index d6ac987e231..86d9fb004f2 100644 --- a/features/mbedtls/src/pkparse.c +++ b/features/mbedtls/src/pkparse.c @@ -1295,6 +1295,7 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk, return( 0 ); mbedtls_pk_free( pk ); + mbedtls_pk_init( pk ); if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH ) { @@ -1306,39 +1307,42 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk, return( 0 ); mbedtls_pk_free( pk ); + mbedtls_pk_init( pk ); #if defined(MBEDTLS_RSA_C) pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ); - if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || - ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), - key, keylen ) ) != 0 ) - { - mbedtls_pk_free( pk ); - } - else + if( mbedtls_pk_setup( pk, pk_info ) == 0 && + pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), key, keylen ) == 0 ) { return( 0 ); } + mbedtls_pk_free( pk ); + mbedtls_pk_init( pk ); #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) - pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ); - if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || - ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), - key, keylen ) ) != 0 ) - { - mbedtls_pk_free( pk ); - } - else + if( mbedtls_pk_setup( pk, pk_info ) == 0 && + pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), + key, keylen ) == 0 ) { return( 0 ); } - + mbedtls_pk_free( pk ); #endif /* MBEDTLS_ECP_C */ + /* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't, + * it is ok to leave the PK context initialized but not + * freed: It is the caller's responsibility to call pk_init() + * before calling this function, and to call pk_free() + * when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C + * isn't, this leads to mbedtls_pk_free() being called + * twice, once here and once by the caller, but this is + * also ok and in line with the mbedtls_pk_free() calls + * on failed PEM parsing attempts. */ + return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); } diff --git a/features/mbedtls/src/pkwrite.c b/features/mbedtls/src/pkwrite.c index 8eabd889b55..d34714b342e 100644 --- a/features/mbedtls/src/pkwrite.c +++ b/features/mbedtls/src/pkwrite.c @@ -46,6 +46,9 @@ #include "mbedtls/pem.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else @@ -161,6 +164,28 @@ int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start, MBEDTLS_ASN1_CHK_ADD( len, pk_write_ec_pubkey( p, start, mbedtls_pk_ec( *key ) ) ); else #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_OPAQUE ) + { + size_t buffer_size; + psa_key_slot_t* key_slot = (psa_key_slot_t*) key->pk_ctx; + + if ( *p < start ) + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + + buffer_size = (size_t)( *p - start ); + if ( psa_export_public_key( *key_slot, start, buffer_size, &len ) + != PSA_SUCCESS ) + { + return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); + } + else + { + memmove( *p - len, start, len ); + } + } + else +#endif /* MBEDTLS_USE_PSA_CRYPTO */ return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); return( (int) len ); @@ -177,6 +202,10 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) ); + if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_OPAQUE ) + { + return( (int) len ); + } if( c - buf < 1 ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); diff --git a/features/mbedtls/src/platform.c b/features/mbedtls/src/platform.c index b24b2fa6521..73a6db9ebe2 100644 --- a/features/mbedtls/src/platform.c +++ b/features/mbedtls/src/platform.c @@ -30,7 +30,14 @@ #include "mbedtls/platform.h" #include "mbedtls/platform_util.h" -#if defined(MBEDTLS_PLATFORM_MEMORY) +/* The compile time configuration of memory allocation via the macros + * MBEDTLS_PLATFORM_{FREE/CALLOC}_MACRO takes precedence over the runtime + * configuration via mbedtls_platform_set_calloc_free(). So, omit everything + * related to the latter if MBEDTLS_PLATFORM_{FREE/CALLOC}_MACRO are defined. */ +#if defined(MBEDTLS_PLATFORM_MEMORY) && \ + !( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && \ + defined(MBEDTLS_PLATFORM_FREE_MACRO) ) + #if !defined(MBEDTLS_PLATFORM_STD_CALLOC) static void *platform_calloc_uninit( size_t n, size_t size ) { @@ -71,7 +78,9 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), mbedtls_free_func = free_func; return( 0 ); } -#endif /* MBEDTLS_PLATFORM_MEMORY */ +#endif /* MBEDTLS_PLATFORM_MEMORY && + !( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && + defined(MBEDTLS_PLATFORM_FREE_MACRO) ) */ #if defined(_WIN32) #include diff --git a/features/mbedtls/src/rsa.c b/features/mbedtls/src/rsa.c index 88c1cf10076..7615e1e5c3e 100644 --- a/features/mbedtls/src/rsa.c +++ b/features/mbedtls/src/rsa.c @@ -502,6 +502,7 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, { int ret; mbedtls_mpi H, G, L; + int prime_quality = 0; if( f_rng == NULL || nbits < 128 || exponent < 3 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); @@ -509,6 +510,14 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, if( nbits % 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + /* + * If the modulus is 1024 bit long or shorter, then the security strength of + * the RSA algorithm is less than or equal to 80 bits and therefore an error + * rate of 2^-80 is sufficient. + */ + if( nbits > 1024 ) + prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR; + mbedtls_mpi_init( &H ); mbedtls_mpi_init( &G ); mbedtls_mpi_init( &L ); @@ -523,11 +532,11 @@ int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, do { - MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, 0, - f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->P, nbits >> 1, + prime_quality, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, 0, - f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_gen_prime( &ctx->Q, nbits >> 1, + prime_quality, f_rng, p_rng ) ); /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &H, &ctx->P, &ctx->Q ) ); @@ -1521,7 +1530,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, size_t olen; unsigned char *p = sig; unsigned char salt[MBEDTLS_MD_MAX_SIZE]; - unsigned int slen, hlen, offset = 0; + size_t slen, min_slen, hlen, offset = 0; int ret; size_t msb; const mbedtls_md_info_t *md_info; @@ -1550,10 +1559,20 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); hlen = mbedtls_md_get_size( md_info ); - slen = hlen; - if( olen < hlen + slen + 2 ) + /* Calculate the largest possible salt length. Normally this is the hash + * length, which is the maximum length the salt can have. If there is not + * enough room, use the maximum salt length that fits. The constraint is + * that the hash length plus the salt length plus 2 bytes must be at most + * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017 + * (PKCS#1 v2.2) §9.1.1 step 3. */ + min_slen = hlen - 2; + if( olen < hlen + min_slen + 2 ) return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); + else if( olen >= hlen + hlen + 2 ) + slen = hlen; + else + slen = olen - hlen - 2; memset( sig, 0, olen ); @@ -1563,7 +1582,7 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, /* Note: EMSA-PSS encoding is over the length of N - 1 bits */ msb = mbedtls_mpi_bitlen( &ctx->N ) - 1; - p += olen - hlen * 2 - 2; + p += olen - hlen - slen - 2; *p++ = 0x01; memcpy( p, salt, slen ); p += slen; diff --git a/features/mbedtls/src/rsa_internal.c b/features/mbedtls/src/rsa_internal.c index 507009f131f..9a42d47ceba 100644 --- a/features/mbedtls/src/rsa_internal.c +++ b/features/mbedtls/src/rsa_internal.c @@ -351,15 +351,20 @@ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, */ #if defined(MBEDTLS_GENPRIME) + /* + * When generating keys, the strongest security we support aims for an error + * rate of at most 2^-100 and we are aiming for the same certainty here as + * well. + */ if( f_rng != NULL && P != NULL && - ( ret = mbedtls_mpi_is_prime( P, f_rng, p_rng ) ) != 0 ) + ( ret = mbedtls_mpi_is_prime_ext( P, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } if( f_rng != NULL && Q != NULL && - ( ret = mbedtls_mpi_is_prime( Q, f_rng, p_rng ) ) != 0 ) + ( ret = mbedtls_mpi_is_prime_ext( Q, 50, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; diff --git a/features/mbedtls/src/ssl_cli.c b/features/mbedtls/src/ssl_cli.c index 83857201150..cd25dca91de 100644 --- a/features/mbedtls/src/ssl_cli.c +++ b/features/mbedtls/src/ssl_cli.c @@ -51,6 +51,44 @@ #include "mbedtls/platform_util.h" #endif +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) +static int ssl_conf_has_static_psk( mbedtls_ssl_config const *conf ) +{ + if( conf->psk_identity == NULL || + conf->psk_identity_len == 0 ) + { + return( 0 ); + } + + if( conf->psk != NULL && conf->psk_len != 0 ) + return( 1 ); + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( conf->psk_opaque != 0 ) + return( 1 ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + + return( 0 ); +} + +#if defined(MBEDTLS_USE_PSA_CRYPTO) +static int ssl_conf_has_static_raw_psk( mbedtls_ssl_config const *conf ) +{ + if( conf->psk_identity == NULL || + conf->psk_identity_len == 0 ) + { + return( 0 ); + } + + if( conf->psk != NULL && conf->psk_len != 0 ) + return( 1 ); + + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl, unsigned char *buf, @@ -754,6 +792,15 @@ static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_inf return( 1 ); #endif + /* Don't suggest PSK-based ciphersuite if no PSK is available. */ +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && + ssl_conf_has_static_psk( ssl->conf ) == 0 ) + { + return( 1 ); + } +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + return( 0 ); } @@ -1763,6 +1810,14 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA && + ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) + { + ssl->handshake->ecrs_enabled = 1; + } +#endif + if( comp != MBEDTLS_SSL_COMPRESS_NULL #if defined(MBEDTLS_ZLIB_SUPPORT) && comp != MBEDTLS_SSL_COMPRESS_DEFLATE @@ -2068,6 +2123,10 @@ static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl, (const unsigned char **) p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; +#endif return( ret ); } @@ -2097,7 +2156,7 @@ static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, * * opaque psk_identity_hint<0..2^16-1>; */ - if( (*p) > end - 2 ) + if( end - (*p) < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); @@ -2106,7 +2165,7 @@ static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, len = (*p)[0] << 8 | (*p)[1]; *p += 2; - if( (*p) > end - len ) + if( end - (*p) < (int) len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); @@ -2349,6 +2408,14 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled && + ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing ) + { + goto start_processing; + } +#endif + if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); @@ -2386,6 +2453,12 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing; + +start_processing: +#endif p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p ); @@ -2478,6 +2551,7 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE; unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); size_t params_len = p - params; + void *rs_ctx = NULL; /* * Handle the digitally-signed structure @@ -2600,12 +2674,25 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } - if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk, - md_alg, hash, hashlen, p, sig_len ) ) != 0 ) +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + rs_ctx = &ssl->handshake->ecrs_ctx.pk; +#endif + + if( ( ret = mbedtls_pk_verify_restartable( + &ssl->session_negotiate->peer_cert->pk, + md_alg, hash, hashlen, p, sig_len, rs_ctx ) ) != 0 ) { - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) +#endif + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; +#endif return( ret ); } } @@ -2903,6 +2990,16 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) */ i = 4; +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + { + if( ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret ) + goto ecdh_calc_secret; + + mbedtls_ecdh_enable_restart( &ssl->handshake->ecdh_ctx ); + } +#endif + ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n, &ssl->out_msg[i], 1000, @@ -2910,11 +3007,26 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; +#endif return( ret ); } MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + { + ssl->handshake->ecrs_n = n; + ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret; + } + +ecdh_calc_secret: + if( ssl->handshake->ecrs_enabled ) + n = ssl->handshake->ecrs_n; +#endif if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, @@ -2922,6 +3034,10 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; +#endif return( ret ); } @@ -2938,10 +3054,12 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) /* * opaque psk_identity<0..2^16-1>; */ - if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ) + if( ssl_conf_has_static_psk( ssl->conf ) == 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) ); - return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); + /* We don't offer PSK suites if we don't have a PSK, + * and we check that the server's choice is among the + * ciphersuites we offered, so this should never happen. */ + return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } i = 4; @@ -2970,6 +3088,12 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only suites. */ + if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 ) return( ret ); } @@ -2978,6 +3102,12 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only suites. */ + if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + /* * ClientDiffieHellmanPublic public (DHM send G^X mod P) */ @@ -3008,6 +3138,12 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only suites. */ + if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + /* * ClientECDiffieHellmanPublic public; */ @@ -3029,6 +3165,17 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) && \ + defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) + if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK && + ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && + ssl_conf_has_static_raw_psk( ssl->conf ) == 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); + } + else +#endif /* MBEDTLS_USE_PSA_CRYPTO && + MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { @@ -3140,9 +3287,18 @@ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) unsigned char *hash_start = hash; mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE; unsigned int hashlen; + void *rs_ctx = NULL; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled && + ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign ) + { + goto sign; + } +#endif + if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); @@ -3174,8 +3330,15 @@ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) } /* - * Make an RSA signature of the handshake digests + * Make a signature of the handshake digests */ +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign; + +sign: +#endif + ssl->handshake->calc_verify( ssl, hash ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ @@ -3252,11 +3415,21 @@ static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } - if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen, +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled ) + rs_ctx = &ssl->handshake->ecrs_ctx.pk; +#endif + + if( ( ret = mbedtls_pk_sign_restartable( mbedtls_ssl_own_key( ssl ), + md_alg, hash_start, hashlen, ssl->out_msg + 6 + offset, &n, - ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) + ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS; +#endif return( ret ); } diff --git a/features/mbedtls/src/ssl_srv.c b/features/mbedtls/src/ssl_srv.c index 36ca0d69f9a..4d99f884ddd 100644 --- a/features/mbedtls/src/ssl_srv.c +++ b/features/mbedtls/src/ssl_srv.c @@ -149,6 +149,48 @@ static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl, } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) +static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf ) +{ + if( conf->f_psk != NULL ) + return( 1 ); + + if( conf->psk_identity_len == 0 || conf->psk_identity == NULL ) + return( 0 ); + + if( conf->psk != NULL && conf->psk_len != 0 ) + return( 1 ); + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( conf->psk_opaque != 0 ) + return( 1 ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + + return( 0 ); +} + +#if defined(MBEDTLS_USE_PSA_CRYPTO) +static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) +{ + if( ssl->conf->f_psk != NULL ) + { + /* If we've used a callback to select the PSK, + * the static configuration is irrelevant. */ + + if( ssl->handshake->psk_opaque != 0 ) + return( 1 ); + + return( 0 ); + } + + if( ssl->conf->psk_opaque != 0 ) + return( 1 ); + + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) @@ -867,9 +909,7 @@ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, /* If the ciphersuite requires a pre-shared key and we don't * have one, skip it now rather than failing later */ if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && - ssl->conf->f_psk == NULL && - ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || - ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) + ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) ); return( 0 ); @@ -3648,9 +3688,7 @@ static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned cha int ret = 0; size_t n; - if( ssl->conf->f_psk == NULL && - ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || - ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) + if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); @@ -3828,6 +3866,13 @@ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* For opaque PSKs, we perform the PSK-to-MS derivation atomatically + * and skip the intermediate PMS. */ + if( ssl_use_opaque_psk( ssl ) == 1 ) + MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); + else +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { @@ -3859,6 +3904,12 @@ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) return( ret ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only. */ + if( ssl_use_opaque_psk( ssl ) == 1 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif + if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret ); @@ -3888,6 +3939,12 @@ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) return( ret ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only. */ + if( ssl_use_opaque_psk( ssl ) == 1 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif + if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); @@ -3919,6 +3976,12 @@ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Opaque PSKs are currently only supported for PSK-only. */ + if( ssl_use_opaque_psk( ssl ) == 1 ) + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); +#endif + MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp ", &ssl->handshake->ecdh_ctx.Qp ); if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, diff --git a/features/mbedtls/src/ssl_ticket.c b/features/mbedtls/src/ssl_ticket.c index a2b304869e0..9fc690f4c65 100644 --- a/features/mbedtls/src/ssl_ticket.c +++ b/features/mbedtls/src/ssl_ticket.c @@ -54,6 +54,19 @@ void mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx ) #define MAX_KEY_BYTES 32 /* 256 bits */ +#define TICKET_KEY_NAME_BYTES 4 +#define TICKET_IV_BYTES 12 +#define TICKET_CRYPT_LEN_BYTES 2 +#define TICKET_AUTH_TAG_BYTES 16 + +#define TICKET_MIN_LEN ( TICKET_KEY_NAME_BYTES + \ + TICKET_IV_BYTES + \ + TICKET_CRYPT_LEN_BYTES + \ + TICKET_AUTH_TAG_BYTES ) +#define TICKET_ADD_DATA_LEN ( TICKET_KEY_NAME_BYTES + \ + TICKET_IV_BYTES + \ + TICKET_CRYPT_LEN_BYTES ) + /* * Generate/update a key */ @@ -97,7 +110,7 @@ static int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx ) uint32_t current_time = (uint32_t) mbedtls_time( NULL ); uint32_t key_time = ctx->keys[ctx->active].generation_time; - if( current_time > key_time && + if( current_time >= key_time && current_time - key_time < ctx->ticket_lifetime ) { return( 0 ); @@ -141,11 +154,27 @@ int mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx, if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 || - ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 ) - { +#if defined(MBEDTLS_USE_PSA_CRYPTO) + ret = mbedtls_cipher_setup_psa( &ctx->keys[0].ctx, + cipher_info, TICKET_AUTH_TAG_BYTES ); + if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) + return( ret ); + /* We don't yet expect to support all ciphers through PSA, + * so allow fallback to ordinary mbedtls_cipher_setup(). */ + if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 ) + return( ret ); + +#if defined(MBEDTLS_USE_PSA_CRYPTO) + ret = mbedtls_cipher_setup_psa( &ctx->keys[1].ctx, + cipher_info, TICKET_AUTH_TAG_BYTES ); + if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) + return( ret ); + if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + if( ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 ) return( ret ); - } if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 || ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 ) @@ -278,6 +307,7 @@ static int ssl_load_session( mbedtls_ssl_session *session, * The key_name, iv, and length of encrypted_state are the additional * authenticated data. */ + int mbedtls_ssl_ticket_write( void *p_ticket, const mbedtls_ssl_session *session, unsigned char *start, @@ -289,9 +319,9 @@ int mbedtls_ssl_ticket_write( void *p_ticket, mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = start; - unsigned char *iv = start + 4; - unsigned char *state_len_bytes = iv + 12; - unsigned char *state = state_len_bytes + 2; + unsigned char *iv = start + TICKET_KEY_NAME_BYTES; + unsigned char *state_len_bytes = iv + TICKET_IV_BYTES; + unsigned char *state = state_len_bytes + TICKET_CRYPT_LEN_BYTES; unsigned char *tag; size_t clear_len, ciph_len; @@ -302,7 +332,7 @@ int mbedtls_ssl_ticket_write( void *p_ticket, /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag, * in addition to session itself, that will be checked when writing it. */ - if( end - start < 4 + 12 + 2 + 16 ) + if( end - start < TICKET_MIN_LEN ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); #if defined(MBEDTLS_THREADING_C) @@ -317,9 +347,9 @@ int mbedtls_ssl_ticket_write( void *p_ticket, *ticket_lifetime = ctx->ticket_lifetime; - memcpy( key_name, key->name, 4 ); + memcpy( key_name, key->name, TICKET_KEY_NAME_BYTES ); - if( ( ret = ctx->f_rng( ctx->p_rng, iv, 12 ) ) != 0 ) + if( ( ret = ctx->f_rng( ctx->p_rng, iv, TICKET_IV_BYTES ) ) != 0 ) goto cleanup; /* Dump session state */ @@ -335,8 +365,11 @@ int mbedtls_ssl_ticket_write( void *p_ticket, /* Encrypt and authenticate */ tag = state + clear_len; if( ( ret = mbedtls_cipher_auth_encrypt( &key->ctx, - iv, 12, key_name, 4 + 12 + 2, - state, clear_len, state, &ciph_len, tag, 16 ) ) != 0 ) + iv, TICKET_IV_BYTES, + /* Additional data: key name, IV and length */ + key_name, TICKET_ADD_DATA_LEN, + state, clear_len, state, &ciph_len, + tag, TICKET_AUTH_TAG_BYTES ) ) != 0 ) { goto cleanup; } @@ -346,7 +379,7 @@ int mbedtls_ssl_ticket_write( void *p_ticket, goto cleanup; } - *tlen = 4 + 12 + 2 + 16 + ciph_len; + *tlen = TICKET_MIN_LEN + ciph_len; cleanup: #if defined(MBEDTLS_THREADING_C) @@ -385,17 +418,16 @@ int mbedtls_ssl_ticket_parse( void *p_ticket, mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = buf; - unsigned char *iv = buf + 4; - unsigned char *enc_len_p = iv + 12; - unsigned char *ticket = enc_len_p + 2; + unsigned char *iv = buf + TICKET_KEY_NAME_BYTES; + unsigned char *enc_len_p = iv + TICKET_IV_BYTES; + unsigned char *ticket = enc_len_p + TICKET_CRYPT_LEN_BYTES; unsigned char *tag; size_t enc_len, clear_len; if( ctx == NULL || ctx->f_rng == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - /* See mbedtls_ssl_ticket_write() */ - if( len < 4 + 12 + 2 + 16 ) + if( len < TICKET_MIN_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_THREADING_C) @@ -409,7 +441,7 @@ int mbedtls_ssl_ticket_parse( void *p_ticket, enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1]; tag = ticket + enc_len; - if( len != 4 + 12 + 2 + enc_len + 16 ) + if( len != TICKET_MIN_LEN + enc_len ) { ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; goto cleanup; @@ -425,9 +457,13 @@ int mbedtls_ssl_ticket_parse( void *p_ticket, } /* Decrypt and authenticate */ - if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx, iv, 12, - key_name, 4 + 12 + 2, ticket, enc_len, - ticket, &clear_len, tag, 16 ) ) != 0 ) + if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx, + iv, TICKET_IV_BYTES, + /* Additional data: key name, IV and length */ + key_name, TICKET_ADD_DATA_LEN, + ticket, enc_len, + ticket, &clear_len, + tag, TICKET_AUTH_TAG_BYTES ) ) != 0 ) { if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) ret = MBEDTLS_ERR_SSL_INVALID_MAC; diff --git a/features/mbedtls/src/ssl_tls.c b/features/mbedtls/src/ssl_tls.c index 8bd74db8d70..d14434af053 100644 --- a/features/mbedtls/src/ssl_tls.c +++ b/features/mbedtls/src/ssl_tls.c @@ -151,7 +151,7 @@ static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl { int ret; size_t remaining, expansion; - size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN; + size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl ); @@ -212,7 +212,10 @@ static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) * delivered) of any compliant IPv4 (and IPv6) network, and should work * on most non-IP stacks too. */ if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min ) + { ssl->handshake->mtu = 508; + MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) ); + } new_timeout = 2 * ssl->handshake->retransmit_timeout; @@ -604,9 +607,34 @@ static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char * #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && \ + defined(MBEDTLS_USE_PSA_CRYPTO) +static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) +{ + if( ssl->conf->f_psk != NULL ) + { + /* If we've used a callback to select the PSK, + * the static configuration is irrelevant. */ + if( ssl->handshake->psk_opaque != 0 ) + return( 1 ); + + return( 0 ); + } + + if( ssl->conf->psk_opaque != 0 ) + return( 1 ); + + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO && + MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) { int ret = 0; +#if defined(MBEDTLS_USE_PSA_CRYPTO) + int psa_fallthrough; +#endif /* MBEDTLS_USE_PSA_CRYPTO */ unsigned char tmp[64]; unsigned char keyblk[256]; unsigned char *key1; @@ -615,9 +643,18 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) unsigned char *mac_dec; size_t mac_key_len; size_t iv_copy_len; + size_t taglen = 0; const mbedtls_cipher_info_t *cipher_info; const mbedtls_md_info_t *md_info; + /* cf. RFC 5246, Section 8.1: + * "The master secret is always exactly 48 bytes in length." */ + size_t const master_secret_len = 48; + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + unsigned char session_hash[48]; +#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ + mbedtls_ssl_session *session = ssl->session_negotiate; mbedtls_ssl_transform *transform = ssl->transform_negotiate; mbedtls_ssl_handshake_params *handshake = ssl->handshake; @@ -697,68 +734,127 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) * TLSv1+: * master = PRF( premaster, "master secret", randbytes )[0..47] */ - if( handshake->resume == 0 ) + if( handshake->resume != 0 ) { - MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, - handshake->pmslen ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); + } + else + { + /* The label for the KDF used for key expansion. + * This is either "master secret" or "extended master secret" + * depending on whether the Extended Master Secret extension + * is used. */ + char const *lbl = "master secret"; + + /* The salt for the KDF used for key expansion. + * - If the Extended Master Secret extension is not used, + * this is ClientHello.Random + ServerHello.Random + * (see Sect. 8.1 in RFC 5246). + * - If the Extended Master Secret extension is used, + * this is the transcript of the handshake so far. + * (see Sect. 4 in RFC 7627). */ + unsigned char const *salt = handshake->randbytes; + size_t salt_len = 64; + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + const mbedtls_ssl_ciphersuite_t *ciphersuite_info = + ssl->transform_negotiate->ciphersuite_info; + mbedtls_md_type_t const md_type = ciphersuite_info->mac; +#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED ) { - unsigned char session_hash[48]; - size_t hash_len; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) ); + lbl = "extended master secret"; + salt = session_hash; ssl->handshake->calc_verify( ssl, session_hash ); - #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { #if defined(MBEDTLS_SHA512_C) - if( ssl->transform_negotiate->ciphersuite_info->mac == - MBEDTLS_MD_SHA384 ) - { - hash_len = 48; - } + if( md_type == MBEDTLS_MD_SHA384 ) + salt_len = 48; else -#endif - hash_len = 32; +#endif /* MBEDTLS_SHA512_C */ + salt_len = 32; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - hash_len = 36; + salt_len = 36; - MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len ); + MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, salt_len ); + } +#endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */ - ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, - "extended master secret", - session_hash, hash_len, - session->master, 48 ); - if( ret != 0 ) +#if defined(MBEDTLS_USE_PSA_CRYPTO) && \ + defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) + if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK && + ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && + ssl_use_opaque_psk( ssl ) == 1 ) + { + /* Perform PSK-to-MS expansion in a single step. */ + psa_status_t status; + psa_algorithm_t alg; + psa_crypto_generator_t generator = PSA_CRYPTO_GENERATOR_INIT; + psa_key_slot_t psk; + + MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) ); + + psk = ssl->conf->psk_opaque; + if( ssl->handshake->psk_opaque != 0 ) + psk = ssl->handshake->psk_opaque; + + if( md_type == MBEDTLS_MD_SHA384 ) + alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384); + else + alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256); + + status = psa_key_derivation( &generator, psk, alg, + salt, salt_len, + (unsigned char const *) lbl, + (size_t) strlen( lbl ), + master_secret_len ); + if( status != PSA_SUCCESS ) { - MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); - return( ret ); + psa_generator_abort( &generator ); + return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } + status = psa_generator_read( &generator, session->master, + master_secret_len ); + if( status != PSA_SUCCESS ) + { + psa_generator_abort( &generator ); + return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); + } + + status = psa_generator_abort( &generator ); + if( status != PSA_SUCCESS ) + return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } else #endif - ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, - "master secret", - handshake->randbytes, 64, - session->master, 48 ); - if( ret != 0 ) { - MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); - return( ret ); - } + ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, + lbl, salt, salt_len, + session->master, + master_secret_len ); + if( ret != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); + return( ret ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", + handshake->premaster, + handshake->pmslen ); - mbedtls_platform_zeroize( handshake->premaster, - sizeof(handshake->premaster) ); + mbedtls_platform_zeroize( handshake->premaster, + sizeof(handshake->premaster) ); + } } - else - MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); /* * Swap the client and server random values. @@ -807,7 +903,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) cipher_info->mode == MBEDTLS_MODE_CCM || cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) { - size_t taglen, explicit_ivlen; + size_t explicit_ivlen; transform->maclen = 0; mac_key_len = 0; @@ -1027,6 +1123,43 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) } #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) + + /* Only use PSA-based ciphers for TLS-1.2. + * That's relevant at least for TLS-1.0, where + * we assume that mbedtls_cipher_crypt() updates + * the structure field for the IV, which the PSA-based + * implementation currently doesn't. */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) + if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) + { + ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_enc, + cipher_info, taglen ); + if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret ); + return( ret ); + } + + if( ret == 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "Successfully setup PSA-based encryption cipher context" ) ); + psa_fallthrough = 0; + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record encryption - fall through to default setup." ) ); + psa_fallthrough = 1; + } + } + else + psa_fallthrough = 1; +#else + psa_fallthrough = 1; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ + + if( psa_fallthrough == 1 ) +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc, cipher_info ) ) != 0 ) { @@ -1034,6 +1167,42 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) return( ret ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) + /* Only use PSA-based ciphers for TLS-1.2. + * That's relevant at least for TLS-1.0, where + * we assume that mbedtls_cipher_crypt() updates + * the structure field for the IV, which the PSA-based + * implementation currently doesn't. */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) + if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) + { + ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_dec, + cipher_info, taglen ); + if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret ); + return( ret ); + } + + if( ret == 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "Successfully setup PSA-based decryption cipher context" ) ); + psa_fallthrough = 0; + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record decryption - fall through to default setup." ) ); + psa_fallthrough = 1; + } + } + else + psa_fallthrough = 1; +#else + psa_fallthrough = 1; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ + + if( psa_fallthrough == 1 ) +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec, cipher_info ) ) != 0 ) { @@ -2304,13 +2473,13 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl ) correct = 0; } auth_done++; - - /* - * Finally check the correct flag - */ - if( correct == 0 ) - return( MBEDTLS_ERR_SSL_INVALID_MAC ); } + + /* + * Finally check the correct flag + */ + if( correct == 0 ) + return( MBEDTLS_ERR_SSL_INVALID_MAC ); #endif /* SSL_SOME_MODES_USE_MAC */ /* Make extra sure authentication was performed, exactly once */ @@ -5429,60 +5598,16 @@ int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) return( ret ); } -int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) +/* + * Once the certificate message is read, parse it into a cert chain and + * perform basic checks, but leave actual verification to the caller + */ +static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl ) { - int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + int ret; size_t i, n; - const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; - int authmode = ssl->conf->authmode; uint8_t alert; - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); - - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) - authmode = ssl->handshake->sni_authmode; -#endif - - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - authmode == MBEDTLS_SSL_VERIFY_NONE ) - { - ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } -#endif - - if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) - { - /* mbedtls_ssl_read_record may have sent an alert already. We - let it decide whether to alert. */ - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - - ssl->state++; - #if defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_SSL_PROTO_SSL3) /* @@ -5502,10 +5627,7 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) one. The client should know what's going on, so we don't send an alert. */ ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - return( 0 ); - else - return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); + return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ @@ -5526,10 +5648,7 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) one. The client should know what's going on, so we don't send an alert. */ ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - return( 0 ); - else - return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); + return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ @@ -5679,6 +5798,94 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) } #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ + return( 0 ); +} + +int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) +{ + int ret; + const mbedtls_ssl_ciphersuite_t * const ciphersuite_info = + ssl->transform_negotiate->ciphersuite_info; +#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) + const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET + ? ssl->handshake->sni_authmode + : ssl->conf->authmode; +#else + const int authmode = ssl->conf->authmode; +#endif + void *rs_ctx = NULL; + + MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); + + if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || + ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || + ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || + ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); + ssl->state++; + return( 0 ); + } + +#if defined(MBEDTLS_SSL_SRV_C) + if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && + ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); + ssl->state++; + return( 0 ); + } + + if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && + authmode == MBEDTLS_SSL_VERIFY_NONE ) + { + ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; + MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); + + ssl->state++; + return( 0 ); + } +#endif + +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled && + ssl->handshake->ecrs_state == ssl_ecrs_crt_verify ) + { + goto crt_verify; + } +#endif + + if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) + { + /* mbedtls_ssl_read_record may have sent an alert already. We + let it decide whether to alert. */ + MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); + return( ret ); + } + + if( ( ret = ssl_parse_certificate_chain( ssl ) ) != 0 ) + { +#if defined(MBEDTLS_SSL_SRV_C) + if( ret == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE && + authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) + { + ret = 0; + } +#endif + + ssl->state++; + return( ret ); + } + +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ssl->handshake->ecrs_enabled) + ssl->handshake->ecrs_state = ssl_ecrs_crt_verify; + +crt_verify: + if( ssl->handshake->ecrs_enabled) + rs_ctx = &ssl->handshake->ecrs_ctx; +#endif + if( authmode != MBEDTLS_SSL_VERIFY_NONE ) { mbedtls_x509_crt *ca_chain; @@ -5700,19 +5907,24 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) /* * Main check: verify certificate */ - ret = mbedtls_x509_crt_verify_with_profile( + ret = mbedtls_x509_crt_verify_restartable( ssl->session_negotiate->peer_cert, ca_chain, ca_crl, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, - ssl->conf->f_vrfy, ssl->conf->p_vrfy ); + ssl->conf->f_vrfy, ssl->conf->p_vrfy, rs_ctx ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); } +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS ); +#endif + /* * Secondary checks: always done, but change 'ret' only if it was 0 */ @@ -5765,6 +5977,8 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) if( ret != 0 ) { + uint8_t alert; + /* The certificate may have been rejected for several reasons. Pick one and send the corresponding alert. Which alert to send may be a subject of debate in some cases. */ @@ -5807,6 +6021,8 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) #endif /* MBEDTLS_DEBUG_C */ } + ssl->state++; + MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); return( ret ); @@ -6584,6 +6800,10 @@ static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake ) #endif #endif +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx ); +#endif + #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET; #endif @@ -7272,23 +7492,23 @@ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) -int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, - const unsigned char *psk, size_t psk_len, - const unsigned char *psk_identity, size_t psk_identity_len ) -{ - if( psk == NULL || psk_identity == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - if( psk_len > MBEDTLS_PSK_MAX_LEN ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - /* Identity len will be encoded on two bytes */ - if( ( psk_identity_len >> 16 ) != 0 || - psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) +static void ssl_conf_remove_psk( mbedtls_ssl_config *conf ) +{ + /* Remove reference to existing PSK, if any. */ +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( conf->psk_opaque != 0 ) { - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + /* The maintenance of the PSK key slot is the + * user's responsibility. */ + conf->psk_opaque = 0; } - + /* This and the following branch should never + * be taken simultaenously as we maintain the + * invariant that raw and opaque PSKs are never + * configured simultaneously. As a safeguard, + * though, `else` is omitted here. */ +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( conf->psk != NULL ) { mbedtls_platform_zeroize( conf->psk, conf->psk_len ); @@ -7297,41 +7517,75 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, conf->psk = NULL; conf->psk_len = 0; } + + /* Remove reference to PSK identity, if any. */ if( conf->psk_identity != NULL ) { mbedtls_free( conf->psk_identity ); conf->psk_identity = NULL; conf->psk_identity_len = 0; } +} - if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL || - ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL ) +/* This function assumes that PSK identity in the SSL config is unset. + * It checks that the provided identity is well-formed and attempts + * to make a copy of it in the SSL config. + * On failure, the PSK identity in the config remains unset. */ +static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf, + unsigned char const *psk_identity, + size_t psk_identity_len ) +{ + /* Identity len will be encoded on two bytes */ + if( psk_identity == NULL || + ( psk_identity_len >> 16 ) != 0 || + psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { - mbedtls_free( conf->psk ); - mbedtls_free( conf->psk_identity ); - conf->psk = NULL; - conf->psk_identity = NULL; - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } - conf->psk_len = psk_len; - conf->psk_identity_len = psk_identity_len; + conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ); + if( conf->psk_identity == NULL ) + return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - memcpy( conf->psk, psk, conf->psk_len ); + conf->psk_identity_len = psk_identity_len; memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len ); return( 0 ); } -int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, - const unsigned char *psk, size_t psk_len ) +int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, + const unsigned char *psk, size_t psk_len, + const unsigned char *psk_identity, size_t psk_identity_len ) { - if( psk == NULL || ssl->handshake == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + int ret; + /* Remove opaque/raw PSK + PSK Identity */ + ssl_conf_remove_psk( conf ); - if( psk_len > MBEDTLS_PSK_MAX_LEN ) + /* Check and set raw PSK */ + if( psk == NULL || psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) + return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); + conf->psk_len = psk_len; + memcpy( conf->psk, psk, conf->psk_len ); + + /* Check and set PSK Identity */ + ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len ); + if( ret != 0 ) + ssl_conf_remove_psk( conf ); + return( ret ); +} + +static void ssl_remove_psk( mbedtls_ssl_context *ssl ) +{ +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( ssl->handshake->psk_opaque != 0 ) + { + ssl->handshake->psk_opaque = 0; + } + else +#endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ssl->handshake->psk != NULL ) { mbedtls_platform_zeroize( ssl->handshake->psk, @@ -7339,6 +7593,18 @@ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, mbedtls_free( ssl->handshake->psk ); ssl->handshake->psk_len = 0; } +} + +int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, + const unsigned char *psk, size_t psk_len ) +{ + if( psk == NULL || ssl->handshake == NULL ) + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + + if( psk_len > MBEDTLS_PSK_MAX_LEN ) + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + + ssl_remove_psk( ssl ); if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); @@ -7349,6 +7615,42 @@ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, return( 0 ); } +#if defined(MBEDTLS_USE_PSA_CRYPTO) +int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf, + psa_key_slot_t psk_slot, + const unsigned char *psk_identity, + size_t psk_identity_len ) +{ + int ret; + /* Clear opaque/raw PSK + PSK Identity, if present. */ + ssl_conf_remove_psk( conf ); + + /* Check and set opaque PSK */ + if( psk_slot == 0 ) + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + conf->psk_opaque = psk_slot; + + /* Check and set PSK Identity */ + ret = ssl_conf_set_psk_identity( conf, psk_identity, + psk_identity_len ); + if( ret != 0 ) + ssl_conf_remove_psk( conf ); + + return( ret ); +} + +int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl, + psa_key_slot_t psk_slot ) +{ + if( psk_slot == 0 || ssl->handshake == NULL ) + return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); + + ssl_remove_psk( ssl ); + ssl->handshake->psk_opaque = psk_slot; + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), @@ -7905,6 +8207,12 @@ size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_SSL_PROTO_DTLS) static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl ) { + /* Return unlimited mtu for client hello messages to avoid fragmentation. */ + if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && + ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO || + ssl->state == MBEDTLS_SSL_SERVER_HELLO ) ) + return ( 0 ); + if( ssl->handshake == NULL || ssl->handshake->mtu == 0 ) return( ssl->mtu ); @@ -8741,6 +9049,7 @@ static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, if( hs_buf->is_valid == 1 ) { hs->buffering.total_bytes_buffered -= hs_buf->data_len; + mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len ); mbedtls_free( hs_buf->data ); memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) ); } @@ -8825,6 +9134,10 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */ +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx ); +#endif + #if defined(MBEDTLS_SSL_PROTO_DTLS) mbedtls_free( handshake->verify_cookie ); ssl_flight_free( handshake->flight ); diff --git a/features/mbedtls/src/timing.c b/features/mbedtls/src/timing.c index 3e8139f1f9a..413d133fb6d 100644 --- a/features/mbedtls/src/timing.c +++ b/features/mbedtls/src/timing.c @@ -52,6 +52,7 @@ #include #include +#include struct _hr_time { @@ -267,18 +268,17 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int /* It's OK to use a global because alarm() is supposed to be global anyway */ static DWORD alarmMs; -static DWORD WINAPI TimerProc( LPVOID TimerContext ) +static void TimerProc( void *TimerContext ) { - ((void) TimerContext); + (void) TimerContext; Sleep( alarmMs ); mbedtls_timing_alarmed = 1; - return( TRUE ); + /* _endthread will be called implicitly on return + * That ensures execution of thread funcition's epilogue */ } void mbedtls_set_alarm( int seconds ) { - DWORD ThreadId; - if( seconds == 0 ) { /* No need to create a thread for this simple case. @@ -289,7 +289,7 @@ void mbedtls_set_alarm( int seconds ) mbedtls_timing_alarmed = 0; alarmMs = seconds * 1000; - CloseHandle( CreateThread( NULL, 0, TimerProc, NULL, 0, &ThreadId ) ); + (void) _beginthread( TimerProc, 0, NULL ); } #else /* _WIN32 && !EFIX64 && !EFI32 */ diff --git a/features/mbedtls/src/version_features.c b/features/mbedtls/src/version_features.c index 777b6034c41..e2e99490627 100644 --- a/features/mbedtls/src/version_features.c +++ b/features/mbedtls/src/version_features.c @@ -339,6 +339,9 @@ static const char *features[] = { #if defined(MBEDTLS_ECP_NIST_OPTIM) "MBEDTLS_ECP_NIST_OPTIM", #endif /* MBEDTLS_ECP_NIST_OPTIM */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + "MBEDTLS_ECP_RESTARTABLE", +#endif /* MBEDTLS_ECP_RESTARTABLE */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) "MBEDTLS_ECDSA_DETERMINISTIC", #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ @@ -510,6 +513,9 @@ static const char *features[] = { #if defined(MBEDTLS_THREADING_PTHREAD) "MBEDTLS_THREADING_PTHREAD", #endif /* MBEDTLS_THREADING_PTHREAD */ +#if defined(MBEDTLS_USE_PSA_CRYPTO) + "MBEDTLS_USE_PSA_CRYPTO", +#endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_VERSION_FEATURES) "MBEDTLS_VERSION_FEATURES", #endif /* MBEDTLS_VERSION_FEATURES */ @@ -678,6 +684,9 @@ static const char *features[] = { #if defined(MBEDTLS_POLY1305_C) "MBEDTLS_POLY1305_C", #endif /* MBEDTLS_POLY1305_C */ +#if defined(MBEDTLS_PSA_CRYPTO_C) + "MBEDTLS_PSA_CRYPTO_C", +#endif /* MBEDTLS_PSA_CRYPTO_C */ #if defined(MBEDTLS_RIPEMD160_C) "MBEDTLS_RIPEMD160_C", #endif /* MBEDTLS_RIPEMD160_C */ diff --git a/features/mbedtls/src/x509_create.c b/features/mbedtls/src/x509_create.c index df20ec8ebd7..546e8fa1a99 100644 --- a/features/mbedtls/src/x509_create.c +++ b/features/mbedtls/src/x509_create.c @@ -33,48 +33,84 @@ #include +/* Structure linking OIDs for X.509 DN AttributeTypes to their + * string representations and default string encodings used by Mbed TLS. */ typedef struct { - const char *name; - size_t name_len; - const char*oid; + const char *name; /* String representation of AttributeType, e.g. + * "CN" or "emailAddress". */ + size_t name_len; /* Length of 'name', without trailing 0 byte. */ + const char *oid; /* String representation of OID of AttributeType, + * as per RFC 5280, Appendix A.1. */ + int default_tag; /* The default character encoding used for the + * given attribute type, e.g. + * MBEDTLS_ASN1_UTF8_STRING for UTF-8. */ } x509_attr_descriptor_t; #define ADD_STRLEN( s ) s, sizeof( s ) - 1 +/* X.509 DN attributes from RFC 5280, Appendix A.1. */ static const x509_attr_descriptor_t x509_attrs[] = { - { ADD_STRLEN( "CN" ), MBEDTLS_OID_AT_CN }, - { ADD_STRLEN( "commonName" ), MBEDTLS_OID_AT_CN }, - { ADD_STRLEN( "C" ), MBEDTLS_OID_AT_COUNTRY }, - { ADD_STRLEN( "countryName" ), MBEDTLS_OID_AT_COUNTRY }, - { ADD_STRLEN( "O" ), MBEDTLS_OID_AT_ORGANIZATION }, - { ADD_STRLEN( "organizationName" ), MBEDTLS_OID_AT_ORGANIZATION }, - { ADD_STRLEN( "L" ), MBEDTLS_OID_AT_LOCALITY }, - { ADD_STRLEN( "locality" ), MBEDTLS_OID_AT_LOCALITY }, - { ADD_STRLEN( "R" ), MBEDTLS_OID_PKCS9_EMAIL }, - { ADD_STRLEN( "OU" ), MBEDTLS_OID_AT_ORG_UNIT }, - { ADD_STRLEN( "organizationalUnitName" ), MBEDTLS_OID_AT_ORG_UNIT }, - { ADD_STRLEN( "ST" ), MBEDTLS_OID_AT_STATE }, - { ADD_STRLEN( "stateOrProvinceName" ), MBEDTLS_OID_AT_STATE }, - { ADD_STRLEN( "emailAddress" ), MBEDTLS_OID_PKCS9_EMAIL }, - { ADD_STRLEN( "serialNumber" ), MBEDTLS_OID_AT_SERIAL_NUMBER }, - { ADD_STRLEN( "postalAddress" ), MBEDTLS_OID_AT_POSTAL_ADDRESS }, - { ADD_STRLEN( "postalCode" ), MBEDTLS_OID_AT_POSTAL_CODE }, - { ADD_STRLEN( "dnQualifier" ), MBEDTLS_OID_AT_DN_QUALIFIER }, - { ADD_STRLEN( "title" ), MBEDTLS_OID_AT_TITLE }, - { ADD_STRLEN( "surName" ), MBEDTLS_OID_AT_SUR_NAME }, - { ADD_STRLEN( "SN" ), MBEDTLS_OID_AT_SUR_NAME }, - { ADD_STRLEN( "givenName" ), MBEDTLS_OID_AT_GIVEN_NAME }, - { ADD_STRLEN( "GN" ), MBEDTLS_OID_AT_GIVEN_NAME }, - { ADD_STRLEN( "initials" ), MBEDTLS_OID_AT_INITIALS }, - { ADD_STRLEN( "pseudonym" ), MBEDTLS_OID_AT_PSEUDONYM }, - { ADD_STRLEN( "generationQualifier" ), MBEDTLS_OID_AT_GENERATION_QUALIFIER }, - { ADD_STRLEN( "domainComponent" ), MBEDTLS_OID_DOMAIN_COMPONENT }, - { ADD_STRLEN( "DC" ), MBEDTLS_OID_DOMAIN_COMPONENT }, - { NULL, 0, NULL } + { ADD_STRLEN( "CN" ), + MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "commonName" ), + MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "C" ), + MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "countryName" ), + MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "O" ), + MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "organizationName" ), + MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "L" ), + MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "locality" ), + MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "R" ), + MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, + { ADD_STRLEN( "OU" ), + MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "organizationalUnitName" ), + MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "ST" ), + MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "stateOrProvinceName" ), + MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "emailAddress" ), + MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING }, + { ADD_STRLEN( "serialNumber" ), + MBEDTLS_OID_AT_SERIAL_NUMBER, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "postalAddress" ), + MBEDTLS_OID_AT_POSTAL_ADDRESS, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "postalCode" ), + MBEDTLS_OID_AT_POSTAL_CODE, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "dnQualifier" ), + MBEDTLS_OID_AT_DN_QUALIFIER, MBEDTLS_ASN1_PRINTABLE_STRING }, + { ADD_STRLEN( "title" ), + MBEDTLS_OID_AT_TITLE, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "surName" ), + MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "SN" ), + MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "givenName" ), + MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "GN" ), + MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "initials" ), + MBEDTLS_OID_AT_INITIALS, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "pseudonym" ), + MBEDTLS_OID_AT_PSEUDONYM, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "generationQualifier" ), + MBEDTLS_OID_AT_GENERATION_QUALIFIER, MBEDTLS_ASN1_UTF8_STRING }, + { ADD_STRLEN( "domainComponent" ), + MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, + { ADD_STRLEN( "DC" ), + MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING }, + { NULL, 0, NULL, MBEDTLS_ASN1_NULL } }; -static const char *x509_at_oid_from_name( const char *name, size_t name_len ) +static const x509_attr_descriptor_t *x509_attr_descr_from_name( const char *name, size_t name_len ) { const x509_attr_descriptor_t *cur; @@ -83,7 +119,10 @@ static const char *x509_at_oid_from_name( const char *name, size_t name_len ) strncmp( cur->name, name, name_len ) == 0 ) break; - return( cur->oid ); + if ( cur->name == NULL ) + return( NULL ); + + return( cur ); } int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ) @@ -92,6 +131,7 @@ int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *na const char *s = name, *c = s; const char *end = s + strlen( s ); const char *oid = NULL; + const x509_attr_descriptor_t* attr_descr = NULL; int in_tag = 1; char data[MBEDTLS_X509_MAX_DN_NAME_SIZE]; char *d = data; @@ -103,12 +143,13 @@ int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *na { if( in_tag && *c == '=' ) { - if( ( oid = x509_at_oid_from_name( s, c - s ) ) == NULL ) + if( ( attr_descr = x509_attr_descr_from_name( s, c - s ) ) == NULL ) { ret = MBEDTLS_ERR_X509_UNKNOWN_OID; goto exit; } + oid = attr_descr->oid; s = c + 1; in_tag = 0; d = data; @@ -127,13 +168,19 @@ int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *na } else if( !in_tag && ( *c == ',' || c == end ) ) { - if( mbedtls_asn1_store_named_data( head, oid, strlen( oid ), - (unsigned char *) data, - d - data ) == NULL ) + mbedtls_asn1_named_data* cur = + mbedtls_asn1_store_named_data( head, oid, strlen( oid ), + (unsigned char *) data, + d - data ); + + if(cur == NULL ) { return( MBEDTLS_ERR_X509_ALLOC_FAILED ); } + // set tagType + cur->val.tag = attr_descr->default_tag; + while( c < end && *(c + 1) == ' ' ) c++; @@ -192,46 +239,40 @@ int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, * * AttributeValue ::= ANY DEFINED BY AttributeType */ -static int x509_write_name( unsigned char **p, unsigned char *start, - const char *oid, size_t oid_len, - const unsigned char *name, size_t name_len ) +static int x509_write_name( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data* cur_name) { int ret; size_t len = 0; - - // Write PrintableString for all except MBEDTLS_OID_PKCS9_EMAIL - // - if( MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_EMAIL ) == oid_len && - memcmp( oid, MBEDTLS_OID_PKCS9_EMAIL, oid_len ) == 0 ) - { - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_ia5_string( p, start, - (const char *) name, - name_len ) ); - } - else - { - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_printable_string( p, start, - (const char *) name, - name_len ) ); - } - + const char *oid = (const char*)cur_name->oid.p; + size_t oid_len = cur_name->oid.len; + const unsigned char *name = cur_name->val.p; + size_t name_len = cur_name->val.len; + + // Write correct string tag and value + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tagged_string( p, start, + cur_name->val.tag, + (const char *) name, + name_len ) ); // Write OID // - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, oid_len ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( p, start, oid, + oid_len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); return( (int) len ); } int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, - mbedtls_asn1_named_data *first ) + mbedtls_asn1_named_data *first ) { int ret; size_t len = 0; @@ -239,9 +280,7 @@ int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, while( cur != NULL ) { - MBEDTLS_ASN1_CHK_ADD( len, x509_write_name( p, start, (char *) cur->oid.p, - cur->oid.len, - cur->val.p, cur->val.len ) ); + MBEDTLS_ASN1_CHK_ADD( len, x509_write_name( p, start, cur ) ); cur = cur->next; } diff --git a/features/mbedtls/src/x509_crt.c b/features/mbedtls/src/x509_crt.c index a390f81ca01..c5b6a124898 100644 --- a/features/mbedtls/src/x509_crt.c +++ b/features/mbedtls/src/x509_crt.c @@ -43,16 +43,21 @@ #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" -#include #include #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#include "mbedtls/psa_util.h" +#endif + #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else +#include #include #define mbedtls_free free #define mbedtls_calloc calloc @@ -227,6 +232,153 @@ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile, return( -1 ); } +/* + * Like memcmp, but case-insensitive and always returns -1 if different + */ +static int x509_memcasecmp( const void *s1, const void *s2, size_t len ) +{ + size_t i; + unsigned char diff; + const unsigned char *n1 = s1, *n2 = s2; + + for( i = 0; i < len; i++ ) + { + diff = n1[i] ^ n2[i]; + + if( diff == 0 ) + continue; + + if( diff == 32 && + ( ( n1[i] >= 'a' && n1[i] <= 'z' ) || + ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) ) + { + continue; + } + + return( -1 ); + } + + return( 0 ); +} + +/* + * Return 0 if name matches wildcard, -1 otherwise + */ +static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name ) +{ + size_t i; + size_t cn_idx = 0, cn_len = strlen( cn ); + + /* We can't have a match if there is no wildcard to match */ + if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' ) + return( -1 ); + + for( i = 0; i < cn_len; ++i ) + { + if( cn[i] == '.' ) + { + cn_idx = i; + break; + } + } + + if( cn_idx == 0 ) + return( -1 ); + + if( cn_len - cn_idx == name->len - 1 && + x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 ) + { + return( 0 ); + } + + return( -1 ); +} + +/* + * Compare two X.509 strings, case-insensitive, and allowing for some encoding + * variations (but not all). + * + * Return 0 if equal, -1 otherwise. + */ +static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b ) +{ + if( a->tag == b->tag && + a->len == b->len && + memcmp( a->p, b->p, b->len ) == 0 ) + { + return( 0 ); + } + + if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && + ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && + a->len == b->len && + x509_memcasecmp( a->p, b->p, b->len ) == 0 ) + { + return( 0 ); + } + + return( -1 ); +} + +/* + * Compare two X.509 Names (aka rdnSequence). + * + * See RFC 5280 section 7.1, though we don't implement the whole algorithm: + * we sometimes return unequal when the full algorithm would return equal, + * but never the other way. (In particular, we don't do Unicode normalisation + * or space folding.) + * + * Return 0 if equal, -1 otherwise. + */ +static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b ) +{ + /* Avoid recursion, it might not be optimised by the compiler */ + while( a != NULL || b != NULL ) + { + if( a == NULL || b == NULL ) + return( -1 ); + + /* type */ + if( a->oid.tag != b->oid.tag || + a->oid.len != b->oid.len || + memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 ) + { + return( -1 ); + } + + /* value */ + if( x509_string_cmp( &a->val, &b->val ) != 0 ) + return( -1 ); + + /* structure of the list of sets */ + if( a->next_merged != b->next_merged ) + return( -1 ); + + a = a->next; + b = b->next; + } + + /* a == NULL == b */ + return( 0 ); +} + +/* + * Reset (init or clear) a verify_chain + */ +static void x509_crt_verify_chain_reset( + mbedtls_x509_crt_verify_chain *ver_chain ) +{ + size_t i; + + for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ ) + { + ver_chain->items[i].crt = NULL; + ver_chain->items[i].flags = -1; + } + + ver_chain->len = 0; +} + /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ @@ -1667,9 +1819,7 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, while( crl_list != NULL ) { if( crl_list->version == 0 || - crl_list->issuer_raw.len != ca->subject_raw.len || - memcmp( crl_list->issuer_raw.p, ca->subject_raw.p, - crl_list->issuer_raw.len ) != 0 ) + x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 ) { crl_list = crl_list->next; continue; @@ -1679,7 +1829,8 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, * Check if the CA is configured to sign CRLs */ #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) - if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 ) + if( mbedtls_x509_crt_check_key_usage( ca, + MBEDTLS_X509_KU_CRL_SIGN ) != 0 ) { flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; @@ -1740,159 +1891,59 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, #endif /* MBEDTLS_X509_CRL_PARSE_C */ /* - * Like memcmp, but case-insensitive and always returns -1 if different + * Check the signature of a certificate by its parent */ -static int x509_memcasecmp( const void *s1, const void *s2, size_t len ) +static int x509_crt_check_signature( const mbedtls_x509_crt *child, + mbedtls_x509_crt *parent, + mbedtls_x509_crt_restart_ctx *rs_ctx ) { - size_t i; - unsigned char diff; - const unsigned char *n1 = s1, *n2 = s2; - - for( i = 0; i < len; i++ ) - { - diff = n1[i] ^ n2[i]; - - if( diff == 0 ) - continue; - - if( diff == 32 && - ( ( n1[i] >= 'a' && n1[i] <= 'z' ) || - ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) ) - { - continue; - } + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + size_t hash_len; +#if !defined(MBEDTLS_USE_PSA_CRYPTO) + const mbedtls_md_info_t *md_info; + md_info = mbedtls_md_info_from_type( child->sig_md ); + hash_len = mbedtls_md_get_size( md_info ); + /* Note: hash errors can happen only after an internal error */ + if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 ) return( -1 ); - } - - return( 0 ); -} - -/* - * Return 0 if name matches wildcard, -1 otherwise - */ -static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name ) -{ - size_t i; - size_t cn_idx = 0, cn_len = strlen( cn ); +#else + psa_hash_operation_t hash_operation; + psa_algorithm_t hash_alg = mbedtls_psa_translate_md( child->sig_md ); - /* We can't have a match if there is no wildcard to match */ - if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' ) + if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS ) return( -1 ); - for( i = 0; i < cn_len; ++i ) + if( psa_hash_update( &hash_operation, child->tbs.p, child->tbs.len ) + != PSA_SUCCESS ) { - if( cn[i] == '.' ) - { - cn_idx = i; - break; - } - } - - if( cn_idx == 0 ) return( -1 ); - - if( cn_len - cn_idx == name->len - 1 && - x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 ) - { - return( 0 ); } - return( -1 ); -} - -/* - * Compare two X.509 strings, case-insensitive, and allowing for some encoding - * variations (but not all). - * - * Return 0 if equal, -1 otherwise. - */ -static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b ) -{ - if( a->tag == b->tag && - a->len == b->len && - memcmp( a->p, b->p, b->len ) == 0 ) + if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len ) + != PSA_SUCCESS ) { - return( 0 ); - } - - if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && - ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && - a->len == b->len && - x509_memcasecmp( a->p, b->p, b->len ) == 0 ) - { - return( 0 ); - } - - return( -1 ); -} - -/* - * Compare two X.509 Names (aka rdnSequence). - * - * See RFC 5280 section 7.1, though we don't implement the whole algorithm: - * we sometimes return unequal when the full algorithm would return equal, - * but never the other way. (In particular, we don't do Unicode normalisation - * or space folding.) - * - * Return 0 if equal, -1 otherwise. - */ -static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b ) -{ - /* Avoid recursion, it might not be optimised by the compiler */ - while( a != NULL || b != NULL ) - { - if( a == NULL || b == NULL ) - return( -1 ); - - /* type */ - if( a->oid.tag != b->oid.tag || - a->oid.len != b->oid.len || - memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 ) - { - return( -1 ); - } - - /* value */ - if( x509_string_cmp( &a->val, &b->val ) != 0 ) - return( -1 ); - - /* structure of the list of sets */ - if( a->next_merged != b->next_merged ) - return( -1 ); - - a = a->next; - b = b->next; - } - - /* a == NULL == b */ - return( 0 ); -} - -/* - * Check the signature of a certificate by its parent - */ -static int x509_crt_check_signature( const mbedtls_x509_crt *child, - mbedtls_x509_crt *parent ) -{ - const mbedtls_md_info_t *md_info; - unsigned char hash[MBEDTLS_MD_MAX_SIZE]; - - md_info = mbedtls_md_info_from_type( child->sig_md ); - if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 ) - { - /* Note: this can't happen except after an internal error */ return( -1 ); } +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + /* Skip expensive computation on obvious mismatch */ + if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) ) + return( -1 ); - if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, - child->sig_md, hash, mbedtls_md_get_size( md_info ), - child->sig.p, child->sig.len ) != 0 ) +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA ) { - return( -1 ); + return( mbedtls_pk_verify_restartable( &parent->pk, + child->sig_md, hash, hash_len, + child->sig.p, child->sig.len, &rs_ctx->pk ) ); } +#else + (void) rs_ctx; +#endif - return( 0 ); + return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, + child->sig_md, hash, hash_len, + child->sig.p, child->sig.len ) ); } /* @@ -1939,6 +1990,7 @@ static int x509_crt_check_parent( const mbedtls_x509_crt *child, * 1. subject name matches child's issuer * 2. if necessary, the CA bit is set and key usage allows signing certs * 3. for trusted roots, the signature is correct + * (for intermediates, the signature is checked and the result reported) * 4. pathlen constraints are satisfied * * If there's a suitable candidate which is also time-valid, return the first @@ -1961,23 +2013,54 @@ static int x509_crt_check_parent( const mbedtls_x509_crt *child, * Arguments: * - [in] child: certificate for which we're looking for a parent * - [in] candidates: chained list of potential parents + * - [out] r_parent: parent found (or NULL) + * - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0 * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top * of the chain, 0 otherwise * - [in] path_cnt: number of intermediates seen so far * - [in] self_cnt: number of self-signed intermediates seen so far * (will never be greater than path_cnt) + * - [in-out] rs_ctx: context for restarting operations * * Return value: - * - the first suitable parent found (see above regarding time-validity) - * - NULL if no suitable parent was found + * - 0 on success + * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ -static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child, - mbedtls_x509_crt *candidates, - int top, - size_t path_cnt, - size_t self_cnt ) +static int x509_crt_find_parent_in( + mbedtls_x509_crt *child, + mbedtls_x509_crt *candidates, + mbedtls_x509_crt **r_parent, + int *r_signature_is_good, + int top, + unsigned path_cnt, + unsigned self_cnt, + mbedtls_x509_crt_restart_ctx *rs_ctx ) { - mbedtls_x509_crt *parent, *badtime_parent = NULL; + int ret; + mbedtls_x509_crt *parent, *fallback_parent; + int signature_is_good, fallback_signature_is_good; + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /* did we have something in progress? */ + if( rs_ctx != NULL && rs_ctx->parent != NULL ) + { + /* restore saved state */ + parent = rs_ctx->parent; + fallback_parent = rs_ctx->fallback_parent; + fallback_signature_is_good = rs_ctx->fallback_signature_is_good; + + /* clear saved state */ + rs_ctx->parent = NULL; + rs_ctx->fallback_parent = NULL; + rs_ctx->fallback_signature_is_good = 0; + + /* resume where we left */ + goto check_signature; + } +#endif + + fallback_parent = NULL; + fallback_signature_is_good = 0; for( parent = candidates; parent != NULL; parent = parent->next ) { @@ -1993,17 +2076,38 @@ static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child, } /* Signature */ - if( top && x509_crt_check_signature( child, parent ) != 0 ) +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +check_signature: +#endif + ret = x509_crt_check_signature( child, parent, rs_ctx ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { - continue; + /* save state */ + rs_ctx->parent = parent; + rs_ctx->fallback_parent = fallback_parent; + rs_ctx->fallback_signature_is_good = fallback_signature_is_good; + + return( ret ); } +#else + (void) ret; +#endif + + signature_is_good = ret == 0; + if( top && ! signature_is_good ) + continue; /* optional time check */ if( mbedtls_x509_time_is_past( &parent->valid_to ) || mbedtls_x509_time_is_future( &parent->valid_from ) ) { - if( badtime_parent == NULL ) - badtime_parent = parent; + if( fallback_parent == NULL ) + { + fallback_parent = parent; + fallback_signature_is_good = signature_is_good; + } continue; } @@ -2011,10 +2115,18 @@ static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child, break; } - if( parent == NULL ) - parent = badtime_parent; + if( parent != NULL ) + { + *r_parent = parent; + *r_signature_is_good = signature_is_good; + } + else + { + *r_parent = fallback_parent; + *r_signature_is_good = fallback_signature_is_good; + } - return( parent ); + return( 0 ); } /* @@ -2026,34 +2138,78 @@ static mbedtls_x509_crt *x509_crt_find_parent_in( mbedtls_x509_crt *child, * Arguments: * - [in] child: certificate for which we're looking for a parent, followed * by a chain of possible intermediates - * - [in] trust_ca: locally trusted CAs - * - [out] 1 if parent was found in trust_ca, 0 if found in provided chain - * - [in] path_cnt: number of intermediates seen so far - * - [in] self_cnt: number of self-signed intermediates seen so far + * - [in] trust_ca: list of locally trusted certificates + * - [out] parent: parent found (or NULL) + * - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0 + * - [out] signature_is_good: 1 if child signature by parent is valid, or 0 + * - [in] path_cnt: number of links in the chain so far (EE -> ... -> child) + * - [in] self_cnt: number of self-signed certs in the chain so far * (will always be no greater than path_cnt) + * - [in-out] rs_ctx: context for restarting operations * * Return value: - * - the first suitable parent found (see find_parent_in() for "suitable") - * - NULL if no suitable parent was found + * - 0 on success + * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ -static mbedtls_x509_crt *x509_crt_find_parent( mbedtls_x509_crt *child, - mbedtls_x509_crt *trust_ca, - int *parent_is_trusted, - size_t path_cnt, - size_t self_cnt ) +static int x509_crt_find_parent( + mbedtls_x509_crt *child, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crt **parent, + int *parent_is_trusted, + int *signature_is_good, + unsigned path_cnt, + unsigned self_cnt, + mbedtls_x509_crt_restart_ctx *rs_ctx ) { - mbedtls_x509_crt *parent; + int ret; + mbedtls_x509_crt *search_list; - /* Look for a parent in trusted CAs */ *parent_is_trusted = 1; - parent = x509_crt_find_parent_in( child, trust_ca, 1, path_cnt, self_cnt ); - if( parent != NULL ) - return( parent ); +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /* restore then clear saved state if we have some stored */ + if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 ) + { + *parent_is_trusted = rs_ctx->parent_is_trusted; + rs_ctx->parent_is_trusted = -1; + } +#endif + + while( 1 ) { + search_list = *parent_is_trusted ? trust_ca : child->next; + + ret = x509_crt_find_parent_in( child, search_list, + parent, signature_is_good, + *parent_is_trusted, + path_cnt, self_cnt, rs_ctx ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + { + /* save state */ + rs_ctx->parent_is_trusted = *parent_is_trusted; + return( ret ); + } +#else + (void) ret; +#endif + + /* stop here if found or already in second iteration */ + if( *parent != NULL || *parent_is_trusted == 0 ) + break; + + /* prepare second iteration */ + *parent_is_trusted = 0; + } - /* Look for a parent upwards the chain */ - *parent_is_trusted = 0; - return( x509_crt_find_parent_in( child, child->next, 0, path_cnt, self_cnt ) ); + /* extra precaution against mistakes in the caller */ + if( parent == NULL ) + { + *parent_is_trusted = 0; + *signature_is_good = 0; + } + + return( 0 ); } /* @@ -2102,11 +2258,24 @@ static int x509_crt_check_ee_locally_trusted( * - EE, Ci1, ..., Ciq cannot be continued with a trusted root * -> return that chain with NOT_TRUSTED set on Ciq * + * Tests for (aspects of) this function should include at least: + * - trusted EE + * - EE -> trusted root + * - EE -> intermedate CA -> trusted root + * - if relevant: EE untrusted + * - if relevant: EE -> intermediate, untrusted + * with the aspect under test checked at each relevant level (EE, int, root). + * For some aspects longer chains are required, but usually length 2 is + * enough (but length 1 is not in general). + * * Arguments: * - [in] crt: the cert list EE, C1, ..., Cn * - [in] trust_ca: the trusted list R1, ..., Rp * - [in] ca_crl, profile: as in verify_with_profile() - * - [out] ver_chain, chain_len: the built and verified chain + * - [out] ver_chain: the built and verified chain + * Only valid when return value is 0, may contain garbage otherwise! + * Restart note: need not be the same when calling again to resume. + * - [in-out] rs_ctx: context for restarting operations * * Return value: * - non-zero if the chain could not be fully built and examined @@ -2118,24 +2287,50 @@ static int x509_crt_verify_chain( mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, - x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE], - size_t *chain_len ) + mbedtls_x509_crt_verify_chain *ver_chain, + mbedtls_x509_crt_restart_ctx *rs_ctx ) { + /* Don't initialize any of those variables here, so that the compiler can + * catch potential issues with jumping ahead when restarting */ + int ret; uint32_t *flags; + mbedtls_x509_crt_verify_chain_item *cur; mbedtls_x509_crt *child; mbedtls_x509_crt *parent; - int parent_is_trusted = 0; - int child_is_trusted = 0; - size_t self_cnt = 0; + int parent_is_trusted; + int child_is_trusted; + int signature_is_good; + unsigned self_cnt; + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /* resume if we had an operation in progress */ + if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent ) + { + /* restore saved state */ + *ver_chain = rs_ctx->ver_chain; /* struct copy */ + self_cnt = rs_ctx->self_cnt; + + /* restore derived state */ + cur = &ver_chain->items[ver_chain->len - 1]; + child = cur->crt; + flags = &cur->flags; + + goto find_parent; + } +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ child = crt; - *chain_len = 0; + self_cnt = 0; + parent_is_trusted = 0; + child_is_trusted = 0; while( 1 ) { /* Add certificate to the verification chain */ - ver_chain[*chain_len].crt = child; - flags = &ver_chain[*chain_len].flags; - ++*chain_len; + cur = &ver_chain->items[ver_chain->len]; + cur->crt = child; + cur->flags = 0; + ver_chain->len++; + flags = &cur->flags; /* Check time-validity (all certificates) */ if( mbedtls_x509_time_is_past( &child->valid_to ) ) @@ -2156,15 +2351,33 @@ static int x509_crt_verify_chain( *flags |= MBEDTLS_X509_BADCERT_BAD_PK; /* Special case: EE certs that are locally trusted */ - if( *chain_len == 1 && + if( ver_chain->len == 1 && x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 ) { return( 0 ); } +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +find_parent: +#endif /* Look for a parent in trusted CAs or up the chain */ - parent = x509_crt_find_parent( child, trust_ca, &parent_is_trusted, - *chain_len - 1, self_cnt ); + ret = x509_crt_find_parent( child, trust_ca, &parent, + &parent_is_trusted, &signature_is_good, + ver_chain->len - 1, self_cnt, rs_ctx ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) + { + /* save state */ + rs_ctx->in_progress = x509_crt_rs_find_parent; + rs_ctx->self_cnt = self_cnt; + rs_ctx->ver_chain = *ver_chain; /* struct copy */ + + return( ret ); + } +#else + (void) ret; +#endif /* No parent? We're done here */ if( parent == NULL ) @@ -2176,7 +2389,7 @@ static int x509_crt_verify_chain( /* Count intermediate self-issued (not necessarily self-signed) certs. * These can occur with some strategies for key rollover, see [SIRO], * and should be excluded from max_pathlen checks. */ - if( *chain_len != 1 && + if( ver_chain->len != 1 && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) { self_cnt++; @@ -2185,14 +2398,14 @@ static int x509_crt_verify_chain( /* path_cnt is 0 for the first intermediate CA, * and if parent is trusted it's not an intermediate CA */ if( ! parent_is_trusted && - *chain_len > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) + ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { /* return immediately to avoid overflow the chain array */ return( MBEDTLS_ERR_X509_FATAL_ERROR ); } - /* if parent is trusted, the signature was checked by find_parent() */ - if( ! parent_is_trusted && x509_crt_check_signature( child, parent ) != 0 ) + /* signature was checked while searching parent */ + if( ! signature_is_good ) *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; /* check size of signing key */ @@ -2210,6 +2423,7 @@ static int x509_crt_verify_chain( child = parent; parent = NULL; child_is_trusted = parent_is_trusted; + signature_is_good = 0; } } @@ -2278,21 +2492,22 @@ static void x509_crt_verify_name( const mbedtls_x509_crt *crt, */ static int x509_crt_merge_flags_with_cb( uint32_t *flags, - x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE], - size_t chain_len, + const mbedtls_x509_crt_verify_chain *ver_chain, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; - size_t i; + unsigned i; uint32_t cur_flags; + const mbedtls_x509_crt_verify_chain_item *cur; - for( i = chain_len; i != 0; --i ) + for( i = ver_chain->len; i != 0; --i ) { - cur_flags = ver_chain[i-1].flags; + cur = &ver_chain->items[i-1]; + cur_flags = cur->flags; if( NULL != f_vrfy ) - if( ( ret = f_vrfy( p_vrfy, ver_chain[i-1].crt, (int) i-1, &cur_flags ) ) != 0 ) + if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 ) return( ret ); *flags |= cur_flags; @@ -2302,7 +2517,7 @@ static int x509_crt_merge_flags_with_cb( } /* - * Verify the certificate validity + * Verify the certificate validity (default profile, not restartable) */ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, @@ -2311,12 +2526,28 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { - return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl, - &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) ); + return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl, + &mbedtls_x509_crt_profile_default, cn, flags, + f_vrfy, p_vrfy, NULL ) ); +} + +/* + * Verify the certificate validity (user-chosen profile, not restartable) + */ +int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + const char *cn, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ) +{ + return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl, + profile, cn, flags, f_vrfy, p_vrfy, NULL ) ); } /* - * Verify the certificate validity, with profile + * Verify the certificate validity, with profile, restartable version * * This function: * - checks the requested CN (if any) @@ -2325,23 +2556,23 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, * - builds and verifies the chain * - then calls the callback and merges the flags */ -int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, +int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), - void *p_vrfy ) + void *p_vrfy, + mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret; mbedtls_pk_type_t pk_type; - x509_crt_verify_chain_item ver_chain[X509_MAX_VERIFY_CHAIN_SIZE]; - size_t chain_len; - uint32_t *ee_flags = &ver_chain[0].flags; + mbedtls_x509_crt_verify_chain ver_chain; + uint32_t ee_flags; *flags = 0; - memset( ver_chain, 0, sizeof( ver_chain ) ); - chain_len = 0; + ee_flags = 0; + x509_crt_verify_chain_reset( &ver_chain ); if( profile == NULL ) { @@ -2351,28 +2582,36 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, /* check name if requested */ if( cn != NULL ) - x509_crt_verify_name( crt, cn, ee_flags ); + x509_crt_verify_name( crt, cn, &ee_flags ); /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) - *ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK; + ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, &crt->pk ) != 0 ) - *ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY; + ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Check the chain */ ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile, - ver_chain, &chain_len ); + &ver_chain, rs_ctx ); + if( ret != 0 ) goto exit; + /* Merge end-entity flags */ + ver_chain.items[0].flags |= ee_flags; + /* Build final flags, calling callback on the way if any */ - ret = x509_crt_merge_flags_with_cb( flags, - ver_chain, chain_len, f_vrfy, p_vrfy ); + ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy ); exit: +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) + mbedtls_x509_crt_restart_free( rs_ctx ); +#endif + /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by * the SSL module for authmode optional, but non-zero return from the * callback means a fatal error so it shouldn't be ignored */ @@ -2483,4 +2722,36 @@ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) while( cert_cur != NULL ); } +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/* + * Initialize a restart context + */ +void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx ) +{ + mbedtls_pk_restart_init( &ctx->pk ); + + ctx->parent = NULL; + ctx->fallback_parent = NULL; + ctx->fallback_signature_is_good = 0; + + ctx->parent_is_trusted = -1; + + ctx->in_progress = x509_crt_rs_none; + ctx->self_cnt = 0; + x509_crt_verify_chain_reset( &ctx->ver_chain ); +} + +/* + * Free the components of a restart context + */ +void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx ) +{ + if( ctx == NULL ) + return; + + mbedtls_pk_restart_free( &ctx->pk ); + mbedtls_x509_crt_restart_init( ctx ); +} +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + #endif /* MBEDTLS_X509_CRT_PARSE_C */ diff --git a/features/mbedtls/src/x509write_csr.c b/features/mbedtls/src/x509write_csr.c index 66cee56014c..f2950ad2fa3 100644 --- a/features/mbedtls/src/x509write_csr.c +++ b/features/mbedtls/src/x509write_csr.c @@ -37,6 +37,11 @@ #include "mbedtls/asn1write.h" #include "mbedtls/platform_util.h" +#if defined(MBEDTLS_USE_PSA_CRYPTO) +#include "psa/crypto.h" +#include "mbedtls/psa_util.h" +#endif + #include #include @@ -136,7 +141,11 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s size_t pub_len = 0, sig_and_oid_len = 0, sig_len; size_t len = 0; mbedtls_pk_type_t pk_alg; - +#if defined(MBEDTLS_USE_PSA_CRYPTO) + psa_hash_operation_t hash_operation; + size_t hash_len; + psa_algorithm_t hash_alg = mbedtls_psa_translate_md( ctx->md_alg ); +#endif /* MBEDTLS_USE_PSA_CRYPTO */ /* * Prepare data to be signed in tmp_buf */ @@ -187,9 +196,23 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s /* * Prepare signature + * Note: hash errors can happen only after an internal error */ - mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ); +#if defined(MBEDTLS_USE_PSA_CRYPTO) + if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS ) + return( MBEDTLS_ERR_X509_FATAL_ERROR ); + + if( psa_hash_update( &hash_operation, c, len ) != PSA_SUCCESS ) + return( MBEDTLS_ERR_X509_FATAL_ERROR ); + if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len ) + != PSA_SUCCESS ) + { + return( MBEDTLS_ERR_X509_FATAL_ERROR ); + } +#else /* MBEDTLS_USE_PSA_CRYPTO */ + mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ); +#endif if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len, f_rng, p_rng ) ) != 0 ) {