From be58c81aff4cd4c0ccf43dbd7998da4a6a08c03b Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 21 Apr 2024 19:43:51 +0200 Subject: Adding upstream version 2.10.0+dfsg. Signed-off-by: Daniel Baumann --- drivers/auth/mbedtls/mbedtls_common.c | 73 +++ drivers/auth/mbedtls/mbedtls_common.mk | 164 +++++++ drivers/auth/mbedtls/mbedtls_crypto.c | 417 +++++++++++++++++ drivers/auth/mbedtls/mbedtls_crypto.mk | 16 + drivers/auth/mbedtls/mbedtls_psa_crypto.c | 696 +++++++++++++++++++++++++++++ drivers/auth/mbedtls/mbedtls_x509.mk | 9 + drivers/auth/mbedtls/mbedtls_x509_parser.c | 508 +++++++++++++++++++++ 7 files changed, 1883 insertions(+) create mode 100644 drivers/auth/mbedtls/mbedtls_common.c create mode 100644 drivers/auth/mbedtls/mbedtls_common.mk create mode 100644 drivers/auth/mbedtls/mbedtls_crypto.c create mode 100644 drivers/auth/mbedtls/mbedtls_crypto.mk create mode 100644 drivers/auth/mbedtls/mbedtls_psa_crypto.c create mode 100644 drivers/auth/mbedtls/mbedtls_x509.mk create mode 100644 drivers/auth/mbedtls/mbedtls_x509_parser.c (limited to 'drivers/auth/mbedtls') diff --git a/drivers/auth/mbedtls/mbedtls_common.c b/drivers/auth/mbedtls/mbedtls_common.c new file mode 100644 index 0000000..4f30d82 --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_common.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015-2023, Arm Limited and Contributors. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include + +/* mbed TLS headers */ +#include +#include +#include + +#include +#include + +#include + +static void cleanup(void) +{ + ERROR("EXIT from BL2\n"); + panic(); +} + +/* + * mbed TLS initialization function + */ +void mbedtls_init(void) +{ + static int ready; + void *heap_addr; + size_t heap_size = 0; + int err; + + if (!ready) { + if (atexit(cleanup)) + panic(); + + err = plat_get_mbedtls_heap(&heap_addr, &heap_size); + + /* Ensure heap setup is proper */ + if (err < 0) { + ERROR("Mbed TLS failed to get a heap\n"); + panic(); + } + assert(heap_size >= TF_MBEDTLS_HEAP_SIZE); + + /* Initialize the mbed TLS heap */ + mbedtls_memory_buffer_alloc_init(heap_addr, heap_size); + +#ifdef MBEDTLS_PLATFORM_SNPRINTF_ALT + mbedtls_platform_set_snprintf(snprintf); +#endif + ready = 1; + } +} + +/* + * The following helper function simply returns the default allocated heap. + * It can be used by platforms for their plat_get_mbedtls_heap() implementation. + */ +int get_mbedtls_heap_helper(void **heap_addr, size_t *heap_size) +{ + static unsigned char heap[TF_MBEDTLS_HEAP_SIZE]; + + assert(heap_addr != NULL); + assert(heap_size != NULL); + + *heap_addr = heap; + *heap_size = sizeof(heap); + return 0; +} diff --git a/drivers/auth/mbedtls/mbedtls_common.mk b/drivers/auth/mbedtls/mbedtls_common.mk new file mode 100644 index 0000000..a2c6430 --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_common.mk @@ -0,0 +1,164 @@ +# +# Copyright (c) 2015-2023, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +ifneq (${MBEDTLS_COMMON_MK},1) +MBEDTLS_COMMON_MK := 1 + +# MBEDTLS_DIR must be set to the mbed TLS main directory (it must contain +# the 'include' and 'library' subdirectories). +ifeq (${MBEDTLS_DIR},) + $(error Error: MBEDTLS_DIR not set) +endif + +MBEDTLS_INC = -I${MBEDTLS_DIR}/include + +MBEDTLS_MAJOR=$(shell grep -hP "define MBEDTLS_VERSION_MAJOR" ${MBEDTLS_DIR}/include/mbedtls/*.h | grep -oe '\([0-9.]*\)') +MBEDTLS_MINOR=$(shell grep -hP "define MBEDTLS_VERSION_MINOR" ${MBEDTLS_DIR}/include/mbedtls/*.h | grep -oe '\([0-9.]*\)') +$(info MBEDTLS_VERSION_MAJOR is [${MBEDTLS_MAJOR}] MBEDTLS_VERSION_MINOR is [${MBEDTLS_MINOR}]) + +# Specify mbed TLS configuration file +ifeq (${MBEDTLS_MAJOR}, 2) + $(info Deprecation Notice: Please migrate to Mbedtls version 3.x (refer to TF-A documentation for the exact version number)) + MBEDTLS_CONFIG_FILE ?= "" +else ifeq (${MBEDTLS_MAJOR}, 3) + ifeq (${PSA_CRYPTO},1) + MBEDTLS_CONFIG_FILE ?= "" + else + MBEDTLS_CONFIG_FILE ?= "" + endif +endif + +$(eval $(call add_define,MBEDTLS_CONFIG_FILE)) + +MBEDTLS_SOURCES += drivers/auth/mbedtls/mbedtls_common.c + +LIBMBEDTLS_SRCS += $(addprefix ${MBEDTLS_DIR}/library/, \ + aes.c \ + asn1parse.c \ + asn1write.c \ + cipher.c \ + cipher_wrap.c \ + constant_time.c \ + memory_buffer_alloc.c \ + oid.c \ + platform.c \ + platform_util.c \ + bignum.c \ + gcm.c \ + md.c \ + pk.c \ + pk_wrap.c \ + pkparse.c \ + pkwrite.c \ + sha256.c \ + sha512.c \ + ecdsa.c \ + ecp_curves.c \ + ecp.c \ + rsa.c \ + x509.c \ + x509_crt.c \ + ) + +ifeq (${MBEDTLS_MAJOR}, 2) + LIBMBEDTLS_SRCS += $(addprefix ${MBEDTLS_DIR}/library/, \ + rsa_internal.c \ + ) +else ifeq (${MBEDTLS_MAJOR}, 3) + LIBMBEDTLS_SRCS += $(addprefix ${MBEDTLS_DIR}/library/, \ + bignum_core.c \ + rsa_alt_helpers.c \ + hash_info.c \ + ) + + # Currently on Mbedtls-3 there is outstanding bug due to usage + # of redundant declaration[1], So disable redundant-decls + # compilation flag to avoid compilation error when compiling with + # Mbedtls-3. + # [1]: https://github.com/Mbed-TLS/mbedtls/issues/6910 + LIBMBEDTLS_CFLAGS += -Wno-error=redundant-decls +endif + +ifeq (${PSA_CRYPTO},1) +LIBMBEDTLS_SRCS += $(addprefix ${MBEDTLS_DIR}/library/, \ + psa_crypto.c \ + psa_crypto_client.c \ + psa_crypto_driver_wrappers.c \ + psa_crypto_hash.c \ + psa_crypto_rsa.c \ + psa_crypto_ecp.c \ + psa_crypto_slot_management.c \ + ) +endif + +# The platform may define the variable 'TF_MBEDTLS_KEY_ALG' to select the key +# algorithm to use. If the variable is not defined, select it based on +# algorithm used for key generation `KEY_ALG`. If `KEY_ALG` is not defined, +# then it is set to `rsa`. +ifeq (${TF_MBEDTLS_KEY_ALG},) + ifeq (${KEY_ALG}, ecdsa) + TF_MBEDTLS_KEY_ALG := ecdsa + else + TF_MBEDTLS_KEY_ALG := rsa + endif +endif + +ifeq (${TF_MBEDTLS_KEY_SIZE},) + ifneq ($(findstring rsa,${TF_MBEDTLS_KEY_ALG}),) + ifeq (${KEY_SIZE},) + TF_MBEDTLS_KEY_SIZE := 2048 + else ifneq ($(filter $(KEY_SIZE), 1024 2048 3072 4096),) + TF_MBEDTLS_KEY_SIZE := ${KEY_SIZE} + else + $(error "Invalid value for KEY_SIZE: ${KEY_SIZE}") + endif + else ifneq ($(findstring ecdsa,${TF_MBEDTLS_KEY_ALG}),) + ifeq (${KEY_SIZE},) + TF_MBEDTLS_KEY_SIZE := 256 + else ifneq ($(filter $(KEY_SIZE), 256 384),) + TF_MBEDTLS_KEY_SIZE := ${KEY_SIZE} + else + $(error "Invalid value for KEY_SIZE: ${KEY_SIZE}") + endif + endif +endif + +ifeq (${HASH_ALG}, sha384) + TF_MBEDTLS_HASH_ALG_ID := TF_MBEDTLS_SHA384 +else ifeq (${HASH_ALG}, sha512) + TF_MBEDTLS_HASH_ALG_ID := TF_MBEDTLS_SHA512 +else + TF_MBEDTLS_HASH_ALG_ID := TF_MBEDTLS_SHA256 +endif + +ifeq (${TF_MBEDTLS_KEY_ALG},ecdsa) + TF_MBEDTLS_KEY_ALG_ID := TF_MBEDTLS_ECDSA +else ifeq (${TF_MBEDTLS_KEY_ALG},rsa) + TF_MBEDTLS_KEY_ALG_ID := TF_MBEDTLS_RSA +else ifeq (${TF_MBEDTLS_KEY_ALG},rsa+ecdsa) + TF_MBEDTLS_KEY_ALG_ID := TF_MBEDTLS_RSA_AND_ECDSA +else + $(error "TF_MBEDTLS_KEY_ALG=${TF_MBEDTLS_KEY_ALG} not supported on mbed TLS") +endif + +ifeq (${DECRYPTION_SUPPORT}, aes_gcm) + TF_MBEDTLS_USE_AES_GCM := 1 +else + TF_MBEDTLS_USE_AES_GCM := 0 +endif + +# Needs to be set to drive mbed TLS configuration correctly +$(eval $(call add_defines,\ + $(sort \ + TF_MBEDTLS_KEY_ALG_ID \ + TF_MBEDTLS_KEY_SIZE \ + TF_MBEDTLS_HASH_ALG_ID \ + TF_MBEDTLS_USE_AES_GCM \ +))) + +$(eval $(call MAKE_LIB,mbedtls)) + +endif diff --git a/drivers/auth/mbedtls/mbedtls_crypto.c b/drivers/auth/mbedtls/mbedtls_crypto.c new file mode 100644 index 0000000..230cec9 --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_crypto.c @@ -0,0 +1,417 @@ +/* + * Copyright (c) 2015-2023, Arm Limited and Contributors. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +/* mbed TLS headers */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#define LIB_NAME "mbed TLS" + +#if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +/* + * CRYPTO_MD_MAX_SIZE value is as per current stronger algorithm available + * so make sure that mbed TLS MD maximum size must be lesser than this. + */ +CASSERT(CRYPTO_MD_MAX_SIZE >= MBEDTLS_MD_MAX_SIZE, + assert_mbedtls_md_size_overflow); + +#endif /* CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ + CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */ + +/* + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm AlgorithmIdentifier, + * digest OCTET STRING + * } + */ + +/* + * Initialize the library and export the descriptor + */ +static void init(void) +{ + /* Initialize mbed TLS */ + mbedtls_init(); +} + +#if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +/* + * Verify a signature. + * + * Parameters are passed using the DER encoding format following the ASN.1 + * structures detailed above. + */ +static int verify_signature(void *data_ptr, unsigned int data_len, + void *sig_ptr, unsigned int sig_len, + void *sig_alg, unsigned int sig_alg_len, + void *pk_ptr, unsigned int pk_len) +{ + mbedtls_asn1_buf sig_oid, sig_params; + mbedtls_asn1_buf signature; + mbedtls_md_type_t md_alg; + mbedtls_pk_type_t pk_alg; + mbedtls_pk_context pk = {0}; + int rc; + void *sig_opts = NULL; + const mbedtls_md_info_t *md_info; + unsigned char *p, *end; + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + + /* Get pointers to signature OID and parameters */ + p = (unsigned char *)sig_alg; + end = (unsigned char *)(p + sig_alg_len); + rc = mbedtls_asn1_get_alg(&p, end, &sig_oid, &sig_params); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + /* Get the actual signature algorithm (MD + PK) */ + rc = mbedtls_x509_get_sig_alg(&sig_oid, &sig_params, &md_alg, &pk_alg, &sig_opts); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + /* Parse the public key */ + mbedtls_pk_init(&pk); + p = (unsigned char *)pk_ptr; + end = (unsigned char *)(p + pk_len); + rc = mbedtls_pk_parse_subpubkey(&p, end, &pk); + if (rc != 0) { + rc = CRYPTO_ERR_SIGNATURE; + goto end2; + } + + /* Get the signature (bitstring) */ + p = (unsigned char *)sig_ptr; + end = (unsigned char *)(p + sig_len); + signature.tag = *p; + rc = mbedtls_asn1_get_bitstring_null(&p, end, &signature.len); + if ((rc != 0) || ((size_t)(end - p) != signature.len)) { + rc = CRYPTO_ERR_SIGNATURE; + goto end1; + } + signature.p = p; + + /* Calculate the hash of the data */ + md_info = mbedtls_md_info_from_type(md_alg); + if (md_info == NULL) { + rc = CRYPTO_ERR_SIGNATURE; + goto end1; + } + p = (unsigned char *)data_ptr; + rc = mbedtls_md(md_info, p, data_len, hash); + if (rc != 0) { + rc = CRYPTO_ERR_SIGNATURE; + goto end1; + } + + /* Verify the signature */ + rc = mbedtls_pk_verify_ext(pk_alg, sig_opts, &pk, md_alg, hash, + mbedtls_md_get_size(md_info), + signature.p, signature.len); + if (rc != 0) { + rc = CRYPTO_ERR_SIGNATURE; + goto end1; + } + + /* Signature verification success */ + rc = CRYPTO_SUCCESS; + +end1: + mbedtls_pk_free(&pk); +end2: + mbedtls_free(sig_opts); + return rc; +} + +/* + * Match a hash + * + * Digest info is passed in DER format following the ASN.1 structure detailed + * above. + */ +static int verify_hash(void *data_ptr, unsigned int data_len, + void *digest_info_ptr, unsigned int digest_info_len) +{ + mbedtls_asn1_buf hash_oid, params; + mbedtls_md_type_t md_alg; + const mbedtls_md_info_t *md_info; + unsigned char *p, *end, *hash; + unsigned char data_hash[MBEDTLS_MD_MAX_SIZE]; + size_t len; + int rc; + + /* + * Digest info should be an MBEDTLS_ASN1_SEQUENCE, but padding after + * it is allowed. This is necessary to support multiple hash + * algorithms. + */ + p = (unsigned char *)digest_info_ptr; + end = p + digest_info_len; + rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + end = p + len; + + /* Get the hash algorithm */ + rc = mbedtls_asn1_get_alg(&p, end, &hash_oid, ¶ms); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + rc = mbedtls_oid_get_md_alg(&hash_oid, &md_alg); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + md_info = mbedtls_md_info_from_type(md_alg); + if (md_info == NULL) { + return CRYPTO_ERR_HASH; + } + + /* Hash should be octet string type and consume all bytes */ + rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); + if ((rc != 0) || ((size_t)(end - p) != len)) { + return CRYPTO_ERR_HASH; + } + + /* Length of hash must match the algorithm's size */ + if (len != mbedtls_md_get_size(md_info)) { + return CRYPTO_ERR_HASH; + } + hash = p; + + /* Calculate the hash of the data */ + p = (unsigned char *)data_ptr; + rc = mbedtls_md(md_info, p, data_len, data_hash); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + /* Compare values */ + rc = memcmp(data_hash, hash, mbedtls_md_get_size(md_info)); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + return CRYPTO_SUCCESS; +} +#endif /* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \ + CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */ + +#if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +/* + * Map a generic crypto message digest algorithm to the corresponding macro used + * by Mbed TLS. + */ +static inline mbedtls_md_type_t md_type(enum crypto_md_algo algo) +{ + switch (algo) { + case CRYPTO_MD_SHA512: + return MBEDTLS_MD_SHA512; + case CRYPTO_MD_SHA384: + return MBEDTLS_MD_SHA384; + case CRYPTO_MD_SHA256: + return MBEDTLS_MD_SHA256; + default: + /* Invalid hash algorithm. */ + return MBEDTLS_MD_NONE; + } +} + +/* + * Calculate a hash + * + * output points to the computed hash + */ +static int calc_hash(enum crypto_md_algo md_algo, void *data_ptr, + unsigned int data_len, + unsigned char output[CRYPTO_MD_MAX_SIZE]) +{ + const mbedtls_md_info_t *md_info; + + md_info = mbedtls_md_info_from_type(md_type(md_algo)); + if (md_info == NULL) { + return CRYPTO_ERR_HASH; + } + + /* + * Calculate the hash of the data, it is safe to pass the + * 'output' hash buffer pointer considering its size is always + * bigger than or equal to MBEDTLS_MD_MAX_SIZE. + */ + return mbedtls_md(md_info, data_ptr, data_len, output); +} +#endif /* CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ + CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */ + +#if TF_MBEDTLS_USE_AES_GCM +/* + * Stack based buffer allocation for decryption operation. It could + * be configured to balance stack usage vs execution speed. + */ +#define DEC_OP_BUF_SIZE 128 + +static int aes_gcm_decrypt(void *data_ptr, size_t len, const void *key, + unsigned int key_len, const void *iv, + unsigned int iv_len, const void *tag, + unsigned int tag_len) +{ + mbedtls_gcm_context ctx; + mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES; + unsigned char buf[DEC_OP_BUF_SIZE]; + unsigned char tag_buf[CRYPTO_MAX_TAG_SIZE]; + unsigned char *pt = data_ptr; + size_t dec_len; + int diff, i, rc; + size_t output_length __unused; + + mbedtls_gcm_init(&ctx); + + rc = mbedtls_gcm_setkey(&ctx, cipher, key, key_len * 8); + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len, NULL, 0); +#else + rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len); +#endif + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + while (len > 0) { + dec_len = MIN(sizeof(buf), len); + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_update(&ctx, dec_len, pt, buf); +#else + rc = mbedtls_gcm_update(&ctx, pt, dec_len, buf, sizeof(buf), &output_length); +#endif + + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + memcpy(pt, buf, dec_len); + pt += dec_len; + len -= dec_len; + } + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_finish(&ctx, tag_buf, sizeof(tag_buf)); +#else + rc = mbedtls_gcm_finish(&ctx, NULL, 0, &output_length, tag_buf, sizeof(tag_buf)); +#endif + + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + /* Check tag in "constant-time" */ + for (diff = 0, i = 0; i < tag_len; i++) + diff |= ((const unsigned char *)tag)[i] ^ tag_buf[i]; + + if (diff != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + /* GCM decryption success */ + rc = CRYPTO_SUCCESS; + +exit_gcm: + mbedtls_gcm_free(&ctx); + return rc; +} + +/* + * Authenticated decryption of an image + */ +static int auth_decrypt(enum crypto_dec_algo dec_algo, void *data_ptr, + size_t len, const void *key, unsigned int key_len, + unsigned int key_flags, const void *iv, + unsigned int iv_len, const void *tag, + unsigned int tag_len) +{ + int rc; + + assert((key_flags & ENC_KEY_IS_IDENTIFIER) == 0); + + switch (dec_algo) { + case CRYPTO_GCM_DECRYPT: + rc = aes_gcm_decrypt(data_ptr, len, key, key_len, iv, iv_len, + tag, tag_len); + if (rc != 0) + return rc; + break; + default: + return CRYPTO_ERR_DECRYPTION; + } + + return CRYPTO_SUCCESS; +} +#endif /* TF_MBEDTLS_USE_AES_GCM */ + +/* + * Register crypto library descriptor + */ +#if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +#if TF_MBEDTLS_USE_AES_GCM +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash, + auth_decrypt, NULL); +#else +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash, + NULL, NULL); +#endif +#elif CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY +#if TF_MBEDTLS_USE_AES_GCM +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL, + auth_decrypt, NULL); +#else +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL, + NULL, NULL); +#endif +#elif CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY +REGISTER_CRYPTO_LIB(LIB_NAME, init, NULL, NULL, calc_hash, NULL, NULL); +#endif /* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */ diff --git a/drivers/auth/mbedtls/mbedtls_crypto.mk b/drivers/auth/mbedtls/mbedtls_crypto.mk new file mode 100644 index 0000000..bd36730 --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_crypto.mk @@ -0,0 +1,16 @@ +# +# Copyright (c) 2015-2023, Arm Limited and Contributors. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +include drivers/auth/mbedtls/mbedtls_common.mk + +ifeq (${PSA_CRYPTO},1) + # Some of the PSA functions are declared in multiple header files + # that triggers this warning. + TF_CFLAGS += -Wno-error=redundant-decls + MBEDTLS_SOURCES += drivers/auth/mbedtls/mbedtls_psa_crypto.c +else + MBEDTLS_SOURCES += drivers/auth/mbedtls/mbedtls_crypto.c +endif diff --git a/drivers/auth/mbedtls/mbedtls_psa_crypto.c b/drivers/auth/mbedtls/mbedtls_psa_crypto.c new file mode 100644 index 0000000..5891acf --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_psa_crypto.c @@ -0,0 +1,696 @@ +/* + * Copyright (c) 2023, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +/* mbed TLS headers */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define LIB_NAME "mbed TLS PSA" + +/* Maximum length of R_S pair in the ECDSA signature in bytes */ +#define MAX_ECDSA_R_S_PAIR_LEN 64U + +/* Size of ASN.1 length and tag in bytes*/ +#define SIZE_OF_ASN1_LEN 1U +#define SIZE_OF_ASN1_TAG 1U + +#if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +/* + * CRYPTO_MD_MAX_SIZE value is as per current stronger algorithm available + * so make sure that mbed TLS MD maximum size must be lesser than this. + */ +CASSERT(CRYPTO_MD_MAX_SIZE >= MBEDTLS_MD_MAX_SIZE, + assert_mbedtls_md_size_overflow); + +#endif /* + * CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ + * CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC + */ + +static inline psa_algorithm_t mbedtls_md_psa_alg_from_type( + mbedtls_md_type_t md_type) +{ + assert((md_type == MBEDTLS_MD_SHA256) || + (md_type == MBEDTLS_MD_SHA384) || + (md_type == MBEDTLS_MD_SHA512)); + + return PSA_ALG_CATEGORY_HASH | (psa_algorithm_t) (md_type + 0x5); +} + +/* + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm AlgorithmIdentifier, + * digest OCTET STRING + * } + */ + +/* + * We pretend using an external RNG (through MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + * mbedTLS config option) so we need to provide an implementation of + * mbedtls_psa_external_get_random(). Provide a fake one, since we do not + * actually have any external RNG and TF-A itself doesn't engage in + * cryptographic operations that demands randomness. + */ +psa_status_t mbedtls_psa_external_get_random( + mbedtls_psa_external_random_context_t *context, + uint8_t *output, size_t output_size, + size_t *output_length) +{ + return PSA_ERROR_INSUFFICIENT_ENTROPY; +} + +/* + * Initialize the library and export the descriptor + */ +static void init(void) +{ + /* Initialize mbed TLS */ + mbedtls_init(); + + /* Initialise PSA mbedTLS */ + psa_status_t status = psa_crypto_init(); + + if (status != PSA_SUCCESS) { + ERROR("Failed to initialize %s crypto (%d).\n", LIB_NAME, status); + panic(); + } + + INFO("PSA crypto initialized successfully!\n"); +} + +#if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC + +static void construct_psa_key_alg_and_type(mbedtls_pk_type_t pk_alg, + mbedtls_md_type_t md_alg, + psa_ecc_family_t psa_ecc_family, + psa_algorithm_t *psa_alg, + psa_key_type_t *psa_key_type) +{ + psa_algorithm_t psa_md_alg = mbedtls_md_psa_alg_from_type(md_alg); + + switch (pk_alg) { + case MBEDTLS_PK_RSASSA_PSS: + *psa_alg = PSA_ALG_RSA_PSS(psa_md_alg); + *psa_key_type = PSA_KEY_TYPE_RSA_PUBLIC_KEY; + break; + case MBEDTLS_PK_ECDSA: + *psa_alg = PSA_ALG_ECDSA(psa_md_alg); + *psa_key_type = PSA_KEY_TYPE_ECC_PUBLIC_KEY(psa_ecc_family); + break; + default: + *psa_alg = PSA_ALG_NONE; + *psa_key_type = PSA_KEY_TYPE_NONE; + break; + } +} + + +#if TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_ECDSA || \ +TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_RSA_AND_ECDSA + +/* + * This is a helper function to detect padding byte (if the MSB bit of the + * first data byte is set to 1, for example 0x80) and on detection, ignore the + * padded byte(0x00) and increase the buffer pointer beyond padded byte and + * decrease the length of the buffer by 1. + * + * On Success returns 0, error otherwise. + **/ +static inline int ignore_asn1_int_padding_byte(unsigned char **buf_start, + size_t *buf_len) +{ + unsigned char *local_buf = *buf_start; + + /* Check for negative number */ + if ((local_buf[0] & 0x80U) != 0U) { + return -1; + } + + if ((local_buf[0] == 0U) && (local_buf[1] > 0x7FU) && + (*buf_len > 1U)) { + *buf_start = &local_buf[1]; + (*buf_len)--; + } + + return 0; +} + +/* + * This is a helper function that gets a pointer to the encoded ECDSA publicKey + * and its length (as per RFC5280) and returns corresponding decoded publicKey + * and its length. As well, it retrieves the family of ECC key in the PSA + * format. + * + * This function returns error(CRYPTO_ERR_SIGNATURE) on ASN.1 parsing failure, + * otherwise success(0). + **/ +static int get_ecdsa_pkinfo_from_asn1(unsigned char **pk_start, + unsigned int *pk_len, + psa_ecc_family_t *psa_ecc_family) +{ + mbedtls_asn1_buf alg_oid, alg_params; + mbedtls_ecp_group_id grp_id; + int rc; + unsigned char *pk_end; + size_t len; + size_t curve_bits; + unsigned char *pk_ptr = *pk_start; + + pk_end = pk_ptr + *pk_len; + rc = mbedtls_asn1_get_tag(&pk_ptr, pk_end, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + pk_end = pk_ptr + len; + rc = mbedtls_asn1_get_alg(&pk_ptr, pk_end, &alg_oid, &alg_params); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + if (alg_params.tag == MBEDTLS_ASN1_OID) { + if (mbedtls_oid_get_ec_grp(&alg_params, &grp_id) != 0) { + return CRYPTO_ERR_SIGNATURE; + } + *psa_ecc_family = mbedtls_ecc_group_to_psa(grp_id, + &curve_bits); + } else { + return CRYPTO_ERR_SIGNATURE; + } + + pk_end = pk_ptr + len - (alg_oid.len + alg_params.len + + 2 * (SIZE_OF_ASN1_LEN + SIZE_OF_ASN1_TAG)); + rc = mbedtls_asn1_get_bitstring_null(&pk_ptr, pk_end, &len); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + *pk_start = pk_ptr; + *pk_len = len; + + return rc; +} + +/* + * Ecdsa-Sig-Value ::= SEQUENCE { + * r INTEGER, + * s INTEGER + * } + * + * This helper function that gets a pointer to the encoded ECDSA signature and + * its length (as per RFC5280) and returns corresponding decoded signature + * (R_S pair) and its size. + * + * This function returns error(CRYPTO_ERR_SIGNATURE) on ASN.1 parsing failure, + * otherwise success(0). + **/ +static int get_ecdsa_signature_from_asn1(unsigned char *sig_ptr, + size_t *sig_len, + unsigned char *r_s_pair) +{ + int rc; + unsigned char *sig_end; + size_t len, r_len, s_len; + + sig_end = sig_ptr + *sig_len; + rc = mbedtls_asn1_get_tag(&sig_ptr, sig_end, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + sig_end = sig_ptr + len; + rc = mbedtls_asn1_get_tag(&sig_ptr, sig_end, &r_len, + MBEDTLS_ASN1_INTEGER); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + if (ignore_asn1_int_padding_byte(&sig_ptr, &r_len) != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + (void)memcpy((void *)&r_s_pair[0], (const void *)sig_ptr, r_len); + + sig_ptr = sig_ptr + r_len; + sig_end = sig_ptr + len - (r_len + (SIZE_OF_ASN1_LEN + + SIZE_OF_ASN1_TAG)); + rc = mbedtls_asn1_get_tag(&sig_ptr, sig_end, &s_len, + MBEDTLS_ASN1_INTEGER); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + if (ignore_asn1_int_padding_byte(&sig_ptr, &s_len) != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + (void)memcpy((void *)&r_s_pair[r_len], (const void *)sig_ptr, s_len); + + *sig_len = s_len + r_len; + + return 0; +} +#endif /* + * TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_ECDSA || \ + * TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_RSA_AND_ECDSA + **/ + +/* + * Verify a signature. + * + * Parameters are passed using the DER encoding format following the ASN.1 + * structures detailed above. + */ +static int verify_signature(void *data_ptr, unsigned int data_len, + void *sig_ptr, unsigned int sig_len, + void *sig_alg, unsigned int sig_alg_len, + void *pk_ptr, unsigned int pk_len) +{ + mbedtls_asn1_buf sig_oid, sig_params; + mbedtls_asn1_buf signature; + mbedtls_md_type_t md_alg; + mbedtls_pk_type_t pk_alg; + int rc; + void *sig_opts = NULL; + unsigned char *p, *end; + unsigned char *local_sig_ptr; + size_t local_sig_len; + psa_ecc_family_t psa_ecc_family = 0U; + __unused unsigned char reformatted_sig[MAX_ECDSA_R_S_PAIR_LEN] = {0}; + + /* construct PSA key algo and type */ + psa_status_t status = PSA_SUCCESS; + psa_key_attributes_t psa_key_attr = PSA_KEY_ATTRIBUTES_INIT; + psa_key_id_t psa_key_id = PSA_KEY_ID_NULL; + psa_key_type_t psa_key_type; + psa_algorithm_t psa_alg; + + /* Get pointers to signature OID and parameters */ + p = (unsigned char *)sig_alg; + end = (unsigned char *)(p + sig_alg_len); + rc = mbedtls_asn1_get_alg(&p, end, &sig_oid, &sig_params); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + /* Get the actual signature algorithm (MD + PK) */ + rc = mbedtls_x509_get_sig_alg(&sig_oid, &sig_params, &md_alg, &pk_alg, &sig_opts); + if (rc != 0) { + return CRYPTO_ERR_SIGNATURE; + } + + /* Get the signature (bitstring) */ + p = (unsigned char *)sig_ptr; + end = (unsigned char *)(p + sig_len); + signature.tag = *p; + rc = mbedtls_asn1_get_bitstring_null(&p, end, &signature.len); + if ((rc != 0) || ((size_t)(end - p) != signature.len)) { + rc = CRYPTO_ERR_SIGNATURE; + goto end2; + } + + local_sig_ptr = p; + local_sig_len = signature.len; + +#if TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_ECDSA || \ +TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_RSA_AND_ECDSA + if (pk_alg == MBEDTLS_PK_ECDSA) { + rc = get_ecdsa_signature_from_asn1(local_sig_ptr, + &local_sig_len, + reformatted_sig); + if (rc != 0) { + goto end2; + } + + local_sig_ptr = reformatted_sig; + + rc = get_ecdsa_pkinfo_from_asn1((unsigned char **)&pk_ptr, + &pk_len, + &psa_ecc_family); + if (rc != 0) { + goto end2; + } + } +#endif /* + * TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_ECDSA || \ + * TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_RSA_AND_ECDSA + **/ + + /* Convert this pk_alg and md_alg to PSA key type and key algorithm */ + construct_psa_key_alg_and_type(pk_alg, md_alg, psa_ecc_family, + &psa_alg, &psa_key_type); + + + if ((psa_alg == PSA_ALG_NONE) || (psa_key_type == PSA_KEY_TYPE_NONE)) { + rc = CRYPTO_ERR_SIGNATURE; + goto end2; + } + + /* filled-in key_attributes */ + psa_set_key_algorithm(&psa_key_attr, psa_alg); + psa_set_key_type(&psa_key_attr, psa_key_type); + psa_set_key_usage_flags(&psa_key_attr, PSA_KEY_USAGE_VERIFY_MESSAGE); + + /* Get the key_id using import API */ + status = psa_import_key(&psa_key_attr, + pk_ptr, + (size_t)pk_len, + &psa_key_id); + + if (status != PSA_SUCCESS) { + rc = CRYPTO_ERR_SIGNATURE; + goto end2; + } + + /* + * Hash calculation and Signature verification of the given data payload + * is wrapped under the psa_verify_message function. + */ + status = psa_verify_message(psa_key_id, psa_alg, + data_ptr, data_len, + local_sig_ptr, local_sig_len); + + if (status != PSA_SUCCESS) { + rc = CRYPTO_ERR_SIGNATURE; + goto end1; + } + + /* Signature verification success */ + rc = CRYPTO_SUCCESS; + +end1: + /* + * Destroy the key if it is created successfully + */ + psa_destroy_key(psa_key_id); +end2: + mbedtls_free(sig_opts); + return rc; +} + +/* + * Match a hash + * + * Digest info is passed in DER format following the ASN.1 structure detailed + * above. + */ +static int verify_hash(void *data_ptr, unsigned int data_len, + void *digest_info_ptr, unsigned int digest_info_len) +{ + mbedtls_asn1_buf hash_oid, params; + mbedtls_md_type_t md_alg; + unsigned char *p, *end, *hash; + size_t len; + int rc; + psa_status_t status; + psa_algorithm_t psa_md_alg; + + /* + * Digest info should be an MBEDTLS_ASN1_SEQUENCE, but padding after + * it is allowed. This is necessary to support multiple hash + * algorithms. + */ + p = (unsigned char *)digest_info_ptr; + end = p + digest_info_len; + rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + end = p + len; + + /* Get the hash algorithm */ + rc = mbedtls_asn1_get_alg(&p, end, &hash_oid, ¶ms); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + /* Hash should be octet string type and consume all bytes */ + rc = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); + if ((rc != 0) || ((size_t)(end - p) != len)) { + return CRYPTO_ERR_HASH; + } + hash = p; + + rc = mbedtls_oid_get_md_alg(&hash_oid, &md_alg); + if (rc != 0) { + return CRYPTO_ERR_HASH; + } + + /* convert the md_alg to psa_algo */ + psa_md_alg = mbedtls_md_psa_alg_from_type(md_alg); + + /* Length of hash must match the algorithm's size */ + if (len != PSA_HASH_LENGTH(psa_md_alg)) { + return CRYPTO_ERR_HASH; + } + + /* + * Calculate Hash and compare it against the retrieved hash from + * the certificate (one shot API). + */ + status = psa_hash_compare(psa_md_alg, + data_ptr, (size_t)data_len, + (const uint8_t *)hash, len); + + if (status != PSA_SUCCESS) { + return CRYPTO_ERR_HASH; + } + + return CRYPTO_SUCCESS; +} +#endif /* + * CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY || \ + * CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC + */ + +#if CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ +CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +/* + * Map a generic crypto message digest algorithm to the corresponding macro used + * by Mbed TLS. + */ +static inline mbedtls_md_type_t md_type(enum crypto_md_algo algo) +{ + switch (algo) { + case CRYPTO_MD_SHA512: + return MBEDTLS_MD_SHA512; + case CRYPTO_MD_SHA384: + return MBEDTLS_MD_SHA384; + case CRYPTO_MD_SHA256: + return MBEDTLS_MD_SHA256; + default: + /* Invalid hash algorithm. */ + return MBEDTLS_MD_NONE; + } +} + +/* + * Calculate a hash + * + * output points to the computed hash + */ +static int calc_hash(enum crypto_md_algo md_algo, void *data_ptr, + unsigned int data_len, + unsigned char output[CRYPTO_MD_MAX_SIZE]) +{ + size_t hash_length; + psa_status_t status; + psa_algorithm_t psa_md_alg; + + /* convert the md_alg to psa_algo */ + psa_md_alg = mbedtls_md_psa_alg_from_type(md_type(md_algo)); + + /* + * Calculate the hash of the data, it is safe to pass the + * 'output' hash buffer pointer considering its size is always + * bigger than or equal to MBEDTLS_MD_MAX_SIZE. + */ + status = psa_hash_compute(psa_md_alg, data_ptr, (size_t)data_len, + (uint8_t *)output, CRYPTO_MD_MAX_SIZE, + &hash_length); + if (status != PSA_SUCCESS) { + return CRYPTO_ERR_HASH; + } + + return CRYPTO_SUCCESS; +} +#endif /* + * CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY || \ + * CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC + */ + +#if TF_MBEDTLS_USE_AES_GCM +/* + * Stack based buffer allocation for decryption operation. It could + * be configured to balance stack usage vs execution speed. + */ +#define DEC_OP_BUF_SIZE 128 + +static int aes_gcm_decrypt(void *data_ptr, size_t len, const void *key, + unsigned int key_len, const void *iv, + unsigned int iv_len, const void *tag, + unsigned int tag_len) +{ + mbedtls_gcm_context ctx; + mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES; + unsigned char buf[DEC_OP_BUF_SIZE]; + unsigned char tag_buf[CRYPTO_MAX_TAG_SIZE]; + unsigned char *pt = data_ptr; + size_t dec_len; + int diff, i, rc; + size_t output_length __unused; + + mbedtls_gcm_init(&ctx); + + rc = mbedtls_gcm_setkey(&ctx, cipher, key, key_len * 8); + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len, NULL, 0); +#else + rc = mbedtls_gcm_starts(&ctx, MBEDTLS_GCM_DECRYPT, iv, iv_len); +#endif + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + while (len > 0) { + dec_len = MIN(sizeof(buf), len); + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_update(&ctx, dec_len, pt, buf); +#else + rc = mbedtls_gcm_update(&ctx, pt, dec_len, buf, sizeof(buf), &output_length); +#endif + + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + memcpy(pt, buf, dec_len); + pt += dec_len; + len -= dec_len; + } + +#if (MBEDTLS_VERSION_MAJOR < 3) + rc = mbedtls_gcm_finish(&ctx, tag_buf, sizeof(tag_buf)); +#else + rc = mbedtls_gcm_finish(&ctx, NULL, 0, &output_length, tag_buf, sizeof(tag_buf)); +#endif + + if (rc != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + /* Check tag in "constant-time" */ + for (diff = 0, i = 0; i < tag_len; i++) + diff |= ((const unsigned char *)tag)[i] ^ tag_buf[i]; + + if (diff != 0) { + rc = CRYPTO_ERR_DECRYPTION; + goto exit_gcm; + } + + /* GCM decryption success */ + rc = CRYPTO_SUCCESS; + +exit_gcm: + mbedtls_gcm_free(&ctx); + return rc; +} + +/* + * Authenticated decryption of an image + */ +static int auth_decrypt(enum crypto_dec_algo dec_algo, void *data_ptr, + size_t len, const void *key, unsigned int key_len, + unsigned int key_flags, const void *iv, + unsigned int iv_len, const void *tag, + unsigned int tag_len) +{ + int rc; + + assert((key_flags & ENC_KEY_IS_IDENTIFIER) == 0); + + switch (dec_algo) { + case CRYPTO_GCM_DECRYPT: + rc = aes_gcm_decrypt(data_ptr, len, key, key_len, iv, iv_len, + tag, tag_len); + if (rc != 0) + return rc; + break; + default: + return CRYPTO_ERR_DECRYPTION; + } + + return CRYPTO_SUCCESS; +} +#endif /* TF_MBEDTLS_USE_AES_GCM */ + +/* + * Register crypto library descriptor + */ +#if CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC +#if TF_MBEDTLS_USE_AES_GCM +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash, + auth_decrypt, NULL); +#else +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, calc_hash, + NULL, NULL); +#endif +#elif CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_ONLY +#if TF_MBEDTLS_USE_AES_GCM +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL, + auth_decrypt, NULL); +#else +REGISTER_CRYPTO_LIB(LIB_NAME, init, verify_signature, verify_hash, NULL, + NULL, NULL); +#endif +#elif CRYPTO_SUPPORT == CRYPTO_HASH_CALC_ONLY +REGISTER_CRYPTO_LIB(LIB_NAME, init, NULL, NULL, calc_hash, NULL, NULL); +#endif /* CRYPTO_SUPPORT == CRYPTO_AUTH_VERIFY_AND_HASH_CALC */ diff --git a/drivers/auth/mbedtls/mbedtls_x509.mk b/drivers/auth/mbedtls/mbedtls_x509.mk new file mode 100644 index 0000000..a0557e2 --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_x509.mk @@ -0,0 +1,9 @@ +# +# Copyright (c) 2015, ARM Limited and Contributors. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +include drivers/auth/mbedtls/mbedtls_common.mk + +MBEDTLS_SOURCES += drivers/auth/mbedtls/mbedtls_x509_parser.c diff --git a/drivers/auth/mbedtls/mbedtls_x509_parser.c b/drivers/auth/mbedtls/mbedtls_x509_parser.c new file mode 100644 index 0000000..8bde5bb --- /dev/null +++ b/drivers/auth/mbedtls/mbedtls_x509_parser.c @@ -0,0 +1,508 @@ +/* + * Copyright (c) 2015-2023, ARM Limited and Contributors. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * X509 parser based on mbed TLS + * + * This module implements functions to check the integrity of a X509v3 + * certificate ASN.1 structure and extract authentication parameters from the + * extensions field, such as an image hash or a public key. + */ + +#include +#include +#include +#include + +/* mbed TLS headers */ +#include +#include +#include + +#include +#include +#include +#include + +/* Maximum OID string length ("a.b.c.d.e.f ...") */ +#define MAX_OID_STR_LEN 64 + +#define LIB_NAME "mbed TLS X509v3" + +/* Temporary variables to speed up the authentication parameters search. These + * variables are assigned once during the integrity check and used any time an + * authentication parameter is requested, so we do not have to parse the image + * again */ +static mbedtls_asn1_buf tbs; +static mbedtls_asn1_buf v3_ext; +static mbedtls_asn1_buf pk; +static mbedtls_asn1_buf sig_alg; +static mbedtls_asn1_buf signature; + +/* + * Clear all static temporary variables. + */ +static void clear_temp_vars(void) +{ +#define ZERO_AND_CLEAN(x) \ + do { \ + zeromem(&x, sizeof(x)); \ + clean_dcache_range((uintptr_t)&x, sizeof(x)); \ + } while (0); + + ZERO_AND_CLEAN(tbs) + ZERO_AND_CLEAN(v3_ext); + ZERO_AND_CLEAN(pk); + ZERO_AND_CLEAN(sig_alg); + ZERO_AND_CLEAN(signature); + +#undef ZERO_AND_CLEAN +} + +/* + * Get X509v3 extension + * + * Global variable 'v3_ext' must point to the extensions region + * in the certificate. OID may be NULL to request that get_ext() + * is only being called for integrity checking. + */ +static int get_ext(const char *oid, void **ext, unsigned int *ext_len) +{ + int oid_len, ret, is_critical; + size_t len; + unsigned char *p; + const unsigned char *end; + char oid_str[MAX_OID_STR_LEN]; + mbedtls_asn1_buf extn_oid; + + p = v3_ext.p; + end = v3_ext.p + v3_ext.len; + + /* + * Check extensions integrity. At least one extension is + * required: the ASN.1 specifies a minimum size of 1, and at + * least one extension is needed to authenticate the next stage + * in the boot chain. + */ + do { + unsigned char *end_ext_data; + + ret = mbedtls_asn1_get_tag(&p, end, &len, + MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + end_ext_data = p + len; + + /* Get extension ID */ + ret = mbedtls_asn1_get_tag(&p, end_ext_data, &extn_oid.len, + MBEDTLS_ASN1_OID); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + extn_oid.tag = MBEDTLS_ASN1_OID; + extn_oid.p = p; + p += extn_oid.len; + + /* Get optional critical */ + ret = mbedtls_asn1_get_bool(&p, end_ext_data, &is_critical); + if ((ret != 0) && (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG)) { + return IMG_PARSER_ERR_FORMAT; + } + + /* + * Data should be octet string type and must use all bytes in + * the Extension. + */ + ret = mbedtls_asn1_get_tag(&p, end_ext_data, &len, + MBEDTLS_ASN1_OCTET_STRING); + if ((ret != 0) || ((p + len) != end_ext_data)) { + return IMG_PARSER_ERR_FORMAT; + } + + /* Detect requested extension */ + oid_len = mbedtls_oid_get_numeric_string(oid_str, + MAX_OID_STR_LEN, + &extn_oid); + if ((oid_len == MBEDTLS_ERR_OID_BUF_TOO_SMALL) || (oid_len < 0)) { + return IMG_PARSER_ERR; + } + + if ((oid != NULL) && + ((size_t)oid_len == strlen(oid_str)) && + (strcmp(oid, oid_str) == 0)) { + /* Extension must be ASN.1 DER */ + if (len < 2) { + /* too short */ + return IMG_PARSER_ERR_FORMAT; + } + + if ((p[0] & 0x1F) == 0x1F) { + /* multi-byte ASN.1 DER tag, not allowed */ + return IMG_PARSER_ERR_FORMAT; + } + + if ((p[0] & 0xDF) == 0) { + /* UNIVERSAL 0 tag, not allowed */ + return IMG_PARSER_ERR_FORMAT; + } + + *ext = (void *)p; + *ext_len = (unsigned int)len; + + /* Advance past the tag byte */ + p++; + + if (mbedtls_asn1_get_len(&p, end_ext_data, &len)) { + /* not valid DER */ + return IMG_PARSER_ERR_FORMAT; + } + + if (p + len != end_ext_data) { + /* junk after ASN.1 object */ + return IMG_PARSER_ERR_FORMAT; + } + + return IMG_PARSER_OK; + } + + /* Next */ + p = end_ext_data; + } while (p < end); + + return (oid == NULL) ? IMG_PARSER_OK : IMG_PARSER_ERR_NOT_FOUND; +} + + +/* + * Check the integrity of the certificate ASN.1 structure. + * + * Extract the relevant data that will be used later during authentication. + * + * This function doesn't clear the static variables located on the top of this + * file in case of an error. It is only called from check_integrity(), which + * performs the cleanup if necessary. + */ +static int cert_parse(void *img, unsigned int img_len) +{ + int ret; + size_t len; + unsigned char *p, *end, *crt_end, *pk_end; + mbedtls_asn1_buf sig_alg1; + /* + * The unique ASN.1 DER encoding of [0] EXPLICIT INTEGER { v3(2} }. + */ + static const char v3[] = { + /* The outer CONTEXT SPECIFIC 0 tag */ + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0, + /* The number bytes used to encode the inner INTEGER */ + 3, + /* The tag of the inner INTEGER */ + MBEDTLS_ASN1_INTEGER, + /* The number of bytes needed to represent 2 */ + 1, + /* The actual value 2 */ + 2, + }; + + p = (unsigned char *)img; + len = img_len; + crt_end = p + len; + end = crt_end; + + /* + * Certificate ::= SEQUENCE { + * tbsCertificate TBSCertificate, + * signatureAlgorithm AlgorithmIdentifier, + * signatureValue BIT STRING } + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if ((ret != 0) || ((p + len) != end)) { + return IMG_PARSER_ERR_FORMAT; + } + + /* + * TBSCertificate ::= SEQUENCE { + */ + tbs.p = p; + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + end = p + len; + tbs.len = end - tbs.p; + + /* + * Version ::= [0] EXPLICIT INTEGER { v1(0), v2(1), v3(2) } + * -- only v3 accepted + */ + if (((end - p) <= (ptrdiff_t)sizeof(v3)) || + (memcmp(p, v3, sizeof(v3)) != 0)) { + return IMG_PARSER_ERR_FORMAT; + } + p += sizeof(v3); + + /* + * CertificateSerialNumber ::= INTEGER + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + + /* + * signature AlgorithmIdentifier + */ + sig_alg1.p = p; + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + sig_alg1.len = (p + len) - sig_alg1.p; + p += len; + + /* + * issuer Name + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + + /* + * Validity ::= SEQUENCE { + * notBefore Time, + * notAfter Time } + * + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + + /* + * subject Name + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + + /* + * SubjectPublicKeyInfo + */ + pk.p = p; + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + pk_end = p + len; + pk.len = pk_end - pk.p; + + /* algorithm */ + ret = mbedtls_asn1_get_tag(&p, pk_end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + + /* Key is a BIT STRING and must use all bytes in SubjectPublicKeyInfo */ + ret = mbedtls_asn1_get_bitstring_null(&p, pk_end, &len); + if ((ret != 0) || (p + len != pk_end)) { + return IMG_PARSER_ERR_FORMAT; + } + p = pk_end; + + /* + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, + * -- technically these contain BIT STRINGs but that is not worth + * -- validating + */ + for (int i = 1; i < 3; i++) { + ret = mbedtls_asn1_get_tag(&p, end, &len, + MBEDTLS_ASN1_CONTEXT_SPECIFIC | + MBEDTLS_ASN1_CONSTRUCTED | i); + /* + * Unique IDs are obsolete, so MBEDTLS_ERR_ASN1_UNEXPECTED_TAG + * is the common case. + */ + if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) { + if (ret != 0) { + return IMG_PARSER_ERR_FORMAT; + } + p += len; + } + } + + /* + * extensions [3] EXPLICIT Extensions OPTIONAL + * } + * + * X.509 and RFC5280 allow omitting the extensions entirely. + * However, in TF-A, a certificate with no extensions would + * always fail later on, as the extensions contain the + * information needed to authenticate the next stage in the + * boot chain. Furthermore, get_ext() assumes that the + * extensions have been parsed into v3_ext, and allowing + * there to be no extensions would pointlessly complicate + * the code. Therefore, just reject certificates without + * extensions. This is also why version 1 and 2 certificates + * are rejected above. + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, + MBEDTLS_ASN1_CONTEXT_SPECIFIC | + MBEDTLS_ASN1_CONSTRUCTED | 3); + if ((ret != 0) || (len != (size_t)(end - p))) { + return IMG_PARSER_ERR_FORMAT; + } + + /* + * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension + * -- must use all remaining bytes in TBSCertificate + */ + ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | + MBEDTLS_ASN1_SEQUENCE); + if ((ret != 0) || (len != (size_t)(end - p))) { + return IMG_PARSER_ERR_FORMAT; + } + v3_ext.p = p; + v3_ext.len = len; + p += len; + + /* Check extensions integrity */ + ret = get_ext(NULL, NULL, NULL); + if (ret != IMG_PARSER_OK) { + return ret; + } + + end = crt_end; + + /* + * } + * -- end of TBSCertificate + * + * signatureAlgorithm AlgorithmIdentifier + * -- Does not need to be parsed. Ensuring it is bitwise + * -- identical (including the tag!) with the first signature + * -- algorithm is sufficient. + */ + if ((sig_alg1.len >= (size_t)(end - p)) || + (0 != memcmp(sig_alg1.p, p, sig_alg1.len))) { + return IMG_PARSER_ERR_FORMAT; + } + p += sig_alg1.len; + memcpy(&sig_alg, &sig_alg1, sizeof(sig_alg)); + + /* + * signatureValue BIT STRING + * } -- must consume all bytes + */ + signature.p = p; + ret = mbedtls_asn1_get_bitstring_null(&p, end, &len); + if ((ret != 0) || ((p + len) != end)) { + return IMG_PARSER_ERR_FORMAT; + } + signature.len = end - signature.p; + + return IMG_PARSER_OK; +} + + +/* Exported functions */ + +static void init(void) +{ + mbedtls_init(); +} + +/* + * Wrapper for cert_parse() that clears the static variables used by it in case + * of an error. + */ +static int check_integrity(void *img, unsigned int img_len) +{ + int rc = cert_parse(img, img_len); + + if (rc != IMG_PARSER_OK) + clear_temp_vars(); + + return rc; +} + +/* + * Extract an authentication parameter from an X509v3 certificate + * + * This function returns a pointer to the extracted data and its length. + * Depending on the type of parameter, a pointer to the data stored in the + * certificate may be returned (i.e. an octet string containing a hash). Other + * data may need to be copied and formatted (i.e. integers). In the later case, + * a buffer of the correct type needs to be statically allocated, filled and + * returned. + */ +static int get_auth_param(const auth_param_type_desc_t *type_desc, + void *img, unsigned int img_len, + void **param, unsigned int *param_len) +{ + int rc = IMG_PARSER_OK; + + /* We do not use img because the check_integrity function has already + * extracted the relevant data (v3_ext, pk, sig_alg, etc) */ + + switch (type_desc->type) { + case AUTH_PARAM_RAW_DATA: + /* Data to be signed */ + *param = (void *)tbs.p; + *param_len = (unsigned int)tbs.len; + break; + case AUTH_PARAM_HASH: + case AUTH_PARAM_NV_CTR: + /* All these parameters are included as X509v3 extensions */ + rc = get_ext(type_desc->cookie, param, param_len); + break; + case AUTH_PARAM_PUB_KEY: + if (type_desc->cookie != NULL) { + /* Get public key from extension */ + rc = get_ext(type_desc->cookie, param, param_len); + } else { + /* Get the subject public key */ + *param = (void *)pk.p; + *param_len = (unsigned int)pk.len; + } + break; + case AUTH_PARAM_SIG_ALG: + /* Get the certificate signature algorithm */ + *param = (void *)sig_alg.p; + *param_len = (unsigned int)sig_alg.len; + break; + case AUTH_PARAM_SIG: + /* Get the certificate signature */ + *param = (void *)signature.p; + *param_len = (unsigned int)signature.len; + break; + default: + rc = IMG_PARSER_ERR_NOT_FOUND; + break; + } + + return rc; +} + +REGISTER_IMG_PARSER_LIB(IMG_CERT, LIB_NAME, init, + check_integrity, get_auth_param); -- cgit v1.2.3