diff --git a/.gitignore b/.gitignore index 3da68113d3..bb38bb5104 100644 --- a/.gitignore +++ b/.gitignore @@ -99,7 +99,8 @@ test_suite.json DELIVERY/ # Directory used to clone and build TF-M -features/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_IGNORE/ +platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/TARGET_IGNORE/ +platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_IGNORE/ # CMake CMakeCache.txt diff --git a/connectivity/drivers/mbedtls/TARGET_Cypress/TARGET_MXCRYPTO/ecp_alt.c b/connectivity/drivers/mbedtls/TARGET_Cypress/TARGET_MXCRYPTO/ecp_alt.c index 715cf98328..01fca251e0 100644 --- a/connectivity/drivers/mbedtls/TARGET_Cypress/TARGET_MXCRYPTO/ecp_alt.c +++ b/connectivity/drivers/mbedtls/TARGET_Cypress/TARGET_MXCRYPTO/ecp_alt.c @@ -2619,6 +2619,44 @@ cleanup: return( ret ); } +/* + * Write a private key. + */ +int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key, + unsigned char *buf, size_t buflen ) +{ + int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + + ECP_VALIDATE_RET( key != NULL ); + ECP_VALIDATE_RET( buf != NULL ); + +#if defined(ECP_MONTGOMERY) + if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) + { + if( key->grp.id == MBEDTLS_ECP_DP_CURVE25519 ) + { + if( buflen < ECP_CURVE25519_KEY_SIZE ) + return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; + + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &key->d, buf, buflen ) ); + } + else + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + } + +#endif +#if defined(ECP_SHORTWEIERSTRASS) + if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &key->d, buf, buflen ) ); + } + +#endif +cleanup: + + return( ret ); +} + /* * Check a public-private key pair */ diff --git a/connectivity/mbedtls/CMakeLists.txt b/connectivity/mbedtls/CMakeLists.txt index 07ea78117f..cac099b0a6 100644 --- a/connectivity/mbedtls/CMakeLists.txt +++ b/connectivity/mbedtls/CMakeLists.txt @@ -12,6 +12,7 @@ target_include_directories(mbed-mbedtls target_sources(mbed-mbedtls INTERFACE + platform/src/hash_wrappers.c platform/src/mbed_trng.cpp platform/src/platform_alt.cpp platform/src/shared_rng.cpp @@ -46,7 +47,6 @@ target_sources(mbed-mbedtls source/entropy_poll.c source/error.c source/gcm.c - source/hash_wrappers.c source/havege.c source/hkdf.c source/hmac_drbg.c diff --git a/connectivity/mbedtls/include/mbedtls/aes.h b/connectivity/mbedtls/include/mbedtls/aes.h index 63c0f672bb..052f47c9d1 100644 --- a/connectivity/mbedtls/include/mbedtls/aes.h +++ b/connectivity/mbedtls/include/mbedtls/aes.h @@ -20,7 +20,8 @@ * . */ -/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -34,8 +35,6 @@ * 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_AES_H diff --git a/connectivity/mbedtls/include/mbedtls/aesni.h b/connectivity/mbedtls/include/mbedtls/aesni.h index 955b7c9909..c1d22f59af 100644 --- a/connectivity/mbedtls/include/mbedtls/aesni.h +++ b/connectivity/mbedtls/include/mbedtls/aesni.h @@ -7,7 +7,7 @@ * functions; you must not call them directly. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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_AESNI_H #define MBEDTLS_AESNI_H diff --git a/connectivity/mbedtls/include/mbedtls/arc4.h b/connectivity/mbedtls/include/mbedtls/arc4.h index acad623ad3..17728f4173 100644 --- a/connectivity/mbedtls/include/mbedtls/arc4.h +++ b/connectivity/mbedtls/include/mbedtls/arc4.h @@ -7,7 +7,7 @@ * security risk. We recommend considering stronger ciphers instead. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_ARC4_H #define MBEDTLS_ARC4_H diff --git a/connectivity/mbedtls/include/mbedtls/aria.h b/connectivity/mbedtls/include/mbedtls/aria.h index a72a8c22a3..a4b27b33bc 100644 --- a/connectivity/mbedtls/include/mbedtls/aria.h +++ b/connectivity/mbedtls/include/mbedtls/aria.h @@ -9,7 +9,8 @@ * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) * and also described by the IETF in RFC 5794. */ -/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +24,6 @@ * 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_ARIA_H diff --git a/connectivity/mbedtls/include/mbedtls/asn1.h b/connectivity/mbedtls/include/mbedtls/asn1.h index 4c61b6e1c3..6b791966f1 100644 --- a/connectivity/mbedtls/include/mbedtls/asn1.h +++ b/connectivity/mbedtls/include/mbedtls/asn1.h @@ -4,7 +4,7 @@ * \brief Generic ASN.1 parsing */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ASN1_H #define MBEDTLS_ASN1_H diff --git a/connectivity/mbedtls/include/mbedtls/asn1write.h b/connectivity/mbedtls/include/mbedtls/asn1write.h index 0bce28ed13..44afae0e56 100644 --- a/connectivity/mbedtls/include/mbedtls/asn1write.h +++ b/connectivity/mbedtls/include/mbedtls/asn1write.h @@ -4,7 +4,7 @@ * \brief ASN.1 buffer writing functionality */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ASN1_WRITE_H #define MBEDTLS_ASN1_WRITE_H diff --git a/connectivity/mbedtls/include/mbedtls/base64.h b/connectivity/mbedtls/include/mbedtls/base64.h index 07ae3bf541..7e73a8bd16 100644 --- a/connectivity/mbedtls/include/mbedtls/base64.h +++ b/connectivity/mbedtls/include/mbedtls/base64.h @@ -4,7 +4,7 @@ * \brief RFC 1521 base64 encoding/decoding */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_BASE64_H #define MBEDTLS_BASE64_H diff --git a/connectivity/mbedtls/include/mbedtls/bignum.h b/connectivity/mbedtls/include/mbedtls/bignum.h index 1d00c560a6..0d019b9c44 100644 --- a/connectivity/mbedtls/include/mbedtls/bignum.h +++ b/connectivity/mbedtls/include/mbedtls/bignum.h @@ -4,7 +4,7 @@ * \brief Multi-precision integer library */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_BIGNUM_H #define MBEDTLS_BIGNUM_H diff --git a/connectivity/mbedtls/include/mbedtls/blowfish.h b/connectivity/mbedtls/include/mbedtls/blowfish.h index 1e5dba3a39..c2a6ff9168 100644 --- a/connectivity/mbedtls/include/mbedtls/blowfish.h +++ b/connectivity/mbedtls/include/mbedtls/blowfish.h @@ -4,7 +4,7 @@ * \brief Blowfish block cipher */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_BLOWFISH_H #define MBEDTLS_BLOWFISH_H diff --git a/connectivity/mbedtls/include/mbedtls/bn_mul.h b/connectivity/mbedtls/include/mbedtls/bn_mul.h index 163869ae79..17d057f3ab 100644 --- a/connectivity/mbedtls/include/mbedtls/bn_mul.h +++ b/connectivity/mbedtls/include/mbedtls/bn_mul.h @@ -4,7 +4,7 @@ * \brief Multi-precision integer library */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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) */ /* * Multiply source vector [s] with b, add result diff --git a/connectivity/mbedtls/include/mbedtls/camellia.h b/connectivity/mbedtls/include/mbedtls/camellia.h index a8324543c8..f7d2b23a45 100644 --- a/connectivity/mbedtls/include/mbedtls/camellia.h +++ b/connectivity/mbedtls/include/mbedtls/camellia.h @@ -4,7 +4,7 @@ * \brief Camellia block cipher */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_CAMELLIA_H #define MBEDTLS_CAMELLIA_H diff --git a/connectivity/mbedtls/include/mbedtls/ccm.h b/connectivity/mbedtls/include/mbedtls/ccm.h index ceac36ca39..81965ba4df 100644 --- a/connectivity/mbedtls/include/mbedtls/ccm.h +++ b/connectivity/mbedtls/include/mbedtls/ccm.h @@ -28,7 +28,7 @@ * consistent with RFC 3610. */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -42,8 +42,6 @@ * 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_CCM_H diff --git a/connectivity/mbedtls/include/mbedtls/certs.h b/connectivity/mbedtls/include/mbedtls/certs.h index 8beb380ffe..c93c741c7f 100644 --- a/connectivity/mbedtls/include/mbedtls/certs.h +++ b/connectivity/mbedtls/include/mbedtls/certs.h @@ -4,7 +4,7 @@ * \brief Sample certificates and DHM parameters for testing */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_CERTS_H #define MBEDTLS_CERTS_H diff --git a/connectivity/mbedtls/include/mbedtls/chacha20.h b/connectivity/mbedtls/include/mbedtls/chacha20.h index 243ae63af7..e59dd1fa30 100644 --- a/connectivity/mbedtls/include/mbedtls/chacha20.h +++ b/connectivity/mbedtls/include/mbedtls/chacha20.h @@ -12,7 +12,8 @@ * \author Daniel King */ -/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -26,8 +27,6 @@ * 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_CHACHA20_H diff --git a/connectivity/mbedtls/include/mbedtls/chachapoly.h b/connectivity/mbedtls/include/mbedtls/chachapoly.h index 3d842ef19e..1007f95bbb 100644 --- a/connectivity/mbedtls/include/mbedtls/chachapoly.h +++ b/connectivity/mbedtls/include/mbedtls/chachapoly.h @@ -12,7 +12,8 @@ * \author Daniel King */ -/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -26,8 +27,6 @@ * 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_CHACHAPOLY_H diff --git a/connectivity/mbedtls/include/mbedtls/check_config.h b/connectivity/mbedtls/include/mbedtls/check_config.h index 8db7825406..3a1929ba93 100644 --- a/connectivity/mbedtls/include/mbedtls/check_config.h +++ b/connectivity/mbedtls/include/mbedtls/check_config.h @@ -4,7 +4,7 @@ * \brief Consistency checks for configuration options */ /* - * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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) */ /* @@ -103,6 +101,17 @@ #if defined(MBEDTLS_ECDSA_C) && \ ( !defined(MBEDTLS_ECP_C) || \ + !( defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) ) || \ !defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_ASN1_WRITE_C) ) #error "MBEDTLS_ECDSA_C defined, but not all prerequisites" @@ -156,6 +165,14 @@ #error "MBEDTLS_ECP_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_ECP_C) && !( \ + defined(MBEDTLS_ECP_ALT) || \ + defined(MBEDTLS_CTR_DRBG_C) || \ + defined(MBEDTLS_HMAC_DRBG_C) || \ + defined(MBEDTLS_ECP_NO_INTERNAL_RNG)) +#error "MBEDTLS_ECP_C requires a DRBG module unless MBEDTLS_ECP_NO_INTERNAL_RNG is defined or an alternative implementation is used" +#endif + #if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C) #error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites" #endif @@ -178,6 +195,16 @@ #error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites" #endif +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) +#define MBEDTLS_HAS_MEMSAN +#endif +#endif +#if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) && !defined(MBEDTLS_HAS_MEMSAN) +#error "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN requires building with MemorySanitizer" +#endif +#undef MBEDTLS_HAS_MEMSAN + #if defined(MBEDTLS_TEST_NULL_ENTROPY) && \ ( !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) ) #error "MBEDTLS_TEST_NULL_ENTROPY defined, but not all prerequisites" @@ -238,12 +265,14 @@ #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \ - ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) ) + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) || \ + !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ - ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) ) + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) || \ + !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites" #endif @@ -614,6 +643,11 @@ #error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites" #endif +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) && ( !defined(MBEDTLS_HKDF_C) && \ + !defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA512_C) ) +#error "MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL defined, but not all prerequisites" +#endif + #if (defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)) && \ !(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ diff --git a/connectivity/mbedtls/include/mbedtls/cipher.h b/connectivity/mbedtls/include/mbedtls/cipher.h index 96efd937f8..014786ad51 100644 --- a/connectivity/mbedtls/include/mbedtls/cipher.h +++ b/connectivity/mbedtls/include/mbedtls/cipher.h @@ -8,7 +8,7 @@ * \author Adriaan de Jong */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_CIPHER_H diff --git a/connectivity/mbedtls/include/mbedtls/cipher_internal.h b/connectivity/mbedtls/include/mbedtls/cipher_internal.h index 5930f0e2a1..d28310847a 100644 --- a/connectivity/mbedtls/include/mbedtls/cipher_internal.h +++ b/connectivity/mbedtls/include/mbedtls/cipher_internal.h @@ -6,7 +6,7 @@ * \author Adriaan de Jong */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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_CIPHER_WRAP_H #define MBEDTLS_CIPHER_WRAP_H diff --git a/connectivity/mbedtls/include/mbedtls/cmac.h b/connectivity/mbedtls/include/mbedtls/cmac.h index 792fbdc339..cb538d0925 100644 --- a/connectivity/mbedtls/include/mbedtls/cmac.h +++ b/connectivity/mbedtls/include/mbedtls/cmac.h @@ -7,7 +7,7 @@ * Authentication is defined in RFC-4493: The AES-CMAC Algorithm. */ /* - * Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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_CMAC_H diff --git a/connectivity/mbedtls/include/mbedtls/common.h b/connectivity/mbedtls/include/mbedtls/common.h new file mode 100644 index 0000000000..5845766ac1 --- /dev/null +++ b/connectivity/mbedtls/include/mbedtls/common.h @@ -0,0 +1,53 @@ +/** + * \file common.h + * + * \brief Utility macros for internal use in the library + */ +/* + * Copyright The Mbed TLS Contributors + * 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 MBEDTLS_LIBRARY_COMMON_H +#define MBEDTLS_LIBRARY_COMMON_H + +#if defined(MBEDTLS_CONFIG_FILE) +#include MBEDTLS_CONFIG_FILE +#else +#include "mbedtls/config.h" +#endif + +/** Helper to define a function as static except when building invasive tests. + * + * If a function is only used inside its own source file and should be + * declared `static` to allow the compiler to optimize for code size, + * but that function has unit tests, define it with + * ``` + * MBEDTLS_STATIC_TESTABLE int mbedtls_foo(...) { ... } + * ``` + * and declare it in a header in the `library/` directory with + * ``` + * #if defined(MBEDTLS_TEST_HOOKS) + * int mbedtls_foo(...); + * #endif + * ``` + */ +#if defined(MBEDTLS_TEST_HOOKS) +#define MBEDTLS_STATIC_TESTABLE +#else +#define MBEDTLS_STATIC_TESTABLE static +#endif + +#endif /* MBEDTLS_LIBRARY_COMMON_H */ diff --git a/connectivity/mbedtls/include/mbedtls/compat-1.3.h b/connectivity/mbedtls/include/mbedtls/compat-1.3.h index b268734be0..40177512ca 100644 --- a/connectivity/mbedtls/include/mbedtls/compat-1.3.h +++ b/connectivity/mbedtls/include/mbedtls/compat-1.3.h @@ -7,7 +7,7 @@ * \deprecated Use the new names directly instead */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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) diff --git a/connectivity/mbedtls/include/mbedtls/config-no-entropy.h b/connectivity/mbedtls/include/mbedtls/config-no-entropy.h index ccdd75c63a..aa298ba7b7 100644 --- a/connectivity/mbedtls/include/mbedtls/config-no-entropy.h +++ b/connectivity/mbedtls/include/mbedtls/config-no-entropy.h @@ -4,7 +4,7 @@ * \brief Minimal configuration of features that do not require an entropy source */ /* - * Copyright (C) 2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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) */ /* * Minimal configuration of features that do not require an entropy source diff --git a/connectivity/mbedtls/include/mbedtls/config.h b/connectivity/mbedtls/include/mbedtls/config.h index 7192f384e1..5ab37d996a 100644 --- a/connectivity/mbedtls/include/mbedtls/config.h +++ b/connectivity/mbedtls/include/mbedtls/config.h @@ -8,7 +8,7 @@ * memory footprint. */ /* - * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_CONFIG_H @@ -772,6 +770,7 @@ * * Comment macros to disable the curve and functions for it */ +/* Short Weierstrass curves (supporting ECP, ECDH, ECDSA) */ //#define MBEDTLS_ECP_DP_SECP192R1_ENABLED //#define MBEDTLS_ECP_DP_SECP224R1_ENABLED #define MBEDTLS_ECP_DP_SECP256R1_ENABLED @@ -783,6 +782,7 @@ //#define MBEDTLS_ECP_DP_BP256R1_ENABLED //#define MBEDTLS_ECP_DP_BP384R1_ENABLED //#define MBEDTLS_ECP_DP_BP512R1_ENABLED +/* Montgomery curves (supporting ECP) */ #define MBEDTLS_ECP_DP_CURVE25519_ENABLED #define MBEDTLS_ECP_DP_CURVE448_ENABLED @@ -797,6 +797,28 @@ */ #define MBEDTLS_ECP_NIST_OPTIM +/** + * \def MBEDTLS_ECP_NO_INTERNAL_RNG + * + * When this option is disabled, mbedtls_ecp_mul() will make use of an + * internal RNG when called with a NULL \c f_rng argument, in order to protect + * against some side-channel attacks. + * + * This protection introduces a dependency of the ECP module on one of the + * DRBG modules. For very constrained implementations that don't require this + * protection (for example, because you're only doing signature verification, + * so not manipulating any secret, or because local/physical side-channel + * attacks are outside your threat model), it might be desirable to get rid of + * that dependency. + * + * \warning Enabling this option makes some uses of ECP vulnerable to some + * side-channel attacks. Only enable it if you know that's not a problem for + * your use case. + * + * Uncomment this macro to disable some counter-measures in ECP. + */ +//#define MBEDTLS_ECP_NO_INTERNAL_RNG + /** * \def MBEDTLS_ECP_RESTARTABLE * @@ -1077,7 +1099,7 @@ * * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. * - * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): @@ -1101,7 +1123,7 @@ * * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. * - * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): @@ -1722,6 +1744,25 @@ */ #define MBEDTLS_SSL_PROTO_TLS1_2 +/** + * \def MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL + * + * This macro is used to selectively enable experimental parts + * of the code that contribute to the ongoing development of + * the prototype TLS 1.3 and DTLS 1.3 implementation, and provide + * no other purpose. + * + * \warning TLS 1.3 and DTLS 1.3 aren't yet supported in Mbed TLS, + * and no feature exposed through this macro is part of the + * public API. In particular, features under the control + * of this macro are experimental and don't come with any + * stability guarantees. + * + * Uncomment this macro to enable experimental and partial + * functionality specific to TLS 1.3. + */ +//#define MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL + /** * \def MBEDTLS_SSL_PROTO_DTLS * @@ -1881,6 +1922,62 @@ */ //#define MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH +/** + * \def MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN + * + * Enable testing of the constant-flow nature of some sensitive functions with + * clang's MemorySanitizer. This causes some existing tests to also test + * this non-functional property of the code under test. + * + * This setting requires compiling with clang -fsanitize=memory. The test + * suites can then be run normally. + * + * \warning This macro is only used for extended testing; it is not considered + * part of the library's API, so it may change or disappear at any time. + * + * Uncomment to enable testing of the constant-flow nature of selected code. + */ +//#define MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN + +/** + * \def MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND + * + * Enable testing of the constant-flow nature of some sensitive functions with + * valgrind's memcheck tool. This causes some existing tests to also test + * this non-functional property of the code under test. + * + * This setting requires valgrind headers for building, and is only useful for + * testing if the tests suites are run with valgrind's memcheck. This can be + * done for an individual test suite with 'valgrind ./test_suite_xxx', or when + * using CMake, this can be done for all test suites with 'make memcheck'. + * + * \warning This macro is only used for extended testing; it is not considered + * part of the library's API, so it may change or disappear at any time. + * + * Uncomment to enable testing of the constant-flow nature of selected code. + */ +//#define MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND + +/** + * \def MBEDTLS_TEST_HOOKS + * + * Enable features for invasive testing such as introspection functions and + * hooks for fault injection. This enables additional unit tests. + * + * Merely enabling this feature should not change the behavior of the product. + * It only adds new code, and new branching points where the default behavior + * is the same as when this feature is disabled. + * However, this feature increases the attack surface: there is an added + * risk of vulnerabilities, and more gadgets that can make exploits easier. + * Therefore this feature must never be enabled in production. + * + * See `docs/architecture/testing/mbed-crypto-invasive-testing.md` for more + * information. + * + * Uncomment to enable invasive tests. + */ +//#define MBEDTLS_TEST_HOOKS + /** * \def MBEDTLS_THREADING_ALT * @@ -2526,7 +2623,9 @@ * This module is used by the following key exchanges: * ECDHE-ECDSA * - * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C + * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C, + * and at least one MBEDTLS_ECP_DP_XXX_ENABLED for a + * short Weierstrass curve. */ #define MBEDTLS_ECDSA_C @@ -3551,6 +3650,22 @@ */ //#define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16 +/** \def MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY + * + * This option controls the use of record plaintext padding + * in TLS 1.3. + * + * The padding will always be chosen so that the length of the + * padded plaintext is a multiple of the value of this option. + * + * Note: A value of \c 1 means that no padding will be used + * for outgoing records. + * + * Note: On systems lacking division instructions, + * a power of two should be preferred. + */ +//#define MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY 1 + /** \def MBEDTLS_SSL_OUT_CONTENT_LEN * * Maximum length (in bytes) of outgoing plaintext fragments. @@ -3706,6 +3821,7 @@ #include "mbedtls/check_config.h" + #endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_TEST_NULL_ENTROPY && !MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_TEST_NULL_ENTROPY) diff --git a/connectivity/mbedtls/include/mbedtls/ctr_drbg.h b/connectivity/mbedtls/include/mbedtls/ctr_drbg.h index 234e6a0364..6c48ec1edd 100644 --- a/connectivity/mbedtls/include/mbedtls/ctr_drbg.h +++ b/connectivity/mbedtls/include/mbedtls/ctr_drbg.h @@ -22,7 +22,7 @@ * information. */ /* - * Copyright (C) 2006-2019, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -36,8 +36,6 @@ * 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_CTR_DRBG_H diff --git a/connectivity/mbedtls/include/mbedtls/debug.h b/connectivity/mbedtls/include/mbedtls/debug.h index ce2c274e9b..ab5b037034 100644 --- a/connectivity/mbedtls/include/mbedtls/debug.h +++ b/connectivity/mbedtls/include/mbedtls/debug.h @@ -4,7 +4,7 @@ * \brief Functions for controlling and providing debug output from the library. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_DEBUG_H #define MBEDTLS_DEBUG_H diff --git a/connectivity/mbedtls/include/mbedtls/des.h b/connectivity/mbedtls/include/mbedtls/des.h index 1c80b5365f..549d19b4e0 100644 --- a/connectivity/mbedtls/include/mbedtls/des.h +++ b/connectivity/mbedtls/include/mbedtls/des.h @@ -8,7 +8,7 @@ * instead. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +23,6 @@ * 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_DES_H #define MBEDTLS_DES_H diff --git a/connectivity/mbedtls/include/mbedtls/dhm.h b/connectivity/mbedtls/include/mbedtls/dhm.h index 6dcfadd82c..c7830b9ee7 100644 --- a/connectivity/mbedtls/include/mbedtls/dhm.h +++ b/connectivity/mbedtls/include/mbedtls/dhm.h @@ -44,7 +44,7 @@ * */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -58,8 +58,6 @@ * 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_DHM_H diff --git a/connectivity/mbedtls/include/mbedtls/ecdh.h b/connectivity/mbedtls/include/mbedtls/ecdh.h index 3948d7c98f..05855cdf10 100644 --- a/connectivity/mbedtls/include/mbedtls/ecdh.h +++ b/connectivity/mbedtls/include/mbedtls/ecdh.h @@ -13,7 +13,7 @@ * Cryptography. */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -27,8 +27,6 @@ * 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_ECDH_H diff --git a/connectivity/mbedtls/include/mbedtls/ecdsa.h b/connectivity/mbedtls/include/mbedtls/ecdsa.h index b009e73456..264a638bb5 100644 --- a/connectivity/mbedtls/include/mbedtls/ecdsa.h +++ b/connectivity/mbedtls/include/mbedtls/ecdsa.h @@ -11,7 +11,7 @@ * */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -25,8 +25,6 @@ * 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_ECDSA_H diff --git a/connectivity/mbedtls/include/mbedtls/ecjpake.h b/connectivity/mbedtls/include/mbedtls/ecjpake.h index 97387c3b48..891705d8c4 100644 --- a/connectivity/mbedtls/include/mbedtls/ecjpake.h +++ b/connectivity/mbedtls/include/mbedtls/ecjpake.h @@ -4,7 +4,7 @@ * \brief Elliptic curve J-PAKE */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ECJPAKE_H #define MBEDTLS_ECJPAKE_H diff --git a/connectivity/mbedtls/include/mbedtls/ecp.h b/connectivity/mbedtls/include/mbedtls/ecp.h index 4c05b4fd0a..34dd0eaa6e 100644 --- a/connectivity/mbedtls/include/mbedtls/ecp.h +++ b/connectivity/mbedtls/include/mbedtls/ecp.h @@ -15,7 +15,7 @@ */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -29,8 +29,6 @@ * 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_ECP_H @@ -61,6 +59,26 @@ #define MBEDTLS_ERR_ECP_IN_PROGRESS -0x4B00 /**< Operation in progress, call again with the same parameters to continue. */ +/* Flags indicating whether to include code that is specific to certain + * types of curves. These flags are for internal library use only. */ +#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) +#define MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED +#endif +#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \ + defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) +#define MBEDTLS_ECP_MONTGOMERY_ENABLED +#endif + #ifdef __cplusplus extern "C" { #endif @@ -74,6 +92,20 @@ extern "C" { * parameters. Therefore, only standardized domain parameters from trusted * sources should be used. See mbedtls_ecp_group_load(). */ +/* Note: when adding a new curve: + * - Add it at the end of this enum, otherwise you'll break the ABI by + * changing the numerical value for existing curves. + * - Increment MBEDTLS_ECP_DP_MAX below if needed. + * - Add the corresponding MBEDTLS_ECP_DP_xxx_ENABLED macro definition to + * config.h. + * - List the curve as a dependency of MBEDTLS_ECP_C and + * MBEDTLS_ECDSA_C if supported in check_config.h. + * - Add the curve to the appropriate curve type macro + * MBEDTLS_ECP_yyy_ENABLED above. + * - Add the necessary definitions to ecp_curves.c. + * - Add the curve to the ecp_supported_curves array in ecp.c. + * - Add the curve to applicable profiles in x509_crt.c if applicable. + */ typedef enum { MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */ @@ -846,6 +878,9 @@ int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, * intermediate results to prevent potential timing attacks * targeting these results. We recommend always providing * a non-NULL \p f_rng. The overhead is negligible. + * Note: unless #MBEDTLS_ECP_NO_INTERNAL_RNG is defined, when + * \p f_rng is NULL, an internal RNG (seeded from the value + * of \p m) will be used instead. * * \param grp The ECP group to use. * This must be initialized and have group parameters @@ -903,6 +938,7 @@ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ); +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q @@ -912,6 +948,10 @@ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * \note In contrast to mbedtls_ecp_mul(), this function does not * guarantee a constant execution flow and timing. * + * \note This function is only defined for short Weierstrass curves. + * It may not be included in builds without any short + * Weierstrass curve. + * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). @@ -930,6 +970,8 @@ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * 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_FEATURE_UNAVAILABLE if \p grp does not + * designate a short Weierstrass curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, @@ -947,6 +989,10 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * but it can return early and restart according to the limit * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. * + * \note This function is only defined for short Weierstrass curves. + * It may not be included in builds without any short + * Weierstrass curve. + * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). @@ -966,6 +1012,8 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * 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_FEATURE_UNAVAILABLE if \p grp does not + * designate a short Weierstrass curve. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another negative error code on other kinds of failure. @@ -975,6 +1023,7 @@ int mbedtls_ecp_muladd_restartable( const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q, mbedtls_ecp_restart_ctx *rs_ctx ); +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ /** * \brief This function checks that a point is a valid public key @@ -1146,6 +1195,26 @@ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, */ int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, const unsigned char *buf, size_t buflen ); + +/** + * \brief This function exports an elliptic curve private key. + * + * \param key The private key. + * \param buf The output buffer for containing the binary representation + * of the key. (Big endian integer for Weierstrass curves, byte + * string for Montgomery curves.) + * \param buflen The total length of the buffer in bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the \p key + representation is larger than the available space in \p buf. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for + * the group is not implemented. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key, + unsigned char *buf, size_t buflen ); + /** * \brief This function checks that the keypair objects * \p pub and \p prv have the same group and the diff --git a/connectivity/mbedtls/include/mbedtls/ecp_internal.h b/connectivity/mbedtls/include/mbedtls/ecp_internal.h index 3b6fbf1121..6a47a8ff27 100644 --- a/connectivity/mbedtls/include/mbedtls/ecp_internal.h +++ b/connectivity/mbedtls/include/mbedtls/ecp_internal.h @@ -5,7 +5,7 @@ * point arithmetic. */ /* - * Copyright (C) 2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,8 +19,6 @@ * 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) */ /* @@ -105,7 +103,7 @@ int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp ); */ void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp ); -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) /** @@ -245,9 +243,9 @@ int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt ); #endif -#endif /* ECP_SHORTWEIERSTRASS */ +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp, @@ -291,7 +289,7 @@ int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P ); #endif -#endif /* ECP_MONTGOMERY */ +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ #endif /* MBEDTLS_ECP_INTERNAL_ALT */ diff --git a/connectivity/mbedtls/include/mbedtls/entropy.h b/connectivity/mbedtls/include/mbedtls/entropy.h index 06aaffaf79..5a9c11c3f2 100644 --- a/connectivity/mbedtls/include/mbedtls/entropy.h +++ b/connectivity/mbedtls/include/mbedtls/entropy.h @@ -4,7 +4,7 @@ * \brief Entropy accumulator implementation */ /* - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ENTROPY_H #define MBEDTLS_ENTROPY_H diff --git a/connectivity/mbedtls/include/mbedtls/entropy_poll.h b/connectivity/mbedtls/include/mbedtls/entropy_poll.h index ba42805f06..e1d7491aa2 100644 --- a/connectivity/mbedtls/include/mbedtls/entropy_poll.h +++ b/connectivity/mbedtls/include/mbedtls/entropy_poll.h @@ -4,7 +4,7 @@ * \brief Platform-specific and custom entropy polling functions */ /* - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ENTROPY_POLL_H #define MBEDTLS_ENTROPY_POLL_H diff --git a/connectivity/mbedtls/include/mbedtls/error.h b/connectivity/mbedtls/include/mbedtls/error.h index 82b018813e..cd7731e6be 100644 --- a/connectivity/mbedtls/include/mbedtls/error.h +++ b/connectivity/mbedtls/include/mbedtls/error.h @@ -4,7 +4,7 @@ * \brief Error to string translation */ /* - * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_ERROR_H #define MBEDTLS_ERROR_H @@ -101,7 +99,7 @@ * ECP 4 10 (Started from top) * MD 5 5 * HKDF 5 1 (Started from top) - * SSL 5 1 (Started from 0x5F00) + * SSL 5 2 (Started from 0x5F00) * CIPHER 6 8 (Started from 0x6080) * SSL 6 24 (Started from top, plus 0x6000) * SSL 7 32 @@ -127,6 +125,36 @@ extern "C" { */ void mbedtls_strerror( int errnum, char *buffer, size_t buflen ); +/** + * \brief Translate the high-level part of an Mbed TLS error code into a string + * representation. + * + * This function returns a const pointer to an un-modifiable string. The caller + * must not try to modify the string. It is intended to be used mostly for + * logging purposes. + * + * \param error_code error code + * + * \return The string representation of the error code, or \c NULL if the error + * code is unknown. + */ +const char * mbedtls_high_level_strerr( int error_code ); + +/** + * \brief Translate the low-level part of an Mbed TLS error code into a string + * representation. + * + * This function returns a const pointer to an un-modifiable string. The caller + * must not try to modify the string. It is intended to be used mostly for + * logging purposes. + * + * \param error_code error code + * + * \return The string representation of the error code, or \c NULL if the error + * code is unknown. + */ +const char * mbedtls_low_level_strerr( int error_code ); + #ifdef __cplusplus } #endif diff --git a/connectivity/mbedtls/include/mbedtls/gcm.h b/connectivity/mbedtls/include/mbedtls/gcm.h index a71a2af467..ed23cb9c6c 100644 --- a/connectivity/mbedtls/include/mbedtls/gcm.h +++ b/connectivity/mbedtls/include/mbedtls/gcm.h @@ -12,7 +12,7 @@ * */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -26,8 +26,6 @@ * 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_GCM_H diff --git a/connectivity/mbedtls/include/mbedtls/havege.h b/connectivity/mbedtls/include/mbedtls/havege.h index acd7e489ab..7d27039e8c 100644 --- a/connectivity/mbedtls/include/mbedtls/havege.h +++ b/connectivity/mbedtls/include/mbedtls/havege.h @@ -4,7 +4,7 @@ * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_HAVEGE_H #define MBEDTLS_HAVEGE_H diff --git a/connectivity/mbedtls/include/mbedtls/hkdf.h b/connectivity/mbedtls/include/mbedtls/hkdf.h index 77a99ab6b2..2e6b363045 100644 --- a/connectivity/mbedtls/include/mbedtls/hkdf.h +++ b/connectivity/mbedtls/include/mbedtls/hkdf.h @@ -7,7 +7,7 @@ * specified by RFC 5869. */ /* - * Copyright (C) 2018-2019, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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_HKDF_H #define MBEDTLS_HKDF_H diff --git a/connectivity/mbedtls/include/mbedtls/hmac_drbg.h b/connectivity/mbedtls/include/mbedtls/hmac_drbg.h index 00be9df408..57ce9d98f4 100644 --- a/connectivity/mbedtls/include/mbedtls/hmac_drbg.h +++ b/connectivity/mbedtls/include/mbedtls/hmac_drbg.h @@ -8,7 +8,7 @@ * Deterministic Random Bit Generators. */ /* - * Copyright (C) 2006-2019, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_HMAC_DRBG_H #define MBEDTLS_HMAC_DRBG_H diff --git a/connectivity/mbedtls/include/mbedtls/md.h b/connectivity/mbedtls/include/mbedtls/md.h index 0b0ec91ff5..e4354badc5 100644 --- a/connectivity/mbedtls/include/mbedtls/md.h +++ b/connectivity/mbedtls/include/mbedtls/md.h @@ -6,7 +6,7 @@ * \author Adriaan de Jong */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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_MD_H @@ -104,6 +102,8 @@ typedef struct mbedtls_md_context_t * \brief This function returns the list of digests supported by the * generic digest module. * + * \note The list starts with the strongest available hashes. + * * \return A statically allocated array of digests. Each element * in the returned list is an integer belonging to the * message-digest enumeration #mbedtls_md_type_t. diff --git a/connectivity/mbedtls/include/mbedtls/md2.h b/connectivity/mbedtls/include/mbedtls/md2.h index df1d5f7e62..23c48f47c6 100644 --- a/connectivity/mbedtls/include/mbedtls/md2.h +++ b/connectivity/mbedtls/include/mbedtls/md2.h @@ -8,7 +8,7 @@ * instead. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +23,6 @@ * 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_MD2_H #define MBEDTLS_MD2_H diff --git a/connectivity/mbedtls/include/mbedtls/md4.h b/connectivity/mbedtls/include/mbedtls/md4.h index e7accd455c..eeb1670903 100644 --- a/connectivity/mbedtls/include/mbedtls/md4.h +++ b/connectivity/mbedtls/include/mbedtls/md4.h @@ -8,7 +8,7 @@ * instead. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +23,6 @@ * 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_MD4_H #define MBEDTLS_MD4_H diff --git a/connectivity/mbedtls/include/mbedtls/md5.h b/connectivity/mbedtls/include/mbedtls/md5.h index 4206c1fbfd..aaca0f274a 100644 --- a/connectivity/mbedtls/include/mbedtls/md5.h +++ b/connectivity/mbedtls/include/mbedtls/md5.h @@ -8,7 +8,7 @@ * digests instead. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_MD5_H #define MBEDTLS_MD5_H diff --git a/connectivity/mbedtls/include/mbedtls/md_internal.h b/connectivity/mbedtls/include/mbedtls/md_internal.h index 0922dff9d3..f33cdf6086 100644 --- a/connectivity/mbedtls/include/mbedtls/md_internal.h +++ b/connectivity/mbedtls/include/mbedtls/md_internal.h @@ -8,7 +8,7 @@ * \author Adriaan de Jong */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_MD_WRAP_H #define MBEDTLS_MD_WRAP_H diff --git a/connectivity/mbedtls/include/mbedtls/memory_buffer_alloc.h b/connectivity/mbedtls/include/mbedtls/memory_buffer_alloc.h index 8e77f6f7c8..233977252a 100644 --- a/connectivity/mbedtls/include/mbedtls/memory_buffer_alloc.h +++ b/connectivity/mbedtls/include/mbedtls/memory_buffer_alloc.h @@ -4,7 +4,7 @@ * \brief Buffer-based memory allocator */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_MEMORY_BUFFER_ALLOC_H #define MBEDTLS_MEMORY_BUFFER_ALLOC_H diff --git a/connectivity/mbedtls/include/mbedtls/net.h b/connectivity/mbedtls/include/mbedtls/net.h index 341aae84a4..66921887da 100644 --- a/connectivity/mbedtls/include/mbedtls/net.h +++ b/connectivity/mbedtls/include/mbedtls/net.h @@ -6,7 +6,7 @@ * \deprecated Superseded by mbedtls/net_sockets.h */ /* - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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" diff --git a/connectivity/mbedtls/include/mbedtls/net_sockets.h b/connectivity/mbedtls/include/mbedtls/net_sockets.h index adb589ee96..55fd18b52f 100644 --- a/connectivity/mbedtls/include/mbedtls/net_sockets.h +++ b/connectivity/mbedtls/include/mbedtls/net_sockets.h @@ -20,7 +20,7 @@ * */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -34,8 +34,6 @@ * 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_NET_SOCKETS_H #define MBEDTLS_NET_SOCKETS_H diff --git a/connectivity/mbedtls/include/mbedtls/nist_kw.h b/connectivity/mbedtls/include/mbedtls/nist_kw.h index b39406f449..7f3e64a525 100644 --- a/connectivity/mbedtls/include/mbedtls/nist_kw.h +++ b/connectivity/mbedtls/include/mbedtls/nist_kw.h @@ -16,7 +16,7 @@ * */ /* - * Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -30,8 +30,6 @@ * 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_NIST_KW_H diff --git a/connectivity/mbedtls/include/mbedtls/oid.h b/connectivity/mbedtls/include/mbedtls/oid.h index 59ce0206be..e4c697b2d6 100644 --- a/connectivity/mbedtls/include/mbedtls/oid.h +++ b/connectivity/mbedtls/include/mbedtls/oid.h @@ -4,7 +4,7 @@ * \brief Object Identifier (OID) database */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_OID_H #define MBEDTLS_OID_H diff --git a/connectivity/mbedtls/include/mbedtls/padlock.h b/connectivity/mbedtls/include/mbedtls/padlock.h index 513d72f3d4..78dbeb60d2 100644 --- a/connectivity/mbedtls/include/mbedtls/padlock.h +++ b/connectivity/mbedtls/include/mbedtls/padlock.h @@ -8,7 +8,7 @@ * functions; you must not call them directly. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -22,8 +22,6 @@ * 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_PADLOCK_H #define MBEDTLS_PADLOCK_H diff --git a/connectivity/mbedtls/include/mbedtls/pem.h b/connectivity/mbedtls/include/mbedtls/pem.h index f7bf1a6676..4769bec5fb 100644 --- a/connectivity/mbedtls/include/mbedtls/pem.h +++ b/connectivity/mbedtls/include/mbedtls/pem.h @@ -4,7 +4,7 @@ * \brief Privacy Enhanced Mail (PEM) decoding */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_PEM_H #define MBEDTLS_PEM_H diff --git a/connectivity/mbedtls/include/mbedtls/pk.h b/connectivity/mbedtls/include/mbedtls/pk.h index 99e7a55a1d..22fab13bda 100644 --- a/connectivity/mbedtls/include/mbedtls/pk.h +++ b/connectivity/mbedtls/include/mbedtls/pk.h @@ -4,7 +4,7 @@ * \brief Public Key abstraction layer */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_PK_H diff --git a/connectivity/mbedtls/include/mbedtls/pk_internal.h b/connectivity/mbedtls/include/mbedtls/pk_internal.h index 7ef6322e40..47f7767700 100644 --- a/connectivity/mbedtls/include/mbedtls/pk_internal.h +++ b/connectivity/mbedtls/include/mbedtls/pk_internal.h @@ -4,7 +4,7 @@ * \brief Public Key abstraction layer: wrapper functions */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_PK_WRAP_H diff --git a/connectivity/mbedtls/include/mbedtls/pkcs11.h b/connectivity/mbedtls/include/mbedtls/pkcs11.h index cf8d8c4297..3530ee1688 100644 --- a/connectivity/mbedtls/include/mbedtls/pkcs11.h +++ b/connectivity/mbedtls/include/mbedtls/pkcs11.h @@ -6,7 +6,7 @@ * \author Adriaan de Jong */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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_PKCS11_H #define MBEDTLS_PKCS11_H diff --git a/connectivity/mbedtls/include/mbedtls/pkcs12.h b/connectivity/mbedtls/include/mbedtls/pkcs12.h index 9d42d7ffe9..4b8ce7ed0d 100644 --- a/connectivity/mbedtls/include/mbedtls/pkcs12.h +++ b/connectivity/mbedtls/include/mbedtls/pkcs12.h @@ -4,7 +4,7 @@ * \brief PKCS#12 Personal Information Exchange Syntax */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_PKCS12_H #define MBEDTLS_PKCS12_H diff --git a/connectivity/mbedtls/include/mbedtls/pkcs5.h b/connectivity/mbedtls/include/mbedtls/pkcs5.h index bbec7e7ed4..8f348ce524 100644 --- a/connectivity/mbedtls/include/mbedtls/pkcs5.h +++ b/connectivity/mbedtls/include/mbedtls/pkcs5.h @@ -6,7 +6,7 @@ * \author Mathias Olsson */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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_PKCS5_H #define MBEDTLS_PKCS5_H diff --git a/connectivity/mbedtls/include/mbedtls/platform.h b/connectivity/mbedtls/include/mbedtls/platform.h index b402f8f972..fde5ee8c8b 100644 --- a/connectivity/mbedtls/include/mbedtls/platform.h +++ b/connectivity/mbedtls/include/mbedtls/platform.h @@ -13,7 +13,7 @@ * dynamically configured at runtime. */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -27,8 +27,6 @@ * 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_PLATFORM_H #define MBEDTLS_PLATFORM_H diff --git a/connectivity/mbedtls/include/mbedtls/platform_time.h b/connectivity/mbedtls/include/mbedtls/platform_time.h index fe484fd75b..7e7daab692 100644 --- a/connectivity/mbedtls/include/mbedtls/platform_time.h +++ b/connectivity/mbedtls/include/mbedtls/platform_time.h @@ -4,7 +4,7 @@ * \brief mbed TLS Platform time abstraction */ /* - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_PLATFORM_TIME_H #define MBEDTLS_PLATFORM_TIME_H diff --git a/connectivity/mbedtls/include/mbedtls/platform_util.h b/connectivity/mbedtls/include/mbedtls/platform_util.h index cf0130a84c..fbc2a0d1c0 100644 --- a/connectivity/mbedtls/include/mbedtls/platform_util.h +++ b/connectivity/mbedtls/include/mbedtls/platform_util.h @@ -5,7 +5,7 @@ * library. */ /* - * Copyright (C) 2018, Arm Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,8 +19,6 @@ * 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_PLATFORM_UTIL_H #define MBEDTLS_PLATFORM_UTIL_H diff --git a/connectivity/mbedtls/include/mbedtls/poly1305.h b/connectivity/mbedtls/include/mbedtls/poly1305.h index 05866a2da6..905c145a35 100644 --- a/connectivity/mbedtls/include/mbedtls/poly1305.h +++ b/connectivity/mbedtls/include/mbedtls/poly1305.h @@ -12,7 +12,8 @@ * \author Daniel King */ -/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -26,8 +27,6 @@ * 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_POLY1305_H diff --git a/connectivity/mbedtls/include/mbedtls/psa_util.h b/connectivity/mbedtls/include/mbedtls/psa_util.h index 8db118f59d..3c037068ed 100644 --- a/connectivity/mbedtls/include/mbedtls/psa_util.h +++ b/connectivity/mbedtls/include/mbedtls/psa_util.h @@ -7,7 +7,7 @@ * change at any time. */ /* - * Copyright (C) 2006-2020, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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 @@ -160,93 +158,12 @@ static inline psa_algorithm_t mbedtls_psa_translate_md( mbedtls_md_type_t md_alg /* Translations for ECC. */ static inline int mbedtls_psa_get_ecc_oid_from_id( - psa_ecc_curve_t curve, size_t bits, + psa_ecc_family_t curve, size_t bits, char const **oid, size_t *oid_len ) { -#if TARGET_TFM - /* Use older Crypto API, at least until TF-M updates its crypto - * implementation to Mbed TLS 2.22.0. See - * https://github.com/ARMmbed/mbed-os/issues/13025 for details. */ - (void) bits; switch( curve ) { -#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) - case PSA_ECC_CURVE_SECP192R1: - *oid = MBEDTLS_OID_EC_GRP_SECP192R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) - case PSA_ECC_CURVE_SECP224R1: - *oid = MBEDTLS_OID_EC_GRP_SECP224R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) - case PSA_ECC_CURVE_SECP256R1: - *oid = MBEDTLS_OID_EC_GRP_SECP256R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) - case PSA_ECC_CURVE_SECP384R1: - *oid = MBEDTLS_OID_EC_GRP_SECP384R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP384R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) - case PSA_ECC_CURVE_SECP521R1: - *oid = MBEDTLS_OID_EC_GRP_SECP521R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP521R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) - case PSA_ECC_CURVE_SECP192K1: - *oid = MBEDTLS_OID_EC_GRP_SECP192K1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192K1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) - case PSA_ECC_CURVE_SECP224K1: - *oid = MBEDTLS_OID_EC_GRP_SECP224K1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224K1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) - case PSA_ECC_CURVE_SECP256K1: - *oid = MBEDTLS_OID_EC_GRP_SECP256K1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256K1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) - case PSA_ECC_CURVE_BRAINPOOL_P256R1: - *oid = MBEDTLS_OID_EC_GRP_BP256R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP256R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) - case PSA_ECC_CURVE_BRAINPOOL_P384R1: - *oid = MBEDTLS_OID_EC_GRP_BP384R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP384R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ -#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) - case PSA_ECC_CURVE_BRAINPOOL_P512R1: - *oid = MBEDTLS_OID_EC_GRP_BP512R1; - *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP512R1 ); - return( 0 ); -#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ - default: - (void) oid; - (void) oid_len; - return( -1 ); - } -#else - /* Use more up to date Crypto API */ - - switch( curve ) - { - case PSA_ECC_CURVE_SECP_R1: + case PSA_ECC_FAMILY_SECP_R1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) @@ -281,7 +198,7 @@ static inline int mbedtls_psa_get_ecc_oid_from_id( #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ } break; - case PSA_ECC_CURVE_SECP_K1: + case PSA_ECC_FAMILY_SECP_K1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) @@ -304,7 +221,7 @@ static inline int mbedtls_psa_get_ecc_oid_from_id( #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ } break; - case PSA_ECC_CURVE_BRAINPOOL_P_R1: + case PSA_ECC_FAMILY_BRAINPOOL_P_R1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) @@ -331,7 +248,6 @@ static inline int mbedtls_psa_get_ecc_oid_from_id( (void) oid; (void) oid_len; return( -1 ); -#endif /* TARGET_TFM */ } #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH 1 @@ -451,17 +367,12 @@ static inline int mbedtls_psa_err_translate_pk( psa_status_t status ) static inline psa_key_type_t mbedtls_psa_parse_tls_ecc_group( uint16_t tls_ecc_grp_reg_id, size_t *bits ) { -#if TARGET_TFM - *bits = PSA_ECC_CURVE_BITS( tls_ecc_grp_reg_id ); - return( PSA_KEY_TYPE_ECC_KEY_PAIR( tls_ecc_grp_reg_id )); -#else const mbedtls_ecp_curve_info *curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_ecc_grp_reg_id ); if( curve_info == NULL ) return( 0 ); return( PSA_KEY_TYPE_ECC_KEY_PAIR( mbedtls_ecc_group_to_psa( curve_info->grp_id, bits ) ) ); -#endif } #endif /* MBEDTLS_ECP_C */ diff --git a/connectivity/mbedtls/include/mbedtls/ripemd160.h b/connectivity/mbedtls/include/mbedtls/ripemd160.h index 3c1f5bf50d..381c725e16 100644 --- a/connectivity/mbedtls/include/mbedtls/ripemd160.h +++ b/connectivity/mbedtls/include/mbedtls/ripemd160.h @@ -4,7 +4,7 @@ * \brief RIPE MD-160 message digest */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_RIPEMD160_H #define MBEDTLS_RIPEMD160_H diff --git a/connectivity/mbedtls/include/mbedtls/rsa.h b/connectivity/mbedtls/include/mbedtls/rsa.h index ec8d0d8ded..6a315144d3 100644 --- a/connectivity/mbedtls/include/mbedtls/rsa.h +++ b/connectivity/mbedtls/include/mbedtls/rsa.h @@ -10,7 +10,7 @@ * */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -24,8 +24,6 @@ * 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_RSA_H #define MBEDTLS_RSA_H diff --git a/connectivity/mbedtls/include/mbedtls/rsa_internal.h b/connectivity/mbedtls/include/mbedtls/rsa_internal.h index c1c844ef75..d55492bb16 100644 --- a/connectivity/mbedtls/include/mbedtls/rsa_internal.h +++ b/connectivity/mbedtls/include/mbedtls/rsa_internal.h @@ -35,7 +35,7 @@ * */ /* - * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -50,8 +50,6 @@ * 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_RSA_INTERNAL_H diff --git a/connectivity/mbedtls/include/mbedtls/sha1.h b/connectivity/mbedtls/include/mbedtls/sha1.h index 988d2f93d9..86a3d06bf1 100644 --- a/connectivity/mbedtls/include/mbedtls/sha1.h +++ b/connectivity/mbedtls/include/mbedtls/sha1.h @@ -11,7 +11,7 @@ * digests instead. */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -25,8 +25,6 @@ * 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_SHA1_H #define MBEDTLS_SHA1_H diff --git a/connectivity/mbedtls/include/mbedtls/sha256.h b/connectivity/mbedtls/include/mbedtls/sha256.h index 1c59740219..73d9544df0 100644 --- a/connectivity/mbedtls/include/mbedtls/sha256.h +++ b/connectivity/mbedtls/include/mbedtls/sha256.h @@ -7,7 +7,7 @@ * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -21,8 +21,6 @@ * 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_SHA256_H #define MBEDTLS_SHA256_H diff --git a/connectivity/mbedtls/include/mbedtls/sha512.h b/connectivity/mbedtls/include/mbedtls/sha512.h index 8e54ce01a7..9036ed4990 100644 --- a/connectivity/mbedtls/include/mbedtls/sha512.h +++ b/connectivity/mbedtls/include/mbedtls/sha512.h @@ -6,7 +6,7 @@ * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). */ /* - * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -20,8 +20,6 @@ * 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_SHA512_H #define MBEDTLS_SHA512_H diff --git a/connectivity/mbedtls/include/mbedtls/ssl.h b/connectivity/mbedtls/include/mbedtls/ssl.h index 1c98a5e5a8..f086bdfdce 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl.h +++ b/connectivity/mbedtls/include/mbedtls/ssl.h @@ -4,7 +4,7 @@ * \brief SSL/TLS functions. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_H #define MBEDTLS_SSL_H @@ -129,6 +127,7 @@ #define MBEDTLS_ERR_SSL_UNEXPECTED_CID -0x6000 /**< An encrypted DTLS-frame with an unexpected CID was received. */ #define MBEDTLS_ERR_SSL_VERSION_MISMATCH -0x5F00 /**< An operation failed due to an unexpected version or configuration. */ #define MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS -0x7000 /**< A cryptographic operation is in progress. Try again later. */ +#define MBEDTLS_ERR_SSL_BAD_CONFIG -0x5E80 /**< Invalid value in SSL config */ /* * Various constants @@ -138,11 +137,15 @@ #define MBEDTLS_SSL_MINOR_VERSION_1 1 /*!< TLS v1.0 */ #define MBEDTLS_SSL_MINOR_VERSION_2 2 /*!< TLS v1.1 */ #define MBEDTLS_SSL_MINOR_VERSION_3 3 /*!< TLS v1.2 */ +#define MBEDTLS_SSL_MINOR_VERSION_4 4 /*!< TLS v1.3 (experimental) */ #define MBEDTLS_SSL_TRANSPORT_STREAM 0 /*!< TLS */ #define MBEDTLS_SSL_TRANSPORT_DATAGRAM 1 /*!< DTLS */ #define MBEDTLS_SSL_MAX_HOST_NAME_LEN 255 /*!< Maximum host name defined in RFC 1035 */ +#define MBEDTLS_SSL_MAX_ALPN_NAME_LEN 255 /*!< Maximum size in bytes of a protocol name in alpn ext., RFC 7301 */ + +#define MBEDTLS_SSL_MAX_ALPN_LIST_LEN 65535 /*!< Maximum size in bytes of list in alpn ext., RFC 7301 */ /* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c * NONE must be zero so that memset()ing structure to zero works */ @@ -276,6 +279,10 @@ #define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16 #endif +#if !defined(MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY) +#define MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY 1 +#endif + /* \} name SECTION: Module settings */ /* @@ -2682,6 +2689,9 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, * \note This is mainly useful for clients. Servers will usually * want to use \c mbedtls_ssl_conf_psk_cb() instead. * + * \note A PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback + * takes precedence over a PSK configured by this function. + * * \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. @@ -2715,6 +2725,10 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, * \note This is mainly useful for clients. Servers will usually * want to use \c mbedtls_ssl_conf_psk_cb() instead. * + * \note An opaque PSK set by \c mbedtls_ssl_set_hs_psk_opaque() in + * the PSK callback takes precedence over an opaque PSK + * configured by this function. + * * \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. @@ -2752,6 +2766,9 @@ int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf, * \note This should only be called inside the PSK callback, * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb(). * + * \note A PSK set by this function takes precedence over a PSK + * configured by \c mbedtls_ssl_conf_psk(). + * * \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. @@ -2769,6 +2786,9 @@ int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, * \note This should only be called inside the PSK callback, * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb(). * + * \note An opaque PSK set by this function takes precedence over an + * opaque PSK configured by \c mbedtls_ssl_conf_psk_opaque(). + * * \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 @@ -2807,9 +2827,14 @@ int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl, * 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(). + * \note A dynamic PSK (i.e. set by the PSK callback) takes + * precedence over a static PSK (i.e. set by + * \c mbedtls_ssl_conf_psk() or + * \c mbedtls_ssl_conf_psk_opaque()). + * This means that if you set a PSK callback using this + * function, you don't need to set a PSK using + * \c mbedtls_ssl_conf_psk() or + * \c mbedtls_ssl_conf_psk_opaque()). * * \param conf The SSL configuration to register the callback with. * \param f_psk The callback for selecting and setting the PSK based diff --git a/connectivity/mbedtls/include/mbedtls/ssl_cache.h b/connectivity/mbedtls/include/mbedtls/ssl_cache.h index d049f6e293..c6ef2960f4 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl_cache.h +++ b/connectivity/mbedtls/include/mbedtls/ssl_cache.h @@ -4,7 +4,7 @@ * \brief SSL session cache implementation */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_CACHE_H #define MBEDTLS_SSL_CACHE_H diff --git a/connectivity/mbedtls/include/mbedtls/ssl_ciphersuites.h b/connectivity/mbedtls/include/mbedtls/ssl_ciphersuites.h index 7fbafa48d4..93c32a5eda 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl_ciphersuites.h +++ b/connectivity/mbedtls/include/mbedtls/ssl_ciphersuites.h @@ -4,7 +4,7 @@ * \brief SSL Ciphersuites for mbed TLS */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_CIPHERSUITES_H #define MBEDTLS_SSL_CIPHERSUITES_H diff --git a/connectivity/mbedtls/include/mbedtls/ssl_cookie.h b/connectivity/mbedtls/include/mbedtls/ssl_cookie.h index 3dbaf223a8..0a238708e5 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl_cookie.h +++ b/connectivity/mbedtls/include/mbedtls/ssl_cookie.h @@ -4,7 +4,7 @@ * \brief DTLS cookie callbacks implementation */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_COOKIE_H #define MBEDTLS_SSL_COOKIE_H diff --git a/connectivity/mbedtls/include/mbedtls/ssl_internal.h b/connectivity/mbedtls/include/mbedtls/ssl_internal.h index f83d01454f..b3d53d34ae 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl_internal.h +++ b/connectivity/mbedtls/include/mbedtls/ssl_internal.h @@ -4,7 +4,7 @@ * \brief Internal functions shared by the SSL modules */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_INTERNAL_H #define MBEDTLS_SSL_INTERNAL_H @@ -146,12 +144,26 @@ #define MBEDTLS_SSL_COMPRESSION_ADD 0 #endif +/* This macro determines whether CBC is supported. */ +#if defined(MBEDTLS_CIPHER_MODE_CBC) && \ + ( defined(MBEDTLS_AES_C) || \ + defined(MBEDTLS_CAMELLIA_C) || \ + defined(MBEDTLS_ARIA_C) || \ + defined(MBEDTLS_DES_C) ) +#define MBEDTLS_SSL_SOME_SUITES_USE_CBC +#endif + +/* This macro determines whether the CBC construct used in TLS 1.0-1.2 (as + * opposed to the very different CBC construct used in SSLv3) is supported. */ +#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ + ( defined(MBEDTLS_SSL_PROTO_TLS1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) ) +#define MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC +#endif + #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ - ( defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || \ - defined(MBEDTLS_CAMELLIA_C) || \ - defined(MBEDTLS_ARIA_C) || \ - defined(MBEDTLS_DES_C) ) ) + defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) #define MBEDTLS_SSL_SOME_MODES_USE_MAC #endif @@ -207,6 +219,12 @@ : ( MBEDTLS_SSL_IN_CONTENT_LEN ) \ ) +/* Maximum size in bytes of list in sig-hash algorithm ext., RFC 5246 */ +#define MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN 65534 + +/* Maximum size in bytes of list in supported elliptic curve ext., RFC 4492 */ +#define MBEDTLS_SSL_MAX_CURVE_LIST_LEN 65535 + /* * Check that we obey the standard's message size bounds */ @@ -299,6 +317,41 @@ static inline uint32_t mbedtls_ssl_get_input_buflen( const mbedtls_ssl_context * #define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0) #define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK (1 << 1) +/** + * \brief This function checks if the remaining size in a buffer is + * greater or equal than a needed space. + * + * \param cur Pointer to the current position in the buffer. + * \param end Pointer to one past the end of the buffer. + * \param need Needed space in bytes. + * + * \return Zero if the needed space is available in the buffer, non-zero + * otherwise. + */ +static inline int mbedtls_ssl_chk_buf_ptr( const uint8_t *cur, + const uint8_t *end, size_t need ) +{ + return( ( cur > end ) || ( need > (size_t)( end - cur ) ) ); +} + +/** + * \brief This macro checks if the remaining size in a buffer is + * greater or equal than a needed space. If it is not the case, + * it returns an SSL_BUFFER_TOO_SMALL error. + * + * \param cur Pointer to the current position in the buffer. + * \param end Pointer to one past the end of the buffer. + * \param need Needed space in bytes. + * + */ +#define MBEDTLS_SSL_CHK_BUF_PTR( cur, end, need ) \ + do { \ + if( mbedtls_ssl_chk_buf_ptr( ( cur ), ( end ), ( need ) ) != 0 ) \ + { \ + return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); \ + } \ + } while( 0 ) + #ifdef __cplusplus extern "C" { #endif @@ -554,6 +607,10 @@ typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer; * time with the 8-byte record sequence number, without prepending the * latter to the encrypted record. * + * Additionally, DTLS 1.2 + CID as well as TLS 1.3 use an inner plaintext + * which allows to add flexible length padding and to hide a record's true + * content type. + * * In addition to type and version, the following parameters are relevant: * - The symmetric cipher algorithm to be used. * - The (static) encryption/decryption keys for the cipher. @@ -921,7 +978,60 @@ void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ); -#endif + +/** + * Get the first defined PSK by order of precedence: + * 1. handshake PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback + * 2. static PSK configured by \c mbedtls_ssl_conf_psk() + * Return a code and update the pair (PSK, PSK length) passed to this function + */ +static inline int mbedtls_ssl_get_psk( const mbedtls_ssl_context *ssl, + const unsigned char **psk, size_t *psk_len ) +{ + if( ssl->handshake->psk != NULL && ssl->handshake->psk_len > 0 ) + { + *psk = ssl->handshake->psk; + *psk_len = ssl->handshake->psk_len; + } + + else if( ssl->conf->psk != NULL && ssl->conf->psk_len > 0 ) + { + *psk = ssl->conf->psk; + *psk_len = ssl->conf->psk_len; + } + + else + { + *psk = NULL; + *psk_len = 0; + return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); + } + + return( 0 ); +} + +#if defined(MBEDTLS_USE_PSA_CRYPTO) +/** + * Get the first defined opaque PSK by order of precedence: + * 1. handshake PSK set by \c mbedtls_ssl_set_hs_psk_opaque() in the PSK + * callback + * 2. static PSK configured by \c mbedtls_ssl_conf_psk_opaque() + * Return an opaque PSK + */ +static inline psa_key_handle_t mbedtls_ssl_get_opaque_psk( + const mbedtls_ssl_context *ssl ) +{ + if( ssl->handshake->psk_opaque != 0 ) + return( ssl->handshake->psk_opaque ); + + if( ssl->conf->psk_opaque != 0 ) + return( ssl->conf->psk_opaque ); + + return( 0 ); +} +#endif /* MBEDTLS_USE_PSA_CRYPTO */ + +#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ #if defined(MBEDTLS_PK_C) unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ); diff --git a/connectivity/mbedtls/include/mbedtls/ssl_ticket.h b/connectivity/mbedtls/include/mbedtls/ssl_ticket.h index 8561f6d886..bf5fc97028 100644 --- a/connectivity/mbedtls/include/mbedtls/ssl_ticket.h +++ b/connectivity/mbedtls/include/mbedtls/ssl_ticket.h @@ -4,7 +4,7 @@ * \brief TLS server ticket callbacks implementation */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_SSL_TICKET_H #define MBEDTLS_SSL_TICKET_H diff --git a/connectivity/mbedtls/include/mbedtls/threading.h b/connectivity/mbedtls/include/mbedtls/threading.h index cab40f71af..8baf15a75b 100644 --- a/connectivity/mbedtls/include/mbedtls/threading.h +++ b/connectivity/mbedtls/include/mbedtls/threading.h @@ -4,7 +4,7 @@ * \brief Threading abstraction layer */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_THREADING_H #define MBEDTLS_THREADING_H diff --git a/connectivity/mbedtls/include/mbedtls/timing.h b/connectivity/mbedtls/include/mbedtls/timing.h index b264a5a95d..b7290cfcab 100644 --- a/connectivity/mbedtls/include/mbedtls/timing.h +++ b/connectivity/mbedtls/include/mbedtls/timing.h @@ -4,7 +4,7 @@ * \brief Portable interface to timeouts and to the CPU cycle counter */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_TIMING_H #define MBEDTLS_TIMING_H diff --git a/connectivity/mbedtls/include/mbedtls/version.h b/connectivity/mbedtls/include/mbedtls/version.h index b89e36efd5..665a283e15 100644 --- a/connectivity/mbedtls/include/mbedtls/version.h +++ b/connectivity/mbedtls/include/mbedtls/version.h @@ -4,7 +4,7 @@ * \brief Run-time version information */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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) */ /* * This set of compile-time defines and run-time variables can be used to @@ -39,7 +37,7 @@ * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 -#define MBEDTLS_VERSION_MINOR 22 +#define MBEDTLS_VERSION_MINOR 24 #define MBEDTLS_VERSION_PATCH 0 /** @@ -47,9 +45,9 @@ * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x02160000 -#define MBEDTLS_VERSION_STRING "2.22.0" -#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.22.0" +#define MBEDTLS_VERSION_NUMBER 0x02180000 +#define MBEDTLS_VERSION_STRING "2.24.0" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.24.0" #if defined(MBEDTLS_VERSION_C) diff --git a/connectivity/mbedtls/include/mbedtls/x509.h b/connectivity/mbedtls/include/mbedtls/x509.h index 9b6b51f45e..08525e26dd 100644 --- a/connectivity/mbedtls/include/mbedtls/x509.h +++ b/connectivity/mbedtls/include/mbedtls/x509.h @@ -4,7 +4,7 @@ * \brief X.509 generic defines and structures */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_X509_H #define MBEDTLS_X509_H diff --git a/connectivity/mbedtls/include/mbedtls/x509_crl.h b/connectivity/mbedtls/include/mbedtls/x509_crl.h index 072a53671e..7e9e8885f4 100644 --- a/connectivity/mbedtls/include/mbedtls/x509_crl.h +++ b/connectivity/mbedtls/include/mbedtls/x509_crl.h @@ -4,7 +4,7 @@ * \brief X.509 certificate revocation list parsing */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_X509_CRL_H #define MBEDTLS_X509_CRL_H diff --git a/connectivity/mbedtls/include/mbedtls/x509_crt.h b/connectivity/mbedtls/include/mbedtls/x509_crt.h index e4fb135432..8e389f8c0e 100644 --- a/connectivity/mbedtls/include/mbedtls/x509_crt.h +++ b/connectivity/mbedtls/include/mbedtls/x509_crt.h @@ -4,7 +4,7 @@ * \brief X.509 certificate parsing and writing */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_X509_CRT_H #define MBEDTLS_X509_CRT_H @@ -303,6 +301,90 @@ int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ); +/** + * \brief The type of certificate extension callbacks. + * + * Callbacks of this type are passed to and used by the + * mbedtls_x509_crt_parse_der_with_ext_cb() routine when + * it encounters either an unsupported extension or a + * "certificate policies" extension containing any + * unsupported certificate policies. + * Future versions of the library may invoke the callback + * in other cases, if and when the need arises. + * + * \param p_ctx An opaque context passed to the callback. + * \param crt The certificate being parsed. + * \param oid The OID of the extension. + * \param critical Whether the extension is critical. + * \param p Pointer to the start of the extension value + * (the content of the OCTET STRING). + * \param end End of extension value. + * + * \note The callback must fail and return a negative error code + * if it can not parse or does not support the extension. + * When the callback fails to parse a critical extension + * mbedtls_x509_crt_parse_der_with_ext_cb() also fails. + * When the callback fails to parse a non critical extension + * mbedtls_x509_crt_parse_der_with_ext_cb() simply skips + * the extension and continues parsing. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +typedef int (*mbedtls_x509_crt_ext_cb_t)( void *p_ctx, + mbedtls_x509_crt const *crt, + mbedtls_x509_buf const *oid, + int critical, + const unsigned char *p, + const unsigned char *end ); + +/** + * \brief Parse a single DER formatted certificate and add it + * to the end of the provided chained list. + * + * \param chain The pointer to the start of the CRT chain to attach to. + * When parsing the first CRT in a chain, this should point + * to an instance of ::mbedtls_x509_crt initialized through + * mbedtls_x509_crt_init(). + * \param buf The buffer holding the DER encoded certificate. + * \param buflen The size in Bytes of \p buf. + * \param make_copy When not zero this function makes an internal copy of the + * CRT buffer \p buf. In particular, \p buf may be destroyed + * or reused after this call returns. + * When zero this function avoids duplicating the CRT buffer + * by taking temporary ownership thereof until the CRT + * is destroyed (like mbedtls_x509_crt_parse_der_nocopy()) + * \param cb A callback invoked for every unsupported certificate + * extension. + * \param p_ctx An opaque context passed to the callback. + * + * \note This call is functionally equivalent to + * mbedtls_x509_crt_parse_der(), and/or + * mbedtls_x509_crt_parse_der_nocopy() + * but it calls the callback with every unsupported + * certificate extension and additionally the + * "certificate policies" extension if it contains any + * unsupported certificate policies. + * The callback must return a negative error code if it + * does not know how to handle such an extension. + * When the callback fails to parse a critical extension + * mbedtls_x509_crt_parse_der_with_ext_cb() also fails. + * When the callback fails to parse a non critical extension + * mbedtls_x509_crt_parse_der_with_ext_cb() simply skips + * the extension and continues parsing. + * Future versions of the library may invoke the callback + * in other cases, if and when the need arises. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_x509_crt_parse_der_with_ext_cb( mbedtls_x509_crt *chain, + const unsigned char *buf, + size_t buflen, + int make_copy, + mbedtls_x509_crt_ext_cb_t cb, + void *p_ctx ); + /** * \brief Parse a single DER formatted certificate and add it * to the end of the provided chained list. This is a @@ -501,8 +583,11 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, * \param crt The certificate chain to be verified. * \param trust_ca The list of trusted CAs. * \param ca_crl The list of CRLs for trusted CAs. - * \param cn The expected Common Name. This may be \c NULL if the - * CN need not be verified. + * \param cn The expected Common Name. This will be checked to be + * present in the certificate's subjectAltNames extension or, + * if this extension is absent, as a CN component in its + * Subject name. Currently only DNS names are supported. This + * may be \c NULL if the CN need not be verified. * \param flags The address at which to store the result of the verification. * If the verification couldn't be completed, the flag value is * set to (uint32_t) -1. diff --git a/connectivity/mbedtls/include/mbedtls/x509_csr.h b/connectivity/mbedtls/include/mbedtls/x509_csr.h index 25b23bbc0c..b1dfc21f1f 100644 --- a/connectivity/mbedtls/include/mbedtls/x509_csr.h +++ b/connectivity/mbedtls/include/mbedtls/x509_csr.h @@ -4,7 +4,7 @@ * \brief X.509 certificate signing request parsing and writing */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_X509_CSR_H #define MBEDTLS_X509_CSR_H diff --git a/connectivity/mbedtls/include/mbedtls/xtea.h b/connectivity/mbedtls/include/mbedtls/xtea.h index 2dc0afc737..473dd4b795 100644 --- a/connectivity/mbedtls/include/mbedtls/xtea.h +++ b/connectivity/mbedtls/include/mbedtls/xtea.h @@ -4,7 +4,7 @@ * \brief XTEA block cipher (32-bit) */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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_XTEA_H #define MBEDTLS_XTEA_H diff --git a/connectivity/mbedtls/source/hash_wrappers.c b/connectivity/mbedtls/platform/src/hash_wrappers.c similarity index 94% rename from connectivity/mbedtls/source/hash_wrappers.c rename to connectivity/mbedtls/platform/src/hash_wrappers.c index d393ed8a1b..aacaed06b8 100644 --- a/connectivity/mbedtls/source/hash_wrappers.c +++ b/connectivity/mbedtls/platform/src/hash_wrappers.c @@ -1,3 +1,19 @@ +/* Copyright (c) 2018-2021 Arm Limited + * 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. + */ + #include "mbedtls/md2.h" #include "mbedtls/md4.h" #include "mbedtls/md5.h" diff --git a/connectivity/mbedtls/source/.gitignore b/connectivity/mbedtls/source/.gitignore deleted file mode 100644 index 3a63a63a43..0000000000 --- a/connectivity/mbedtls/source/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.o -libmbed* -*.sln -*.vcxproj diff --git a/connectivity/mbedtls/source/Makefile b/connectivity/mbedtls/source/Makefile deleted file mode 100644 index f9cd468a5f..0000000000 --- a/connectivity/mbedtls/source/Makefile +++ /dev/null @@ -1,216 +0,0 @@ - -# Also see "include/mbedtls/config.h" - -CFLAGS ?= -O2 -WARNING_CFLAGS ?= -Wall -Wextra -LDFLAGS ?= - -LOCAL_CFLAGS = $(WARNING_CFLAGS) -I../include -D_FILE_OFFSET_BITS=64 -LOCAL_LDFLAGS = - -ifdef DEBUG -LOCAL_CFLAGS += -g3 -endif - -# MicroBlaze specific options: -# CFLAGS += -mno-xl-soft-mul -mxl-barrel-shift - -# To compile on Plan9: -# CFLAGS += -D_BSD_EXTENSION - -# if were running on Windows build for Windows -ifdef WINDOWS -WINDOWS_BUILD=1 -else ifeq ($(shell uname -s),Darwin) -ifeq ($(AR),ar) -APPLE_BUILD ?= 1 -endif -endif - -# To compile as a shared library: -ifdef SHARED -# all code is position-indep with mingw, avoid warning about useless flag -ifndef WINDOWS_BUILD -LOCAL_CFLAGS += -fPIC -fpic -endif -endif - -SOEXT_TLS=so.13 -SOEXT_X509=so.1 -SOEXT_CRYPTO=so.4 - -# Set AR_DASH= (empty string) to use an ar implementation that does not accept -# the - prefix for command line options (e.g. llvm-ar) -AR_DASH ?= - - -ARFLAGS = $(AR_DASH)src -ifdef APPLE_BUILD -ifneq ($(APPLE_BUILD),0) -ARFLAGS = $(AR_DASH)Src -RLFLAGS = -no_warning_for_no_symbols -c -RL ?= ranlib -endif -endif - -DLEXT ?= so -ifdef WINDOWS_BUILD -# Windows shared library extension: -DLEXT = dll -else ifdef APPLE_BUILD -ifneq ($(APPLE_BUILD),0) -# Mac OS X shared library extension: -DLEXT = dylib -endif -endif - -OBJS_CRYPTO= aes.o aesni.o arc4.o \ - aria.o asn1parse.o asn1write.o \ - base64.o bignum.o blowfish.o \ - camellia.o ccm.o chacha20.o \ - chachapoly.o cipher.o cipher_wrap.o \ - cmac.o ctr_drbg.o des.o \ - dhm.o ecdh.o ecdsa.o \ - ecjpake.o ecp.o \ - ecp_curves.o entropy.o entropy_poll.o \ - error.o gcm.o havege.o \ - hkdf.o \ - hmac_drbg.o md.o md2.o \ - md4.o md5.o \ - memory_buffer_alloc.o nist_kw.o \ - oid.o padlock.o pem.o \ - pk.o pk_wrap.o pkcs12.o \ - pkcs5.o pkparse.o pkwrite.o \ - platform.o platform_util.o poly1305.o \ - psa_crypto.o psa_crypto_se.o \ - psa_crypto_slot_management.o \ - psa_crypto_storage.o \ - psa_its_file.o \ - ripemd160.o rsa_internal.o rsa.o \ - sha1.o sha256.o sha512.o \ - threading.o timing.o \ - version.o version_features.o \ - xtea.o - -include ../3rdparty/Makefile.inc -LOCAL_CFLAGS+=$(THIRDPARTY_INCLUDES) -OBJS_CRYPTO+=$(THIRDPARTY_CRYPTO_OBJECTS) - -OBJS_X509= certs.o pkcs11.o x509.o \ - x509_create.o x509_crl.o x509_crt.o \ - x509_csr.o x509write_crt.o x509write_csr.o - -OBJS_TLS= debug.o net_sockets.o \ - ssl_cache.o ssl_ciphersuites.o \ - ssl_cli.o ssl_cookie.o \ - ssl_msg.o \ - ssl_srv.o ssl_ticket.o \ - ssl_tls.o - -.SILENT: - -.PHONY: all static shared clean - -ifndef SHARED -all: static -else -all: shared static -endif - -static: libmbedcrypto.a libmbedx509.a libmbedtls.a - -shared: libmbedcrypto.$(DLEXT) libmbedx509.$(DLEXT) libmbedtls.$(DLEXT) - -# tls -libmbedtls.a: $(OBJS_TLS) - echo " AR $@" - $(AR) $(ARFLAGS) $@ $(OBJS_TLS) -ifdef APPLE_BUILD -ifneq ($(APPLE_BUILD),0) - echo " RL $@" - $(RL) $(RLFLAGS) $@ -endif -endif - -libmbedtls.$(SOEXT_TLS): $(OBJS_TLS) libmbedx509.so - echo " LD $@" - $(CC) -shared -Wl,-soname,$@ -L. -lmbedcrypto -lmbedx509 $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS) - -libmbedtls.so: libmbedtls.$(SOEXT_TLS) - echo " LN $@ -> $<" - ln -sf $< $@ - -libmbedtls.dylib: $(OBJS_TLS) libmbedx509.dylib - echo " LD $@" - $(CC) -dynamiclib -L. -lmbedcrypto -lmbedx509 $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS) - -libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll - echo " LD $@" - $(CC) -shared -Wl,-soname,$@ -Wl,--out-implib,$@.a -o $@ $(OBJS_TLS) -lws2_32 -lwinmm -lgdi32 -L. -lmbedcrypto -lmbedx509 -static-libgcc $(LOCAL_LDFLAGS) $(LDFLAGS) - -# x509 -libmbedx509.a: $(OBJS_X509) - echo " AR $@" - $(AR) $(ARFLAGS) $@ $(OBJS_X509) -ifdef APPLE_BUILD -ifneq ($(APPLE_BUILD),0) - echo " RL $@" - $(RL) $(RLFLAGS) $@ -endif -endif - -libmbedx509.$(SOEXT_X509): $(OBJS_X509) libmbedcrypto.so - echo " LD $@" - $(CC) -shared -Wl,-soname,$@ -L. -lmbedcrypto $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509) - -libmbedx509.so: libmbedx509.$(SOEXT_X509) - echo " LN $@ -> $<" - ln -sf $< $@ - -libmbedx509.dylib: $(OBJS_X509) libmbedcrypto.dylib - echo " LD $@" - $(CC) -dynamiclib -L. -lmbedcrypto $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509) - -libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll - echo " LD $@" - $(CC) -shared -Wl,-soname,$@ -Wl,--out-implib,$@.a -o $@ $(OBJS_X509) -lws2_32 -lwinmm -lgdi32 -L. -lmbedcrypto -static-libgcc $(LOCAL_LDFLAGS) $(LDFLAGS) - -# crypto -libmbedcrypto.a: $(OBJS_CRYPTO) - echo " AR $@" - $(AR) $(ARFLAGS) $@ $(OBJS_CRYPTO) -ifdef APPLE_BUILD -ifneq ($(APPLE_BUILD),0) - echo " RL $@" - $(RL) $(RLFLAGS) $@ -endif -endif - -libmbedcrypto.$(SOEXT_CRYPTO): $(OBJS_CRYPTO) - echo " LD $@" - $(CC) -shared -Wl,-soname,$@ $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_CRYPTO) - -libmbedcrypto.so: libmbedcrypto.$(SOEXT_CRYPTO) - echo " LN $@ -> $<" - ln -sf $< $@ - -libmbedcrypto.dylib: $(OBJS_CRYPTO) - echo " LD $@" - $(CC) -dynamiclib $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(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) - -.c.o: - echo " CC $<" - $(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $< - -clean: -ifndef WINDOWS - rm -f *.o libmbed* - rm -f $(THIRDPARTY_CRYPTO_OBJECTS) -else - if exist *.o del /Q /F *.o - if exist libmbed* del /Q /F libmbed* - del /Q /F del_errors_out_if_the_file_list_is_empty_but_not_if_a_file_does_not_exist $(subst /,\,$(THIRDPARTY_CRYPTO_OBJECTS)) -endif diff --git a/connectivity/mbedtls/source/aes.c b/connectivity/mbedtls/source/aes.c index 604d0f3d7f..ed48b24d3b 100644 --- a/connectivity/mbedtls/source/aes.c +++ b/connectivity/mbedtls/source/aes.c @@ -1,7 +1,7 @@ /* * FIPS-197 compliant AES implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The AES block cipher was designed by Vincent Rijmen and Joan Daemen. @@ -25,11 +23,7 @@ * http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_AES_C) @@ -1847,7 +1841,7 @@ int mbedtls_aes_self_test( int verbose ) mode = i & 1; if( verbose != 0 ) - mbedtls_printf( " AES-ECB-%3d (%s): ", keybits, + mbedtls_printf( " AES-ECB-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memset( buf, 0, 16 ); @@ -1909,7 +1903,7 @@ int mbedtls_aes_self_test( int verbose ) mode = i & 1; if( verbose != 0 ) - mbedtls_printf( " AES-CBC-%3d (%s): ", keybits, + mbedtls_printf( " AES-CBC-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memset( iv , 0, 16 ); @@ -1984,7 +1978,7 @@ int mbedtls_aes_self_test( int verbose ) mode = i & 1; if( verbose != 0 ) - mbedtls_printf( " AES-CFB128-%3d (%s): ", keybits, + mbedtls_printf( " AES-CFB128-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memcpy( iv, aes_test_cfb128_iv, 16 ); @@ -2047,7 +2041,7 @@ int mbedtls_aes_self_test( int verbose ) mode = i & 1; if( verbose != 0 ) - mbedtls_printf( " AES-OFB-%3d (%s): ", keybits, + mbedtls_printf( " AES-OFB-%3u (%s): ", keybits, ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); memcpy( iv, aes_test_ofb_iv, 16 ); diff --git a/connectivity/mbedtls/source/aesni.c b/connectivity/mbedtls/source/aesni.c index 062708b047..996292ff6d 100644 --- a/connectivity/mbedtls/source/aesni.c +++ b/connectivity/mbedtls/source/aesni.c @@ -1,7 +1,7 @@ /* * AES-NI support functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -24,11 +22,7 @@ * [CLMUL-WP] http://software.intel.com/en-us/articles/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode/ */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_AESNI_C) diff --git a/connectivity/mbedtls/source/arc4.c b/connectivity/mbedtls/source/arc4.c index b8998ac6cd..b34dc5e754 100644 --- a/connectivity/mbedtls/source/arc4.c +++ b/connectivity/mbedtls/source/arc4.c @@ -1,7 +1,7 @@ /* * An implementation of the ARCFOUR algorithm * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The ARCFOUR algorithm was publicly disclosed on 94/09. @@ -24,11 +22,7 @@ * http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_ARC4_C) diff --git a/connectivity/mbedtls/source/aria.c b/connectivity/mbedtls/source/aria.c index aff66d667f..1875635522 100644 --- a/connectivity/mbedtls/source/aria.c +++ b/connectivity/mbedtls/source/aria.c @@ -1,7 +1,7 @@ /* * ARIA implementation * - * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -25,11 +23,7 @@ * [2] https://tools.ietf.org/html/rfc5794 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_ARIA_C) diff --git a/connectivity/mbedtls/source/asn1parse.c b/connectivity/mbedtls/source/asn1parse.c index 34c660775d..22747d3ba4 100644 --- a/connectivity/mbedtls/source/asn1parse.c +++ b/connectivity/mbedtls/source/asn1parse.c @@ -1,7 +1,7 @@ /* * Generic ASN.1 parsing * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_ASN1_PARSE_C) diff --git a/connectivity/mbedtls/source/asn1write.c b/connectivity/mbedtls/source/asn1write.c index 503db930b5..deb1a2ff65 100644 --- a/connectivity/mbedtls/source/asn1write.c +++ b/connectivity/mbedtls/source/asn1write.c @@ -1,7 +1,7 @@ /* * ASN.1 buffer writing functionality * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_ASN1_WRITE_C) diff --git a/connectivity/mbedtls/source/base64.c b/connectivity/mbedtls/source/base64.c index f06b57b31f..d39474a084 100644 --- a/connectivity/mbedtls/source/base64.c +++ b/connectivity/mbedtls/source/base64.c @@ -1,7 +1,7 @@ /* * RFC 1521 base64 encoding/decoding * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_BASE64_C) diff --git a/connectivity/mbedtls/source/bignum.c b/connectivity/mbedtls/source/bignum.c index d53aefd5b0..9325632b42 100644 --- a/connectivity/mbedtls/source/bignum.c +++ b/connectivity/mbedtls/source/bignum.c @@ -1,7 +1,7 @@ /* * Multi-precision integer library * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -35,11 +33,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_BIGNUM_C) @@ -243,6 +237,22 @@ void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y ) memcpy( Y, &T, sizeof( mbedtls_mpi ) ); } +/* + * Conditionally assign dest = src, without leaking information + * about whether the assignment was made or not. + * dest and src must be arrays of limbs of size n. + * assign must be 0 or 1. + */ +static void mpi_safe_cond_assign( size_t n, + mbedtls_mpi_uint *dest, + const mbedtls_mpi_uint *src, + unsigned char assign ) +{ + size_t i; + for( i = 0; i < n; i++ ) + dest[i] = dest[i] * ( 1 - assign ) + src[i] * assign; +} + /* * Conditionally assign X = Y, without leaking information * about whether the assignment was made or not. @@ -262,10 +272,9 @@ int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned X->s = X->s * ( 1 - assign ) + Y->s * assign; - for( i = 0; i < Y->n; i++ ) - X->p[i] = X->p[i] * ( 1 - assign ) + Y->p[i] * assign; + mpi_safe_cond_assign( Y->n, X->p, Y->p, assign ); - for( ; i < X->n; i++ ) + for( i = Y->n; i < X->n; i++ ) X->p[i] *= ( 1 - assign ); cleanup: @@ -1327,10 +1336,24 @@ cleanup: return( ret ); } -/* - * Helper for mbedtls_mpi subtraction +/** + * Helper for mbedtls_mpi subtraction. + * + * Calculate d - s where d and s have the same size. + * This function operates modulo (2^ciL)^n and returns the carry + * (1 if there was a wraparound, i.e. if `d < s`, and 0 otherwise). + * + * \param n Number of limbs of \p d and \p s. + * \param[in,out] d On input, the left operand. + * On output, the result of the subtraction: + * \param[in] s The right operand. + * + * \return 1 if `d < s`. + * 0 if `d >= s`. */ -static void mpi_sub_hlp( size_t n, mbedtls_mpi_uint *s, mbedtls_mpi_uint *d ) +static mbedtls_mpi_uint mpi_sub_hlp( size_t n, + mbedtls_mpi_uint *d, + const mbedtls_mpi_uint *s ) { size_t i; mbedtls_mpi_uint c, z; @@ -1341,28 +1364,22 @@ static void mpi_sub_hlp( size_t n, mbedtls_mpi_uint *s, mbedtls_mpi_uint *d ) c = ( *d < *s ) + z; *d -= *s; } - while( c != 0 ) - { - z = ( *d < c ); *d -= c; - c = z; d++; - } + return( c ); } /* - * Unsigned subtraction: X = |A| - |B| (HAC 14.9) + * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10) */ int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B ) { mbedtls_mpi TB; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; + mbedtls_mpi_uint carry; MPI_VALIDATE_RET( X != NULL ); MPI_VALIDATE_RET( A != NULL ); MPI_VALIDATE_RET( B != NULL ); - if( mbedtls_mpi_cmp_abs( A, B ) < 0 ) - return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE ); - mbedtls_mpi_init( &TB ); if( X == B ) @@ -1385,7 +1402,18 @@ int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi if( B->p[n - 1] != 0 ) break; - mpi_sub_hlp( n, B->p, X->p ); + carry = mpi_sub_hlp( n, X->p, B->p ); + if( carry != 0 ) + { + /* Propagate the carry to the first nonzero limb of X. */ + for( ; n < X->n && X->p[n] == 0; n++ ) + --X->p[n]; + /* If we ran out of space for the carry, it means that the result + * is negative. */ + if( n == X->n ) + return( MBEDTLS_ERR_MPI_NEGATIVE_VALUE ); + --X->p[n]; + } cleanup: @@ -1975,18 +2003,34 @@ static void mpi_montg_init( mbedtls_mpi_uint *mm, const mbedtls_mpi *N ) *mm = ~x + 1; } -/* - * Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36) +/** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36) + * + * \param[in,out] A One of the numbers to multiply. + * It must have at least as many limbs as N + * (A->n >= N->n), and any limbs beyond n are ignored. + * On successful completion, A contains the result of + * the multiplication A * B * R^-1 mod N where + * R = (2^ciL)^n. + * \param[in] B One of the numbers to multiply. + * It must be nonzero and must not have more limbs than N + * (B->n <= N->n). + * \param[in] N The modulo. N must be odd. + * \param mm The value calculated by `mpi_montg_init(&mm, N)`. + * This is -N^-1 mod 2^ciL. + * \param[in,out] T A bignum for temporary storage. + * It must be at least twice the limb size of N plus 2 + * (T->n >= 2 * (N->n + 1)). + * Its initial content is unused and + * its final content is indeterminate. + * Note that unlike the usual convention in the library + * for `const mbedtls_mpi*`, the content of T can change. */ -static int mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm, +static void mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *N, mbedtls_mpi_uint mm, const mbedtls_mpi *T ) { size_t i, n, m; mbedtls_mpi_uint u0, u1, *d; - if( T->n < N->n + 1 || T->p == NULL ) - return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); - memset( T->p, 0, T->n * ciL ); d = T->p; @@ -2007,22 +2051,34 @@ static int mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi *d++ = u0; d[n + 1] = 0; } - memcpy( A->p, d, ( n + 1 ) * ciL ); + /* At this point, d is either the desired result or the desired result + * plus N. We now potentially subtract N, avoiding leaking whether the + * subtraction is performed through side channels. */ - if( mbedtls_mpi_cmp_abs( A, N ) >= 0 ) - mpi_sub_hlp( n, N->p, A->p ); - else - /* prevent timing attacks */ - mpi_sub_hlp( n, A->p, T->p ); - - return( 0 ); + /* Copy the n least significant limbs of d to A, so that + * A = d if d < N (recall that N has n limbs). */ + memcpy( A->p, d, n * ciL ); + /* If d >= N then we want to set A to d - N. To prevent timing attacks, + * do the calculation without using conditional tests. */ + /* Set d to d0 + (2^biL)^n - N where d0 is the current value of d. */ + d[n] += 1; + d[n] -= mpi_sub_hlp( n, d, N->p ); + /* If d0 < N then d < (2^biL)^n + * so d[n] == 0 and we want to keep A as it is. + * If d0 >= N then d >= (2^biL)^n, and d <= (2^biL)^n + N < 2 * (2^biL)^n + * so d[n] == 1 and we want to set A to the result of the subtraction + * which is d - (2^biL)^n, i.e. the n least significant limbs of d. + * This exactly corresponds to a conditional assignment. */ + mpi_safe_cond_assign( n, A->p, d, (unsigned char) d[n] ); } /* * Montgomery reduction: A = A * R^-1 mod N + * + * See mpi_montmul() regarding constraints and guarantees on the parameters. */ -static int mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N, - mbedtls_mpi_uint mm, const mbedtls_mpi *T ) +static void mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N, + mbedtls_mpi_uint mm, const mbedtls_mpi *T ) { mbedtls_mpi_uint z = 1; mbedtls_mpi U; @@ -2030,7 +2086,7 @@ static int mpi_montred( mbedtls_mpi *A, const mbedtls_mpi *N, U.n = U.s = (int) z; U.p = &z; - return( mpi_montmul( A, &U, N, mm, T ) ); + mpi_montmul( A, &U, N, mm, T ); } /* @@ -2116,13 +2172,13 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, else MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[1], A ) ); - MBEDTLS_MPI_CHK( mpi_montmul( &W[1], &RR, N, mm, &T ) ); + mpi_montmul( &W[1], &RR, N, mm, &T ); /* * X = R^2 * R^-1 mod N = R mod N */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) ); - MBEDTLS_MPI_CHK( mpi_montred( X, N, mm, &T ) ); + mpi_montred( X, N, mm, &T ); if( wsize > 1 ) { @@ -2135,7 +2191,7 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) ); for( i = 0; i < wsize - 1; i++ ) - MBEDTLS_MPI_CHK( mpi_montmul( &W[j], &W[j], N, mm, &T ) ); + mpi_montmul( &W[j], &W[j], N, mm, &T ); /* * W[i] = W[i - 1] * W[1] @@ -2145,7 +2201,7 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) ); - MBEDTLS_MPI_CHK( mpi_montmul( &W[i], &W[1], N, mm, &T ) ); + mpi_montmul( &W[i], &W[1], N, mm, &T ); } } @@ -2182,7 +2238,7 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, /* * out of window, square X */ - MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) ); + mpi_montmul( X, X, N, mm, &T ); continue; } @@ -2200,12 +2256,12 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, * X = X^wsize R^-1 mod N */ for( i = 0; i < wsize; i++ ) - MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) ); + mpi_montmul( X, X, N, mm, &T ); /* * X = X * W[wbits] R^-1 mod N */ - MBEDTLS_MPI_CHK( mpi_montmul( X, &W[wbits], N, mm, &T ) ); + mpi_montmul( X, &W[wbits], N, mm, &T ); state--; nbits = 0; @@ -2218,18 +2274,18 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, */ for( i = 0; i < nbits; i++ ) { - MBEDTLS_MPI_CHK( mpi_montmul( X, X, N, mm, &T ) ); + mpi_montmul( X, X, N, mm, &T ); wbits <<= 1; if( ( wbits & ( one << wsize ) ) != 0 ) - MBEDTLS_MPI_CHK( mpi_montmul( X, &W[1], N, mm, &T ) ); + mpi_montmul( X, &W[1], N, mm, &T ); } /* * X = A^E * R * R^-1 mod N = A^E mod N */ - MBEDTLS_MPI_CHK( mpi_montred( X, N, mm, &T ) ); + mpi_montred( X, N, mm, &T ); if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 ) { @@ -2938,7 +2994,7 @@ int mbedtls_mpi_self_test( int verbose ) cleanup: if( ret != 0 && verbose != 0 ) - mbedtls_printf( "Unexpected error, return code = %08X\n", ret ); + mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret ); mbedtls_mpi_free( &A ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &N ); mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &U ); mbedtls_mpi_free( &V ); diff --git a/connectivity/mbedtls/source/blowfish.c b/connectivity/mbedtls/source/blowfish.c index cbf9238246..76da448976 100644 --- a/connectivity/mbedtls/source/blowfish.c +++ b/connectivity/mbedtls/source/blowfish.c @@ -1,7 +1,7 @@ /* * Blowfish implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The Blowfish block cipher was designed by Bruce Schneier in 1993. @@ -25,11 +23,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_BLOWFISH_C) diff --git a/connectivity/mbedtls/source/camellia.c b/connectivity/mbedtls/source/camellia.c index 22262b89a8..d60f931880 100644 --- a/connectivity/mbedtls/source/camellia.c +++ b/connectivity/mbedtls/source/camellia.c @@ -1,7 +1,7 @@ /* * Camellia implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The Camellia block cipher was designed by NTT and Mitsubishi Electric @@ -25,11 +23,7 @@ * http://info.isl.ntt.co.jp/crypt/eng/camellia/dl/01espec.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_CAMELLIA_C) diff --git a/connectivity/mbedtls/source/ccm.c b/connectivity/mbedtls/source/ccm.c index eaef106a11..e6ca588bab 100644 --- a/connectivity/mbedtls/source/ccm.c +++ b/connectivity/mbedtls/source/ccm.c @@ -1,7 +1,7 @@ /* * NIST SP800-38C compliant CCM implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -28,11 +26,7 @@ * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_CCM_C) diff --git a/connectivity/mbedtls/source/certs.c b/connectivity/mbedtls/source/certs.c index f152c283a7..a5695e3c8e 100644 --- a/connectivity/mbedtls/source/certs.c +++ b/connectivity/mbedtls/source/certs.c @@ -1,7 +1,7 @@ /* * X.509 test certificates * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #include "mbedtls/certs.h" diff --git a/connectivity/mbedtls/source/chacha20.c b/connectivity/mbedtls/source/chacha20.c index 343b2167cd..78467d3fc6 100644 --- a/connectivity/mbedtls/source/chacha20.c +++ b/connectivity/mbedtls/source/chacha20.c @@ -5,7 +5,7 @@ * * \author Daniel King * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,15 +19,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_CHACHA20_C) @@ -520,6 +514,9 @@ static const size_t test_lengths[2] = 375U }; +/* Make sure no other definition is already present. */ +#undef ASSERT + #define ASSERT( cond, args ) \ do \ { \ diff --git a/connectivity/mbedtls/source/chachapoly.c b/connectivity/mbedtls/source/chachapoly.c index f0af5ded26..77d547731c 100644 --- a/connectivity/mbedtls/source/chachapoly.c +++ b/connectivity/mbedtls/source/chachapoly.c @@ -3,7 +3,7 @@ * * \brief ChaCha20-Poly1305 AEAD construction based on RFC 7539. * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -17,14 +17,8 @@ * 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 +#include "common.h" #if defined(MBEDTLS_CHACHAPOLY_C) @@ -476,6 +470,9 @@ static const unsigned char test_mac[1][16] = } }; +/* Make sure no other definition is already present. */ +#undef ASSERT + #define ASSERT( cond, args ) \ do \ { \ diff --git a/connectivity/mbedtls/source/cipher.c b/connectivity/mbedtls/source/cipher.c index 409c3fe674..853eeec203 100644 --- a/connectivity/mbedtls/source/cipher.c +++ b/connectivity/mbedtls/source/cipher.c @@ -5,7 +5,7 @@ * * \author Adriaan de Jong * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,15 +19,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_CIPHER_C) diff --git a/connectivity/mbedtls/source/cipher_wrap.c b/connectivity/mbedtls/source/cipher_wrap.c index a813426be2..8eb2ec02b8 100644 --- a/connectivity/mbedtls/source/cipher_wrap.c +++ b/connectivity/mbedtls/source/cipher_wrap.c @@ -5,7 +5,7 @@ * * \author Adriaan de Jong * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,15 +19,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_CIPHER_C) diff --git a/connectivity/mbedtls/source/cmac.c b/connectivity/mbedtls/source/cmac.c index 642680d556..816bf13da3 100644 --- a/connectivity/mbedtls/source/cmac.c +++ b/connectivity/mbedtls/source/cmac.c @@ -3,7 +3,7 @@ * * \brief NIST SP800-38B compliant CMAC implementation for AES and 3DES * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -17,8 +17,6 @@ * 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) */ /* @@ -40,11 +38,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_CMAC_C) @@ -784,7 +778,7 @@ static int cmac_test_subkeys( int verbose, for( i = 0; i < num_tests; i++ ) { if( verbose != 0 ) - mbedtls_printf( " %s CMAC subkey #%u: ", testname, i + 1 ); + mbedtls_printf( " %s CMAC subkey #%d: ", testname, i + 1 ); mbedtls_cipher_init( &ctx ); @@ -865,7 +859,7 @@ static int cmac_test_wth_cipher( int verbose, for( i = 0; i < num_tests; i++ ) { if( verbose != 0 ) - mbedtls_printf( " %s CMAC #%u: ", testname, i + 1 ); + mbedtls_printf( " %s CMAC #%d: ", testname, i + 1 ); if( ( ret = mbedtls_cipher_cmac( cipher_info, key, keybits, messages, message_lengths[i], output ) ) != 0 ) @@ -900,7 +894,7 @@ static int test_aes128_cmac_prf( int verbose ) for( i = 0; i < NB_PRF_TESTS; i++ ) { - mbedtls_printf( " AES CMAC 128 PRF #%u: ", i ); + mbedtls_printf( " AES CMAC 128 PRF #%d: ", i ); ret = mbedtls_aes_cmac_prf_128( PRFK, PRFKlen[i], PRFM, 20, output ); if( ret != 0 || memcmp( output, PRFT[i], MBEDTLS_AES_BLOCK_SIZE ) != 0 ) diff --git a/connectivity/mbedtls/source/ctr_drbg.c b/connectivity/mbedtls/source/ctr_drbg.c index 8a2920a328..54843a7be6 100644 --- a/connectivity/mbedtls/source/ctr_drbg.c +++ b/connectivity/mbedtls/source/ctr_drbg.c @@ -1,7 +1,7 @@ /* * CTR_DRBG implementation based on AES-256 (NIST SP 800-90) * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The NIST SP 800-90 DRBGs are described in the following publication. @@ -24,11 +22,7 @@ * http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_CTR_DRBG_C) diff --git a/connectivity/mbedtls/source/debug.c b/connectivity/mbedtls/source/debug.c index ae78a697a4..c3384be359 100644 --- a/connectivity/mbedtls/source/debug.c +++ b/connectivity/mbedtls/source/debug.c @@ -1,7 +1,7 @@ /* * Debugging routines * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_DEBUG_C) @@ -132,7 +126,7 @@ void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level, return; mbedtls_snprintf( str, sizeof( str ), "%s() returned %d (-0x%04x)\n", - text, ret, -ret ); + text, ret, (unsigned int) -ret ); debug_send_line( ssl, level, file, line, str ); } diff --git a/connectivity/mbedtls/source/des.c b/connectivity/mbedtls/source/des.c index 24e517ed91..eddf55e789 100644 --- a/connectivity/mbedtls/source/des.c +++ b/connectivity/mbedtls/source/des.c @@ -1,7 +1,7 @@ /* * FIPS-46-3 compliant Triple-DES implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * DES, on which TDES is based, was originally designed by Horst Feistel @@ -25,11 +23,7 @@ * http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_DES_C) diff --git a/connectivity/mbedtls/source/dhm.c b/connectivity/mbedtls/source/dhm.c index 392ed0c150..f796812310 100644 --- a/connectivity/mbedtls/source/dhm.c +++ b/connectivity/mbedtls/source/dhm.c @@ -1,7 +1,7 @@ /* * Diffie-Hellman-Merkle key exchange * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The following sources were referenced in the design of this implementation @@ -27,11 +25,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_DHM_C) @@ -324,6 +318,32 @@ cleanup: return( 0 ); } +/* + * Pick a random R in the range [2, M) for blinding purposes + */ +static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) +{ + int ret, count; + + count = 0; + do + { + MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( R, mbedtls_mpi_size( M ), f_rng, p_rng ) ); + + while( mbedtls_mpi_cmp_mpi( R, M ) >= 0 ) + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( R, 1 ) ); + + if( count++ > 10 ) + return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ); + } + while( mbedtls_mpi_cmp_int( R, 1 ) <= 0 ); + +cleanup: + return( ret ); +} + + /* * Use the blinding method and optimisation suggested in section 10 of: * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA, @@ -333,7 +353,10 @@ cleanup: static int dhm_update_blinding( mbedtls_dhm_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { - int ret, count; + int ret; + mbedtls_mpi R; + + mbedtls_mpi_init( &R ); /* * Don't use any blinding the first time a particular X is used, @@ -368,24 +391,23 @@ static int dhm_update_blinding( mbedtls_dhm_context *ctx, */ /* Vi = random( 2, P-1 ) */ - count = 0; - do - { - MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vi, mbedtls_mpi_size( &ctx->P ), f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( dhm_random_below( &ctx->Vi, &ctx->P, f_rng, p_rng ) ); - while( mbedtls_mpi_cmp_mpi( &ctx->Vi, &ctx->P ) >= 0 ) - MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->Vi, 1 ) ); + /* Vf = Vi^-X mod P + * First compute Vi^-1 = R * (R Vi)^-1, (avoiding leaks from inv_mod), + * then elevate to the Xth power. */ + MBEDTLS_MPI_CHK( dhm_random_below( &R, &ctx->P, f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vi, &R ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vf, &ctx->Vf, &ctx->P ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vf, &ctx->Vf, &R ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vf, &ctx->Vf, &ctx->P ) ); - if( count++ > 10 ) - return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ); - } - while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) <= 0 ); - - /* Vf = Vi^-X mod P */ - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vf, &ctx->Vi, &ctx->P ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP ) ); cleanup: + mbedtls_mpi_free( &R ); + return( ret ); } diff --git a/connectivity/mbedtls/source/ecdh.c b/connectivity/mbedtls/source/ecdh.c index 3cf5333712..9dfa868063 100644 --- a/connectivity/mbedtls/source/ecdh.c +++ b/connectivity/mbedtls/source/ecdh.c @@ -1,7 +1,7 @@ /* * Elliptic curve Diffie-Hellman * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -26,11 +24,7 @@ * RFC 4492 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_ECDH_C) diff --git a/connectivity/mbedtls/source/ecdsa.c b/connectivity/mbedtls/source/ecdsa.c index 5acd2d00e8..22fb5e38d2 100644 --- a/connectivity/mbedtls/source/ecdsa.c +++ b/connectivity/mbedtls/source/ecdsa.c @@ -1,7 +1,7 @@ /* * Elliptic curve DSA * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -25,11 +23,7 @@ * SEC1 http://www.secg.org/index.php?action=secg,docs_secg */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_ECDSA_C) diff --git a/connectivity/mbedtls/source/ecjpake.c b/connectivity/mbedtls/source/ecjpake.c index 79ea3cbec4..315da4a4e2 100644 --- a/connectivity/mbedtls/source/ecjpake.c +++ b/connectivity/mbedtls/source/ecjpake.c @@ -1,7 +1,7 @@ /* * Elliptic curve J-PAKE * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -24,11 +22,7 @@ * available to members of the Thread Group http://threadgroup.org/ */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_ECJPAKE_C) diff --git a/connectivity/mbedtls/source/ecp.c b/connectivity/mbedtls/source/ecp.c index d3e42a94db..5d00de5cf9 100644 --- a/connectivity/mbedtls/source/ecp.c +++ b/connectivity/mbedtls/source/ecp.c @@ -1,7 +1,7 @@ /* * Elliptic curves over GF(p): generic functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -41,11 +39,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" /** * \brief Function level alternative implementation. @@ -105,6 +99,16 @@ #include "mbedtls/ecp_internal.h" +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) +#if defined(MBEDTLS_HMAC_DRBG_C) +#include "mbedtls/hmac_drbg.h" +#elif defined(MBEDTLS_CTR_DRBG_C) +#include "mbedtls/ctr_drbg.h" +#else +#error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid." +#endif +#endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */ + #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline @@ -118,6 +122,144 @@ static unsigned long add_count, dbl_count, mul_count; #endif +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) +/* + * Currently ecp_mul() takes a RNG function as an argument, used for + * side-channel protection, but it can be NULL. The initial reasoning was + * that people will pass non-NULL RNG when they care about side-channels, but + * unfortunately we have some APIs that call ecp_mul() with a NULL RNG, with + * no opportunity for the user to do anything about it. + * + * The obvious strategies for addressing that include: + * - change those APIs so that they take RNG arguments; + * - require a global RNG to be available to all crypto modules. + * + * Unfortunately those would break compatibility. So what we do instead is + * have our own internal DRBG instance, seeded from the secret scalar. + * + * The following is a light-weight abstraction layer for doing that with + * HMAC_DRBG (first choice) or CTR_DRBG. + */ + +#if defined(MBEDTLS_HMAC_DRBG_C) + +/* DRBG context type */ +typedef mbedtls_hmac_drbg_context ecp_drbg_context; + +/* DRBG context init */ +static inline void ecp_drbg_init( ecp_drbg_context *ctx ) +{ + mbedtls_hmac_drbg_init( ctx ); +} + +/* DRBG context free */ +static inline void ecp_drbg_free( ecp_drbg_context *ctx ) +{ + mbedtls_hmac_drbg_free( ctx ); +} + +/* DRBG function */ +static inline int ecp_drbg_random( void *p_rng, + unsigned char *output, size_t output_len ) +{ + return( mbedtls_hmac_drbg_random( p_rng, output, output_len ) ); +} + +/* DRBG context seeding */ +static int ecp_drbg_seed( ecp_drbg_context *ctx, + const mbedtls_mpi *secret, size_t secret_len ) +{ + int ret; + unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES]; + /* The list starts with strong hashes */ + const mbedtls_md_type_t md_type = mbedtls_md_list()[0]; + const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_type ); + + if( secret_len > MBEDTLS_ECP_MAX_BYTES ) + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } + + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret, + secret_bytes, secret_len ) ); + + ret = mbedtls_hmac_drbg_seed_buf( ctx, md_info, secret_bytes, secret_len ); + +cleanup: + mbedtls_platform_zeroize( secret_bytes, secret_len ); + + return( ret ); +} + +#elif defined(MBEDTLS_CTR_DRBG_C) + +/* DRBG context type */ +typedef mbedtls_ctr_drbg_context ecp_drbg_context; + +/* DRBG context init */ +static inline void ecp_drbg_init( ecp_drbg_context *ctx ) +{ + mbedtls_ctr_drbg_init( ctx ); +} + +/* DRBG context free */ +static inline void ecp_drbg_free( ecp_drbg_context *ctx ) +{ + mbedtls_ctr_drbg_free( ctx ); +} + +/* DRBG function */ +static inline int ecp_drbg_random( void *p_rng, + unsigned char *output, size_t output_len ) +{ + return( mbedtls_ctr_drbg_random( p_rng, output, output_len ) ); +} + +/* + * Since CTR_DRBG doesn't have a seed_buf() function the way HMAC_DRBG does, + * we need to pass an entropy function when seeding. So we use a dummy + * function for that, and pass the actual entropy as customisation string. + * (During seeding of CTR_DRBG the entropy input and customisation string are + * concatenated before being used to update the secret state.) + */ +static int ecp_ctr_drbg_null_entropy(void *ctx, unsigned char *out, size_t len) +{ + (void) ctx; + memset( out, 0, len ); + return( 0 ); +} + +/* DRBG context seeding */ +static int ecp_drbg_seed( ecp_drbg_context *ctx, + const mbedtls_mpi *secret, size_t secret_len ) +{ + int ret; + unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES]; + + if( secret_len > MBEDTLS_ECP_MAX_BYTES ) + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } + + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret, + secret_bytes, secret_len ) ); + + ret = mbedtls_ctr_drbg_seed( ctx, ecp_ctr_drbg_null_entropy, NULL, + secret_bytes, secret_len ); + +cleanup: + mbedtls_platform_zeroize( secret_bytes, secret_len ); + + return( ret ); +} + +#else +#error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid." +#endif /* DRBG modules */ +#endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */ + #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Maximum number of "basic operations" to be done in a row. @@ -165,6 +307,10 @@ struct mbedtls_ecp_restart_mul ecp_rsm_comb_core, /* ecp_mul_comb_core() */ ecp_rsm_final_norm, /* do the final normalization */ } state; +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_context drbg_ctx; + unsigned char drbg_seeded; +#endif }; /* @@ -177,6 +323,10 @@ static void ecp_restart_rsm_init( mbedtls_ecp_restart_mul_ctx *ctx ) ctx->T = NULL; ctx->T_size = 0; ctx->state = ecp_rsm_init; +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_init( &ctx->drbg_ctx ); + ctx->drbg_seeded = 0; +#endif } /* @@ -198,6 +348,10 @@ static void ecp_restart_rsm_free( mbedtls_ecp_restart_mul_ctx *ctx ) mbedtls_free( ctx->T ); } +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_free( &ctx->drbg_ctx ); +#endif + ecp_restart_rsm_init( ctx ); } @@ -345,25 +499,6 @@ int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, #endif /* MBEDTLS_ECP_RESTARTABLE */ -#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ - defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) -#define ECP_SHORTWEIERSTRASS -#endif - -#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \ - defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) -#define ECP_MONTGOMERY -#endif - /* * List of supported curves: * - internal ID @@ -741,7 +876,8 @@ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, plen = mbedtls_mpi_size( &grp->P ); -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) + (void) format; /* Montgomery curves always use the same point format */ if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { *olen = plen; @@ -751,7 +887,7 @@ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &P->X, buf, plen ) ); } #endif -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* @@ -814,7 +950,7 @@ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, plen = mbedtls_mpi_size( &grp->P ); -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { if( plen != ilen ) @@ -830,7 +966,7 @@ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) ); } #endif -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { if( buf[0] == 0x00 ) @@ -1148,7 +1284,7 @@ cleanup: return( ret ); } -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * For curves in short Weierstrass form, we do all the internal operations in * Jacobian coordinates. @@ -1544,7 +1680,10 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) ); if( count++ > 10 ) - return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } } while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 ); @@ -1894,7 +2033,9 @@ static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R 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 defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != 0 ) +#endif MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) ); } @@ -2015,6 +2156,7 @@ static int ecp_mul_comb_after_precomp( const mbedtls_ecp_group *grp, rs_ctx->rsm->state = ecp_rsm_final_norm; final_norm: + MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); #endif /* * Knowledge of the jacobian coordinates may leak the last few bits of the @@ -2027,10 +2169,11 @@ final_norm: * * Avoid the leak by randomizing coordinates before we normalize them. */ +#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != 0 ) +#endif MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, RR, f_rng, p_rng ) ); - MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV ); MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, RR ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) @@ -2101,11 +2244,44 @@ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char w, p_eq_g, i; size_t d; - unsigned char T_size, T_ok; - mbedtls_ecp_point *T; + unsigned char T_size = 0, T_ok = 0; + mbedtls_ecp_point *T = NULL; +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_context drbg_ctx; + + ecp_drbg_init( &drbg_ctx ); +#endif ECP_RS_ENTER( rsm ); +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + if( f_rng == NULL ) + { + /* Adjust pointers */ + f_rng = &ecp_drbg_random; +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + p_rng = &rs_ctx->rsm->drbg_ctx; + else +#endif + p_rng = &drbg_ctx; + + /* Initialize internal DRBG if necessary */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx == NULL || rs_ctx->rsm == NULL || + rs_ctx->rsm->drbg_seeded == 0 ) +#endif + { + const size_t m_len = ( grp->nbits + 7 ) / 8; + MBEDTLS_MPI_CHK( ecp_drbg_seed( p_rng, m, m_len ) ); + } +#if defined(MBEDTLS_ECP_RESTARTABLE) + if( rs_ctx != NULL && rs_ctx->rsm != NULL ) + rs_ctx->rsm->drbg_seeded = 1; +#endif + } +#endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */ + /* 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 && @@ -2177,6 +2353,10 @@ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, cleanup: +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_free( &drbg_ctx ); +#endif + /* does T belong to the group? */ if( T == grp->T ) T = NULL; @@ -2213,9 +2393,9 @@ cleanup: return( ret ); } -#endif /* ECP_SHORTWEIERSTRASS */ +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) /* * For Montgomery curves, we do all the internal arithmetic in projective * coordinates. Import/export of points uses only the x coordinates, which is @@ -2278,7 +2458,10 @@ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) ); if( count++ > 10 ) - return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } } while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 ); @@ -2332,7 +2515,7 @@ static int ecp_double_add_mxz( const mbedtls_ecp_group *grp, MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &D, &Q->X, &Q->Z ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &DA, &D, &A ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &CB, &C, &B ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &S->X, &DA, &CB ) ); MOD_MUL( S->X ); + MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &S->X, &DA, &CB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->X, &S->X, &S->X ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S->Z, &DA, &CB ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->Z, &S->Z, &S->Z ) ); @@ -2364,9 +2547,23 @@ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, unsigned char b; mbedtls_ecp_point RP; mbedtls_mpi PX; +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_context drbg_ctx; + ecp_drbg_init( &drbg_ctx ); +#endif mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX ); +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + if( f_rng == NULL ) + { + const size_t m_len = ( grp->nbits + 7 ) / 8; + MBEDTLS_MPI_CHK( ecp_drbg_seed( &drbg_ctx, m, m_len ) ); + f_rng = &ecp_drbg_random; + p_rng = &drbg_ctx; + } +#endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */ + /* Save PX and read from P before writing to R, in case P == R */ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->X ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) ); @@ -2380,7 +2577,9 @@ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, MOD_ADD( RP.X ); /* Randomize coordinates of the starting point */ +#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != NULL ) +#endif MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) ); /* Loop invariant: R = result so far, RP = R + P */ @@ -2413,18 +2612,24 @@ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, * * Avoid the leak by randomizing coordinates before we normalize them. */ +#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) if( f_rng != NULL ) +#endif MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, R, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) ); cleanup: +#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + ecp_drbg_free( &drbg_ctx ); +#endif + mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX ); return( ret ); } -#endif /* ECP_MONTGOMERY */ +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ /* * Restartable multiplication R = m * P @@ -2447,6 +2652,8 @@ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, /* reset ops count for this call if top-level */ if( rs_ctx != NULL && rs_ctx->depth++ == 0 ) rs_ctx->ops_done = 0; +#else + (void) rs_ctx; #endif #if defined(MBEDTLS_ECP_INTERNAL_ALT) @@ -2468,11 +2675,11 @@ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, } ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA; -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) MBEDTLS_MPI_CHK( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) ); #endif -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) MBEDTLS_MPI_CHK( ecp_mul_comb( grp, R, m, P, f_rng, p_rng, rs_ctx ) ); #endif @@ -2506,7 +2713,7 @@ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, return( mbedtls_ecp_mul_restartable( grp, R, m, P, f_rng, p_rng, NULL ) ); } -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * Check that an affine point is valid as a public key, * short weierstrass curves (SEC1 3.2.3.1) @@ -2554,8 +2761,9 @@ cleanup: return( ret ); } -#endif /* ECP_SHORTWEIERSTRASS */ +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* * R = m * P with shortcuts for m == 1 and m == -1 * NOT constant-time - ONLY for short Weierstrass! @@ -2701,8 +2909,9 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, ECP_VALIDATE_RET( Q != NULL ); return( mbedtls_ecp_muladd_restartable( grp, R, m, P, n, Q, NULL ) ); } +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) /* * Check validity of a public key for Montgomery curves with x-only schemes */ @@ -2716,7 +2925,7 @@ static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_ return( 0 ); } -#endif /* ECP_MONTGOMERY */ +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ /* * Check that a point is valid as a public key @@ -2731,11 +2940,11 @@ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, if( mbedtls_mpi_cmp_int( &pt->Z, 1 ) != 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) return( ecp_check_pubkey_mx( grp, pt ) ); #endif -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) return( ecp_check_pubkey_sw( grp, pt ) ); #endif @@ -2751,7 +2960,7 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, ECP_VALIDATE_RET( grp != NULL ); ECP_VALIDATE_RET( d != NULL ); -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* see RFC 7748 sec. 5 para. 5 */ @@ -2766,8 +2975,8 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, return( 0 ); } -#endif /* ECP_MONTGOMERY */ -#if defined(ECP_SHORTWEIERSTRASS) +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* see SEC1 3.2 */ @@ -2777,7 +2986,7 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, else return( 0 ); } -#endif /* ECP_SHORTWEIERSTRASS */ +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } @@ -2799,7 +3008,7 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, n_size = ( grp->nbits + 7 ) / 8; -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* [M225] page 5 */ @@ -2825,9 +3034,9 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) ); } } -#endif /* ECP_MONTGOMERY */ +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { /* SEC1 3.2.1: Generate d such that 1 <= n < N */ @@ -2856,7 +3065,10 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, * such as secp224k1 are actually very close to the worst case. */ if( ++count > 30 ) - return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); + { + ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; + goto cleanup; + } ret = mbedtls_mpi_lt_mpi_ct( d, &grp->N, &cmp ); if( ret != 0 ) @@ -2866,7 +3078,7 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, } while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || cmp != 1 ); } -#endif /* ECP_SHORTWEIERSTRASS */ +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ cleanup: return( ret ); @@ -2944,7 +3156,7 @@ int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; -#if defined(ECP_MONTGOMERY) +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) { /* @@ -2979,7 +3191,7 @@ int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, } #endif -#if defined(ECP_SHORTWEIERSTRASS) +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) { MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &key->d, buf, buflen ) ); @@ -2996,6 +3208,45 @@ cleanup: return( ret ); } +/* + * Write a private key. + */ +int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key, + unsigned char *buf, size_t buflen ) +{ + int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + + ECP_VALIDATE_RET( key != NULL ); + ECP_VALIDATE_RET( buf != NULL ); + +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) + if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY ) + { + if( key->grp.id == MBEDTLS_ECP_DP_CURVE25519 ) + { + if( buflen < ECP_CURVE25519_KEY_SIZE ) + return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL; + + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &key->d, buf, buflen ) ); + } + else + ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE; + } + +#endif +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) + if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) + { + MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &key->d, buf, buflen ) ); + } + +#endif +cleanup: + + return( ret ); +} + + /* * Check a public-private key pair */ @@ -3042,33 +3293,141 @@ cleanup: #if defined(MBEDTLS_SELF_TEST) +/* Adjust the exponent to be a valid private point for the specified curve. + * This is sometimes necessary because we use a single set of exponents + * for all curves but the validity of values depends on the curve. */ +static int self_test_adjust_exponent( const mbedtls_ecp_group *grp, + mbedtls_mpi *m ) +{ + int ret = 0; + switch( grp->id ) + { + /* If Curve25519 is available, then that's what we use for the + * Montgomery test, so we don't need the adjustment code. */ +#if ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) +#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + case MBEDTLS_ECP_DP_CURVE448: + /* Move highest bit from 254 to N-1. Setting bit N-1 is + * necessary to enforce the highest-bit-set constraint. */ + MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, 254, 0 ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, grp->nbits, 1 ) ); + /* Copy second-highest bit from 253 to N-2. This is not + * necessary but improves the test variety a bit. */ + MBEDTLS_MPI_CHK( + mbedtls_mpi_set_bit( m, grp->nbits - 1, + mbedtls_mpi_get_bit( m, 253 ) ) ); + break; +#endif +#endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */ + default: + /* Non-Montgomery curves and Curve25519 need no adjustment. */ + (void) grp; + (void) m; + goto cleanup; + } +cleanup: + return( ret ); +} + +/* Calculate R = m.P for each m in exponents. Check that the number of + * basic operations doesn't depend on the value of m. */ +static int self_test_point( int verbose, + mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, + mbedtls_mpi *m, + const mbedtls_ecp_point *P, + const char *const *exponents, + size_t n_exponents ) +{ + int ret = 0; + size_t i = 0; + unsigned long add_c_prev, dbl_c_prev, mul_c_prev; + add_count = 0; + dbl_count = 0; + mul_count = 0; + + MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[0] ) ); + MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); + + for( i = 1; i < n_exponents; i++ ) + { + add_c_prev = add_count; + dbl_c_prev = dbl_count; + mul_c_prev = mul_count; + add_count = 0; + dbl_count = 0; + mul_count = 0; + + MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[i] ) ); + MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) ); + + if( add_count != add_c_prev || + dbl_count != dbl_c_prev || + mul_count != mul_c_prev ) + { + ret = 1; + break; + } + } + +cleanup: + if( verbose != 0 ) + { + if( ret != 0 ) + mbedtls_printf( "failed (%u)\n", (unsigned int) i ); + else + mbedtls_printf( "passed\n" ); + } + return( ret ); +} + /* * Checkup routine */ int mbedtls_ecp_self_test( int verbose ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - size_t i; mbedtls_ecp_group grp; mbedtls_ecp_point R, P; mbedtls_mpi m; - unsigned long add_c_prev, dbl_c_prev, mul_c_prev; - /* exponents especially adapted for secp192r1 */ - const char *exponents[] = + +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) + /* Exponents especially adapted for secp192k1, which has the lowest + * order n of all supported curves (secp192r1 is in a slightly larger + * field but the order of its base point is slightly smaller). */ + const char *sw_exponents[] = { "000000000000000000000000000000000000000000000001", /* one */ - "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22830", /* N - 1 */ + "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */ "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */ "400000000000000000000000000000000000000000000000", /* one and zeros */ "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */ "555555555555555555555555555555555555555555555555", /* 101010... */ }; +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) + const char *m_exponents[] = + { + /* Valid private values for Curve25519. In a build with Curve448 + * but not Curve25519, they will be adjusted in + * self_test_adjust_exponent(). */ + "4000000000000000000000000000000000000000000000000000000000000000", + "5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30", + "5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8", + "41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460", + "5555555555555555555555555555555555555555555555555555555555555550", + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8", + }; +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ mbedtls_ecp_group_init( &grp ); mbedtls_ecp_point_init( &R ); mbedtls_ecp_point_init( &P ); mbedtls_mpi_init( &m ); +#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /* Use secp192r1 if available, or any available curve */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) ); @@ -3077,86 +3436,53 @@ int mbedtls_ecp_self_test( int verbose ) #endif if( verbose != 0 ) - mbedtls_printf( " ECP test #1 (constant op_count, base point G): " ); - + mbedtls_printf( " ECP SW test #1 (constant op_count, base point G): " ); /* Do a dummy multiplication first to trigger precomputation */ MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) ); - - add_count = 0; - dbl_count = 0; - mul_count = 0; - MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) ); - - for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ ) - { - add_c_prev = add_count; - dbl_c_prev = dbl_count; - mul_c_prev = mul_count; - add_count = 0; - dbl_count = 0; - mul_count = 0; - - MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) ); - - if( add_count != add_c_prev || - dbl_count != dbl_c_prev || - mul_count != mul_c_prev ) - { - if( verbose != 0 ) - mbedtls_printf( "failed (%u)\n", (unsigned int) i ); - - ret = 1; - goto cleanup; - } - } + ret = self_test_point( verbose, + &grp, &R, &m, &grp.G, + sw_exponents, + sizeof( sw_exponents ) / sizeof( sw_exponents[0] )); + if( ret != 0 ) + goto cleanup; if( verbose != 0 ) - mbedtls_printf( "passed\n" ); - - if( verbose != 0 ) - mbedtls_printf( " ECP test #2 (constant op_count, other point): " ); + mbedtls_printf( " ECP SW test #2 (constant op_count, other point): " ); /* We computed P = 2G last time, use it */ + ret = self_test_point( verbose, + &grp, &R, &m, &P, + sw_exponents, + sizeof( sw_exponents ) / sizeof( sw_exponents[0] )); + if( ret != 0 ) + goto cleanup; - add_count = 0; - dbl_count = 0; - mul_count = 0; - MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) ); - - for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ ) - { - add_c_prev = add_count; - dbl_c_prev = dbl_count; - mul_c_prev = mul_count; - add_count = 0; - dbl_count = 0; - mul_count = 0; - - MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) ); - MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) ); - - if( add_count != add_c_prev || - dbl_count != dbl_c_prev || - mul_count != mul_c_prev ) - { - if( verbose != 0 ) - mbedtls_printf( "failed (%u)\n", (unsigned int) i ); - - ret = 1; - goto cleanup; - } - } + mbedtls_ecp_group_free( &grp ); + mbedtls_ecp_point_free( &R ); +#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ +#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) if( verbose != 0 ) - mbedtls_printf( "passed\n" ); + mbedtls_printf( " ECP Montgomery test (constant op_count): " ); +#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) + MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE25519 ) ); +#elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) + MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE448 ) ); +#else +#error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test" +#endif + ret = self_test_point( verbose, + &grp, &R, &m, &grp.G, + m_exponents, + sizeof( m_exponents ) / sizeof( m_exponents[0] )); + if( ret != 0 ) + goto cleanup; +#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */ cleanup: if( ret < 0 && verbose != 0 ) - mbedtls_printf( "Unexpected error, return code = %08X\n", ret ); + mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret ); mbedtls_ecp_group_free( &grp ); mbedtls_ecp_point_free( &R ); diff --git a/connectivity/mbedtls/source/ecp_curves.c b/connectivity/mbedtls/source/ecp_curves.c index a24a50c031..05df307cbe 100644 --- a/connectivity/mbedtls/source/ecp_curves.c +++ b/connectivity/mbedtls/source/ecp_curves.c @@ -1,7 +1,7 @@ /* * Elliptic curves over GF(p): curve-specific data and functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_ECP_C) @@ -557,6 +551,22 @@ static const mbedtls_mpi_uint brainpoolP512r1_n[] = { }; #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ +#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ + defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) +/* For these curves, we build the group parameters dynamically. */ +#define ECP_LOAD_GROUP +#endif + +#if defined(ECP_LOAD_GROUP) /* * Create an MPI from embedded constants * (assumes len is an exact multiple of sizeof mbedtls_mpi_uint) @@ -607,6 +617,7 @@ static int ecp_group_load( mbedtls_ecp_group *grp, return( 0 ); } +#endif /* ECP_LOAD_GROUP */ #if defined(MBEDTLS_ECP_NIST_OPTIM) /* Forward declarations */ @@ -648,6 +659,7 @@ static int ecp_mod_p224k1( mbedtls_mpi * ); static int ecp_mod_p256k1( mbedtls_mpi * ); #endif +#if defined(ECP_LOAD_GROUP) #define LOAD_GROUP_A( G ) ecp_group_load( grp, \ G ## _p, sizeof( G ## _p ), \ G ## _a, sizeof( G ## _a ), \ @@ -663,6 +675,7 @@ static int ecp_mod_p256k1( mbedtls_mpi * ); G ## _gx, sizeof( G ## _gx ), \ G ## _gy, sizeof( G ## _gy ), \ G ## _n, sizeof( G ## _n ) ) +#endif /* ECP_LOAD_GROUP */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) /* diff --git a/connectivity/mbedtls/source/entropy.c b/connectivity/mbedtls/source/entropy.c index 102f9f1c40..db61f16d84 100644 --- a/connectivity/mbedtls/source/entropy.c +++ b/connectivity/mbedtls/source/entropy.c @@ -1,7 +1,7 @@ /* * Entropy accumulator implementation * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_ENTROPY_C) diff --git a/connectivity/mbedtls/source/entropy_poll.c b/connectivity/mbedtls/source/entropy_poll.c index c9b2c95c60..4bf660e055 100644 --- a/connectivity/mbedtls/source/entropy_poll.c +++ b/connectivity/mbedtls/source/entropy_poll.c @@ -1,7 +1,7 @@ /* * Platform-specific and custom entropy polling functions * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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(__linux__) @@ -24,11 +22,7 @@ #define _GNU_SOURCE #endif -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #include @@ -52,7 +46,7 @@ #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \ - !defined(__HAIKU__) + !defined(__HAIKU__) && !defined(__midipix__) #error "Platform entropy sources only work on Unix and Windows, see MBEDTLS_NO_PLATFORM_ENTROPY in config.h" #endif @@ -95,7 +89,7 @@ int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len * Since there is no wrapper in the libc yet, use the generic syscall wrapper * available in GNU libc and compatible libc's (eg uClibc). */ -#if defined(__linux__) && defined(__GLIBC__) +#if ((defined(__linux__) && defined(__GLIBC__)) || defined(__midipix__)) #include #include #if defined(SYS_getrandom) @@ -113,7 +107,42 @@ static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags ) return( syscall( SYS_getrandom, buf, buflen, flags ) ); } #endif /* SYS_getrandom */ -#endif /* __linux__ */ +#endif /* __linux__ || __midipix__ */ + +/* + * Some BSD systems provide KERN_ARND. + * This is equivalent to reading from /dev/urandom, only it doesn't require an + * open file descriptor, and provides up to 256 bytes per call (basically the + * same as getentropy(), but with a longer history). + * + * Documentation: https://netbsd.gw.com/cgi-bin/man-cgi?sysctl+7 + */ +#if (defined(__FreeBSD__) || defined(__NetBSD__)) && !defined(HAVE_GETRANDOM) +#include +#include +#if defined(KERN_ARND) +#define HAVE_SYSCTL_ARND + +static int sysctl_arnd_wrapper( unsigned char *buf, size_t buflen ) +{ + int name[2]; + size_t len; + + name[0] = CTL_KERN; + name[1] = KERN_ARND; + + while( buflen > 0 ) + { + len = buflen > 256 ? 256 : buflen; + if( sysctl(name, 2, buf, &len, NULL, 0) == -1 ) + return( -1 ); + buflen -= len; + buf += len; + } + return( 0 ); +} +#endif /* KERN_ARND */ +#endif /* __FreeBSD__ || __NetBSD__ */ #include @@ -139,6 +168,15 @@ int mbedtls_platform_entropy_poll( void *data, ((void) ret); #endif /* HAVE_GETRANDOM */ +#if defined(HAVE_SYSCTL_ARND) + ((void) file); + ((void) read_len); + if( sysctl_arnd_wrapper( output, len ) == -1 ) + return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED ); + *olen = len; + return( 0 ); +#else + *olen = 0; file = fopen( "/dev/urandom", "rb" ); @@ -156,6 +194,7 @@ int mbedtls_platform_entropy_poll( void *data, *olen = len; return( 0 ); +#endif /* HAVE_SYSCTL_ARND */ } #endif /* _WIN32 && !EFIX64 && !EFI32 */ #endif /* !MBEDTLS_NO_PLATFORM_ENTROPY */ diff --git a/connectivity/mbedtls/source/error.c b/connectivity/mbedtls/source/error.c index ee9c852b59..cba61e9e7e 100644 --- a/connectivity/mbedtls/source/error.c +++ b/connectivity/mbedtls/source/error.c @@ -1,7 +1,7 @@ /* * Error message information * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_ERROR_STRERROR_DUMMY) #include @@ -52,6 +46,10 @@ #include "mbedtls/aria.h" #endif +#if defined(MBEDTLS_ASN1_PARSE_C) +#include "mbedtls/asn1.h" +#endif + #if defined(MBEDTLS_BASE64_C) #include "mbedtls/base64.h" #endif @@ -213,10 +211,694 @@ #endif +const char * mbedtls_high_level_strerr( int error_code ) +{ + int high_level_error_code; + + if( error_code < 0 ) + error_code = -error_code; + + /* Extract the high-level part from the error code. */ + high_level_error_code = error_code & 0xFF80; + + switch( high_level_error_code ) + { + /* Begin Auto-Generated Code. */ +#if defined(MBEDTLS_CIPHER_C) + case -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE): + return( "CIPHER - The selected feature is not available" ); + case -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA): + return( "CIPHER - Bad input parameters" ); + case -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED): + return( "CIPHER - Failed to allocate memory" ); + case -(MBEDTLS_ERR_CIPHER_INVALID_PADDING): + return( "CIPHER - Input data contains invalid padding and is rejected" ); + case -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED): + return( "CIPHER - Decryption of block requires a full block" ); + case -(MBEDTLS_ERR_CIPHER_AUTH_FAILED): + return( "CIPHER - Authentication failed (for AEAD modes)" ); + case -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT): + return( "CIPHER - The context is invalid. For example, because it was freed" ); + case -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED): + return( "CIPHER - Cipher hardware accelerator failed" ); +#endif /* MBEDTLS_CIPHER_C */ + +#if defined(MBEDTLS_DHM_C) + case -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA): + return( "DHM - Bad input parameters" ); + case -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED): + return( "DHM - Reading of the DHM parameters failed" ); + case -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED): + return( "DHM - Making of the DHM parameters failed" ); + case -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED): + return( "DHM - Reading of the public values failed" ); + case -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED): + return( "DHM - Making of the public value failed" ); + case -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED): + return( "DHM - Calculation of the DHM secret failed" ); + case -(MBEDTLS_ERR_DHM_INVALID_FORMAT): + return( "DHM - The ASN.1 data is not formatted correctly" ); + case -(MBEDTLS_ERR_DHM_ALLOC_FAILED): + return( "DHM - Allocation of memory failed" ); + case -(MBEDTLS_ERR_DHM_FILE_IO_ERROR): + return( "DHM - Read or write of file failed" ); + case -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED): + return( "DHM - DHM hardware accelerator failed" ); + case -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED): + return( "DHM - Setting the modulus and generator failed" ); +#endif /* MBEDTLS_DHM_C */ + +#if defined(MBEDTLS_ECP_C) + case -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA): + return( "ECP - Bad input parameters to function" ); + case -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL): + return( "ECP - The buffer is too small to write to" ); + case -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE): + return( "ECP - The requested feature is not available, for example, the requested curve is not supported" ); + case -(MBEDTLS_ERR_ECP_VERIFY_FAILED): + return( "ECP - The signature is not valid" ); + case -(MBEDTLS_ERR_ECP_ALLOC_FAILED): + return( "ECP - Memory allocation failed" ); + case -(MBEDTLS_ERR_ECP_RANDOM_FAILED): + return( "ECP - Generation of random value, such as ephemeral key, failed" ); + case -(MBEDTLS_ERR_ECP_INVALID_KEY): + return( "ECP - Invalid private or public key" ); + case -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH): + return( "ECP - The buffer contains a valid signature followed by more data" ); + case -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED): + return( "ECP - The ECP hardware accelerator failed" ); + case -(MBEDTLS_ERR_ECP_IN_PROGRESS): + return( "ECP - Operation in progress, call again with the same parameters to continue" ); +#endif /* MBEDTLS_ECP_C */ + +#if defined(MBEDTLS_MD_C) + case -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE): + return( "MD - The selected feature is not available" ); + case -(MBEDTLS_ERR_MD_BAD_INPUT_DATA): + return( "MD - Bad input parameters to function" ); + case -(MBEDTLS_ERR_MD_ALLOC_FAILED): + return( "MD - Failed to allocate memory" ); + case -(MBEDTLS_ERR_MD_FILE_IO_ERROR): + return( "MD - Opening or reading of file failed" ); + case -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED): + return( "MD - MD hardware accelerator failed" ); +#endif /* MBEDTLS_MD_C */ + +#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) + case -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT): + return( "PEM - No PEM header or footer found" ); + case -(MBEDTLS_ERR_PEM_INVALID_DATA): + return( "PEM - PEM string is not as expected" ); + case -(MBEDTLS_ERR_PEM_ALLOC_FAILED): + return( "PEM - Failed to allocate memory" ); + case -(MBEDTLS_ERR_PEM_INVALID_ENC_IV): + return( "PEM - RSA IV is not in hex-format" ); + case -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG): + return( "PEM - Unsupported key encryption algorithm" ); + case -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED): + return( "PEM - Private key password can't be empty" ); + case -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH): + return( "PEM - Given private key password does not allow for correct decryption" ); + case -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE): + return( "PEM - Unavailable feature, e.g. hashing/encryption combination" ); + case -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA): + return( "PEM - Bad input parameters to function" ); +#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ + +#if defined(MBEDTLS_PK_C) + case -(MBEDTLS_ERR_PK_ALLOC_FAILED): + return( "PK - Memory allocation failed" ); + case -(MBEDTLS_ERR_PK_TYPE_MISMATCH): + return( "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); + case -(MBEDTLS_ERR_PK_BAD_INPUT_DATA): + return( "PK - Bad input parameters to function" ); + case -(MBEDTLS_ERR_PK_FILE_IO_ERROR): + return( "PK - Read/write of file failed" ); + case -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION): + return( "PK - Unsupported key version" ); + case -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT): + return( "PK - Invalid key tag or value" ); + case -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG): + return( "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); + case -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED): + return( "PK - Private key password can't be empty" ); + case -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH): + return( "PK - Given private key password does not allow for correct decryption" ); + case -(MBEDTLS_ERR_PK_INVALID_PUBKEY): + return( "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); + case -(MBEDTLS_ERR_PK_INVALID_ALG): + return( "PK - The algorithm tag or value is invalid" ); + case -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE): + return( "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); + case -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE): + return( "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); + case -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH): + return( "PK - The buffer contains a valid signature followed by more data" ); + case -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED): + return( "PK - PK hardware accelerator failed" ); +#endif /* MBEDTLS_PK_C */ + +#if defined(MBEDTLS_PKCS12_C) + case -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA): + return( "PKCS12 - Bad input parameters to function" ); + case -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE): + return( "PKCS12 - Feature not available, e.g. unsupported encryption scheme" ); + case -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT): + return( "PKCS12 - PBE ASN.1 data not as expected" ); + case -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH): + return( "PKCS12 - Given private key password does not allow for correct decryption" ); +#endif /* MBEDTLS_PKCS12_C */ + +#if defined(MBEDTLS_PKCS5_C) + case -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA): + return( "PKCS5 - Bad input parameters to function" ); + case -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT): + return( "PKCS5 - Unexpected ASN.1 data" ); + case -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE): + return( "PKCS5 - Requested encryption or digest alg not available" ); + case -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH): + return( "PKCS5 - Given private key password does not allow for correct decryption" ); +#endif /* MBEDTLS_PKCS5_C */ + +#if defined(MBEDTLS_RSA_C) + case -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA): + return( "RSA - Bad input parameters to function" ); + case -(MBEDTLS_ERR_RSA_INVALID_PADDING): + return( "RSA - Input data contains invalid padding and is rejected" ); + case -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED): + return( "RSA - Something failed during generation of a key" ); + case -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED): + return( "RSA - Key failed to pass the validity check of the library" ); + case -(MBEDTLS_ERR_RSA_PUBLIC_FAILED): + return( "RSA - The public key operation failed" ); + case -(MBEDTLS_ERR_RSA_PRIVATE_FAILED): + return( "RSA - The private key operation failed" ); + case -(MBEDTLS_ERR_RSA_VERIFY_FAILED): + return( "RSA - The PKCS#1 verification failed" ); + case -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE): + return( "RSA - The output buffer for decryption is not large enough" ); + case -(MBEDTLS_ERR_RSA_RNG_FAILED): + return( "RSA - The random generator failed to generate non-zeros" ); + case -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION): + return( "RSA - The implementation does not offer the requested operation, for example, because of security violations or lack of functionality" ); + case -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED): + return( "RSA - RSA hardware accelerator failed" ); +#endif /* MBEDTLS_RSA_C */ + +#if defined(MBEDTLS_SSL_TLS_C) + case -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE): + return( "SSL - The requested feature is not available" ); + case -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA): + return( "SSL - Bad input parameters to function" ); + case -(MBEDTLS_ERR_SSL_INVALID_MAC): + return( "SSL - Verification of the message MAC failed" ); + case -(MBEDTLS_ERR_SSL_INVALID_RECORD): + return( "SSL - An invalid SSL record was received" ); + case -(MBEDTLS_ERR_SSL_CONN_EOF): + return( "SSL - The connection indicated an EOF" ); + case -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER): + return( "SSL - An unknown cipher was received" ); + case -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN): + return( "SSL - The server has no ciphersuites in common with the client" ); + case -(MBEDTLS_ERR_SSL_NO_RNG): + return( "SSL - No RNG was provided to the SSL module" ); + case -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE): + return( "SSL - No client certification received from the client, but required by the authentication mode" ); + case -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE): + return( "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); + case -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED): + return( "SSL - The own certificate is not set, but needed by the server" ); + case -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED): + return( "SSL - The own private key or pre-shared key is not set, but needed" ); + case -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED): + return( "SSL - No CA Chain is set, but required to operate" ); + case -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE): + return( "SSL - An unexpected message was received from our peer" ); + case -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE): + return( "SSL - A fatal alert message was received from our peer" ); + case -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED): + return( "SSL - Verification of our peer failed" ); + case -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY): + return( "SSL - The peer notified us that the connection is going to be closed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO): + return( "SSL - Processing of the ClientHello handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO): + return( "SSL - Processing of the ServerHello handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE): + return( "SSL - Processing of the Certificate handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST): + return( "SSL - Processing of the CertificateRequest handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE): + return( "SSL - Processing of the ServerKeyExchange handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE): + return( "SSL - Processing of the ServerHelloDone handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE): + return( "SSL - Processing of the ClientKeyExchange handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP): + return( "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS): + return( "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY): + return( "SSL - Processing of the CertificateVerify handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC): + return( "SSL - Processing of the ChangeCipherSpec handshake message failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED): + return( "SSL - Processing of the Finished handshake message failed" ); + case -(MBEDTLS_ERR_SSL_ALLOC_FAILED): + return( "SSL - Memory allocation failed" ); + case -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED): + return( "SSL - Hardware acceleration function returned with error" ); + case -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH): + return( "SSL - Hardware acceleration function skipped / left alone data" ); + case -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED): + return( "SSL - Processing of the compression / decompression failed" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION): + return( "SSL - Handshake protocol not within min/max boundaries" ); + case -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET): + return( "SSL - Processing of the NewSessionTicket handshake message failed" ); + case -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED): + return( "SSL - Session ticket has expired" ); + case -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH): + return( "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); + case -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY): + return( "SSL - Unknown identity received (eg, PSK identity)" ); + case -(MBEDTLS_ERR_SSL_INTERNAL_ERROR): + return( "SSL - Internal error (eg, unexpected failure in lower-level module)" ); + case -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING): + return( "SSL - A counter would wrap (eg, too many messages exchanged)" ); + case -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO): + return( "SSL - Unexpected message at ServerHello in renegotiation" ); + case -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED): + return( "SSL - DTLS client must retry for hello verification" ); + case -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL): + return( "SSL - A buffer is too small to receive or write a message" ); + case -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE): + return( "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); + case -(MBEDTLS_ERR_SSL_WANT_READ): + return( "SSL - No data of requested type currently available on underlying transport" ); + case -(MBEDTLS_ERR_SSL_WANT_WRITE): + return( "SSL - Connection requires a write call" ); + case -(MBEDTLS_ERR_SSL_TIMEOUT): + return( "SSL - The operation timed out" ); + case -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT): + return( "SSL - The client initiated a reconnect from the same port" ); + case -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD): + return( "SSL - Record header looks valid but is not expected" ); + case -(MBEDTLS_ERR_SSL_NON_FATAL): + return( "SSL - The alert message received indicates a non-fatal error" ); + case -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH): + return( "SSL - Couldn't set the hash for verifying CertificateVerify" ); + case -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING): + return( "SSL - Internal-only message signaling that further message-processing should be done" ); + case -(MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS): + return( "SSL - The asynchronous operation is not completed yet" ); + case -(MBEDTLS_ERR_SSL_EARLY_MESSAGE): + return( "SSL - Internal-only message signaling that a message arrived early" ); + case -(MBEDTLS_ERR_SSL_UNEXPECTED_CID): + return( "SSL - An encrypted DTLS-frame with an unexpected CID was received" ); + case -(MBEDTLS_ERR_SSL_VERSION_MISMATCH): + return( "SSL - An operation failed due to an unexpected version or configuration" ); + case -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS): + return( "SSL - A cryptographic operation is in progress. Try again later" ); + case -(MBEDTLS_ERR_SSL_BAD_CONFIG): + return( "SSL - Invalid value in SSL config" ); +#endif /* MBEDTLS_SSL_TLS_C */ + +#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) + case -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE): + return( "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); + case -(MBEDTLS_ERR_X509_UNKNOWN_OID): + return( "X509 - Requested OID is unknown" ); + case -(MBEDTLS_ERR_X509_INVALID_FORMAT): + return( "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); + case -(MBEDTLS_ERR_X509_INVALID_VERSION): + return( "X509 - The CRT/CRL/CSR version element is invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_SERIAL): + return( "X509 - The serial tag or value is invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_ALG): + return( "X509 - The algorithm tag or value is invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_NAME): + return( "X509 - The name tag or value is invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_DATE): + return( "X509 - The date tag or value is invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_SIGNATURE): + return( "X509 - The signature tag or value invalid" ); + case -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS): + return( "X509 - The extension tag or value is invalid" ); + case -(MBEDTLS_ERR_X509_UNKNOWN_VERSION): + return( "X509 - CRT/CRL/CSR has an unsupported version number" ); + case -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG): + return( "X509 - Signature algorithm (oid) is unsupported" ); + case -(MBEDTLS_ERR_X509_SIG_MISMATCH): + return( "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); + case -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED): + return( "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); + case -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT): + return( "X509 - Format not recognized as DER or PEM" ); + case -(MBEDTLS_ERR_X509_BAD_INPUT_DATA): + return( "X509 - Input invalid" ); + case -(MBEDTLS_ERR_X509_ALLOC_FAILED): + return( "X509 - Allocation of memory failed" ); + case -(MBEDTLS_ERR_X509_FILE_IO_ERROR): + return( "X509 - Read/write of file failed" ); + case -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL): + return( "X509 - Destination buffer is too small" ); + case -(MBEDTLS_ERR_X509_FATAL_ERROR): + return( "X509 - A fatal error occurred, eg the chain is too long or the vrfy callback failed" ); +#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ + /* End Auto-Generated Code. */ + + default: + break; + } + + return( NULL ); +} + +const char * mbedtls_low_level_strerr( int error_code ) +{ + int low_level_error_code; + + if( error_code < 0 ) + error_code = -error_code; + + /* Extract the low-level part from the error code. */ + low_level_error_code = error_code & ~0xFF80; + + switch( low_level_error_code ) + { + /* Begin Auto-Generated Code. */ +#if defined(MBEDTLS_AES_C) + case -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH): + return( "AES - Invalid key length" ); + case -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH): + return( "AES - Invalid data input length" ); + case -(MBEDTLS_ERR_AES_BAD_INPUT_DATA): + return( "AES - Invalid input data" ); + case -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE): + return( "AES - Feature not available. For example, an unsupported AES key size" ); + case -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED): + return( "AES - AES hardware accelerator failed" ); +#endif /* MBEDTLS_AES_C */ + +#if defined(MBEDTLS_ARC4_C) + case -(MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED): + return( "ARC4 - ARC4 hardware accelerator failed" ); +#endif /* MBEDTLS_ARC4_C */ + +#if defined(MBEDTLS_ARIA_C) + case -(MBEDTLS_ERR_ARIA_BAD_INPUT_DATA): + return( "ARIA - Bad input data" ); + case -(MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH): + return( "ARIA - Invalid data input length" ); + case -(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE): + return( "ARIA - Feature not available. For example, an unsupported ARIA key size" ); + case -(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED): + return( "ARIA - ARIA hardware accelerator failed" ); +#endif /* MBEDTLS_ARIA_C */ + +#if defined(MBEDTLS_ASN1_PARSE_C) + case -(MBEDTLS_ERR_ASN1_OUT_OF_DATA): + return( "ASN1 - Out of data when parsing an ASN1 data structure" ); + case -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG): + return( "ASN1 - ASN1 tag was of an unexpected value" ); + case -(MBEDTLS_ERR_ASN1_INVALID_LENGTH): + return( "ASN1 - Error when trying to determine the length or invalid length" ); + case -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH): + return( "ASN1 - Actual length differs from expected length" ); + case -(MBEDTLS_ERR_ASN1_INVALID_DATA): + return( "ASN1 - Data is invalid" ); + case -(MBEDTLS_ERR_ASN1_ALLOC_FAILED): + return( "ASN1 - Memory allocation failed" ); + case -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL): + return( "ASN1 - Buffer too small when writing ASN.1 data structure" ); +#endif /* MBEDTLS_ASN1_PARSE_C */ + +#if defined(MBEDTLS_BASE64_C) + case -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL): + return( "BASE64 - Output buffer too small" ); + case -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER): + return( "BASE64 - Invalid character in input" ); +#endif /* MBEDTLS_BASE64_C */ + +#if defined(MBEDTLS_BIGNUM_C) + case -(MBEDTLS_ERR_MPI_FILE_IO_ERROR): + return( "BIGNUM - An error occurred while reading from or writing to a file" ); + case -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA): + return( "BIGNUM - Bad input parameters to function" ); + case -(MBEDTLS_ERR_MPI_INVALID_CHARACTER): + return( "BIGNUM - There is an invalid character in the digit string" ); + case -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL): + return( "BIGNUM - The buffer is too small to write to" ); + case -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE): + return( "BIGNUM - The input arguments are negative or result in illegal output" ); + case -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO): + return( "BIGNUM - The input argument for division is zero, which is not allowed" ); + case -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE): + return( "BIGNUM - The input arguments are not acceptable" ); + case -(MBEDTLS_ERR_MPI_ALLOC_FAILED): + return( "BIGNUM - Memory allocation failed" ); +#endif /* MBEDTLS_BIGNUM_C */ + +#if defined(MBEDTLS_BLOWFISH_C) + case -(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA): + return( "BLOWFISH - Bad input data" ); + case -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH): + return( "BLOWFISH - Invalid data input length" ); + case -(MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED): + return( "BLOWFISH - Blowfish hardware accelerator failed" ); +#endif /* MBEDTLS_BLOWFISH_C */ + +#if defined(MBEDTLS_CAMELLIA_C) + case -(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA): + return( "CAMELLIA - Bad input data" ); + case -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH): + return( "CAMELLIA - Invalid data input length" ); + case -(MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED): + return( "CAMELLIA - Camellia hardware accelerator failed" ); +#endif /* MBEDTLS_CAMELLIA_C */ + +#if defined(MBEDTLS_CCM_C) + case -(MBEDTLS_ERR_CCM_BAD_INPUT): + return( "CCM - Bad input parameters to the function" ); + case -(MBEDTLS_ERR_CCM_AUTH_FAILED): + return( "CCM - Authenticated decryption failed" ); + case -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED): + return( "CCM - CCM hardware accelerator failed" ); +#endif /* MBEDTLS_CCM_C */ + +#if defined(MBEDTLS_CHACHA20_C) + case -(MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA): + return( "CHACHA20 - Invalid input parameter(s)" ); + case -(MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE): + return( "CHACHA20 - Feature not available. For example, s part of the API is not implemented" ); + case -(MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED): + return( "CHACHA20 - Chacha20 hardware accelerator failed" ); +#endif /* MBEDTLS_CHACHA20_C */ + +#if defined(MBEDTLS_CHACHAPOLY_C) + case -(MBEDTLS_ERR_CHACHAPOLY_BAD_STATE): + return( "CHACHAPOLY - The requested operation is not permitted in the current state" ); + case -(MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED): + return( "CHACHAPOLY - Authenticated decryption failed: data was not authentic" ); +#endif /* MBEDTLS_CHACHAPOLY_C */ + +#if defined(MBEDTLS_CMAC_C) + case -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED): + return( "CMAC - CMAC hardware accelerator failed" ); +#endif /* MBEDTLS_CMAC_C */ + +#if defined(MBEDTLS_CTR_DRBG_C) + case -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED): + return( "CTR_DRBG - The entropy source failed" ); + case -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG): + return( "CTR_DRBG - The requested random buffer length is too big" ); + case -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG): + return( "CTR_DRBG - The input (entropy + additional data) is too large" ); + case -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR): + return( "CTR_DRBG - Read or write error in file" ); +#endif /* MBEDTLS_CTR_DRBG_C */ + +#if defined(MBEDTLS_DES_C) + case -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH): + return( "DES - The data input has an invalid length" ); + case -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED): + return( "DES - DES hardware accelerator failed" ); +#endif /* MBEDTLS_DES_C */ + +#if defined(MBEDTLS_ENTROPY_C) + case -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED): + return( "ENTROPY - Critical entropy source failure" ); + case -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES): + return( "ENTROPY - No more sources can be added" ); + case -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED): + return( "ENTROPY - No sources have been added to poll" ); + case -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE): + return( "ENTROPY - No strong sources have been added to poll" ); + case -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR): + return( "ENTROPY - Read/write error in file" ); +#endif /* MBEDTLS_ENTROPY_C */ + +#if defined(MBEDTLS_ERROR_C) + case -(MBEDTLS_ERR_ERROR_GENERIC_ERROR): + return( "ERROR - Generic error" ); + case -(MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED): + return( "ERROR - This is a bug in the library" ); +#endif /* MBEDTLS_ERROR_C */ + +#if defined(MBEDTLS_GCM_C) + case -(MBEDTLS_ERR_GCM_AUTH_FAILED): + return( "GCM - Authenticated decryption failed" ); + case -(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED): + return( "GCM - GCM hardware accelerator failed" ); + case -(MBEDTLS_ERR_GCM_BAD_INPUT): + return( "GCM - Bad input parameters to function" ); +#endif /* MBEDTLS_GCM_C */ + +#if defined(MBEDTLS_HKDF_C) + case -(MBEDTLS_ERR_HKDF_BAD_INPUT_DATA): + return( "HKDF - Bad input parameters to function" ); +#endif /* MBEDTLS_HKDF_C */ + +#if defined(MBEDTLS_HMAC_DRBG_C) + case -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG): + return( "HMAC_DRBG - Too many random requested in single call" ); + case -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG): + return( "HMAC_DRBG - Input too large (Entropy + additional)" ); + case -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR): + return( "HMAC_DRBG - Read/write error in file" ); + case -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED): + return( "HMAC_DRBG - The entropy source failed" ); +#endif /* MBEDTLS_HMAC_DRBG_C */ + +#if defined(MBEDTLS_MD2_C) + case -(MBEDTLS_ERR_MD2_HW_ACCEL_FAILED): + return( "MD2 - MD2 hardware accelerator failed" ); +#endif /* MBEDTLS_MD2_C */ + +#if defined(MBEDTLS_MD4_C) + case -(MBEDTLS_ERR_MD4_HW_ACCEL_FAILED): + return( "MD4 - MD4 hardware accelerator failed" ); +#endif /* MBEDTLS_MD4_C */ + +#if defined(MBEDTLS_MD5_C) + case -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED): + return( "MD5 - MD5 hardware accelerator failed" ); +#endif /* MBEDTLS_MD5_C */ + +#if defined(MBEDTLS_NET_C) + case -(MBEDTLS_ERR_NET_SOCKET_FAILED): + return( "NET - Failed to open a socket" ); + case -(MBEDTLS_ERR_NET_CONNECT_FAILED): + return( "NET - The connection to the given server / port failed" ); + case -(MBEDTLS_ERR_NET_BIND_FAILED): + return( "NET - Binding of the socket failed" ); + case -(MBEDTLS_ERR_NET_LISTEN_FAILED): + return( "NET - Could not listen on the socket" ); + case -(MBEDTLS_ERR_NET_ACCEPT_FAILED): + return( "NET - Could not accept the incoming connection" ); + case -(MBEDTLS_ERR_NET_RECV_FAILED): + return( "NET - Reading information from the socket failed" ); + case -(MBEDTLS_ERR_NET_SEND_FAILED): + return( "NET - Sending information through the socket failed" ); + case -(MBEDTLS_ERR_NET_CONN_RESET): + return( "NET - Connection was reset by peer" ); + case -(MBEDTLS_ERR_NET_UNKNOWN_HOST): + return( "NET - Failed to get an IP address for the given hostname" ); + case -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL): + return( "NET - Buffer is too small to hold the data" ); + case -(MBEDTLS_ERR_NET_INVALID_CONTEXT): + return( "NET - The context is invalid, eg because it was free()ed" ); + case -(MBEDTLS_ERR_NET_POLL_FAILED): + return( "NET - Polling the net context failed" ); + case -(MBEDTLS_ERR_NET_BAD_INPUT_DATA): + return( "NET - Input invalid" ); +#endif /* MBEDTLS_NET_C */ + +#if defined(MBEDTLS_OID_C) + case -(MBEDTLS_ERR_OID_NOT_FOUND): + return( "OID - OID is not found" ); + case -(MBEDTLS_ERR_OID_BUF_TOO_SMALL): + return( "OID - output buffer is too small" ); +#endif /* MBEDTLS_OID_C */ + +#if defined(MBEDTLS_PADLOCK_C) + case -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED): + return( "PADLOCK - Input data should be aligned" ); +#endif /* MBEDTLS_PADLOCK_C */ + +#if defined(MBEDTLS_PLATFORM_C) + case -(MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED): + return( "PLATFORM - Hardware accelerator failed" ); + case -(MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED): + return( "PLATFORM - The requested feature is not supported by the platform" ); +#endif /* MBEDTLS_PLATFORM_C */ + +#if defined(MBEDTLS_POLY1305_C) + case -(MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA): + return( "POLY1305 - Invalid input parameter(s)" ); + case -(MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE): + return( "POLY1305 - Feature not available. For example, s part of the API is not implemented" ); + case -(MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED): + return( "POLY1305 - Poly1305 hardware accelerator failed" ); +#endif /* MBEDTLS_POLY1305_C */ + +#if defined(MBEDTLS_RIPEMD160_C) + case -(MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED): + return( "RIPEMD160 - RIPEMD160 hardware accelerator failed" ); +#endif /* MBEDTLS_RIPEMD160_C */ + +#if defined(MBEDTLS_SHA1_C) + case -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED): + return( "SHA1 - SHA-1 hardware accelerator failed" ); + case -(MBEDTLS_ERR_SHA1_BAD_INPUT_DATA): + return( "SHA1 - SHA-1 input data was malformed" ); +#endif /* MBEDTLS_SHA1_C */ + +#if defined(MBEDTLS_SHA256_C) + case -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED): + return( "SHA256 - SHA-256 hardware accelerator failed" ); + case -(MBEDTLS_ERR_SHA256_BAD_INPUT_DATA): + return( "SHA256 - SHA-256 input data was malformed" ); +#endif /* MBEDTLS_SHA256_C */ + +#if defined(MBEDTLS_SHA512_C) + case -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED): + return( "SHA512 - SHA-512 hardware accelerator failed" ); + case -(MBEDTLS_ERR_SHA512_BAD_INPUT_DATA): + return( "SHA512 - SHA-512 input data was malformed" ); +#endif /* MBEDTLS_SHA512_C */ + +#if defined(MBEDTLS_THREADING_C) + case -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE): + return( "THREADING - The selected feature is not available" ); + case -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA): + return( "THREADING - Bad input parameters to function" ); + case -(MBEDTLS_ERR_THREADING_MUTEX_ERROR): + return( "THREADING - Locking / unlocking / free failed with error code" ); +#endif /* MBEDTLS_THREADING_C */ + +#if defined(MBEDTLS_XTEA_C) + case -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH): + return( "XTEA - The data input has an invalid length" ); + case -(MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED): + return( "XTEA - XTEA hardware accelerator failed" ); +#endif /* MBEDTLS_XTEA_C */ + /* End Auto-Generated Code. */ + + default: + break; + } + + return( NULL ); +} + void mbedtls_strerror( int ret, char *buf, size_t buflen ) { size_t len; int use_ret; + const char * high_level_error_description = NULL; + const char * low_level_error_description = NULL; if( buflen == 0 ) return; @@ -230,356 +912,20 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) { use_ret = ret & 0xFF80; - // High level error codes - // - // BEGIN generated code -#if defined(MBEDTLS_CIPHER_C) - if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) ) - mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid. For example, because it was freed" ); - if( use_ret == -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "CIPHER - Cipher hardware accelerator failed" ); -#endif /* MBEDTLS_CIPHER_C */ + // Translate high level error code. + high_level_error_description = mbedtls_high_level_strerr( ret ); -#if defined(MBEDTLS_DHM_C) - if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters" ); - if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) ) - mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" ); - if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "DHM - Read or write of file failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - DHM hardware accelerator failed" ); - if( use_ret == -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED) ) - mbedtls_snprintf( buf, buflen, "DHM - Setting the modulus and generator failed" ); -#endif /* MBEDTLS_DHM_C */ - -#if defined(MBEDTLS_ECP_C) - if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" ); - if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "ECP - The requested feature is not available, for example, the requested curve is not supported" ); - if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) ) - mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" ); - if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" ); - if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) ) - mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as ephemeral key, failed" ); - if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) ) - mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" ); - if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) ) - 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) - if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" ); - if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" ); - if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" ); - if( use_ret == -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "MD - MD hardware accelerator failed" ); -#endif /* MBEDTLS_MD_C */ - -#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) - if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) ) - mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" ); - if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) ) - mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" ); - if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" ); - if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) ) - mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" ); - if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) ) - mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" ); - if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" ); - if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" ); - if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" ); - if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" ); -#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ - -#if defined(MBEDTLS_PK_C) - if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" ); - if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" ); - if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" ); - if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) ) - mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" ); - if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) ) - mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" ); - if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) ) - mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" ); - if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" ); - if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" ); - if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) ) - mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" ); - if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) ) - mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) ) - mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" ); - if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" ); - if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PK - The buffer contains a valid signature followed by more data" ); - if( use_ret == -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "PK - PK hardware accelerator failed" ); -#endif /* MBEDTLS_PK_C */ - -#if defined(MBEDTLS_PKCS12_C) - if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" ); - if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) ) - mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" ); - if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" ); -#endif /* MBEDTLS_PKCS12_C */ - -#if defined(MBEDTLS_PKCS5_C) - if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) ) - mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" ); - if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" ); - if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" ); -#endif /* MBEDTLS_PKCS5_C */ - -#if defined(MBEDTLS_RSA_C) - if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) ) - mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" ); - if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" ); - if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the validity check of the library" ); - if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" ); - if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" ); - if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" ); - if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) ) - mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" ); - if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" ); - if( use_ret == -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION) ) - mbedtls_snprintf( buf, buflen, "RSA - The implementation does not offer the requested operation, for example, because of security violations or lack of functionality" ); - if( use_ret == -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "RSA - RSA hardware accelerator failed" ); -#endif /* MBEDTLS_RSA_C */ + if( high_level_error_description == NULL ) + mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret ); + else + mbedtls_snprintf( buf, buflen, "%s", high_level_error_description ); #if defined(MBEDTLS_SSL_TLS_C) - if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) ) - mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) ) - mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) ) - mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" ); - if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) ) - mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" ); - if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) ) - mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" ); - if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) ) - mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" ); - if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) ) - mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) ) - mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" ); - if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" ); - if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) ) - mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" ); - if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) ) - { - mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" ); + // Early return in case of a fatal error - do not try to translate low + // level code. + if(use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE)) return; - } - if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) ) - mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) ) - mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" ); - if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) ) - mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" ); - if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) ) - mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) ) - mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" ); - if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) ) - mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" ); - if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" ); - if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) ) - mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" ); - if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) ) - mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" ); - if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) ) - mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" ); - if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) ) - mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" ); - if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) ) - mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" ); - if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" ); - if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) ) - mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" ); - if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) ) - mbedtls_snprintf( buf, buflen, "SSL - No data of requested type currently available on underlying transport" ); - if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) ) - mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" ); - if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) ) - mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) ) - mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" ); - if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) ) - mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" ); - if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) ) - mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" ); - if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) ) - mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" ); - if( use_ret == -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING) ) - mbedtls_snprintf( buf, buflen, "SSL - Internal-only message signaling that further message-processing should be done" ); - if( use_ret == -(MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) ) - 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_UNEXPECTED_CID) ) - mbedtls_snprintf( buf, buflen, "SSL - An encrypted DTLS-frame with an unexpected CID was received" ); - if( use_ret == -(MBEDTLS_ERR_SSL_VERSION_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "SSL - An operation failed due to an unexpected version or configuration" ); - 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) - if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" ); - if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) ) - mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) ) - mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) ) - mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) ) - mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) ) - mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) ) - mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) ) - mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) ) - mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) ) - mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) ) - mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" ); - if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) ) - mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" ); - if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" ); - if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) ) - mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" ); - if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) ) - mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" ); - if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "X509 - Input invalid" ); - if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" ); - if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" ); - if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" ); - if( use_ret == -(MBEDTLS_ERR_X509_FATAL_ERROR) ) - mbedtls_snprintf( buf, buflen, "X509 - A fatal error occurred, eg the chain is too long or the vrfy callback failed" ); -#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ - // END generated code - - if( strlen( buf ) == 0 ) - mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); } use_ret = ret & ~0xFF80; @@ -603,311 +949,13 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen ) buflen -= len + 3; } - // Low level error codes - // - // BEGIN generated code -#if defined(MBEDTLS_AES_C) - if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) ) - mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); - if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); - if( use_ret == -(MBEDTLS_ERR_AES_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "AES - Invalid input data" ); - if( use_ret == -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "AES - Feature not available. For example, an unsupported AES key size" ); - if( use_ret == -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "AES - AES hardware accelerator failed" ); -#endif /* MBEDTLS_AES_C */ + // Translate low level error code. + low_level_error_description = mbedtls_low_level_strerr( ret ); -#if defined(MBEDTLS_ARC4_C) - if( use_ret == -(MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "ARC4 - ARC4 hardware accelerator failed" ); -#endif /* MBEDTLS_ARC4_C */ - -#if defined(MBEDTLS_ARIA_C) - if( use_ret == -(MBEDTLS_ERR_ARIA_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "ARIA - Bad input data" ); - if( use_ret == -(MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "ARIA - Invalid data input length" ); - if( use_ret == -(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "ARIA - Feature not available. For example, an unsupported ARIA key size" ); - if( use_ret == -(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "ARIA - ARIA hardware accelerator failed" ); -#endif /* MBEDTLS_ARIA_C */ - -#if defined(MBEDTLS_ASN1_PARSE_C) - if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) ) - mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" ); - if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" ); -#endif /* MBEDTLS_ASN1_PARSE_C */ - -#if defined(MBEDTLS_BASE64_C) - if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" ); - if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) ) - mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" ); -#endif /* MBEDTLS_BASE64_C */ - -#if defined(MBEDTLS_BIGNUM_C) - if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" ); - if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" ); - if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" ); - if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" ); - if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" ); - if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" ); - if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) ) - mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" ); -#endif /* MBEDTLS_BIGNUM_C */ - -#if defined(MBEDTLS_BLOWFISH_C) - if( use_ret == -(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "BLOWFISH - Bad input data" ); - if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" ); - if( use_ret == -(MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "BLOWFISH - Blowfish hardware accelerator failed" ); -#endif /* MBEDTLS_BLOWFISH_C */ - -#if defined(MBEDTLS_CAMELLIA_C) - if( use_ret == -(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "CAMELLIA - Bad input data" ); - if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" ); - if( use_ret == -(MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "CAMELLIA - Camellia hardware accelerator failed" ); -#endif /* MBEDTLS_CAMELLIA_C */ - -#if defined(MBEDTLS_CCM_C) - if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) ) - mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to the function" ); - if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) ) - mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" ); - if( use_ret == -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "CCM - CCM hardware accelerator failed" ); -#endif /* MBEDTLS_CCM_C */ - -#if defined(MBEDTLS_CHACHA20_C) - if( use_ret == -(MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "CHACHA20 - Invalid input parameter(s)" ); - if( use_ret == -(MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "CHACHA20 - Feature not available. For example, s part of the API is not implemented" ); - if( use_ret == -(MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "CHACHA20 - Chacha20 hardware accelerator failed" ); -#endif /* MBEDTLS_CHACHA20_C */ - -#if defined(MBEDTLS_CHACHAPOLY_C) - if( use_ret == -(MBEDTLS_ERR_CHACHAPOLY_BAD_STATE) ) - mbedtls_snprintf( buf, buflen, "CHACHAPOLY - The requested operation is not permitted in the current state" ); - if( use_ret == -(MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED) ) - mbedtls_snprintf( buf, buflen, "CHACHAPOLY - Authenticated decryption failed: data was not authentic" ); -#endif /* MBEDTLS_CHACHAPOLY_C */ - -#if defined(MBEDTLS_CMAC_C) - if( use_ret == -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "CMAC - CMAC hardware accelerator failed" ); -#endif /* MBEDTLS_CMAC_C */ - -#if defined(MBEDTLS_CTR_DRBG_C) - if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) ) - mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" ); - if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) ) - mbedtls_snprintf( buf, buflen, "CTR_DRBG - The requested random buffer length is too big" ); - if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) ) - mbedtls_snprintf( buf, buflen, "CTR_DRBG - The input (entropy + additional data) is too large" ); - if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read or write error in file" ); -#endif /* MBEDTLS_CTR_DRBG_C */ - -#if defined(MBEDTLS_DES_C) - if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" ); - if( use_ret == -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "DES - DES hardware accelerator failed" ); -#endif /* MBEDTLS_DES_C */ - -#if defined(MBEDTLS_ENTROPY_C) - if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) ) - mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" ); - if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) ) - mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" ); - if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) ) - mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" ); - if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) ) - mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" ); - if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" ); -#endif /* MBEDTLS_ENTROPY_C */ - -#if defined(MBEDTLS_ERROR_C) - if( use_ret == -(MBEDTLS_ERR_ERROR_GENERIC_ERROR) ) - mbedtls_snprintf( buf, buflen, "ERROR - Generic error" ); - if( use_ret == -(MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED) ) - mbedtls_snprintf( buf, buflen, "ERROR - This is a bug in the library" ); -#endif /* MBEDTLS_ERROR_C */ - -#if defined(MBEDTLS_GCM_C) - if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) ) - mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" ); - if( use_ret == -(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "GCM - GCM hardware accelerator failed" ); - if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) ) - mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" ); -#endif /* MBEDTLS_GCM_C */ - -#if defined(MBEDTLS_HKDF_C) - if( use_ret == -(MBEDTLS_ERR_HKDF_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "HKDF - Bad input parameters to function" ); -#endif /* MBEDTLS_HKDF_C */ - -#if defined(MBEDTLS_HMAC_DRBG_C) - if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) ) - mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" ); - if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) ) - mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" ); - if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) ) - mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" ); - if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) ) - mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" ); -#endif /* MBEDTLS_HMAC_DRBG_C */ - -#if defined(MBEDTLS_MD2_C) - if( use_ret == -(MBEDTLS_ERR_MD2_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "MD2 - MD2 hardware accelerator failed" ); -#endif /* MBEDTLS_MD2_C */ - -#if defined(MBEDTLS_MD4_C) - if( use_ret == -(MBEDTLS_ERR_MD4_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "MD4 - MD4 hardware accelerator failed" ); -#endif /* MBEDTLS_MD4_C */ - -#if defined(MBEDTLS_MD5_C) - if( use_ret == -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "MD5 - MD5 hardware accelerator failed" ); -#endif /* MBEDTLS_MD5_C */ - -#if defined(MBEDTLS_NET_C) - if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" ); - if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" ); - if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" ); - if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" ); - if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" ); - if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" ); - if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" ); - if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) ) - mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" ); - if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) ) - mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" ); - if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" ); - if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) ) - mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" ); - if( use_ret == -(MBEDTLS_ERR_NET_POLL_FAILED) ) - mbedtls_snprintf( buf, buflen, "NET - Polling the net context failed" ); - if( use_ret == -(MBEDTLS_ERR_NET_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "NET - Input invalid" ); -#endif /* MBEDTLS_NET_C */ - -#if defined(MBEDTLS_OID_C) - if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) ) - mbedtls_snprintf( buf, buflen, "OID - OID is not found" ); - if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) ) - mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" ); -#endif /* MBEDTLS_OID_C */ - -#if defined(MBEDTLS_PADLOCK_C) - if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) ) - 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)" ); - if( use_ret == -(MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "POLY1305 - Feature not available. For example, s part of the API is not implemented" ); - if( use_ret == -(MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "POLY1305 - Poly1305 hardware accelerator failed" ); -#endif /* MBEDTLS_POLY1305_C */ - -#if defined(MBEDTLS_RIPEMD160_C) - if( use_ret == -(MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "RIPEMD160 - RIPEMD160 hardware accelerator failed" ); -#endif /* MBEDTLS_RIPEMD160_C */ - -#if defined(MBEDTLS_SHA1_C) - if( use_ret == -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "SHA1 - SHA-1 hardware accelerator failed" ); - if( use_ret == -(MBEDTLS_ERR_SHA1_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "SHA1 - SHA-1 input data was malformed" ); -#endif /* MBEDTLS_SHA1_C */ - -#if defined(MBEDTLS_SHA256_C) - if( use_ret == -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "SHA256 - SHA-256 hardware accelerator failed" ); - if( use_ret == -(MBEDTLS_ERR_SHA256_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "SHA256 - SHA-256 input data was malformed" ); -#endif /* MBEDTLS_SHA256_C */ - -#if defined(MBEDTLS_SHA512_C) - if( use_ret == -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "SHA512 - SHA-512 hardware accelerator failed" ); - if( use_ret == -(MBEDTLS_ERR_SHA512_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "SHA512 - SHA-512 input data was malformed" ); -#endif /* MBEDTLS_SHA512_C */ - -#if defined(MBEDTLS_THREADING_C) - if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) ) - mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" ); - if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) ) - mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" ); - if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) ) - mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" ); -#endif /* MBEDTLS_THREADING_C */ - -#if defined(MBEDTLS_XTEA_C) - if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) ) - mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" ); - if( use_ret == -(MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED) ) - mbedtls_snprintf( buf, buflen, "XTEA - XTEA hardware accelerator failed" ); -#endif /* MBEDTLS_XTEA_C */ - // END generated code - - if( strlen( buf ) != 0 ) - return; - - mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret ); + if( low_level_error_description == NULL ) + mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret ); + else + mbedtls_snprintf( buf, buflen, "%s", low_level_error_description ); } #else /* MBEDTLS_ERROR_C */ diff --git a/connectivity/mbedtls/source/gcm.c b/connectivity/mbedtls/source/gcm.c index e34f1dae40..2363e584e9 100644 --- a/connectivity/mbedtls/source/gcm.c +++ b/connectivity/mbedtls/source/gcm.c @@ -1,7 +1,7 @@ /* * NIST SP800-38D compliant GCM implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -29,11 +27,7 @@ * [MGV] 4.1, pp. 12-13, to enhance speed without using too much memory. */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_GCM_C) diff --git a/connectivity/mbedtls/source/havege.c b/connectivity/mbedtls/source/havege.c index ca7dd17fbb..2a360a150c 100644 --- a/connectivity/mbedtls/source/havege.c +++ b/connectivity/mbedtls/source/havege.c @@ -1,7 +1,7 @@ /** * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The HAVEGE RNG was designed by Andre Seznec in 2002. @@ -26,11 +24,7 @@ * Contact: seznec(at)irisa_dot_fr - orocheco(at)irisa_dot_fr */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_HAVEGE_C) diff --git a/connectivity/mbedtls/source/hkdf.c b/connectivity/mbedtls/source/hkdf.c index 82df597a4c..5013729d2a 100644 --- a/connectivity/mbedtls/source/hkdf.c +++ b/connectivity/mbedtls/source/hkdf.c @@ -1,7 +1,7 @@ /* * HKDF implementation -- RFC 5869 * - * Copyright (C) 2016-2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,14 +15,8 @@ * 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 +#include "common.h" #if defined(MBEDTLS_HKDF_C) diff --git a/connectivity/mbedtls/source/hmac_drbg.c b/connectivity/mbedtls/source/hmac_drbg.c index f811885c9f..aa3e251040 100644 --- a/connectivity/mbedtls/source/hmac_drbg.c +++ b/connectivity/mbedtls/source/hmac_drbg.c @@ -1,7 +1,7 @@ /* * HMAC_DRBG implementation (NIST SP 800-90) * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -25,11 +23,7 @@ * References below are based on rev. 1 (January 2012). */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_HMAC_DRBG_C) diff --git a/connectivity/mbedtls/source/md.c b/connectivity/mbedtls/source/md.c index b56c2ddfe1..de77b164b5 100644 --- a/connectivity/mbedtls/source/md.c +++ b/connectivity/mbedtls/source/md.c @@ -5,7 +5,7 @@ * * \author Adriaan de Jong * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,15 +19,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_MD_C) @@ -417,6 +411,10 @@ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_inf if( md_info == NULL || ctx == NULL ) return( MBEDTLS_ERR_MD_BAD_INPUT_DATA ); + ctx->md_info = md_info; + ctx->md_ctx = NULL; + ctx->hmac_ctx = NULL; + switch( md_info->type ) { #if defined(MBEDTLS_MD2_C) @@ -472,8 +470,6 @@ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_inf } } - ctx->md_info = md_info; - return( 0 ); } #undef ALLOC @@ -553,14 +549,12 @@ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, si #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: - return( mbedtls_sha256_update_ret( ctx->md_ctx, input, ilen ) ); case MBEDTLS_MD_SHA256: return( mbedtls_sha256_update_ret( ctx->md_ctx, input, ilen ) ); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) case MBEDTLS_MD_SHA384: - return( mbedtls_sha512_update_ret( ctx->md_ctx, input, ilen ) ); #endif case MBEDTLS_MD_SHA512: return( mbedtls_sha512_update_ret( ctx->md_ctx, input, ilen ) ); @@ -599,14 +593,12 @@ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ) #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: - return( mbedtls_sha256_finish_ret( ctx->md_ctx, output ) ); case MBEDTLS_MD_SHA256: return( mbedtls_sha256_finish_ret( ctx->md_ctx, output ) ); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) case MBEDTLS_MD_SHA384: - return( mbedtls_sha512_finish_ret( ctx->md_ctx, output ) ); #endif case MBEDTLS_MD_SHA512: return( mbedtls_sha512_finish_ret( ctx->md_ctx, output ) ); @@ -856,14 +848,12 @@ int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data ) #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: - return( mbedtls_internal_sha256_process( ctx->md_ctx, data ) ); case MBEDTLS_MD_SHA256: return( mbedtls_internal_sha256_process( ctx->md_ctx, data ) ); #endif #if defined(MBEDTLS_SHA512_C) #if !defined(MBEDTLS_SHA512_NO_SHA384) case MBEDTLS_MD_SHA384: - return( mbedtls_internal_sha512_process( ctx->md_ctx, data ) ); #endif case MBEDTLS_MD_SHA512: return( mbedtls_internal_sha512_process( ctx->md_ctx, data ) ); diff --git a/connectivity/mbedtls/source/md2.c b/connectivity/mbedtls/source/md2.c index 82aed8e73c..5ebf07232a 100644 --- a/connectivity/mbedtls/source/md2.c +++ b/connectivity/mbedtls/source/md2.c @@ -1,7 +1,7 @@ /* * RFC 1115/1319 compliant MD2 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The MD2 algorithm was designed by Ron Rivest in 1989. @@ -25,11 +23,7 @@ * http://www.ietf.org/rfc/rfc1319.txt */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_MD2_C) diff --git a/connectivity/mbedtls/source/md4.c b/connectivity/mbedtls/source/md4.c index 6a658e31d4..ac9507454b 100644 --- a/connectivity/mbedtls/source/md4.c +++ b/connectivity/mbedtls/source/md4.c @@ -1,7 +1,7 @@ /* * RFC 1186/1320 compliant MD4 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The MD4 algorithm was designed by Ron Rivest in 1990. @@ -25,11 +23,7 @@ * http://www.ietf.org/rfc/rfc1320.txt */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_MD4_C) diff --git a/connectivity/mbedtls/source/md5.c b/connectivity/mbedtls/source/md5.c index 2306855f46..8cea902aea 100644 --- a/connectivity/mbedtls/source/md5.c +++ b/connectivity/mbedtls/source/md5.c @@ -1,7 +1,7 @@ /* * RFC 1321 compliant MD5 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The MD5 algorithm was designed by Ron Rivest in 1991. @@ -24,11 +22,7 @@ * http://www.ietf.org/rfc/rfc1321.txt */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_MD5_C) diff --git a/connectivity/mbedtls/source/memory_buffer_alloc.c b/connectivity/mbedtls/source/memory_buffer_alloc.c index 51ea7c41d7..0d5d27d3de 100644 --- a/connectivity/mbedtls/source/memory_buffer_alloc.c +++ b/connectivity/mbedtls/source/memory_buffer_alloc.c @@ -1,7 +1,7 @@ /* * Buffer-based memory allocator * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #include "mbedtls/memory_buffer_alloc.h" diff --git a/connectivity/mbedtls/source/net_sockets.c b/connectivity/mbedtls/source/net_sockets.c index dbde510db8..3f96cabe46 100644 --- a/connectivity/mbedtls/source/net_sockets.c +++ b/connectivity/mbedtls/source/net_sockets.c @@ -1,7 +1,7 @@ /* * TCP/IP or UDP/IP networking functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,26 +15,21 @@ * 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) */ /* Enable definition of getaddrinfo() even when compiling with -std=c99. Must * be set before config.h, which pulls in glibc's features.h indirectly. * Harmless on other platforms. */ #define _POSIX_C_SOURCE 200112L +#define _XOPEN_SOURCE 600 /* sockaddr_storage */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_NET_C) #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \ - !defined(__HAIKU__) + !defined(__HAIKU__) && !defined(__midipix__) #error "This module only works on Unix and Windows, see MBEDTLS_NET_C in config.h" #endif @@ -54,8 +49,7 @@ #define IS_EINTR( ret ) ( ( ret ) == WSAEINTR ) -#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0501) -#undef _WIN32_WINNT +#if !defined(_WIN32_WINNT) /* Enables getaddrinfo() & Co */ #define _WIN32_WINNT 0x0501 #endif @@ -64,6 +58,9 @@ #include #include +#if (_WIN32_WINNT < 0x0501) +#include +#endif #if defined(_MSC_VER) #if defined(_WIN32_WCE) @@ -320,7 +317,8 @@ int mbedtls_net_accept( mbedtls_net_context *bind_ctx, struct sockaddr_storage client_addr; #if defined(__socklen_t_defined) || defined(_SOCKLEN_T) || \ - defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) + defined(_SOCKLEN_T_DECLARED) || defined(__DEFINED_socklen_t) || \ + defined(socklen_t) socklen_t n = (socklen_t) sizeof( client_addr ); socklen_t type_len = (socklen_t) sizeof( type ); #else diff --git a/connectivity/mbedtls/source/nist_kw.c b/connectivity/mbedtls/source/nist_kw.c index 03e807202d..04829a0b97 100644 --- a/connectivity/mbedtls/source/nist_kw.c +++ b/connectivity/mbedtls/source/nist_kw.c @@ -2,7 +2,7 @@ * Implementation of NIST SP 800-38F key wrapping, supporting KW and KWP modes * only * - * Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -16,8 +16,6 @@ * 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) */ /* * Definition of Key Wrapping: @@ -29,11 +27,7 @@ * the wrapping and unwrapping operation than the definition in NIST SP 800-38F. */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_NIST_KW_C) diff --git a/connectivity/mbedtls/source/oid.c b/connectivity/mbedtls/source/oid.c index 891d3cdea9..19c8ac207c 100644 --- a/connectivity/mbedtls/source/oid.c +++ b/connectivity/mbedtls/source/oid.c @@ -3,7 +3,7 @@ * * \brief Object Identifier (OID) database * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -17,15 +17,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_OID_C) @@ -761,7 +755,7 @@ int mbedtls_oid_get_numeric_string( char *buf, size_t size, if( !( oid->p[i] & 0x80 ) ) { /* Last byte */ - ret = mbedtls_snprintf( p, n, ".%d", value ); + ret = mbedtls_snprintf( p, n, ".%u", value ); OID_SAFE_SNPRINTF; value = 0; } diff --git a/connectivity/mbedtls/source/padlock.c b/connectivity/mbedtls/source/padlock.c index b85ff9cd2c..837337413c 100644 --- a/connectivity/mbedtls/source/padlock.c +++ b/connectivity/mbedtls/source/padlock.c @@ -1,7 +1,7 @@ /* * VIA PadLock support functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * This implementation is based on the VIA PadLock Programming Guide: @@ -25,11 +23,7 @@ * programming_guide.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_PADLOCK_C) @@ -58,10 +52,10 @@ int mbedtls_padlock_has_support( int feature ) "cpuid \n\t" "cmpl $0xC0000001, %%eax \n\t" "movl $0, %%edx \n\t" - "jb unsupported \n\t" + "jb 1f \n\t" "movl $0xC0000001, %%eax \n\t" "cpuid \n\t" - "unsupported: \n\t" + "1: \n\t" "movl %%edx, %1 \n\t" "movl %2, %%ebx \n\t" : "=m" (ebx), "=m" (edx) diff --git a/connectivity/mbedtls/source/pem.c b/connectivity/mbedtls/source/pem.c index 31f4a9a25e..534d071b32 100644 --- a/connectivity/mbedtls/source/pem.c +++ b/connectivity/mbedtls/source/pem.c @@ -1,7 +1,7 @@ /* * Privacy Enhanced Mail (PEM) decoding * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) diff --git a/connectivity/mbedtls/source/pk.c b/connectivity/mbedtls/source/pk.c index bbf85d1920..8ffbed2a9a 100644 --- a/connectivity/mbedtls/source/pk.c +++ b/connectivity/mbedtls/source/pk.c @@ -1,7 +1,7 @@ /* * Public Key abstraction layer * - * Copyright (C) 2006-2020, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PK_C) #include "mbedtls/pk.h" @@ -602,7 +596,7 @@ int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk, const mbedtls_ecp_keypair *ec; unsigned char d[MBEDTLS_ECP_MAX_BYTES]; size_t d_len; - psa_ecc_curve_t curve_id; + psa_ecc_family_t curve_id; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_type_t key_type; size_t bits; @@ -617,16 +611,12 @@ int mbedtls_pk_wrap_as_opaque( mbedtls_pk_context *pk, if( ( ret = mbedtls_mpi_write_binary( &ec->d, d, d_len ) ) != 0 ) return( ret ); - /* prepare the key attributes */ -#if TARGET_TFM - curve_id = mbedtls_ecp_curve_info_from_grp_id( ec->grp.id )->tls_id; - key_type = mbedtls_psa_parse_tls_ecc_group ( curve_id, &bits ); -#else curve_id = mbedtls_ecc_group_to_psa( ec->grp.id, &bits ); key_type = PSA_KEY_TYPE_ECC_KEY_PAIR( curve_id ); -#endif - psa_set_key_bits( &attributes, bits ); + + /* prepare the key attributes */ psa_set_key_type( &attributes, key_type ); + psa_set_key_bits( &attributes, bits ); psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH ); psa_set_key_algorithm( &attributes, PSA_ALG_ECDSA(hash_alg) ); diff --git a/connectivity/mbedtls/source/pk_wrap.c b/connectivity/mbedtls/source/pk_wrap.c index 4316debfe4..6bf3169743 100644 --- a/connectivity/mbedtls/source/pk_wrap.c +++ b/connectivity/mbedtls/source/pk_wrap.c @@ -1,7 +1,7 @@ /* * Public Key abstraction layer: wrapper functions * - * Copyright (C) 2006-2020, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PK_C) #include "mbedtls/pk_internal.h" @@ -559,12 +553,8 @@ static int ecdsa_verify_wrap( void *ctx_arg, mbedtls_md_type_t md_alg, mbedtls_pk_info_t pk_info = mbedtls_eckey_info; psa_algorithm_t psa_sig_md, psa_md; size_t curve_bits; - psa_ecc_curve_t curve; -#if TARGET_TFM - curve = mbedtls_ecp_curve_info_from_grp_id( ctx->grp.id )->tls_id; -#else - curve = mbedtls_ecc_group_to_psa( ctx->grp.id, &curve_bits ); -#endif + psa_ecc_family_t curve = + mbedtls_ecc_group_to_psa( ctx->grp.id, &curve_bits ); const size_t signature_part_size = ( ctx->grp.nbits + 7 ) / 8; if( curve == 0 ) diff --git a/connectivity/mbedtls/source/pkcs11.c b/connectivity/mbedtls/source/pkcs11.c index 0ea64252ee..4deccf3f60 100644 --- a/connectivity/mbedtls/source/pkcs11.c +++ b/connectivity/mbedtls/source/pkcs11.c @@ -5,7 +5,7 @@ * * \author Adriaan de Jong * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,8 +19,6 @@ * 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) */ #include "mbedtls/pkcs11.h" diff --git a/connectivity/mbedtls/source/pkcs12.c b/connectivity/mbedtls/source/pkcs12.c index 96c64ad63c..4bdeb6835e 100644 --- a/connectivity/mbedtls/source/pkcs12.c +++ b/connectivity/mbedtls/source/pkcs12.c @@ -1,7 +1,7 @@ /* * PKCS#12 Personal Information Exchange Syntax * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The PKCS #12 Personal Information Exchange Syntax Standard v1.1 @@ -25,11 +23,7 @@ * ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1-1.asn */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_PKCS12_C) diff --git a/connectivity/mbedtls/source/pkcs5.c b/connectivity/mbedtls/source/pkcs5.c index 8832322257..f89cc643c3 100644 --- a/connectivity/mbedtls/source/pkcs5.c +++ b/connectivity/mbedtls/source/pkcs5.c @@ -5,7 +5,7 @@ * * \author Mathias Olsson * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -19,8 +19,6 @@ * 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) */ /* * PKCS#5 includes PBKDF2 and more @@ -29,11 +27,7 @@ * http://tools.ietf.org/html/rfc6070 (Test vectors) */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_PKCS5_C) diff --git a/connectivity/mbedtls/source/pkparse.c b/connectivity/mbedtls/source/pkparse.c index 1cbb8cc339..a106dbe3ed 100644 --- a/connectivity/mbedtls/source/pkparse.c +++ b/connectivity/mbedtls/source/pkparse.c @@ -1,7 +1,7 @@ /* * Public Key layer for parsing key files and structures * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PK_PARSE_C) diff --git a/connectivity/mbedtls/source/pkwrite.c b/connectivity/mbedtls/source/pkwrite.c index b1b5f4685a..b317ccf223 100644 --- a/connectivity/mbedtls/source/pkwrite.c +++ b/connectivity/mbedtls/source/pkwrite.c @@ -1,7 +1,7 @@ /* * Public Key layer for writing key files and structures * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PK_WRITE_C) @@ -168,7 +162,7 @@ static int pk_write_ec_private( unsigned char **p, unsigned char *start, size_t byte_length = ( ec->grp.pbits + 7 ) / 8; unsigned char tmp[MBEDTLS_ECP_MAX_BYTES]; - ret = mbedtls_mpi_write_binary( &ec->d, tmp, byte_length ); + ret = mbedtls_ecp_write_key( ec, tmp, byte_length ); if( ret != 0 ) goto exit; ret = mbedtls_asn1_write_octet_string( p, start, tmp, byte_length ); @@ -272,7 +266,7 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_type_t key_type; psa_key_handle_t handle; - psa_ecc_curve_t curve; + psa_ecc_family_t curve; size_t bits; handle = *((psa_key_handle_t*) key->pk_ctx ); @@ -282,7 +276,7 @@ int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *key, unsigned char *buf, si bits = psa_get_key_bits( &attributes ); psa_reset_key_attributes( &attributes ); - curve = PSA_KEY_TYPE_GET_CURVE( key_type ); + curve = PSA_KEY_TYPE_ECC_GET_FAMILY( key_type ); if( curve == 0 ) return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); diff --git a/connectivity/mbedtls/source/platform.c b/connectivity/mbedtls/source/platform.c index 420d09ea1e..e742fde7cc 100644 --- a/connectivity/mbedtls/source/platform.c +++ b/connectivity/mbedtls/source/platform.c @@ -1,7 +1,7 @@ /* * Platform abstraction layer * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PLATFORM_C) diff --git a/connectivity/mbedtls/source/platform_util.c b/connectivity/mbedtls/source/platform_util.c index b1f745097c..4e1d617bd1 100644 --- a/connectivity/mbedtls/source/platform_util.c +++ b/connectivity/mbedtls/source/platform_util.c @@ -2,7 +2,7 @@ * Common and shared functions used by multiple modules in the Mbed TLS * library. * - * Copyright (C) 2018, Arm Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -16,8 +16,6 @@ * 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) */ /* @@ -28,11 +26,7 @@ #define _POSIX_C_SOURCE 200112L #endif -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #include "mbedtls/platform_util.h" #include "mbedtls/platform.h" diff --git a/connectivity/mbedtls/source/poly1305.c b/connectivity/mbedtls/source/poly1305.c index bc1e8a6496..492d1457d4 100644 --- a/connectivity/mbedtls/source/poly1305.c +++ b/connectivity/mbedtls/source/poly1305.c @@ -3,7 +3,7 @@ * * \brief Poly1305 authentication algorithm. * - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -17,14 +17,8 @@ * 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 +#include "common.h" #if defined(MBEDTLS_POLY1305_C) @@ -513,6 +507,9 @@ static const unsigned char test_mac[2][16] = } }; +/* Make sure no other definition is already present. */ +#undef ASSERT + #define ASSERT( cond, args ) \ do \ { \ diff --git a/connectivity/mbedtls/source/ripemd160.c b/connectivity/mbedtls/source/ripemd160.c index a62f4b824e..830f61b3cd 100644 --- a/connectivity/mbedtls/source/ripemd160.c +++ b/connectivity/mbedtls/source/ripemd160.c @@ -1,7 +1,7 @@ /* * RIPE MD-160 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -25,11 +23,7 @@ * http://ehash.iaik.tugraz.at/wiki/RIPEMD-160 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_RIPEMD160_C) diff --git a/connectivity/mbedtls/source/rsa.c b/connectivity/mbedtls/source/rsa.c index 6c457468ea..84d87de0d1 100644 --- a/connectivity/mbedtls/source/rsa.c +++ b/connectivity/mbedtls/source/rsa.c @@ -1,7 +1,7 @@ /* * The RSA public-key cryptosystem * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -37,11 +35,7 @@ * */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_RSA_C) @@ -57,7 +51,7 @@ #include "mbedtls/md.h" #endif -#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) +#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__) #include #endif @@ -782,6 +776,9 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret, count = 0; + mbedtls_mpi R; + + mbedtls_mpi_init( &R ); if( ctx->Vf.p != NULL ) { @@ -797,18 +794,41 @@ static int rsa_prepare_blinding( mbedtls_rsa_context *ctx, /* Unblinding value: Vf = random number, invertible mod N */ do { if( count++ > 10 ) - return( MBEDTLS_ERR_RSA_RNG_FAILED ); + { + ret = MBEDTLS_ERR_RSA_RNG_FAILED; + goto cleanup; + } MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vf, ctx->len - 1, f_rng, p_rng ) ); - MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( &ctx->Vi, &ctx->Vf, &ctx->N ) ); - } while( mbedtls_mpi_cmp_int( &ctx->Vi, 1 ) != 0 ); - /* Blinding value: Vi = Vf^(-e) mod N */ - MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vf, &ctx->N ) ); + /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */ + MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &R, ctx->len - 1, f_rng, p_rng ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vf, &R ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); + + /* At this point, Vi is invertible mod N if and only if both Vf and R + * are invertible mod N. If one of them isn't, we don't need to know + * which one, we just loop and choose new values for both of them. + * (Each iteration succeeds with overwhelming probability.) */ + ret = mbedtls_mpi_inv_mod( &ctx->Vi, &ctx->Vi, &ctx->N ); + if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE ) + continue; + if( ret != 0 ) + goto cleanup; + + /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */ + MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ctx->Vi, &ctx->Vi, &R ) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->Vi, &ctx->Vi, &ctx->N ) ); + } while( 0 ); + + /* Blinding value: Vi = Vf^(-e) mod N + * (Vi already contains Vf^-1 at this point) */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN ) ); cleanup: + mbedtls_mpi_free( &R ); + return( ret ); } @@ -2573,7 +2593,7 @@ void mbedtls_rsa_free( mbedtls_rsa_context *ctx ) #if defined(MBEDTLS_PKCS1_V15) static int myrand( void *rng_state, unsigned char *output, size_t len ) { -#if !defined(__OpenBSD__) +#if !defined(__OpenBSD__) && !defined(__NetBSD__) size_t i; if( rng_state != NULL ) @@ -2586,7 +2606,7 @@ static int myrand( void *rng_state, unsigned char *output, size_t len ) rng_state = NULL; arc4random_buf( output, len ); -#endif /* !OpenBSD */ +#endif /* !OpenBSD && !NetBSD */ return( 0 ); } diff --git a/connectivity/mbedtls/source/rsa_internal.c b/connectivity/mbedtls/source/rsa_internal.c index 9a42d47ceb..d6ba97a14b 100644 --- a/connectivity/mbedtls/source/rsa_internal.c +++ b/connectivity/mbedtls/source/rsa_internal.c @@ -1,7 +1,7 @@ /* * Helper functions for the RSA module * - * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -16,15 +16,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_RSA_C) diff --git a/connectivity/mbedtls/source/sha1.c b/connectivity/mbedtls/source/sha1.c index 9233943415..593f79513a 100644 --- a/connectivity/mbedtls/source/sha1.c +++ b/connectivity/mbedtls/source/sha1.c @@ -1,7 +1,7 @@ /* * FIPS-180-1 compliant SHA-1 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The SHA-1 standard was published by NIST in 1993. @@ -24,11 +22,7 @@ * http://www.itl.nist.gov/fipspubs/fip180-1.htm */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SHA1_C) diff --git a/connectivity/mbedtls/source/sha256.c b/connectivity/mbedtls/source/sha256.c index 087a8e349c..b4c4b3624f 100644 --- a/connectivity/mbedtls/source/sha256.c +++ b/connectivity/mbedtls/source/sha256.c @@ -1,7 +1,7 @@ /* * FIPS-180-2 compliant SHA-256 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The SHA-256 Secure Hash Standard was published by NIST in 2002. @@ -24,11 +22,7 @@ * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SHA256_C) diff --git a/connectivity/mbedtls/source/sha512.c b/connectivity/mbedtls/source/sha512.c index 30dd719540..80219d4281 100644 --- a/connectivity/mbedtls/source/sha512.c +++ b/connectivity/mbedtls/source/sha512.c @@ -1,7 +1,7 @@ /* * FIPS-180-2 compliant SHA-384/512 implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The SHA-512 Secure Hash Standard was published by NIST in 2002. @@ -24,11 +22,7 @@ * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SHA512_C) diff --git a/connectivity/mbedtls/source/ssl_cache.c b/connectivity/mbedtls/source/ssl_cache.c index 62a0a29879..7e9d4da05a 100644 --- a/connectivity/mbedtls/source/ssl_cache.c +++ b/connectivity/mbedtls/source/ssl_cache.c @@ -1,7 +1,7 @@ /* * SSL session cache implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,19 +15,13 @@ * 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) */ /* * These session callbacks use a simple chained list * to store and retrieve the session information. */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SSL_CACHE_C) diff --git a/connectivity/mbedtls/source/ssl_ciphersuites.c b/connectivity/mbedtls/source/ssl_ciphersuites.c index 5da1294124..6985fe5f35 100644 --- a/connectivity/mbedtls/source/ssl_ciphersuites.c +++ b/connectivity/mbedtls/source/ssl_ciphersuites.c @@ -3,7 +3,7 @@ * * \brief SSL ciphersuites for mbed TLS * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -17,15 +17,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_SSL_TLS_C) diff --git a/connectivity/mbedtls/source/ssl_cli.c b/connectivity/mbedtls/source/ssl_cli.c index 553e2b6a31..083b720be1 100644 --- a/connectivity/mbedtls/source/ssl_cli.c +++ b/connectivity/mbedtls/source/ssl_cli.c @@ -1,7 +1,7 @@ /* * SSLv3/TLSv1 client-side functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_SSL_CLI_C) @@ -95,29 +89,26 @@ static int ssl_conf_has_static_raw_psk( mbedtls_ssl_config const *conf ) #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, - size_t *olen ) +static int ssl_write_hostname_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t hostname_len; *olen = 0; if( ssl->hostname == NULL ) - return; + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s", - ssl->hostname ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding server name extension: %s", + ssl->hostname ) ); hostname_len = strlen( ssl->hostname ); - if( end < p || (size_t)( end - p ) < hostname_len + 9 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, hostname_len + 9 ); /* * Sect. 3, RFC 6066 (TLS Extensions Definitions) @@ -161,16 +152,18 @@ static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl, memcpy( p, ssl->hostname, hostname_len ); *olen = hostname_len + 9; + + return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_RENEGOTIATION) -static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; @@ -178,21 +171,20 @@ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, * initial ClientHello, in which case also adding the renegotiation * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) - return; + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding renegotiation extension" ) ); - if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 + ssl->verify_data_len ); /* * Secure renegotiation */ - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) + & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) + & 0xFF ); *p++ = 0x00; *p++ = ( ssl->verify_data_len + 1 ) & 0xFF; @@ -201,6 +193,8 @@ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); *olen = 5 + ssl->verify_data_len; + + return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ @@ -209,14 +203,15 @@ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) -static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t sig_alg_len = 0; const int *md; + #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) unsigned char *sig_alg_list = buf + 6; #endif @@ -224,9 +219,13 @@ static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, *olen = 0; if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) - return; + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding signature_algorithms extension" ) ); + + if( ssl->conf->sig_hashes == NULL ) + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ ) { @@ -236,13 +235,19 @@ static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, #if defined(MBEDTLS_RSA_C) sig_alg_len += 2; #endif + if( sig_alg_len > MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "length in bytes of sig-hash-alg extension too big" ) ); + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); + } } - if( end < p || (size_t)( end - p ) < sig_alg_len + 6 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + /* Empty signature algorithms list, this is a configuration error. */ + if( sig_alg_len == 0 ) + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, sig_alg_len + 6 ); /* * Prepare signature_algorithms extension (TLS 1.2) @@ -288,75 +293,75 @@ static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl, *p++ = (unsigned char)( ( sig_alg_len ) & 0xFF ); *olen = 6 + sig_alg_len; + + return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) -static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; unsigned char *elliptic_curve_list = p + 6; size_t elliptic_curve_len = 0; const mbedtls_ecp_curve_info *info; -#if defined(MBEDTLS_ECP_C) const mbedtls_ecp_group_id *grp_id; -#else - ((void) ssl); -#endif *olen = 0; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding supported_elliptic_curves extension" ) ); -#if defined(MBEDTLS_ECP_C) - for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) -#else - for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ ) -#endif + if( ssl->conf->curve_list == NULL ) + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); + + for( grp_id = ssl->conf->curve_list; + *grp_id != MBEDTLS_ECP_DP_NONE; + grp_id++ ) { -#if defined(MBEDTLS_ECP_C) info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); -#endif if( info == NULL ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) ); - return; + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "invalid curve in ssl configuration" ) ); + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); } - elliptic_curve_len += 2; + + if( elliptic_curve_len > MBEDTLS_SSL_MAX_CURVE_LIST_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "malformed supported_elliptic_curves extension in config" ) ); + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); + } } - if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + /* Empty elliptic curve list, this is a configuration error. */ + if( elliptic_curve_len == 0 ) + return( MBEDTLS_ERR_SSL_BAD_CONFIG ); + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + elliptic_curve_len ); elliptic_curve_len = 0; -#if defined(MBEDTLS_ECP_C) - for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ ) -#else - for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ ) -#endif + for( grp_id = ssl->conf->curve_list; + *grp_id != MBEDTLS_ECP_DP_NONE; + grp_id++ ) { -#if defined(MBEDTLS_ECP_C) info = mbedtls_ecp_curve_info_from_grp_id( *grp_id ); -#endif elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8; elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF; } - if( elliptic_curve_len == 0 ) - return; - - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) + & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) + & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF ); @@ -365,27 +370,28 @@ static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl, *p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF ); *olen = 6 + elliptic_curve_len; + + return( 0 ); } -static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; + (void) ssl; /* ssl used for debugging only */ *olen = 0; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding supported_point_formats extension" ) ); + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 ); - if( end < p || (size_t)( end - p ) < 6 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } - - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) + & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) + & 0xFF ); *p++ = 0x00; *p++ = 2; @@ -394,33 +400,32 @@ static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; + + return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) -static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t kkpp_len; *olen = 0; /* Skip costly extension if we can't use EC J-PAKE anyway */ if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) - return; + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding ecjpake_kkpp extension" ) ); - if( end - p < 4 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); @@ -436,19 +441,20 @@ static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, - p + 2, end - p - 2, &kkpp_len, - ssl->conf->f_rng, ssl->conf->p_rng ); + p + 2, end - p - 2, &kkpp_len, + ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { - MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); - return; + MBEDTLS_SSL_DEBUG_RET( 1 , + "mbedtls_ecjpake_write_round_one", ret ); + return( ret ); } ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len ); if( ssl->handshake->ecjpake_cache == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) ); - return; + return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len ); @@ -459,12 +465,7 @@ static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) ); kkpp_len = ssl->handshake->ecjpake_cache_len; - - if( (size_t)( end - p - 2 ) < kkpp_len ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p + 2, end, kkpp_len ); memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len ); } @@ -473,17 +474,19 @@ static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; + + return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) -static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_cid_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; size_t ext_len; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; /* * Quoting draft-ietf-tls-dtls-connection-id-05 @@ -498,17 +501,13 @@ static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM || ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { - return; + return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding CID extension" ) ); /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ - if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, (unsigned)( ssl->own_cid_len + 5 ) ); /* Add extension ID + size */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); @@ -521,33 +520,33 @@ static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; + + return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) -static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, - size_t *olen ) +static int ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; - if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) { - return; - } + if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding max_fragment_length extension" ) ); - if( end < p || (size_t)( end - p ) < 5 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) + & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) + & 0xFF ); *p++ = 0x00; *p++ = 1; @@ -555,30 +554,28 @@ static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, *p++ = ssl->conf->mfl_code; *olen = 5; + + return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) -static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, size_t *olen ) +static int ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ) - { - return; - } + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding truncated_hmac extension" ) ); - if( end < p || (size_t)( end - p ) < 4 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF ); @@ -587,32 +584,29 @@ static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, *p++ = 0x00; *olen = 4; + + return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) -static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, size_t *olen ) +static int ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - return; - } + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac " - "extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding encrypt_then_mac extension" ) ); - if( end < p || (size_t)( end - p ) < 4 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); @@ -621,65 +615,63 @@ static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, *p++ = 0x00; *olen = 4; + + return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) -static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, size_t *olen ) +static int ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - return; - } + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret " - "extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding extended_master_secret extension" ) ); - if( end < p || (size_t)( end - p ) < 4 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); - *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) + & 0xFF ); + *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) + & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; + + return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) -static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, size_t *olen ) +static int ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t tlen = ssl->session_negotiate->ticket_len; *olen = 0; if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ) - { - return; - } + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, adding session ticket extension" ) ); - if( end < p || (size_t)( end - p ) < 4 + tlen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + /* The addition is safe here since the ticket length is 16 bit. */ + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 + tlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); @@ -690,44 +682,40 @@ static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, *olen = 4; if( ssl->session_negotiate->ticket == NULL || tlen == 0 ) - { - return; - } + return( 0 ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "sending session ticket of length %d", tlen ) ); memcpy( p, ssl->session_negotiate->ticket, tlen ); *olen += tlen; + + return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) -static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, - unsigned char *buf, size_t *olen ) +static int ssl_write_alpn_ext( mbedtls_ssl_context *ssl, + unsigned char *buf, + const unsigned char *end, + size_t *olen ) { unsigned char *p = buf; - const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t alpnlen = 0; const char **cur; *olen = 0; if( ssl->conf->alpn_list == NULL ) - { - return; - } + return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) ); for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) - alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1; + alpnlen += strlen( *cur ) + 1; - if( end < p || (size_t)( end - p ) < 6 + alpnlen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); - return; - } + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + alpnlen ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); @@ -745,7 +733,11 @@ static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ ) { - *p = (unsigned char)( strlen( *cur ) & 0xFF ); + /* + * mbedtls_ssl_conf_set_alpn_protocols() checked that the length of + * protocol names is less than 255. + */ + *p = (unsigned char)strlen( *cur ); memcpy( p + 1, *cur, *p ); p += 1 + *p; } @@ -759,6 +751,8 @@ static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */ buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); + + return( 0 ); } #endif /* MBEDTLS_SSL_ALPN */ @@ -815,9 +809,10 @@ static int ssl_generate_random( mbedtls_ssl_context *ssl ) * * \return 0 if valid, else 1 */ -static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info, - const mbedtls_ssl_context * ssl, - int min_minor_ver, int max_minor_ver ) +static int ssl_validate_ciphersuite( + const mbedtls_ssl_ciphersuite_t * suite_info, + const mbedtls_ssl_context * ssl, + int min_minor_ver, int max_minor_ver ) { (void) ssl; if( suite_info == NULL ) @@ -861,8 +856,11 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t i, n, olen, ext_len = 0; + unsigned char *buf; unsigned char *p, *q; + const unsigned char *end; + unsigned char offer_compress; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; @@ -889,23 +887,41 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) if( ssl->conf->max_major_ver == 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, " - "consider using mbedtls_ssl_config_defaults()" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "configured max major version is invalid, consider using mbedtls_ssl_config_defaults()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } + buf = ssl->out_msg; + end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN; + /* - * 0 . 0 handshake type - * 1 . 3 handshake length + * Check if there's enough space for the first part of the ClientHello + * consisting of the 38 bytes described below, the session identifier (at + * most 32 bytes) and its length (1 byte). + * + * Use static upper bounds instead of the actual values + * to allow the compiler to optimize this away. + */ + MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 ); + + /* + * The 38 first bytes of the ClientHello: + * 0 . 0 handshake type (written later) + * 1 . 3 handshake length (written later) * 4 . 5 highest version supported * 6 . 9 current UNIX time * 10 . 37 random bytes + * + * The current UNIX time (4 bytes) and following 28 random bytes are written + * by ssl_generate_random() into ssl->handshake->randbytes buffer and then + * copied from there into the output buffer. */ - buf = ssl->out_msg; - p = buf + 4; - mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, - ssl->conf->transport, p ); + p = buf + 4; + mbedtls_ssl_write_version( ssl->conf->max_major_ver, + ssl->conf->max_minor_ver, + ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]", @@ -925,7 +941,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) * 38 . 38 session id length * 39 . 39+n session id * 39+n . 39+n DTLS only: cookie length (1 byte) - * 40+n . .. DTSL only: cookie + * 40+n . .. DTLS only: cookie * .. . .. ciphersuitelist length (2 bytes) * .. . .. ciphersuitelist * .. . .. compression methods length (1 byte) @@ -956,7 +972,8 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) if( ssl->session_negotiate->ticket != NULL && ssl->session_negotiate->ticket_len != 0 ) { - ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 ); + ret = ssl->conf->f_rng( ssl->conf->p_rng, + ssl->session_negotiate->id, 32 ); if( ret != 0 ) return( ret ); @@ -966,6 +983,12 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ + /* + * The first check of the output buffer size above ( + * MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 );) + * has checked that there is enough space in the output buffer for the + * session identifier length byte and the session identifier (n <= 32). + */ *p++ = (unsigned char) n; for( i = 0; i < n; i++ ) @@ -974,12 +997,27 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n ); + /* + * With 'n' being the length of the session identifier + * + * 39+n . 39+n DTLS only: cookie length (1 byte) + * 40+n . .. DTLS only: cookie + * .. . .. ciphersuitelist length (2 bytes) + * .. . .. ciphersuitelist + * .. . .. compression methods length (1 byte) + * .. . .. compression methods + * .. . .. extensions length (2 bytes) + * .. . .. extensions + */ + /* * DTLS cookie */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 1 ); + if( ssl->handshake->verify_cookie == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) ); @@ -992,6 +1030,9 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) ssl->handshake->verify_cookie_len ); *p++ = ssl->handshake->verify_cookie_len; + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, + ssl->handshake->verify_cookie_len ); memcpy( p, ssl->handshake->verify_cookie, ssl->handshake->verify_cookie_len ); p += ssl->handshake->verify_cookie_len; @@ -1007,6 +1048,8 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) /* Skip writing ciphersuite length for now */ n = 0; q = p; + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); p += 2; for( i = 0; ciphersuites[i] != 0; i++ ) @@ -1018,20 +1061,23 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) ssl->conf->max_minor_ver ) != 0 ) continue; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x", - ciphersuites[i] ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %#04x (%s)", + ciphersuites[i], ciphersuite_info->name ) ); #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info ); #endif + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); + n++; *p++ = (unsigned char)( ciphersuites[i] >> 8 ); *p++ = (unsigned char)( ciphersuites[i] ); } - MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) ); /* * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV @@ -1041,6 +1087,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) #endif { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) ); + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ); n++; @@ -1051,6 +1098,8 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) ); + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ); *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ); n++; @@ -1081,8 +1130,10 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d", - MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) ); + MBEDTLS_SSL_COMPRESS_DEFLATE, + MBEDTLS_SSL_COMPRESS_NULL ) ); + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 3 ); *p++ = 2; *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE; *p++ = MBEDTLS_SSL_COMPRESS_NULL; @@ -1093,27 +1144,45 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d", MBEDTLS_SSL_COMPRESS_NULL ) ); + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); *p++ = 1; *p++ = MBEDTLS_SSL_COMPRESS_NULL; } - // First write extensions, then the total length - // + /* First write extensions, then the total length */ + + MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 ); + #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_hostname_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_hostname_ext", ret ); + return( ret ); + } ext_len += olen; #endif /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) - ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_renegotiation_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) - ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_signature_algorithms_ext", ret ); + return( ret ); + } ext_len += olen; #endif @@ -1121,51 +1190,100 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( uses_ec ) { - ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_elliptic_curves_ext", ret ); + return( ret ); + } ext_len += olen; - ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_point_formats_ext", ret ); + return( ret ); + } ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) - ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_ecjpake_kkpp_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) - ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_cid_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret ); + return( ret ); + } ext_len += olen; #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) - ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_max_fragment_length_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) - ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_truncated_hmac_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_encrypt_then_mac_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) - ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_extended_ms_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) - ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_alpn_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_alpn_ext", ret ); + return( ret ); + } ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) - ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen ); + if( ( ret = ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, + end, &olen ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_session_ticket_ext", ret ); + return( ret ); + } ext_len += olen; #endif @@ -1173,10 +1291,12 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl ) ((void) olen); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d", - ext_len ) ); + ext_len ) ); if( ext_len > 0 ) { + /* No need to check for space here, because the extension + * writing functions already took care of that. */ *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; @@ -1229,8 +1349,10 @@ static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } @@ -1239,9 +1361,12 @@ static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, { if( len != 1 || buf[0] != 0x00 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-zero length renegotiation info" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1264,9 +1389,12 @@ static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, len != 1 || buf[0] != ssl->conf->mfl_code ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-matching max fragment length extension" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1282,9 +1410,12 @@ static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl, if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED || len != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-matching truncated HMAC extension" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1361,9 +1492,12 @@ static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-matching encrypt-then-MAC extension" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1384,9 +1518,12 @@ static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || len != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-matching extended master secret extension" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1406,9 +1543,12 @@ static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED || len != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-matching session ticket extension" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1489,8 +1629,10 @@ static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } @@ -1509,8 +1651,10 @@ static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, if( ssl->conf->alpn_list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1690,12 +1834,13 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) if( ssl->conf->renego_max_records >= 0 && ssl->renego_records_seen > ssl->conf->renego_max_records ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " - "but not honored by server" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "renegotiation requested, but not honored by server" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } - MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "non-handshake message during renegotiation" ) ); ssl->keep_current_message = 1; return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ); @@ -1703,8 +1848,10 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #endif /* MBEDTLS_SSL_RENEGOTIATION */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -1758,11 +1905,13 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->major_ver > ssl->conf->max_major_ver || ssl->minor_ver > ssl->conf->max_minor_ver ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - " - " min: [%d:%d], server: [%d:%d], max: [%d:%d]", - ssl->conf->min_major_ver, ssl->conf->min_minor_ver, - ssl->major_ver, ssl->minor_ver, - ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "server version out of bounds - min: [%d:%d], server: [%d:%d], max: [%d:%d]", + ssl->conf->min_major_ver, + ssl->conf->min_minor_ver, + ssl->major_ver, ssl->minor_ver, + ssl->conf->max_major_ver, + ssl->conf->max_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); @@ -1799,8 +1948,10 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } } @@ -1839,9 +1990,12 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) if( comp != MBEDTLS_SSL_COMPRESS_NULL ) #endif/* MBEDTLS_ZLIB_SUPPORT */ { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "server hello, bad compression: %d", comp ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } @@ -1851,7 +2005,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i ); if( ssl->handshake->ciphersuite_info == NULL ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "ciphersuite info for %04x not found", i ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); @@ -1891,8 +2046,10 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( ret ); } } @@ -1901,7 +2058,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->handshake->resume ? "a" : "no" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) ); - MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", + buf[37 + n] ) ); /* * Perform cipher suite validation in same way as in ssl_write_client_hello. @@ -1912,8 +2070,10 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1924,16 +2084,21 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) } } - suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ); - if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 ) + suite_info = mbedtls_ssl_ciphersuite_from_id( + ssl->session_negotiate->ciphersuite ); + if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, + ssl->minor_ver ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } - MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "server hello, chosen ciphersuite: %s", suite_info->name ) ); #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA && @@ -1950,15 +2115,18 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } ssl->session_negotiate->compression = comp; ext = buf + 40 + n; - MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) ); + MBEDTLS_SSL_DEBUG_MSG( 2, + ( "server hello, total extension length: %d", ext_len ) ); while( ext_len ) { @@ -1970,8 +2138,9 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -1991,7 +2160,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: - MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "found max_fragment_length extension" ) ); if( ( ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ) ) != 0 ) @@ -2044,7 +2214,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: - MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "found extended_master_secret extension" ) ); if( ( ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ) ) != 0 ) @@ -2071,7 +2242,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: - MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "found supported_point_formats extension" ) ); if( ( ret = ssl_parse_supported_point_formats_ext( ssl, ext + 4, ext_size ) ) != 0 ) @@ -2107,8 +2279,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #endif /* MBEDTLS_SSL_ALPN */ default: - MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)", - ext_id ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "unknown extension found: %d (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; @@ -2125,9 +2297,11 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) * Renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && - ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) + ssl->conf->allow_legacy_renegotiation == + MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) @@ -2135,12 +2309,14 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && - ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) + ssl->conf->allow_legacy_renegotiation == + MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; @@ -2149,15 +2325,18 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO ); } @@ -2168,7 +2347,8 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) -static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p, +static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, + unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; @@ -2182,7 +2362,8 @@ static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char * * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ - if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 ) + if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, + p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret ); return( ret ); @@ -2340,7 +2521,8 @@ static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl, if( ssl_check_server_ecdh_params( ssl ) != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "bad server key exchange message (ECDHE curve)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } @@ -2366,8 +2548,8 @@ static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, */ if( end - (*p) < 2 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " - "(psk_identity_hint length)" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; @@ -2375,8 +2557,8 @@ static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, if( end - (*p) < len ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " - "(psk_identity_hint length)" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "bad server key exchange message (psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } @@ -2419,8 +2601,9 @@ static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl, * opaque random[46]; * } PreMasterSecret; */ - mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver, - ssl->conf->transport, p ); + mbedtls_ssl_write_version( ssl->conf->max_major_ver, + ssl->conf->max_minor_ver, + ssl->conf->transport, p ); if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 ) { @@ -2506,20 +2689,22 @@ static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl, /* * Get hash algorithm */ - if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE ) + if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) + == MBEDTLS_MD_NONE ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported " - "HashAlgorithm %d", *(p)[0] ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "Server used unsupported HashAlgorithm %d", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Get signature algorithm */ - if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE ) + if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) + == MBEDTLS_PK_NONE ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported " - "SignatureAlgorithm %d", (*p)[1] ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "server used unsupported SignatureAlgorithm %d", (*p)[1] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } @@ -2528,13 +2713,15 @@ static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl, */ if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered", - *(p)[0] ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "server used HashAlgorithm %d that was not offered", *(p)[0] ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } - MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) ); - MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) ); + MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", + (*p)[1] ) ); + MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", + (*p)[0] ) ); *p += 2; return( 0 ); @@ -2625,8 +2812,10 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( ret ); } @@ -2656,8 +2845,10 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -2676,10 +2867,12 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl ) goto exit; } - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must " - "not be skipped" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "server key exchange message must not be skipped" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -2703,8 +2896,10 @@ start_processing: if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } /* FALLTROUGH */ @@ -2726,8 +2921,10 @@ start_processing: if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } @@ -2743,8 +2940,10 @@ start_processing: if( ssl_parse_server_ecdh_params_psa( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } @@ -2762,8 +2961,10 @@ start_processing: if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } @@ -2779,8 +2980,10 @@ start_processing: if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } @@ -2813,17 +3016,24 @@ start_processing: if( ssl_parse_signature_algorithm( ssl, &p, end, &md_alg, &pk_alg ) != 0 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "bad server key exchange message" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } - if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) + if( pk_alg != + mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "bad server key exchange message" ) ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } } @@ -2853,8 +3063,10 @@ start_processing: if( p > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } sig_len = ( p[0] << 8 ) | p[1]; @@ -2863,8 +3075,10 @@ start_processing: if( p != end - sig_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } @@ -2924,8 +3138,10 @@ start_processing: if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } @@ -2940,8 +3156,10 @@ start_processing: #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED) 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_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_ENABLED) if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) @@ -3013,8 +3231,10 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } @@ -3090,8 +3310,9 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { - size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) - | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); + size_t sig_alg_len = + ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 ) + | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) ); #if defined(MBEDTLS_DEBUG_C) unsigned char* sig_alg; size_t i; @@ -3109,11 +3330,14 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) * buf[...hdr_len + 3 + n + sig_alg_len], * which is one less than we need the buf to be. */ - if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len ) + if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + + 3 + n + sig_alg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST ); } @@ -3121,8 +3345,9 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl ) sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n; for( i = 0; i < sig_alg_len; i += 2 ) { - MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d" - ",%d", sig_alg[i], sig_alg[i + 1] ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, + ( "Supported Signature Algorithm found: %d,%d", + sig_alg[i], sig_alg[i + 1] ) ); } #endif @@ -3213,9 +3438,9 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) header_len = 6; ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx, - (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), - &ssl->out_msg[header_len], content_len, - ssl->conf->f_rng, ssl->conf->p_rng ); + (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), + &ssl->out_msg[header_len], content_len, + ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret ); @@ -3226,10 +3451,10 @@ static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl ) MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, - ssl->handshake->premaster, - MBEDTLS_PREMASTER_SIZE, - &ssl->handshake->pmslen, - ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) + ssl->handshake->premaster, + MBEDTLS_PREMASTER_SIZE, + &ssl->handshake->pmslen, + ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); @@ -3379,10 +3604,10 @@ ecdh_calc_secret: content_len = ssl->handshake->ecrs_n; #endif if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, - &ssl->handshake->pmslen, - ssl->handshake->premaster, - MBEDTLS_MPI_MAX_SIZE, - ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) + &ssl->handshake->pmslen, + ssl->handshake->premaster, + MBEDTLS_MPI_MAX_SIZE, + 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_ENABLED) @@ -3419,8 +3644,8 @@ ecdh_calc_secret: if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or " - "SSL buffer too short" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "psk identity too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } @@ -3471,8 +3696,8 @@ ecdh_calc_secret: if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long" - " or SSL buffer too short" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "psk identity or DHM size too long or SSL buffer too short" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } @@ -3530,7 +3755,8 @@ ecdh_calc_secret: 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" ) ); + MBEDTLS_SSL_DEBUG_MSG( 1, + ( "skip PMS generation for opaque PSK" ) ); } else #endif /* MBEDTLS_USE_PSA_CRYPTO && @@ -3538,7 +3764,8 @@ ecdh_calc_secret: if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); + MBEDTLS_SSL_DEBUG_RET( 1, + "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } @@ -3736,8 +3963,9 @@ sign: * Until we encounter a server that does not, we will take this * shortcut. * - * Reason: Otherwise we should have running hashes for SHA512 and SHA224 - * in order to satisfy 'weird' needs from the server side. + * Reason: Otherwise we should have running hashes for SHA512 and + * SHA224 in order to satisfy 'weird' needs from the server + * side. */ if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { @@ -3821,8 +4049,10 @@ static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl ) if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) ); - mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); + mbedtls_ssl_send_alert_message( + ssl, + MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } diff --git a/connectivity/mbedtls/source/ssl_cookie.c b/connectivity/mbedtls/source/ssl_cookie.c index 4bf9058af4..c8bd1bd529 100644 --- a/connectivity/mbedtls/source/ssl_cookie.c +++ b/connectivity/mbedtls/source/ssl_cookie.c @@ -1,7 +1,7 @@ /* * DTLS cookie callbacks implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,19 +15,13 @@ * 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) */ /* * These session callbacks use a simple chained list * to store and retrieve the session information. */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SSL_COOKIE_C) @@ -134,8 +128,7 @@ static int ssl_cookie_hmac( mbedtls_md_context_t *hmac_ctx, { unsigned char hmac_out[COOKIE_MD_OUTLEN]; - if( (size_t)( end - *p ) < COOKIE_HMAC_LEN ) - return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); + MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_HMAC_LEN ); if( mbedtls_md_hmac_reset( hmac_ctx ) != 0 || mbedtls_md_hmac_update( hmac_ctx, time, 4 ) != 0 || @@ -165,8 +158,7 @@ int mbedtls_ssl_cookie_write( void *p_ctx, if( ctx == NULL || cli_id == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - if( (size_t)( end - *p ) < COOKIE_LEN ) - return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); + MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_LEN ); #if defined(MBEDTLS_HAVE_TIME) t = (unsigned long) mbedtls_time( NULL ); diff --git a/connectivity/mbedtls/source/ssl_invasive.h b/connectivity/mbedtls/source/ssl_invasive.h new file mode 100644 index 0000000000..babbc2768c --- /dev/null +++ b/connectivity/mbedtls/source/ssl_invasive.h @@ -0,0 +1,100 @@ +/** + * \file ssl_invasive.h + * + * \brief SSL module: interfaces for invasive testing only. + * + * The interfaces in this file are intended for testing purposes only. + * They SHOULD NOT be made available in library integrations except when + * building the library for testing. + */ +/* + * Copyright The Mbed TLS Contributors + * 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 MBEDTLS_SSL_INVASIVE_H +#define MBEDTLS_SSL_INVASIVE_H + +#include "common.h" +#include "mbedtls/md.h" + +#if defined(MBEDTLS_TEST_HOOKS) && \ + defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC) +/** \brief Compute the HMAC of variable-length data with constant flow. + * + * This function computes the HMAC of the concatenation of \p add_data and \p + * data, and does with a code flow and memory access pattern that does not + * depend on \p data_len_secret, but only on \p min_data_len and \p + * max_data_len. In particular, this function always reads exactly \p + * max_data_len bytes from \p data. + * + * \param ctx The HMAC context. It must have keys configured + * with mbedtls_md_hmac_starts() and use one of the + * following hashes: SHA-384, SHA-256, SHA-1 or MD-5. + * It is reset using mbedtls_md_hmac_reset() after + * the computation is complete to prepare for the + * next computation. + * \param add_data The additional data prepended to \p data. This + * must point to a readable buffer of \p add_data_len + * bytes. + * \param add_data_len The length of \p add_data in bytes. + * \param data The data appended to \p add_data. This must point + * to a readable buffer of \p max_data_len bytes. + * \param data_len_secret The length of the data to process in \p data. + * This must be no less than \p min_data_len and no + * greater than \p max_data_len. + * \param min_data_len The minimal length of \p data in bytes. + * \param max_data_len The maximal length of \p data in bytes. + * \param output The HMAC will be written here. This must point to + * a writable buffer of sufficient size to hold the + * HMAC value. + * + * \retval 0 + * Success. + * \retval MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED + * The hardware accelerator failed. + */ +int mbedtls_ssl_cf_hmac( + mbedtls_md_context_t *ctx, + const unsigned char *add_data, size_t add_data_len, + const unsigned char *data, size_t data_len_secret, + size_t min_data_len, size_t max_data_len, + unsigned char *output ); + +/** \brief Copy data from a secret position with constant flow. + * + * This function copies \p len bytes from \p src_base + \p offset_secret to \p + * dst, with a code flow and memory access pattern that does not depend on \p + * offset_secret, but only on \p offset_min, \p offset_max and \p len. + * + * \param dst The destination buffer. This must point to a writable + * buffer of at least \p len bytes. + * \param src_base The base of the source buffer. This must point to a + * readable buffer of at least \p offset_max + \p len + * bytes. + * \param offset_secret The offset in the source buffer from which to copy. + * This must be no less than \p offset_min and no greater + * than \p offset_max. + * \param offset_min The minimal value of \p offset_secret. + * \param offset_max The maximal value of \p offset_secret. + * \param len The number of bytes to copy. + */ +void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst, + const unsigned char *src_base, + size_t offset_secret, + size_t offset_min, size_t offset_max, + size_t len ); +#endif /* MBEDTLS_TEST_HOOKS && MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */ + +#endif /* MBEDTLS_SSL_INVASIVE_H */ diff --git a/connectivity/mbedtls/source/ssl_msg.c b/connectivity/mbedtls/source/ssl_msg.c index 976fc7b00b..2ea35808ad 100644 --- a/connectivity/mbedtls/source/ssl_msg.c +++ b/connectivity/mbedtls/source/ssl_msg.c @@ -2,7 +2,7 @@ * Generic SSL/TLS messaging layer functions * (record layer + retransmission state machine) * - * Copyright (C) 2006-2020, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -16,8 +16,6 @@ * 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) */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, @@ -28,11 +26,7 @@ * http://www.ietf.org/rfc/rfc4346.txt */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SSL_TLS_C) @@ -51,6 +45,8 @@ #include "mbedtls/platform_util.h" #include "mbedtls/version.h" +#include "ssl_invasive.h" + #include #if defined(MBEDTLS_USE_PSA_CRYPTO) @@ -316,40 +312,29 @@ int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ -/* The function below is only used in the Lucky 13 counter-measure in - * mbedtls_ssl_decrypt_buf(). These are the defines that guard the call site. */ -#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) && \ - ( defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) ) -/* This function makes sure every byte in the memory region is accessed - * (in ascending addresses order) */ -static void ssl_read_memory( unsigned char *p, size_t len ) -{ - unsigned char acc = 0; - volatile unsigned char force; - - for( ; len != 0; p++, len-- ) - acc ^= *p; - - force = acc; - (void) force; -} -#endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */ - /* * Encryption/decryption functions */ -#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) -/* This functions transforms a DTLS plaintext fragment and a record content - * type into an instance of the DTLSInnerPlaintext structure: +#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + +static size_t ssl_compute_padding_length( size_t len, + size_t granularity ) +{ + return( ( granularity - ( len + 1 ) % granularity ) % granularity ); +} + +/* This functions transforms a (D)TLS plaintext fragment and a record content + * type into an instance of the (D)TLSInnerPlaintext structure. This is used + * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect + * a record's content type. * * struct { * opaque content[DTLSPlaintext.length]; * ContentType real_type; * uint8 zeros[length_of_padding]; - * } DTLSInnerPlaintext; + * } (D)TLSInnerPlaintext; * * Input: * - `content`: The beginning of the buffer holding the @@ -360,23 +345,21 @@ static void ssl_read_memory( unsigned char *p, size_t len ) * - `rec_type`: The desired record content type. * * Output: - * - `content`: The beginning of the resulting DTLSInnerPlaintext structure. - * - `*content_size`: The length of the resulting DTLSInnerPlaintext structure. + * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure. + * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure. * * Returns: * - `0` on success. * - A negative error code if `max_len` didn't offer enough space * for the expansion. */ -static int ssl_cid_build_inner_plaintext( unsigned char *content, - size_t *content_size, - size_t remaining, - uint8_t rec_type ) +static int ssl_build_inner_plaintext( unsigned char *content, + size_t *content_size, + size_t remaining, + uint8_t rec_type, + size_t pad ) { size_t len = *content_size; - size_t pad = ( MBEDTLS_SSL_CID_PADDING_GRANULARITY - - ( len + 1 ) % MBEDTLS_SSL_CID_PADDING_GRANULARITY ) % - MBEDTLS_SSL_CID_PADDING_GRANULARITY; /* Write real content type */ if( remaining == 0 ) @@ -395,9 +378,9 @@ static int ssl_cid_build_inner_plaintext( unsigned char *content, return( 0 ); } -/* This function parses a DTLSInnerPlaintext structure. - * See ssl_cid_build_inner_plaintext() for details. */ -static int ssl_cid_parse_inner_plaintext( unsigned char const *content, +/* This function parses a (D)TLSInnerPlaintext structure. + * See ssl_build_inner_plaintext() for details. */ +static int ssl_parse_inner_plaintext( unsigned char const *content, size_t *content_size, uint8_t *rec_type ) { @@ -416,13 +399,15 @@ static int ssl_cid_parse_inner_plaintext( unsigned char const *content, return( 0 ); } -#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ +#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || + MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ /* `add_data` must have size 13 Bytes if the CID extension is disabled, * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */ static void ssl_extract_add_data_from_record( unsigned char* add_data, size_t *add_data_len, - mbedtls_record *rec ) + mbedtls_record *rec, + unsigned minor_ver ) { /* Quoting RFC 5246 (TLS 1.2): * @@ -438,28 +423,50 @@ static void ssl_extract_add_data_from_record( unsigned char* add_data, * cid + * cid_length + * length_of_DTLSInnerPlaintext; + * + * For TLS 1.3, the record sequence number is dropped from the AAD + * and encoded within the nonce of the AEAD operation instead. */ - memcpy( add_data, rec->ctr, sizeof( rec->ctr ) ); - add_data[8] = rec->type; - memcpy( add_data + 9, rec->ver, sizeof( rec->ver ) ); + unsigned char *cur = add_data; + +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 ) +#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ + { + ((void) minor_ver); + memcpy( cur, rec->ctr, sizeof( rec->ctr ) ); + cur += sizeof( rec->ctr ); + } + + *cur = rec->type; + cur++; + + memcpy( cur, rec->ver, sizeof( rec->ver ) ); + cur += sizeof( rec->ver ); #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { - memcpy( add_data + 11, rec->cid, rec->cid_len ); - add_data[11 + rec->cid_len + 0] = rec->cid_len; - add_data[11 + rec->cid_len + 1] = ( rec->data_len >> 8 ) & 0xFF; - add_data[11 + rec->cid_len + 2] = ( rec->data_len >> 0 ) & 0xFF; - *add_data_len = 13 + 1 + rec->cid_len; + memcpy( cur, rec->cid, rec->cid_len ); + cur += rec->cid_len; + + *cur = rec->cid_len; + cur++; + + cur[0] = ( rec->data_len >> 8 ) & 0xFF; + cur[1] = ( rec->data_len >> 0 ) & 0xFF; + cur += 2; } else #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ { - add_data[11 + 0] = ( rec->data_len >> 8 ) & 0xFF; - add_data[11 + 1] = ( rec->data_len >> 0 ) & 0xFF; - *add_data_len = 13; + cur[0] = ( rec->data_len >> 8 ) & 0xFF; + cur[1] = ( rec->data_len >> 0 ) & 0xFF; + cur += 2; } + + *add_data_len = cur - add_data; } #if defined(MBEDTLS_SSL_PROTO_SSL3) @@ -509,6 +516,57 @@ static void ssl_mac( mbedtls_md_context_t *md_ctx, } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ +#if defined(MBEDTLS_GCM_C) || \ + defined(MBEDTLS_CCM_C) || \ + defined(MBEDTLS_CHACHAPOLY_C) +static int ssl_transform_aead_dynamic_iv_is_explicit( + mbedtls_ssl_transform const *transform ) +{ + return( transform->ivlen != transform->fixed_ivlen ); +} + +/* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV ) + * + * Concretely, this occurs in two variants: + * + * a) Fixed and dynamic IV lengths add up to total IV length, giving + * IV = fixed_iv || dynamic_iv + * + * This variant is used in TLS 1.2 when used with GCM or CCM. + * + * b) Fixed IV lengths matches total IV length, giving + * IV = fixed_iv XOR ( 0 || dynamic_iv ) + * + * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly. + * + * See also the documentation of mbedtls_ssl_transform. + * + * This function has the precondition that + * + * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len ) + * + * which has to be ensured by the caller. If this precondition + * violated, the behavior of this function is undefined. + */ +static void ssl_build_record_nonce( unsigned char *dst_iv, + size_t dst_iv_len, + unsigned char const *fixed_iv, + size_t fixed_iv_len, + unsigned char const *dynamic_iv, + size_t dynamic_iv_len ) +{ + size_t i; + + /* Start with Fixed IV || 0 */ + memset( dst_iv, 0, dst_iv_len ); + memcpy( dst_iv, fixed_iv, fixed_iv_len ); + + dst_iv += dst_iv_len - dynamic_iv_len; + for( i = 0; i < dynamic_iv_len; i++ ) + dst_iv[i] ^= dynamic_iv[i]; +} +#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ + int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec, @@ -530,10 +588,7 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, /* The PRNG is used for dynamic IV generation that's used * for CBC transformations in TLS 1.1 and TLS 1.2. */ -#if !( defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || \ - defined(MBEDTLS_ARIA_C) || \ - defined(MBEDTLS_CAMELLIA_C) ) && \ +#if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) ) ((void) f_rng); ((void) p_rng); @@ -574,6 +629,37 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } + /* The following two code paths implement the (D)TLSInnerPlaintext + * structure present in TLS 1.3 and DTLS 1.2 + CID. + * + * See ssl_build_inner_plaintext() for more information. + * + * Note that this changes `rec->data_len`, and hence + * `post_avail` needs to be recalculated afterwards. + * + * Note also that the two code paths cannot occur simultaneously + * since they apply to different versions of the protocol. There + * is hence no risk of double-addition of the inner plaintext. + */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) + { + size_t padding = + ssl_compute_padding_length( rec->data_len, + MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY ); + if( ssl_build_inner_plaintext( data, + &rec->data_len, + post_avail, + rec->type, + padding ) != 0 ) + { + return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); + } + + rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA; + } +#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ + #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) /* * Add CID information @@ -584,17 +670,21 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, if( rec->cid_len != 0 ) { + size_t padding = + ssl_compute_padding_length( rec->data_len, + MBEDTLS_SSL_CID_PADDING_GRANULARITY ); /* * Wrap plaintext into DTLSInnerPlaintext structure. - * See ssl_cid_build_inner_plaintext() for more information. + * See ssl_build_inner_plaintext() for more information. * * Note that this changes `rec->data_len`, and hence * `post_avail` needs to be recalculated afterwards. */ - if( ssl_cid_build_inner_plaintext( data, + if( ssl_build_inner_plaintext( data, &rec->data_len, post_avail, - rec->type ) != 0 ) + rec->type, + padding ) != 0 ) { return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } @@ -638,7 +728,8 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, { unsigned char mac[MBEDTLS_SSL_MAC_ADD]; - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + ssl_extract_add_data_from_record( add_data, &add_data_len, rec, + transform->minor_ver ); mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, add_data_len ); @@ -704,52 +795,51 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char iv[12]; - size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen; + unsigned char *dynamic_iv; + size_t dynamic_iv_len; + int dynamic_iv_is_explicit = + ssl_transform_aead_dynamic_iv_is_explicit( transform ); - /* Check that there's space for both the authentication tag - * and the explicit IV before and after the record content. */ - if( post_avail < transform->taglen || - rec->data_offset < explicit_iv_len ) + /* Check that there's space for the authentication tag. */ + if( post_avail < transform->taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } /* - * Generate IV + * Build nonce for AEAD encryption. + * + * Note: In the case of CCM and GCM in TLS 1.2, the dynamic + * part of the IV is prepended to the ciphertext and + * can be chosen freely - in particular, it need not + * agree with the record sequence number. + * However, since ChaChaPoly as well as all AEAD modes + * in TLS 1.3 use the record sequence number as the + * dynamic part of the nonce, we uniformly use the + * record sequence number here in all cases. */ - if( transform->ivlen == 12 && transform->fixed_ivlen == 4 ) - { - /* GCM and CCM: fixed || explicit (=seqnum) */ - memcpy( iv, transform->iv_enc, transform->fixed_ivlen ); - memcpy( iv + transform->fixed_ivlen, rec->ctr, - explicit_iv_len ); - /* Prefix record content with explicit IV. */ - memcpy( data - explicit_iv_len, rec->ctr, explicit_iv_len ); - } - else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 ) - { - /* ChachaPoly: fixed XOR sequence number */ - unsigned char i; + dynamic_iv = rec->ctr; + dynamic_iv_len = sizeof( rec->ctr ); - memcpy( iv, transform->iv_enc, transform->fixed_ivlen ); + ssl_build_record_nonce( iv, sizeof( iv ), + transform->iv_enc, + transform->fixed_ivlen, + dynamic_iv, + dynamic_iv_len ); - for( i = 0; i < 8; i++ ) - iv[i+4] ^= rec->ctr[i]; - } - else - { - /* Reminder if we ever add an AEAD mode with a different size */ - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + /* + * Build additional data for AEAD encryption. + * This depends on the TLS version. + */ + ssl_extract_add_data_from_record( add_data, &add_data_len, rec, + transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)", - iv, transform->ivlen ); + iv, transform->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)", - data - explicit_iv_len, explicit_iv_len ); + dynamic_iv, + dynamic_iv_is_explicit ? dynamic_iv_len : 0 ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " @@ -770,19 +860,33 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); return( ret ); } - MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", data + rec->data_len, transform->taglen ); - - rec->data_len += transform->taglen + explicit_iv_len; - rec->data_offset -= explicit_iv_len; + /* Account for authentication tag. */ + rec->data_len += transform->taglen; post_avail -= transform->taglen; + + /* + * Prefix record content with dynamic IV in case it is explicit. + */ + if( dynamic_iv_is_explicit != 0 ) + { + if( rec->data_offset < dynamic_iv_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); + return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); + } + + memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len ); + rec->data_offset -= dynamic_iv_len; + rec->data_len += dynamic_iv_len; + } + auth_done++; } else -#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ -#if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) ) +#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ +#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; @@ -898,7 +1002,8 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + ssl_extract_add_data_from_record( add_data, &add_data_len, + rec, transform->minor_ver ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, @@ -920,8 +1025,7 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ } else -#endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */ +#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); @@ -939,6 +1043,156 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, return( 0 ); } +#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC) +/* + * Constant-flow conditional memcpy: + * - if c1 == c2, equivalent to memcpy(dst, src, len), + * - otherwise, a no-op, + * but with execution flow independent of the values of c1 and c2. + * + * Use only bit operations to avoid branches that could be used by some + * compilers on some platforms to translate comparison operators. + */ +static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst, + const unsigned char *src, + size_t len, + size_t c1, size_t c2 ) +{ + /* diff = 0 if c1 == c2, non-zero otherwise */ + const size_t diff = c1 ^ c2; + + /* MSVC has a warning about unary minus on unsigned integer types, + * but this is well-defined and precisely what we want to do here. */ +#if defined(_MSC_VER) +#pragma warning( push ) +#pragma warning( disable : 4146 ) +#endif + + /* diff_msb's most significant bit is equal to c1 != c2 */ + const size_t diff_msb = ( diff | -diff ); + + /* diff1 = c1 != c2 */ + const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 ); + + /* mask = c1 != c2 ? 0xff : 0x00 */ + const unsigned char mask = (unsigned char) -diff1; + +#if defined(_MSC_VER) +#pragma warning( pop ) +#endif + + /* dst[i] = c1 != c2 ? dst[i] : src[i] */ + for( size_t i = 0; i < len; i++ ) + dst[i] = ( dst[i] & mask ) | ( src[i] & ~mask ); +} + +/* + * Compute HMAC of variable-length data with constant flow. + * + * Only works with MD-5, SHA-1, SHA-256 and SHA-384. + * (Otherwise, computation of block_size needs to be adapted.) + */ +MBEDTLS_STATIC_TESTABLE int mbedtls_ssl_cf_hmac( + mbedtls_md_context_t *ctx, + const unsigned char *add_data, size_t add_data_len, + const unsigned char *data, size_t data_len_secret, + size_t min_data_len, size_t max_data_len, + unsigned char *output ) +{ + /* + * This function breaks the HMAC abstraction and uses the md_clone() + * extension to the MD API in order to get constant-flow behaviour. + * + * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means + * concatenation, and okey/ikey are the XOR of the key with some fixed bit + * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx. + * + * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to + * minlen, then cloning the context, and for each byte up to maxlen + * finishing up the hash computation, keeping only the correct result. + * + * Then we only need to compute HASH(okey + inner_hash) and we're done. + */ + const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info ); + /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5, + * all of which have the same block size except SHA-384. */ + const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64; + const unsigned char * const ikey = ctx->hmac_ctx; + const unsigned char * const okey = ikey + block_size; + const size_t hash_size = mbedtls_md_get_size( ctx->md_info ); + + unsigned char aux_out[MBEDTLS_MD_MAX_SIZE]; + mbedtls_md_context_t aux; + size_t offset; + int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + + mbedtls_md_init( &aux ); + +#define MD_CHK( func_call ) \ + do { \ + ret = (func_call); \ + if( ret != 0 ) \ + goto cleanup; \ + } while( 0 ) + + MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) ); + + /* After hmac_start() of hmac_reset(), ikey has already been hashed, + * so we can start directly with the message */ + MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) ); + MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) ); + + /* For each possible length, compute the hash up to that point */ + for( offset = min_data_len; offset <= max_data_len; offset++ ) + { + MD_CHK( mbedtls_md_clone( &aux, ctx ) ); + MD_CHK( mbedtls_md_finish( &aux, aux_out ) ); + /* Keep only the correct inner_hash in the output buffer */ + mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size, + offset, data_len_secret ); + + if( offset < max_data_len ) + MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) ); + } + + /* Now compute HASH(okey + inner_hash) */ + MD_CHK( mbedtls_md_starts( ctx ) ); + MD_CHK( mbedtls_md_update( ctx, okey, block_size ) ); + MD_CHK( mbedtls_md_update( ctx, output, hash_size ) ); + MD_CHK( mbedtls_md_finish( ctx, output ) ); + + /* Done, get ready for next time */ + MD_CHK( mbedtls_md_hmac_reset( ctx ) ); + +#undef MD_CHK + +cleanup: + mbedtls_md_free( &aux ); + return( ret ); +} + +/* + * Constant-flow memcpy from variable position in buffer. + * - functionally equivalent to memcpy(dst, src + offset_secret, len) + * - but with execution flow independent from the value of offset_secret. + */ +MBEDTLS_STATIC_TESTABLE void mbedtls_ssl_cf_memcpy_offset( + unsigned char *dst, + const unsigned char *src_base, + size_t offset_secret, + size_t offset_min, size_t offset_max, + size_t len ) +{ + size_t offset; + + for( offset = offset_min; offset <= offset_max; offset++ ) + { + mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len, + offset, offset_secret ); + } +} +#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */ + int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, mbedtls_ssl_transform *transform, mbedtls_record *rec ) @@ -1012,61 +1266,61 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, mode == MBEDTLS_MODE_CHACHAPOLY ) { unsigned char iv[12]; - size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen; + unsigned char *dynamic_iv; + size_t dynamic_iv_len; /* - * Prepare IV from explicit and implicit data. + * Extract dynamic part of nonce for AEAD decryption. + * + * Note: In the case of CCM and GCM in TLS 1.2, the dynamic + * part of the IV is prepended to the ciphertext and + * can be chosen freely - in particular, it need not + * agree with the record sequence number. */ - - /* Check that there's enough space for the explicit IV - * (at the beginning of the record) and the MAC (at the - * end of the record). */ - if( rec->data_len < explicit_iv_len + transform->taglen ) + dynamic_iv_len = sizeof( rec->ctr ); + if( ssl_transform_aead_dynamic_iv_is_explicit( transform ) == 1 ) { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) " - "+ taglen (%d)", rec->data_len, - explicit_iv_len, transform->taglen ) ); + if( rec->data_len < dynamic_iv_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) ", + rec->data_len, + dynamic_iv_len ) ); + return( MBEDTLS_ERR_SSL_INVALID_MAC ); + } + dynamic_iv = data; + + data += dynamic_iv_len; + rec->data_offset += dynamic_iv_len; + rec->data_len -= dynamic_iv_len; + } + else + { + dynamic_iv = rec->ctr; + } + + /* Check that there's space for the authentication tag. */ + if( rec->data_len < transform->taglen ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < taglen (%d) " ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } + rec->data_len -= transform->taglen; -#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) - if( transform->ivlen == 12 && transform->fixed_ivlen == 4 ) - { - /* GCM and CCM: fixed || explicit */ + /* + * Prepare nonce from dynamic and static parts. + */ + ssl_build_record_nonce( iv, sizeof( iv ), + transform->iv_dec, + transform->fixed_ivlen, + dynamic_iv, + dynamic_iv_len ); - /* Fixed */ - memcpy( iv, transform->iv_dec, transform->fixed_ivlen ); - /* Explicit */ - memcpy( iv + transform->fixed_ivlen, data, 8 ); - } - else -#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ -#if defined(MBEDTLS_CHACHAPOLY_C) - if( transform->ivlen == 12 && transform->fixed_ivlen == 12 ) - { - /* ChachaPoly: fixed XOR sequence number */ - unsigned char i; - - memcpy( iv, transform->iv_dec, transform->fixed_ivlen ); - - for( i = 0; i < 8; i++ ) - iv[i+4] ^= rec->ctr[i]; - } - else -#endif /* MBEDTLS_CHACHAPOLY_C */ - { - /* Reminder if we ever add an AEAD mode with a different size */ - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - /* Group changes to data, data_len, and add_data, because - * add_data depends on data_len. */ - data += explicit_iv_len; - rec->data_offset += explicit_iv_len; - rec->data_len -= explicit_iv_len + transform->taglen; - - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + /* + * Build additional data for AEAD encryption. + * This depends on the TLS version. + */ + ssl_extract_add_data_from_record( add_data, &add_data_len, rec, + transform->minor_ver ); MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, add_data_len ); @@ -1109,8 +1363,7 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ -#if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) ) +#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) if( mode == MBEDTLS_MODE_CBC ) { size_t minlen = 0; @@ -1178,7 +1431,8 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, * * Further, we still know that data_len > minlen */ rec->data_len -= transform->maclen; - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + ssl_extract_add_data_from_record( add_data, &add_data_len, rec, + transform->minor_ver ); /* Calculate expected MAC. */ MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, @@ -1362,8 +1616,7 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, rec->data_len -= padlen; } else -#endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */ +#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); @@ -1382,6 +1635,7 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, if( auth_done == 0 ) { unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; + unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD]; /* If the initial value of padlen was such that * data_len < maclen + padlen + 1, then padlen @@ -1397,7 +1651,8 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, * hence data_len >= maclen in any case. */ rec->data_len -= transform->maclen; - ssl_extract_add_data_from_record( add_data, &add_data_len, rec ); + ssl_extract_add_data_from_record( add_data, &add_data_len, rec, + transform->minor_ver ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) @@ -1407,6 +1662,7 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, data, rec->data_len, rec->ctr, rec->type, mac_expect ); + memcpy( mac_peer, data + rec->data_len, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ @@ -1414,39 +1670,9 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, defined(MBEDTLS_SSL_PROTO_TLS1_2) if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { - /* - * Process MAC and always update for padlen afterwards to make - * total time independent of padlen. - * - * Known timing attacks: - * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf) - * - * To compensate for different timings for the MAC calculation - * depending on how much padding was removed (which is determined - * by padlen), process extra_run more blocks through the hash - * function. - * - * The formula in the paper is - * extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 ) - * where L1 is the size of the header plus the decrypted message - * plus CBC padding and L2 is the size of the header plus the - * decrypted message. This is for an underlying hash function - * with 64-byte blocks. - * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values - * correctly. We round down instead of up, so -56 is the correct - * value for our calculations instead of -55. - * - * Repeat the formula rather than defining a block_size variable. - * This avoids requiring division by a variable at runtime - * (which would be marginally less efficient and would require - * linking an extra division function in some builds). - */ - size_t j, extra_run = 0; - unsigned char tmp[MBEDTLS_MD_MAX_BLOCK_SIZE]; - /* * The next two sizes are the minimum and maximum values of - * in_msglen over all padlen values. + * data_len over all padlen values. * * They're independent of padlen, since we previously did * data_len -= padlen. @@ -1457,59 +1683,20 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, const size_t max_len = rec->data_len + padlen; const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0; - memset( tmp, 0, sizeof( tmp ) ); - - switch( mbedtls_md_get_type( transform->md_ctx_dec.md_info ) ) + ret = mbedtls_ssl_cf_hmac( &transform->md_ctx_dec, + add_data, add_data_len, + data, rec->data_len, min_len, max_len, + mac_expect ); + if( ret != 0 ) { -#if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \ - defined(MBEDTLS_SHA256_C) - case MBEDTLS_MD_MD5: - case MBEDTLS_MD_SHA1: - case MBEDTLS_MD_SHA256: - /* 8 bytes of message size, 64-byte compression blocks */ - extra_run = - ( add_data_len + rec->data_len + padlen + 8 ) / 64 - - ( add_data_len + rec->data_len + 8 ) / 64; - break; -#endif -#if defined(MBEDTLS_SHA512_C) - case MBEDTLS_MD_SHA384: - /* 16 bytes of message size, 128-byte compression blocks */ - extra_run = - ( add_data_len + rec->data_len + padlen + 16 ) / 128 - - ( add_data_len + rec->data_len + 16 ) / 128; - break; -#endif - default: - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); + MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret ); + return( ret ); } - extra_run &= correct * 0xFF; - - mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data, - add_data_len ); - mbedtls_md_hmac_update( &transform->md_ctx_dec, data, - rec->data_len ); - /* Make sure we access everything even when padlen > 0. This - * makes the synchronisation requirements for just-in-time - * Prime+Probe attacks much tighter and hopefully impractical. */ - ssl_read_memory( data + rec->data_len, padlen ); - mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect ); - - /* Call mbedtls_md_process at least once due to cache attacks - * that observe whether md_process() was called of not */ - for( j = 0; j < extra_run + 1; j++ ) - mbedtls_md_process( &transform->md_ctx_dec, tmp ); - - mbedtls_md_hmac_reset( &transform->md_ctx_dec ); - - /* Make sure we access all the memory that could contain the MAC, - * before we check it in the next code block. This makes the - * synchronisation requirements for just-in-time Prime+Probe - * attacks much tighter and hopefully impractical. */ - ssl_read_memory( data + min_len, - max_len - min_len + transform->maclen ); + mbedtls_ssl_cf_memcpy_offset( mac_peer, data, + rec->data_len, + min_len, max_len, + transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ @@ -1521,10 +1708,10 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); - MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", data + rec->data_len, transform->maclen ); + MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, transform->maclen ); #endif - if( mbedtls_ssl_safer_memcmp( data + rec->data_len, mac_expect, + if( mbedtls_ssl_safer_memcmp( mac_peer, mac_expect, transform->maclen ) != 0 ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) @@ -1549,11 +1736,23 @@ int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) + { + /* Remove inner padding and infer true content type. */ + ret = ssl_parse_inner_plaintext( data, &rec->data_len, + &rec->type ); + + if( ret != 0 ) + return( MBEDTLS_ERR_SSL_INVALID_RECORD ); + } +#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ + #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) if( rec->cid_len != 0 ) { - ret = ssl_cid_parse_inner_plaintext( data, &rec->data_len, - &rec->type ); + ret = ssl_parse_inner_plaintext( data, &rec->data_len, + &rec->type ); if( ret != 0 ) return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } @@ -1897,7 +2096,7 @@ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) if( ret < 0 ) return( ret ); - if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) ) + if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_recv returned %d bytes but only %lu were requested", @@ -1951,7 +2150,7 @@ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) if( ret <= 0 ) return( ret ); - if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) ) + if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "f_send returned %d bytes but only %lu bytes were sent", @@ -4866,6 +5065,15 @@ int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) * and the caller has to make sure there's space for this. */ +static size_t ssl_transform_get_explicit_iv_len( + mbedtls_ssl_transform const *transform ) +{ + if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) + return( 0 ); + + return( transform->ivlen - transform->fixed_ivlen ); +} + void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, mbedtls_ssl_transform *transform ) { @@ -4894,14 +5102,10 @@ void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, ssl->out_iv = ssl->out_hdr + 5; } + ssl->out_msg = ssl->out_iv; /* Adjust out_msg to make space for explicit IV, if used. */ - if( transform != NULL && - ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen; - } - else - ssl->out_msg = ssl->out_iv; + if( transform != NULL ) + ssl->out_msg += ssl_transform_get_explicit_iv_len( transform ); } /* Once ssl->in_hdr as the address of the beginning of the @@ -5425,6 +5629,10 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) memcpy( buf, ssl->in_offt, n ); ssl->in_msglen -= n; + /* Zeroising the plaintext buffer to erase unused application data + from the memory. */ + mbedtls_platform_zeroize( ssl->in_offt, n ); + if( ssl->in_msglen == 0 ) { /* all bytes consumed */ diff --git a/connectivity/mbedtls/source/ssl_srv.c b/connectivity/mbedtls/source/ssl_srv.c index 006bc69c30..2e63fced35 100644 --- a/connectivity/mbedtls/source/ssl_srv.c +++ b/connectivity/mbedtls/source/ssl_srv.c @@ -1,7 +1,7 @@ /* * SSLv3/TLSv1 server-side functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_SSL_SRV_C) @@ -933,7 +927,8 @@ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } - MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %s", suite_info->name ) ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %#04x (%s)", + suite_id, suite_info->name ) ); if( suite_info->min_minor_ver > ssl->minor_ver || suite_info->max_minor_ver < ssl->minor_ver ) @@ -2841,7 +2836,7 @@ static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; - size_t dn_size, total_dn_size; /* excluding length bytes */ + uint16_t dn_size, total_dn_size; /* excluding length bytes */ size_t ct_len, sa_len; /* including length bytes */ unsigned char *buf, *p; const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; @@ -2969,11 +2964,11 @@ static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) while( crt != NULL && crt->version != 0 ) { - dn_size = crt->subject_raw.len; + /* It follows from RFC 5280 A.1 that this length + * can be represented in at most 11 bits. */ + dn_size = (uint16_t) crt->subject_raw.len; - if( end < p || - (size_t)( end - p ) < dn_size || - (size_t)( end - p ) < 2 + dn_size ) + if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) ); break; diff --git a/connectivity/mbedtls/source/ssl_ticket.c b/connectivity/mbedtls/source/ssl_ticket.c index 8a76b42b6b..e3e802315a 100644 --- a/connectivity/mbedtls/source/ssl_ticket.c +++ b/connectivity/mbedtls/source/ssl_ticket.c @@ -1,7 +1,7 @@ /* * TLS server tickets callbacks implementation * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_SSL_TICKET_C) @@ -35,6 +29,7 @@ #define mbedtls_free free #endif +#include "mbedtls/ssl_internal.h" #include "mbedtls/ssl_ticket.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" @@ -224,8 +219,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 < TICKET_MIN_LEN ) - return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); + MBEDTLS_SSL_CHK_BUF_PTR( start, end, TICKET_MIN_LEN ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) diff --git a/connectivity/mbedtls/source/ssl_tls.c b/connectivity/mbedtls/source/ssl_tls.c index d0adfd9515..7062d53b78 100644 --- a/connectivity/mbedtls/source/ssl_tls.c +++ b/connectivity/mbedtls/source/ssl_tls.c @@ -1,7 +1,7 @@ /* * SSLv3/TLSv1 shared functions * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, @@ -27,11 +25,7 @@ * http://www.ietf.org/rfc/rfc4346.txt */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_SSL_TLS_C) @@ -863,7 +857,7 @@ static int ssl_populate_transform( mbedtls_ssl_transform *transform, unsigned char *key2; unsigned char *mac_enc; unsigned char *mac_dec; - size_t mac_key_len; + size_t mac_key_len = 0; size_t iv_copy_len; unsigned keylen; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; @@ -973,15 +967,28 @@ static int ssl_populate_transform( mbedtls_ssl_transform *transform, transform->taglen = ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; - /* All modes haves 96-bit IVs; - * GCM and CCM has 4 implicit and 8 explicit bytes - * ChachaPoly has all 12 bytes implicit + /* All modes haves 96-bit IVs, but the length of the static parts vary + * with mode and version: + * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes + * (to be concatenated with a dynamically chosen IV of 8 Bytes) + * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's + * a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record + * sequence number). */ transform->ivlen = 12; - if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) + { transform->fixed_ivlen = 12; + } else - transform->fixed_ivlen = 4; +#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ + { + if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY ) + transform->fixed_ivlen = 12; + else + transform->fixed_ivlen = 4; + } /* Minimum length of encrypted record */ explicit_ivlen = transform->ivlen - transform->fixed_ivlen; @@ -1175,7 +1182,7 @@ static int ssl_populate_transform( mbedtls_ssl_transform *transform, #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_init != NULL ) { - int ret = 0; + ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) ); @@ -1514,9 +1521,7 @@ static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake, MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) ); - psk = ssl->conf->psk_opaque; - if( handshake->psk_opaque != 0 ) - psk = handshake->psk_opaque; + psk = mbedtls_ssl_get_opaque_psk( ssl ); if( hash_alg == MBEDTLS_MD_SHA384 ) alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384); @@ -1850,14 +1855,18 @@ int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exch { unsigned char *p = ssl->handshake->premaster; unsigned char *end = p + sizeof( ssl->handshake->premaster ); - const unsigned char *psk = ssl->conf->psk; - size_t psk_len = ssl->conf->psk_len; + const unsigned char *psk = NULL; + size_t psk_len = 0; - /* If the psk callback was called, use its result */ - if( ssl->handshake->psk != NULL ) + if( mbedtls_ssl_get_psk( ssl, &psk, &psk_len ) + == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ) { - psk = ssl->handshake->psk; - psk_len = ssl->handshake->psk_len; + /* + * This should never happen because the existence of a PSK is always + * checked before calling this function + */ + MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); + return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* @@ -2745,9 +2754,7 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - ret = 0; - else + if( authmode != MBEDTLS_SSL_VERIFY_OPTIONAL ) ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE; goto exit; @@ -3673,11 +3680,13 @@ static int ssl_handshake_init( mbedtls_ssl_context *ssl ) /* If the buffers are too small - reallocate */ { int modified = 0; - size_t written_in = 0; - size_t written_out = 0; + size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0; + size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0; if( ssl->in_buf != NULL ) { written_in = ssl->in_msg - ssl->in_buf; + iv_offset_in = ssl->in_iv - ssl->in_buf; + len_offset_in = ssl->in_len - ssl->in_buf; if( ssl->in_buf_len < MBEDTLS_SSL_IN_BUFFER_LEN ) { if( resize_buffer( &ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN, @@ -3696,6 +3705,8 @@ static int ssl_handshake_init( mbedtls_ssl_context *ssl ) if( ssl->out_buf != NULL ) { written_out = ssl->out_msg - ssl->out_buf; + iv_offset_out = ssl->out_iv - ssl->out_buf; + len_offset_out = ssl->out_len - ssl->out_buf; if( ssl->out_buf_len < MBEDTLS_SSL_OUT_BUFFER_LEN ) { if( resize_buffer( &ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN, @@ -3715,9 +3726,14 @@ static int ssl_handshake_init( mbedtls_ssl_context *ssl ) /* Update pointers here to avoid doing it twice. */ mbedtls_ssl_reset_in_out_pointers( ssl ); /* Fields below might not be properly updated with record - * splitting, so they are manually updated here. */ + * splitting or with CID, so they are manually updated here. */ ssl->out_msg = ssl->out_buf + written_out; + ssl->out_len = ssl->out_buf + len_offset_out; + ssl->out_iv = ssl->out_buf + iv_offset_out; + ssl->in_msg = ssl->in_buf + written_in; + ssl->in_len = ssl->in_buf + len_offset_in; + ssl->in_iv = ssl->in_buf + iv_offset_in; } } #endif @@ -4652,7 +4668,9 @@ int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **prot cur_len = strlen( *p ); tot_len += cur_len; - if( cur_len == 0 || cur_len > 255 || tot_len > 65535 ) + if( ( cur_len == 0 ) || + ( cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN ) || + ( tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN ) ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } @@ -5947,14 +5965,15 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) { int modified = 0; uint32_t buf_len = mbedtls_ssl_get_input_buflen( ssl ); - size_t written_in = 0; - size_t written_out = 0; + size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0; + size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0; if( ssl->in_buf != NULL ) { written_in = ssl->in_msg - ssl->in_buf; + iv_offset_in = ssl->in_iv - ssl->in_buf; + len_offset_in = ssl->in_len - ssl->in_buf; if( ssl->in_buf_len > buf_len && ssl->in_left < buf_len ) { - written_in = ssl->in_msg - ssl->in_buf; if( resize_buffer( &ssl->in_buf, buf_len, &ssl->in_buf_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "input buffer resizing failed - out of memory" ) ); @@ -5972,6 +5991,8 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) if(ssl->out_buf != NULL ) { written_out = ssl->out_msg - ssl->out_buf; + iv_offset_out = ssl->out_iv - ssl->out_buf; + len_offset_out = ssl->out_len - ssl->out_buf; if( ssl->out_buf_len > mbedtls_ssl_get_output_buflen( ssl ) && ssl->out_left < buf_len ) { @@ -5991,9 +6012,14 @@ void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ) /* Update pointers here to avoid doing it twice. */ mbedtls_ssl_reset_in_out_pointers( ssl ); /* Fields below might not be properly updated with record - * splitting, so they are manually updated here. */ + * splitting or with CID, so they are manually updated here. */ ssl->out_msg = ssl->out_buf + written_out; + ssl->out_len = ssl->out_buf + len_offset_out; + ssl->out_iv = ssl->out_buf + iv_offset_out; + ssl->in_msg = ssl->in_buf + written_in; + ssl->in_len = ssl->in_buf + len_offset_in; + ssl->in_iv = ssl->in_buf + iv_offset_in; } } #endif @@ -6661,14 +6687,6 @@ int mbedtls_ssl_context_load( mbedtls_ssl_context *context, */ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) { -#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) - size_t in_buf_len = ssl->in_buf_len; - size_t out_buf_len = ssl->out_buf_len; -#else - size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; - size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; -#endif - if( ssl == NULL ) return; @@ -6676,6 +6694,12 @@ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) if( ssl->out_buf != NULL ) { +#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) + size_t out_buf_len = ssl->out_buf_len; +#else + size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; +#endif + mbedtls_platform_zeroize( ssl->out_buf, out_buf_len ); mbedtls_free( ssl->out_buf ); ssl->out_buf = NULL; @@ -6683,6 +6707,12 @@ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) if( ssl->in_buf != NULL ) { +#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) + size_t in_buf_len = ssl->in_buf_len; +#else + size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; +#endif + mbedtls_platform_zeroize( ssl->in_buf, in_buf_len ); mbedtls_free( ssl->in_buf ); ssl->in_buf = NULL; diff --git a/connectivity/mbedtls/source/threading.c b/connectivity/mbedtls/source/threading.c index 7c90c7c595..9268da1888 100644 --- a/connectivity/mbedtls/source/threading.c +++ b/connectivity/mbedtls/source/threading.c @@ -1,7 +1,7 @@ /* * Threading abstraction layer * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* @@ -27,11 +25,7 @@ #define _POSIX_C_SOURCE 200112L #endif -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_THREADING_C) diff --git a/connectivity/mbedtls/source/timing.c b/connectivity/mbedtls/source/timing.c index 009516a6e3..eb41461320 100644 --- a/connectivity/mbedtls/source/timing.c +++ b/connectivity/mbedtls/source/timing.c @@ -1,7 +1,7 @@ /* * Portable interface to the CPU cycle counter * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" @@ -40,7 +34,7 @@ #if !defined(unix) && !defined(__unix__) && !defined(__unix) && \ !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \ - !defined(__HAIKU__) + !defined(__HAIKU__) && !defined(__midipix__) #error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h" #endif diff --git a/connectivity/mbedtls/source/version.c b/connectivity/mbedtls/source/version.c index fd96750885..32a0d7d584 100644 --- a/connectivity/mbedtls/source/version.c +++ b/connectivity/mbedtls/source/version.c @@ -1,7 +1,7 @@ /* * Version information * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_VERSION_C) diff --git a/connectivity/mbedtls/source/version_features.c b/connectivity/mbedtls/source/version_features.c index d16ad1bacd..d2840fa3cd 100644 --- a/connectivity/mbedtls/source/version_features.c +++ b/connectivity/mbedtls/source/version_features.c @@ -1,7 +1,7 @@ /* * Version feature information * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_VERSION_C) @@ -354,6 +348,9 @@ static const char * const features[] = { #if defined(MBEDTLS_ECP_NIST_OPTIM) "MBEDTLS_ECP_NIST_OPTIM", #endif /* MBEDTLS_ECP_NIST_OPTIM */ +#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG) + "MBEDTLS_ECP_NO_INTERNAL_RNG", +#endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */ #if defined(MBEDTLS_ECP_RESTARTABLE) "MBEDTLS_ECP_RESTARTABLE", #endif /* MBEDTLS_ECP_RESTARTABLE */ @@ -519,6 +516,9 @@ static const char * const features[] = { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) "MBEDTLS_SSL_PROTO_TLS1_2", #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) + "MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL", +#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #if defined(MBEDTLS_SSL_PROTO_DTLS) "MBEDTLS_SSL_PROTO_DTLS", #endif /* MBEDTLS_SSL_PROTO_DTLS */ @@ -555,6 +555,15 @@ static const char * const features[] = { #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) "MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH", #endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */ +#if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) + "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN", +#endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN */ +#if defined(MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND) + "MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND", +#endif /* MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */ +#if defined(MBEDTLS_TEST_HOOKS) + "MBEDTLS_TEST_HOOKS", +#endif /* MBEDTLS_TEST_HOOKS */ #if defined(MBEDTLS_THREADING_ALT) "MBEDTLS_THREADING_ALT", #endif /* MBEDTLS_THREADING_ALT */ diff --git a/connectivity/mbedtls/source/x509.c b/connectivity/mbedtls/source/x509.c index c451332c28..1579c1abca 100644 --- a/connectivity/mbedtls/source/x509.c +++ b/connectivity/mbedtls/source/x509.c @@ -1,7 +1,7 @@ /* * X.509 common functions for parsing and verification * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The ITU-T X.509 standard defines a certificate format for PKI. @@ -29,11 +27,7 @@ * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_USE_C) @@ -787,7 +781,7 @@ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ) break; c = name->val.p[i]; - if( c < 32 || c == 127 || ( c > 128 && c < 160 ) ) + if( c < 32 || c >= 127 ) s[i] = '?'; else s[i] = c; } @@ -870,7 +864,7 @@ int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *s ret = mbedtls_snprintf( p, n, " (%s, MGF1-%s, 0x%02X)", md_info ? mbedtls_md_get_name( md_info ) : "???", mgf_md_info ? mbedtls_md_get_name( mgf_md_info ) : "???", - pss_opts->expected_salt_len ); + (unsigned int) pss_opts->expected_salt_len ); MBEDTLS_X509_SAFE_SNPRINTF; } #else diff --git a/connectivity/mbedtls/source/x509_create.c b/connectivity/mbedtls/source/x509_create.c index 7df2f0ed56..056bbaa786 100644 --- a/connectivity/mbedtls/source/x509_create.c +++ b/connectivity/mbedtls/source/x509_create.c @@ -1,7 +1,7 @@ /* * X.509 base functions for creating certificates / CSRs * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_X509_CREATE_C) diff --git a/connectivity/mbedtls/source/x509_crl.c b/connectivity/mbedtls/source/x509_crl.c index 371c446be5..edeb39b02d 100644 --- a/connectivity/mbedtls/source/x509_crl.c +++ b/connectivity/mbedtls/source/x509_crl.c @@ -1,7 +1,7 @@ /* * X.509 Certidicate Revocation List (CRL) parsing * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The ITU-T X.509 standard defines a certificate format for PKI. @@ -29,11 +27,7 @@ * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_CRL_PARSE_C) @@ -259,13 +253,13 @@ static int x509_get_entries( unsigned char **p, size_t len2; const unsigned char *end2; + cur_entry->raw.tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &len2, MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ) ) != 0 ) { return( ret ); } - cur_entry->raw.tag = **p; cur_entry->raw.p = *p; cur_entry->raw.len = len2; end2 = *p + len2; diff --git a/connectivity/mbedtls/source/x509_crt.c b/connectivity/mbedtls/source/x509_crt.c index 1e472303b1..71e9cec372 100644 --- a/connectivity/mbedtls/source/x509_crt.c +++ b/connectivity/mbedtls/source/x509_crt.c @@ -1,7 +1,7 @@ /* * X.509 certificate parsing and verification * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The ITU-T X.509 standard defines a certificate format for PKI. @@ -31,11 +29,7 @@ * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_CRT_PARSE_C) @@ -524,6 +518,12 @@ static int x509_get_basic_constraints( unsigned char **p, return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); + /* Do not accept max_pathlen equal to INT_MAX to avoid a signed integer + * overflow, which is an undefined behavior. */ + if( *max_pathlen == INT_MAX ) + return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); + (*max_pathlen)++; return( 0 ); @@ -646,10 +646,6 @@ static int x509_get_subject_alt_name( unsigned char **p, mbedtls_x509_subject_alternative_name dummy_san_buf; memset( &dummy_san_buf, 0, sizeof( dummy_san_buf ) ); - if( ( end - *p ) < 1 ) - return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + - MBEDTLS_ERR_ASN1_OUT_OF_DATA ); - tag = **p; (*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 ) @@ -663,7 +659,7 @@ static int x509_get_subject_alt_name( unsigned char **p, } /* - * Check that the SAN are structured correct. + * Check that the SAN is structured correctly. */ ret = mbedtls_x509_parse_subject_alt_name( &(cur->buf), &dummy_san_buf ); /* @@ -886,11 +882,13 @@ static int x509_get_certificate_policies( unsigned char **p, */ static int x509_get_crt_ext( unsigned char **p, const unsigned char *end, - mbedtls_x509_crt *crt ) + mbedtls_x509_crt *crt, + mbedtls_x509_crt_ext_cb_t cb, + void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; - unsigned char *end_ext_data, *end_ext_octet; + unsigned char *end_ext_data, *start_ext_octet, *end_ext_octet; if( *p == end ) return( 0 ); @@ -936,6 +934,7 @@ static int x509_get_crt_ext( unsigned char **p, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); + start_ext_octet = *p; end_ext_octet = *p + len; if( end_ext_octet != end_ext_data ) @@ -949,6 +948,16 @@ static int x509_get_crt_ext( unsigned char **p, if( ret != 0 ) { + /* Give the callback (if any) a chance to handle the extension */ + if( cb != NULL ) + { + ret = cb( p_ctx, crt, &extn_oid, is_critical, *p, end_ext_octet ); + if( ret != 0 && is_critical ) + return( ret ); + *p = end_ext_octet; + continue; + } + /* No parser found, skip extension */ *p = end_ext_octet; @@ -1011,6 +1020,13 @@ static int x509_get_crt_ext( unsigned char **p, if( ( ret = x509_get_certificate_policies( p, end_ext_octet, &crt->certificate_policies ) ) != 0 ) { + /* Give the callback (if any) a chance to handle the extension + * if it contains unsupported policies */ + if( ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE && cb != NULL && + cb( p_ctx, crt, &extn_oid, is_critical, + start_ext_octet, end_ext_octet ) == 0 ) + break; + #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) return( ret ); @@ -1055,7 +1071,9 @@ static int x509_get_crt_ext( unsigned char **p, static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf, size_t buflen, - int make_copy ) + int make_copy, + mbedtls_x509_crt_ext_cb_t cb, + void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len; @@ -1254,7 +1272,7 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, if( crt->version == 3 ) #endif { - ret = x509_get_crt_ext( &p, end, crt ); + ret = x509_get_crt_ext( &p, end, crt, cb, p_ctx ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); @@ -1317,7 +1335,9 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, static int mbedtls_x509_crt_parse_der_internal( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen, - int make_copy ) + int make_copy, + mbedtls_x509_crt_ext_cb_t cb, + void *p_ctx ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_x509_crt *crt = chain, *prev = NULL; @@ -1349,7 +1369,8 @@ static int mbedtls_x509_crt_parse_der_internal( mbedtls_x509_crt *chain, crt = crt->next; } - if( ( ret = x509_crt_parse_der_core( crt, buf, buflen, make_copy ) ) != 0 ) + ret = x509_crt_parse_der_core( crt, buf, buflen, make_copy, cb, p_ctx ); + if( ret != 0 ) { if( prev ) prev->next = NULL; @@ -1367,14 +1388,24 @@ int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { - return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 0 ) ); + return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 0, NULL, NULL ) ); +} + +int mbedtls_x509_crt_parse_der_with_ext_cb( mbedtls_x509_crt *chain, + const unsigned char *buf, + size_t buflen, + int make_copy, + mbedtls_x509_crt_ext_cb_t cb, + void *p_ctx ) +{ + return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, make_copy, cb, p_ctx ) ); } int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { - return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 1 ) ); + return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 1, NULL, NULL ) ); } /* @@ -2291,8 +2322,7 @@ int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509 if( crt->serial.len == cur->serial.len && memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 ) { - if( mbedtls_x509_time_is_past( &cur->revocation_date ) ) - return( 1 ); + return( 1 ); } cur = cur->next; @@ -2974,6 +3004,25 @@ static int x509_crt_check_cn( const mbedtls_x509_buf *name, return( -1 ); } +/* + * Check for SAN match, see RFC 5280 Section 4.2.1.6 + */ +static int x509_crt_check_san( const mbedtls_x509_buf *name, + const char *cn, size_t cn_len ) +{ + const unsigned char san_type = (unsigned char) name->tag & + MBEDTLS_ASN1_TAG_VALUE_MASK; + + /* dNSName */ + if( san_type == MBEDTLS_X509_SAN_DNS_NAME ) + return( x509_crt_check_cn( name, cn, cn_len ) ); + + /* (We may handle other types here later.) */ + + /* Unrecognized type */ + return( -1 ); +} + /* * Verify the requested CN - only call this if cn is not NULL! */ @@ -2989,7 +3038,7 @@ static void x509_crt_verify_name( const mbedtls_x509_crt *crt, { for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next ) { - if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 ) + if( x509_crt_check_san( &cur->buf, cn, cn_len ) == 0 ) break; } diff --git a/connectivity/mbedtls/source/x509_csr.c b/connectivity/mbedtls/source/x509_csr.c index 7e2cfba2ae..5463f8a9e0 100644 --- a/connectivity/mbedtls/source/x509_csr.c +++ b/connectivity/mbedtls/source/x509_csr.c @@ -1,7 +1,7 @@ /* * X.509 Certificate Signing Request (CSR) parsing * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * The ITU-T X.509 standard defines a certificate format for PKI. @@ -29,11 +27,7 @@ * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_CSR_PARSE_C) diff --git a/connectivity/mbedtls/source/x509write_crt.c b/connectivity/mbedtls/source/x509write_crt.c index 5947e439de..32c6550968 100644 --- a/connectivity/mbedtls/source/x509write_crt.c +++ b/connectivity/mbedtls/source/x509write_crt.c @@ -1,7 +1,7 @@ /* * X.509 certificate writing * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * References: @@ -25,11 +23,7 @@ * - attributes: PKCS#9 v2.0 aka RFC 2985 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_CRT_WRITE_C) diff --git a/connectivity/mbedtls/source/x509write_csr.c b/connectivity/mbedtls/source/x509write_csr.c index 7c5179862c..c7c8032bec 100644 --- a/connectivity/mbedtls/source/x509write_csr.c +++ b/connectivity/mbedtls/source/x509write_csr.c @@ -1,7 +1,7 @@ /* * X.509 Certificate Signing Request writing * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +15,6 @@ * 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) */ /* * References: @@ -24,11 +22,7 @@ * - attributes: PKCS#9 v2.0 aka RFC 2985 */ -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif +#include "common.h" #if defined(MBEDTLS_X509_CSR_WRITE_C) @@ -50,6 +44,14 @@ #include "mbedtls/pem.h" #endif +#if defined(MBEDTLS_PLATFORM_C) +#include "mbedtls/platform.h" +#else +#include +#define mbedtls_calloc calloc +#define mbedtls_free free +#endif + void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ) { memset( ctx, 0, sizeof( mbedtls_x509write_csr ) ); @@ -130,17 +132,18 @@ int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx, return( 0 ); } -int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) +static int x509write_csr_der_internal( mbedtls_x509write_csr *ctx, + unsigned char *buf, + size_t size, + unsigned char *sig, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const char *sig_oid; size_t sig_oid_len = 0; unsigned char *c, *c2; unsigned char hash[64]; - unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE]; - unsigned char tmp_buf[2048]; size_t pub_len = 0, sig_and_oid_len = 0, sig_len; size_t len = 0; mbedtls_pk_type_t pk_alg; @@ -149,56 +152,69 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s 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 - */ - c = tmp_buf + sizeof( tmp_buf ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, tmp_buf, ctx->extensions ) ); + /* Write the CSR backwards starting from the end of buf */ + c = buf + size; + + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, buf, + ctx->extensions ) ); if( len ) { - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SET ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( &c, tmp_buf, MBEDTLS_OID_PKCS9_CSR_EXT_REQ, - MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_CSR_EXT_REQ ) ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_oid( + &c, buf, MBEDTLS_OID_PKCS9_CSR_EXT_REQ, + MBEDTLS_OID_SIZE( MBEDTLS_OID_PKCS9_CSR_EXT_REQ ) ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); } - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ); MBEDTLS_ASN1_CHK_ADD( pub_len, mbedtls_pk_write_pubkey_der( ctx->key, - tmp_buf, c - tmp_buf ) ); + buf, c - buf ) ); c -= pub_len; len += pub_len; /* * Subject ::= Name */ - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, tmp_buf, ctx->subject ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf, + ctx->subject ) ); /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, tmp_buf, 0 ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE ) ); + MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); /* - * Prepare signature + * Sign the written CSR data into the sig buffer * Note: hash errors can happen only after an internal error */ #if defined(MBEDTLS_USE_PSA_CRYPTO) @@ -232,32 +248,68 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s return( MBEDTLS_ERR_X509_INVALID_ALG ); if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, - &sig_oid, &sig_oid_len ) ) != 0 ) + &sig_oid, &sig_oid_len ) ) != 0 ) { return( ret ); } /* - * Write data to output buffer + * Move the written CSR data to the start of buf to create space for + * writing the signature into buf. + */ + memmove( buf, c, len ); + + /* + * Write sig and its OID into buf backwards from the end of buf. + * Note: mbedtls_x509_write_sig will check for c2 - ( buf + len ) < sig_len + * and return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL if needed. */ c2 = buf + size; - MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, buf, - sig_oid, sig_oid_len, sig, sig_len ) ); - - if( len > (size_t)( c2 - buf ) ) - return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); + MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, + mbedtls_x509_write_sig( &c2, buf + len, sig_oid, sig_oid_len, + sig, sig_len ) ); + /* + * Compact the space between the CSR data and signature by moving the + * CSR data to the start of the signature. + */ c2 -= len; - memcpy( c2, c, len ); + memmove( c2, buf, len ); + /* ASN encode the total size and tag the CSR data with it. */ len += sig_and_oid_len; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c2, buf, len ) ); - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c2, buf, MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE ) ); + MBEDTLS_ASN1_CHK_ADD( len, + mbedtls_asn1_write_tag( + &c2, buf, + MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); + + /* Zero the unused bytes at the start of buf */ + memset( buf, 0, c2 - buf); return( (int) len ); } +int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, + size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ) +{ + int ret; + unsigned char *sig; + + if( ( sig = mbedtls_calloc( 1, MBEDTLS_PK_SIGNATURE_MAX_SIZE ) ) == NULL ) + { + return( MBEDTLS_ERR_X509_ALLOC_FAILED ); + } + + ret = x509write_csr_der_internal( ctx, buf, size, sig, f_rng, p_rng ); + + mbedtls_free( sig ); + + return( ret ); +} + #define PEM_BEGIN_CSR "-----BEGIN CERTIFICATE REQUEST-----\n" #define PEM_END_CSR "-----END CERTIFICATE REQUEST-----\n" diff --git a/connectivity/mbedtls/source/xtea.c b/connectivity/mbedtls/source/xtea.c index a33707bc17..4b8c9c0773 100644 --- a/connectivity/mbedtls/source/xtea.c +++ b/connectivity/mbedtls/source/xtea.c @@ -1,7 +1,7 @@ /* * An 32-bit implementation of the XTEA algorithm * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +15,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_XTEA_C) diff --git a/connectivity/mbedtls/tools/importer/Makefile b/connectivity/mbedtls/tools/importer/Makefile index 823427e6c2..bda34cb589 100644 --- a/connectivity/mbedtls/tools/importer/Makefile +++ b/connectivity/mbedtls/tools/importer/Makefile @@ -27,17 +27,17 @@ # # Set the mbed TLS release to import (this can/should be edited before import) -MBED_TLS_RELEASE ?= mbedtls-2.22.0 +MBED_TLS_RELEASE ?= mbedtls-2.24.0 MBED_TLS_REPO_URL ?= git@github.com:ARMmbed/mbedtls.git # Translate between mbed TLS namespace and mbed namespace -TARGET_PREFIX:=../ -TARGET_EXPERIMENTAL:=../../FEATURE_EXPERIMENTAL_API/ -TARGET_SRC:=$(TARGET_PREFIX)src -TARGET_INC:=$(TARGET_PREFIX)inc +TARGET_PREFIX:=../../ +TARGET_EXPERIMENTAL:=../../../../platform/FEATURE_EXPERIMENTAL_API/ +TARGET_SRC:=$(TARGET_PREFIX)source +TARGET_INC:=$(TARGET_PREFIX)include TARGET_PSA:=$(TARGET_EXPERIMENTAL)FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls -TARGET_PSA_INC:=$(TARGET_PSA)/inc -TARGET_TESTS:=$(TARGET_PREFIX)TESTS +TARGET_PSA_INC:=$(TARGET_EXPERIMENTAL)FEATURE_PSA/TARGET_MBED_PSA_SRV/inc +TARGET_TESTS:=$(TARGET_PREFIX)tests/TESTS # mbed TLS source directory - hidden from mbed via TARGET_IGNORE MBED_TLS_DIR:=TARGET_IGNORE/mbedtls @@ -55,23 +55,24 @@ rsync: # # Copying mbed TLS into mbed library... rm -rf $(TARGET_SRC) - rsync -a --exclude='*.txt' $(MBED_TLS_DIR)/library/ $(TARGET_SRC) + rsync -a --include='*.[hc]' --exclude='*' $(MBED_TLS_DIR)/library/ $(TARGET_SRC) # # Copying mbed TLS headers to mbed includes... rm -rf $(TARGET_INC) mkdir -p $(TARGET_INC) - mkdir -p $(TARGET_PSA_INC) rsync -a --delete $(MBED_TLS_API) $(TARGET_INC) - rsync -a --delete --exclude='crypto_struct.h' $(CRYPTO_API) $(TARGET_PSA_INC)/ + # + # Export common.h into the include path, so PSA Crypto can find it + mv $(TARGET_SRC)/common.h $(TARGET_INC)/mbedtls/ # # Copying licenses cp $(MBED_TLS_DIR)/LICENSE $(TARGET_PREFIX) # - # Copying Mbed Crypto into Mbed OS... + # Copying PSA for single-core targets... + rm $(TARGET_PSA_INC)/psa/crypto_*.h + rsync -a --exclude='crypto_struct.h' $(CRYPTO_API) $(TARGET_PSA_INC)/ rm -rf $(TARGET_PSA) - mkdir -p $(TARGET_PSA) - rsync -a --delete $(CRYPTO_API)/crypto_struct.h $(TARGET_PSA)/ rsync -a --delete $(MBED_TLS_DIR)/library/psa_*.c $(TARGET_PSA)/ rsync -a --delete $(MBED_TLS_DIR)/library/psa_*.h $(TARGET_PSA)/ diff --git a/connectivity/mbedtls/tools/importer/TARGET_IGNORE/.gitignore b/connectivity/mbedtls/tools/importer/TARGET_IGNORE/.gitignore index be04f38da4..72e8ffc0db 100644 --- a/connectivity/mbedtls/tools/importer/TARGET_IGNORE/.gitignore +++ b/connectivity/mbedtls/tools/importer/TARGET_IGNORE/.gitignore @@ -1,2 +1 @@ -mbedtls -mbed-tls-lib +* diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto.h index 2b07b7471c..a3161666d7 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto.h @@ -3,7 +3,7 @@ * \brief Platform Security Architecture cryptography module */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -735,11 +735,12 @@ psa_status_t psa_import_key(const psa_key_attributes_t *attributes, * 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. + * `PSA_ECC_FAMILY_CURVEXXX`), and in big-endian order for Weierstrass + * curves (curve types `PSA_ECC_FAMILY_SECTXXX`, `PSA_ECC_FAMILY_SECPXXX` + * and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`). + * For Weierstrass curves, this is the content of the `privateKey` field of + * the `ECPrivateKey` format defined by RFC 5915. For Montgomery curves, + * the format is defined by RFC 7748, and output is masked according to §5. * - For Diffie-Hellman key exchange key pairs (key types for which * #PSA_KEY_TYPE_IS_DH_KEY_PAIR is true), the * format is the representation of the private key `x` as a big-endian byte @@ -3502,9 +3503,9 @@ psa_status_t psa_key_derivation_output_bytes( * length is determined by the curve, and sets the mandatory bits * accordingly. That is: * - * - Curve25519 (#PSA_ECC_CURVE_MONTGOMERY, 255 bits): draw a 32-byte + * - Curve25519 (#PSA_ECC_FAMILY_MONTGOMERY, 255 bits): draw a 32-byte * string and process it as specified in RFC 7748 §5. - * - Curve448 (#PSA_ECC_CURVE_MONTGOMERY, 448 bits): draw a 56-byte + * - Curve448 (#PSA_ECC_FAMILY_MONTGOMERY, 448 bits): draw a 56-byte * string and process it as specified in RFC 7748 §5. * * - For key types for which the key is represented by a single sequence of diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_accel_driver.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_accel_driver.h index 4a540f0fa4..1a193c5b9e 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_accel_driver.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_accel_driver.h @@ -14,7 +14,7 @@ */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_compat.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_compat.h index 1ed5f052b2..4b607b6ff6 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_compat.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_compat.h @@ -11,7 +11,7 @@ * include psa/crypto.h. */ /* - * Copyright (C) 2019, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -25,8 +25,6 @@ * 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_COMPAT_H @@ -50,8 +48,13 @@ extern "C" { typedef MBEDTLS_PSA_DEPRECATED size_t mbedtls_deprecated_size_t; typedef MBEDTLS_PSA_DEPRECATED psa_status_t mbedtls_deprecated_psa_status_t; typedef MBEDTLS_PSA_DEPRECATED psa_key_usage_t mbedtls_deprecated_psa_key_usage_t; -typedef MBEDTLS_PSA_DEPRECATED psa_ecc_curve_t mbedtls_deprecated_psa_ecc_curve_t; -typedef MBEDTLS_PSA_DEPRECATED psa_dh_group_t mbedtls_deprecated_psa_dh_group_t; +typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t mbedtls_deprecated_psa_ecc_family_t; +typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t mbedtls_deprecated_psa_dh_family_t; +typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t psa_ecc_curve_t; +typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t psa_dh_group_t; + +#define PSA_KEY_TYPE_GET_CURVE PSA_KEY_TYPE_ECC_GET_FAMILY +#define PSA_KEY_TYPE_GET_GROUP PSA_KEY_TYPE_DH_GET_FAMILY #define MBEDTLS_DEPRECATED_CONSTANT( type, value ) \ ( (mbedtls_deprecated_##type) ( value ) ) @@ -115,79 +118,110 @@ MBEDTLS_PSA_DEPRECATED static inline psa_status_t psa_asymmetric_verify( psa_key #endif /* MBEDTLS_DEPRECATED_REMOVED */ /* - * Size-specific elliptic curve and Diffie-Hellman group names + * Size-specific elliptic curve families. */ #define PSA_ECC_CURVE_SECP160K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP192K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP224K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP256K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP160R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP192R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP224R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP256R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP384R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP521R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP160R2 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECP_R2 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) #define PSA_ECC_CURVE_SECT163K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT233K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT239K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT283K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT409K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT571K1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_K1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT163R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT193R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT233R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT283R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT409R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT571R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT163R2 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R2 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) #define PSA_ECC_CURVE_SECT193R2 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_SECT_R2 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) #define PSA_ECC_CURVE_BRAINPOOL_P256R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_BRAINPOOL_P_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_BRAINPOOL_P384R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_BRAINPOOL_P_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_BRAINPOOL_P512R1 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_BRAINPOOL_P_R1 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_CURVE25519 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_MONTGOMERY ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) #define PSA_ECC_CURVE_CURVE448 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_curve_t, PSA_ECC_CURVE_MONTGOMERY ) + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) +/* + * Curves that changed name due to PSA specification. + */ +#define PSA_ECC_CURVE_SECP_K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP_R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) +#define PSA_ECC_CURVE_SECT_K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT_R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) +#define PSA_ECC_CURVE_BRAINPOOL_P_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) +#define PSA_ECC_CURVE_MONTGOMERY \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) + +/* + * Finite-field Diffie-Hellman families. + */ #define PSA_DH_GROUP_FFDHE2048 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_dh_group_t, PSA_DH_GROUP_RFC7919 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE3072 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_dh_group_t, PSA_DH_GROUP_RFC7919 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE4096 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_dh_group_t, PSA_DH_GROUP_RFC7919 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE6144 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_dh_group_t, PSA_DH_GROUP_RFC7919 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE8192 \ - MBEDTLS_DEPRECATED_CONSTANT( psa_dh_group_t, PSA_DH_GROUP_RFC7919 ) + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) + +/* + * Diffie-Hellman families that changed name due to PSA specification. + */ +#define PSA_DH_GROUP_RFC7919 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_CUSTOM \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_CUSTOM ) #ifdef __cplusplus } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_driver_common.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_driver_common.h index 6f1a5d5d9b..2ce75d2b0f 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_driver_common.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_driver_common.h @@ -17,7 +17,7 @@ */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_entropy_driver.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_entropy_driver.h index f596b6bd48..61750448bb 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_entropy_driver.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_entropy_driver.h @@ -12,7 +12,7 @@ */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_extra.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_extra.h index 64ab1bfe65..1e6a4bba26 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_extra.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_extra.h @@ -9,7 +9,7 @@ * This file is reserved for vendor-specific definitions. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +23,6 @@ * 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 @@ -34,6 +32,8 @@ #include "crypto_compat.h" +#include "platform/mbed_toolchain.h" + #ifdef __cplusplus extern "C" { #endif @@ -56,15 +56,17 @@ extern "C" { * for, in addition to the algorithm set with * psa_set_key_algorithm(). * - * \warning Setting an enrollment algorithm is not recommended, because - * using the same key with different algorithms can allow some - * attacks based on arithmetic relations between different - * computations made with the same key, or can escalate harmless - * side channels into exploitable ones. Use this function only - * if it is necessary to support a protocol for which it has been - * verified that the usage of the key with multiple algorithms - * is safe. + * \deprecated This is for backward compatibility only. + * Setting an enrollment algorithm is not recommended, because + * using the same key with different algorithms can allow some + * attacks based on arithmetic relations between different + * computations made with the same key, or can escalate harmless + * side channels into exploitable ones. Use this function only + * if it is necessary to support a protocol for which it has been + * verified that the usage of the key with multiple algorithms + * is safe. */ +MBED_DEPRECATED("Setting enrollment algorithm is for backward compatibility and not recommended.") static inline void psa_set_key_enrollment_algorithm( psa_key_attributes_t *attributes, psa_algorithm_t alg2) @@ -77,7 +79,10 @@ static inline void psa_set_key_enrollment_algorithm( * \param[in] attributes The key attribute structure to query. * * \return The enrollment algorithm stored in the attribute structure. + * \deprecated This is for backward compatibility only. + * Deprecated along with psa_set_key_enrollment_algorithm(). */ +MBED_DEPRECATED("Getting enrollment algorithm is for backward compatibility and not recommended.") static inline psa_algorithm_t psa_get_key_enrollment_algorithm( const psa_key_attributes_t *attributes) { @@ -414,11 +419,11 @@ psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed, /** Custom Diffie-Hellman group. * - * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_GROUP_CUSTOM) or - * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_GROUP_CUSTOM), the group data comes + * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or + * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM), the group data comes * from domain parameters set by psa_set_key_domain_parameters(). */ -#define PSA_DH_GROUP_CUSTOM ((psa_dh_group_t) 0x7e) +#define PSA_DH_FAMILY_CUSTOM ((psa_dh_family_t) 0x7e) /** @@ -448,8 +453,8 @@ psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed, * } * ``` * - For Diffie-Hellman key exchange keys - * (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_GROUP_CUSTOM) or - * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_GROUP_CUSTOM)), the + * (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or + * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM)), the * `DomainParameters` format as defined by RFC 3279 §2.3.3. * ``` * DomainParameters ::= SEQUENCE { @@ -575,54 +580,55 @@ psa_status_t psa_get_key_domain_parameters( * \param[out] bits On success, the bit size of the curve. * * \return The corresponding PSA elliptic curve identifier - * (`PSA_ECC_CURVE_xxx`). + * (`PSA_ECC_FAMILY_xxx`). * \return \c 0 on failure (\p grpid is not recognized). */ -static inline psa_ecc_curve_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid, +static inline psa_ecc_family_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid, size_t *bits ) { switch( grpid ) { case MBEDTLS_ECP_DP_SECP192R1: *bits = 192; - return( PSA_ECC_CURVE_SECP_R1 ); + return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP224R1: *bits = 224; - return( PSA_ECC_CURVE_SECP_R1 ); + return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP256R1: *bits = 256; - return( PSA_ECC_CURVE_SECP_R1 ); + return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP384R1: *bits = 384; - return( PSA_ECC_CURVE_SECP_R1 ); + return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP521R1: *bits = 521; - return( PSA_ECC_CURVE_SECP_R1 ); + return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_BP256R1: *bits = 256; - return( PSA_ECC_CURVE_BRAINPOOL_P_R1 ); + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_BP384R1: *bits = 384; - return( PSA_ECC_CURVE_BRAINPOOL_P_R1 ); + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_BP512R1: *bits = 512; - return( PSA_ECC_CURVE_BRAINPOOL_P_R1 ); + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_CURVE25519: *bits = 255; - return( PSA_ECC_CURVE_MONTGOMERY ); + return( PSA_ECC_FAMILY_MONTGOMERY ); case MBEDTLS_ECP_DP_SECP192K1: *bits = 192; - return( PSA_ECC_CURVE_SECP_K1 ); + return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_SECP224K1: *bits = 224; - return( PSA_ECC_CURVE_SECP_K1 ); + return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_SECP256K1: *bits = 256; - return( PSA_ECC_CURVE_SECP_K1 ); + return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_CURVE448: *bits = 448; - return( PSA_ECC_CURVE_MONTGOMERY ); + return( PSA_ECC_FAMILY_MONTGOMERY ); default: + *bits = 0; return( 0 ); } } @@ -633,7 +639,7 @@ static inline psa_ecc_curve_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grp * Mbed TLS and may be removed at any time without notice. * * \param curve A PSA elliptic curve identifier - * (`PSA_ECC_CURVE_xxx`). + * (`PSA_ECC_FAMILY_xxx`). * \param byte_length The byte-length of a private key on \p curve. * * \return The corresponding Mbed TLS elliptic curve identifier @@ -642,7 +648,7 @@ static inline psa_ecc_curve_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grp * \return #MBEDTLS_ECP_DP_NONE if \p byte_length is not * correct for \p curve. */ -mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, +mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve, size_t byte_length ); #endif /* MBEDTLS_ECP_C */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_platform.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_platform.h index d85a719cf1..77c0e5b2f0 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_platform.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_platform.h @@ -14,7 +14,7 @@ * module implements. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -28,8 +28,6 @@ * 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 diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_se_driver.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_se_driver.h index 7ac1ed1c41..46b2d645cb 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_se_driver.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_se_driver.h @@ -16,7 +16,7 @@ */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -119,8 +119,10 @@ typedef struct { * \param[in,out] drv_context The driver context structure. * \param[in,out] persistent_data A pointer to the persistent data * that allows writing. - * \param lifetime The lifetime value for which this driver - * is registered. + * \param location The location value for which this driver + * is registered. The driver will be invoked + * for all keys whose lifetime is in this + * location. * * \retval #PSA_SUCCESS * The driver is operational. @@ -132,7 +134,7 @@ typedef struct { */ typedef psa_status_t (*psa_drv_se_init_t)(psa_drv_se_context_t *drv_context, void *persistent_data, - psa_key_lifetime_t lifetime); + psa_key_location_t location); #if defined(__DOXYGEN_ONLY__) || !defined(MBEDTLS_PSA_CRYPTO_SE_C) /* Mbed Crypto with secure element support enabled defines this type in @@ -1341,17 +1343,19 @@ typedef struct { * after psa_crypto_init(). * * \note Implementations store metadata about keys including the lifetime - * value. Therefore, from one instantiation of the PSA Cryptography + * value, which contains the driver's location indicator. Therefore, + * from one instantiation of the PSA Cryptography * library to the next one, if there is a key in storage with a certain * lifetime value, you must always register the same driver (or an * updated version that communicates with the same secure element) - * with the same lifetime value. + * with the same location value. * - * \param lifetime The lifetime value through which this driver will + * \param location The location value through which this driver will * be exposed to applications. - * The values #PSA_KEY_LIFETIME_VOLATILE and - * #PSA_KEY_LIFETIME_PERSISTENT are reserved and - * may not be used for drivers. Implementations + * This driver will be used for all keys such that + * `location == PSA_KEY_LIFETIME_LOCATION( lifetime )`. + * The value #PSA_KEY_LOCATION_LOCAL_STORAGE is reserved + * and may not be used for drivers. Implementations * may reserve other values. * \param[in] methods The method table of the driver. This structure must * remain valid for as long as the cryptography @@ -1376,7 +1380,7 @@ typedef struct { * \return PSA_ERROR_NOT_PERMITTED */ psa_status_t psa_register_se_driver( - psa_key_lifetime_t lifetime, + psa_key_location_t location, const psa_drv_se_t *methods); /**@}*/ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_sizes.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_sizes.h index 1f04222c24..f6373b8c21 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_sizes.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_sizes.h @@ -21,7 +21,7 @@ * implementation are in crypto.h. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -35,8 +35,6 @@ * 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 @@ -431,7 +429,7 @@ * \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. + * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that @@ -450,9 +448,9 @@ /** Sufficient output buffer size for psa_asymmetric_decrypt(). * - * This macro returns a sufficient buffer size for a ciphertext produced using + * This macro returns a sufficient buffer size for a plaintext 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 + * Note that the actual size of the plaintext may be smaller, depending * on the algorithm. * * \warning This function may call its arguments multiple times or @@ -462,7 +460,7 @@ * \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. + * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_types.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_types.h index d96c66e5c4..17718eb6dc 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_types.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_types.h @@ -14,7 +14,7 @@ * This header file does not declare any function. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -28,8 +28,6 @@ * 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_TYPES_H @@ -74,7 +72,7 @@ typedef uint16_t psa_key_type_t; * Values defined by this standard will never be in the range 0x80-0xff. * Vendors who define additional families must use an encoding in this range. */ -typedef uint8_t psa_ecc_curve_t; +typedef uint8_t psa_ecc_family_t; /** The type of PSA Diffie-Hellman group family identifiers. * @@ -85,7 +83,7 @@ typedef uint8_t psa_ecc_curve_t; * Values defined by this standard will never be in the range 0x80-0xff. * Vendors who define additional families must use an encoding in this range. */ -typedef uint8_t psa_dh_group_t; +typedef uint8_t psa_dh_family_t; /** \brief Encoding of a cryptographic algorithm. * @@ -108,18 +106,117 @@ typedef uint32_t psa_algorithm_t; * The lifetime of a key indicates where it is stored and what system actions * may create and destroy it. * - * Keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE are automatically - * destroyed when the application terminates or on a power reset. + * Lifetime values have the following structure: + * - Bits 0-7 (#PSA_KEY_LIFETIME_GET_PERSISTENCE(\c lifetime)): + * persistence level. This value indicates what device management + * actions can cause it to be destroyed. In particular, it indicates + * whether the key is _volatile_ or _persistent_. + * See ::psa_key_persistence_t for more information. + * - Bits 8-31 (#PSA_KEY_LIFETIME_GET_LOCATION(\c lifetime)): + * location indicator. This value indicates where the key is stored + * and where operations on the key are performed. + * See ::psa_key_location_t for more information. + * + * Volatile keys are automatically destroyed when the application instance + * terminates or on a power reset of the device. Persistent keys are + * preserved until the application explicitly destroys them or until an + * implementation-specific device management event occurs (for example, + * a factory reset). * - * Keys with a lifetime other than #PSA_KEY_LIFETIME_VOLATILE are said - * to be _persistent_. - * Persistent keys are preserved if the application or the system restarts. * Persistent keys have a key identifier of type #psa_key_id_t. + * This identifier remains valid throughout the lifetime of the key, + * even if the application instance that created the key terminates. * The application can call psa_open_key() to open a persistent key that * it created previously. + * + * This specification defines two basic lifetime values: + * - Keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE are volatile. + * All implementations should support this lifetime. + * - Keys with the lifetime #PSA_KEY_LIFETIME_PERSISTENT are persistent. + * All implementations that have access to persistent storage with + * appropriate security guarantees should support this lifetime. */ typedef uint32_t psa_key_lifetime_t; +/** Encoding of key persistence levels. + * + * What distinguishes different persistence levels is what device management + * events may cause keys to be destroyed. _Volatile_ keys are destroyed + * by a power reset. Persistent keys may be destroyed by events such as + * a transfer of ownership or a factory reset. What management events + * actually affect persistent keys at different levels is outside the + * scope of the PSA Cryptography specification. + * + * This specification defines the following values of persistence levels: + * - \c 0 = #PSA_KEY_PERSISTENCE_VOLATILE: volatile key. + * A volatile key is automatically destroyed by the implementation when + * the application instance terminates. In particular, a volatile key + * is automatically destroyed on a power reset of the device. + * - \c 1 = #PSA_KEY_PERSISTENCE_DEFAULT: + * persistent key with a default lifetime. + * Implementations should support this value if they support persistent + * keys at all. + * Applications should use this value if they have no specific needs that + * are only met by implementation-specific features. + * - \c 2-127: persistent key with a PSA-specified lifetime. + * The PSA Cryptography specification does not define the meaning of these + * values, but other PSA specifications may do so. + * - \c 128-254: persistent key with a vendor-specified lifetime. + * No PSA specification will define the meaning of these values, so + * implementations may choose the meaning freely. + * As a guideline, higher persistence levels should cause a key to survive + * more management events than lower levels. + * - \c 255 = #PSA_KEY_PERSISTENCE_READ_ONLY: + * read-only or write-once key. + * A key with this persistence level cannot be destroyed. + * Implementations that support such keys may either allow their creation + * through the PSA Cryptography API, preferably only to applications with + * the appropriate privilege, or only expose keys created through + * implementation-specific means such as a factory ROM engraving process. + * Note that keys that are read-only due to policy restrictions + * rather than due to physical limitations should not have this + * persistence levels. + * + * \note Key persistence levels are 8-bit values. Key management + * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which + * encode the persistence as the lower 8 bits of a 32-bit value. + */ +typedef uint8_t psa_key_persistence_t; + +/** Encoding of key location indicators. + * + * If an implementation of this API can make calls to external + * cryptoprocessors such as secure elements, the location of a key + * indicates which secure element performs the operations on the key. + * If an implementation offers multiple physical locations for persistent + * storage, the location indicator reflects at which physical location + * the key is stored. + * + * This specification defines the following values of location indicators: + * - \c 0: primary local storage. + * All implementations should support this value. + * The primary local storage is typically the same storage area that + * contains the key metadata. + * - \c 1: primary secure element. + * Implementations should support this value if there is a secure element + * attached to the operating environment. + * As a guideline, secure elements may provide higher resistance against + * side channel and physical attacks than the primary local storage, but may + * have restrictions on supported key types, sizes, policies and operations + * and may have different performance characteristics. + * - \c 2-0x7fffff: other locations defined by a PSA specification. + * The PSA Cryptography API does not currently assign any meaning to these + * locations, but future versions of this specification or other PSA + * specifications may do so. + * - \c 0x800000-0xffffff: vendor-defined locations. + * No PSA specification will assign a meaning to locations in this range. + * + * \note Key location indicators are 24-bit values. Key management + * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which + * encode the location as the upper 24 bits of a 32-bit value. + */ +typedef uint32_t psa_key_location_t; + /** Encoding of identifiers of persistent keys. * * - Applications may freely choose key identifiers in the range diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_values.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_values.h index baaabff1e0..a940711803 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_values.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/inc/psa/crypto_values.h @@ -15,7 +15,7 @@ * This header file only defines preprocessor macros. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -29,8 +29,6 @@ * 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_VALUES_H @@ -426,15 +424,15 @@ #define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t)0x00ff) /** Elliptic curve key pair. * - * \param curve A value of type ::psa_ecc_curve_t that identifies the - * ECC curve to be used. + * \param curve A value of type ::psa_ecc_family_t that + * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_KEY_PAIR(curve) \ (PSA_KEY_TYPE_ECC_KEY_PAIR_BASE | (curve)) /** Elliptic curve public key. * - * \param curve A value of type ::psa_ecc_curve_t that identifies the - * ECC curve to be used. + * \param curve A value of type ::psa_ecc_family_t that + * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve) \ (PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve)) @@ -453,8 +451,8 @@ PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) /** 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) ? \ +#define PSA_KEY_TYPE_ECC_GET_FAMILY(type) \ + ((psa_ecc_family_t) (PSA_KEY_TYPE_IS_ECC(type) ? \ ((type) & PSA_KEY_TYPE_ECC_CURVE_MASK) : \ 0)) @@ -466,7 +464,7 @@ * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_SECP_K1 ((psa_ecc_curve_t) 0x17) +#define PSA_ECC_FAMILY_SECP_K1 ((psa_ecc_family_t) 0x17) /** SEC random curves over prime fields. * @@ -476,9 +474,9 @@ * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_SECP_R1 ((psa_ecc_curve_t) 0x12) +#define PSA_ECC_FAMILY_SECP_R1 ((psa_ecc_family_t) 0x12) /* SECP160R2 (SEC2 v1, obsolete) */ -#define PSA_ECC_CURVE_SECP_R2 ((psa_ecc_curve_t) 0x1b) +#define PSA_ECC_FAMILY_SECP_R2 ((psa_ecc_family_t) 0x1b) /** SEC Koblitz curves over binary fields. * @@ -488,7 +486,7 @@ * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_SECT_K1 ((psa_ecc_curve_t) 0x27) +#define PSA_ECC_FAMILY_SECT_K1 ((psa_ecc_family_t) 0x27) /** SEC random curves over binary fields. * @@ -498,7 +496,7 @@ * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_SECT_R1 ((psa_ecc_curve_t) 0x22) +#define PSA_ECC_FAMILY_SECT_R1 ((psa_ecc_family_t) 0x22) /** SEC additional random curves over binary fields. * @@ -508,7 +506,7 @@ * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_SECT_R2 ((psa_ecc_curve_t) 0x2b) +#define PSA_ECC_FAMILY_SECT_R2 ((psa_ecc_family_t) 0x2b) /** Brainpool P random curves. * @@ -517,7 +515,7 @@ * brainpoolP320r1, brainpoolP384r1, brainpoolP512r1. * It is defined in RFC 5639. */ -#define PSA_ECC_CURVE_BRAINPOOL_P_R1 ((psa_ecc_curve_t) 0x30) +#define PSA_ECC_FAMILY_BRAINPOOL_P_R1 ((psa_ecc_family_t) 0x30) /** Curve25519 and Curve448. * @@ -529,21 +527,21 @@ * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve. */ -#define PSA_ECC_CURVE_MONTGOMERY ((psa_ecc_curve_t) 0x41) +#define PSA_ECC_FAMILY_MONTGOMERY ((psa_ecc_family_t) 0x41) #define PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE ((psa_key_type_t)0x4200) #define PSA_KEY_TYPE_DH_KEY_PAIR_BASE ((psa_key_type_t)0x7200) #define PSA_KEY_TYPE_DH_GROUP_MASK ((psa_key_type_t)0x00ff) /** Diffie-Hellman key pair. * - * \param group A value of type ::psa_dh_group_t that identifies the + * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_KEY_PAIR(group) \ (PSA_KEY_TYPE_DH_KEY_PAIR_BASE | (group)) /** Diffie-Hellman public key. * - * \param group A value of type ::psa_dh_group_t that identifies the + * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_PUBLIC_KEY(group) \ @@ -563,8 +561,8 @@ PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE) /** Extract the group from a Diffie-Hellman key type. */ -#define PSA_KEY_TYPE_GET_GROUP(type) \ - ((psa_dh_group_t) (PSA_KEY_TYPE_IS_DH(type) ? \ +#define PSA_KEY_TYPE_DH_GET_FAMILY(type) \ + ((psa_dh_family_t) (PSA_KEY_TYPE_IS_DH(type) ? \ ((type) & PSA_KEY_TYPE_DH_GROUP_MASK) : \ 0)) @@ -574,7 +572,7 @@ * 2048, 3072, 4096, 6144, 8192. A given implementation may support * all of these sizes or only a subset. */ -#define PSA_DH_GROUP_RFC7919 ((psa_dh_group_t) 0x03) +#define PSA_DH_FAMILY_RFC7919 ((psa_dh_family_t) 0x03) #define PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) \ (((type) >> 8) & 7) @@ -672,22 +670,24 @@ #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. +/** Whether the specified algorithm is an asymmetric signature algorithm, + * also known as 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. + * \return 1 if \p alg is an asymmetric 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. +/** Whether the specified algorithm is an asymmetric encryption algorithm, + * also known as 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. + * \return 1 if \p alg is an asymmetric encryption algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ @@ -1205,9 +1205,9 @@ /** Whether the specified algorithm is a hash-and-sign algorithm. * - * Hash-and-sign algorithms are public-key signature algorithms structured - * in two parts: first the calculation of a hash in a way that does not - * depend on the key, then the calculation of a signature from the + * Hash-and-sign algorithms are asymmetric (public-key) signature algorithms + * structured in two parts: first the calculation of a hash in a way that + * does not depend on the key, then the calculation of a signature from the * hash value and the key. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). @@ -1259,7 +1259,7 @@ * #PSA_ALG_IS_HASH(\p hash_alg) is true) to use * for MGF1. * - * \return The corresponding RSA OAEP signature algorithm. + * \return The corresponding RSA OAEP encryption algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ @@ -1481,17 +1481,17 @@ * 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`), + * - For Montgomery curves (curve types `PSA_ECC_FAMILY_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`), + * `PSA_ECC_FAMILY_SECPXXX` and `PSA_ECC_FAMILY_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`), + * `PSA_ECC_FAMILY_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}`. @@ -1539,12 +1539,20 @@ * @{ */ -/** A volatile key only exists as long as the handle to it is not closed. +/** The default lifetime for volatile keys. + * + * A volatile key only exists as long as the handle to it is not closed. * The key material is guaranteed to be erased on a power reset. + * + * A key with this lifetime is typically stored in the RAM area of the + * PSA Crypto subsystem. However this is an implementation choice. + * If an implementation stores data about the key in a non-volatile memory, + * it must release all the resources associated with the key and erase the + * key material if the calling application terminates. */ #define PSA_KEY_LIFETIME_VOLATILE ((psa_key_lifetime_t)0x00000000) -/** The default storage area for persistent keys. +/** The default lifetime for persistent keys. * * A persistent key remains in storage until it is explicitly destroyed or * until the corresponding storage area is wiped. This specification does @@ -1555,9 +1563,77 @@ * This lifetime value is the default storage area for the calling * application. Implementations may offer other storage areas designated * by other lifetime values as implementation-specific extensions. + * See ::psa_key_lifetime_t for more information. */ #define PSA_KEY_LIFETIME_PERSISTENT ((psa_key_lifetime_t)0x00000001) +/** The persistence level of volatile keys. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_VOLATILE ((psa_key_persistence_t)0x00) + +/** The default persistence level for persistent keys. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_DEFAULT ((psa_key_persistence_t)0x01) + +/** A persistence level indicating that a key is never destroyed. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_READ_ONLY ((psa_key_persistence_t)0xff) + +#define PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) \ + ((psa_key_persistence_t)((lifetime) & 0x000000ff)) + +#define PSA_KEY_LIFETIME_GET_LOCATION(lifetime) \ + ((psa_key_location_t)((lifetime) >> 8)) + +/** Whether a key lifetime indicates that the key is volatile. + * + * A volatile key is automatically destroyed by the implementation when + * the application instance terminates. In particular, a volatile key + * is automatically destroyed on a power reset of the device. + * + * A key that is not volatile is persistent. Persistent keys are + * preserved until the application explicitly destroys them or until an + * implementation-specific device management event occurs (for example, + * a factory reset). + * + * \param lifetime The lifetime value to query (value of type + * ::psa_key_lifetime_t). + * + * \return \c 1 if the key is volatile, otherwise \c 0. + */ +#define PSA_KEY_LIFETIME_IS_VOLATILE(lifetime) \ + (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \ + PSA_KEY_PERSISTENCE_VOLATILE) + +/** Construct a lifetime from a persistence level and a location. + * + * \param persistence The persistence level + * (value of type ::psa_key_persistence_t). + * \param location The location indicator + * (value of type ::psa_key_location_t). + * + * \return The constructed lifetime value. + */ +#define PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(persistence, location) \ + ((location) << 8 | (persistence)) + +/** The local storage area for persistent keys. + * + * This storage area is available on all systems that can store persistent + * keys without delegating the storage to a third-party cryptoprocessor. + * + * See ::psa_key_location_t for more information. + */ +#define PSA_KEY_LOCATION_LOCAL_STORAGE ((psa_key_location_t)0x000000) + +#define PSA_KEY_LOCATION_VENDOR_FLAG ((psa_key_location_t)0x800000) + /** The minimum value for a key identifier chosen by the application. */ #define PSA_KEY_ID_USER_MIN ((psa_app_key_id_t)0x00000001) diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/crypto_struct.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/crypto_struct.h index 938abd07b8..67c53db928 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/crypto_struct.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/crypto_struct.h @@ -34,7 +34,7 @@ * copy of the key. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -48,8 +48,6 @@ * 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 diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto.c index 69323184d0..bffddc995b 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto.c @@ -1,7 +1,8 @@ /* * PSA crypto layer on top of Mbed TLS crypto */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +16,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PSA_CRYPTO_C) @@ -375,12 +370,12 @@ static inline int psa_key_slot_is_external( const psa_key_slot_t *slot ) #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ #if defined(MBEDTLS_ECP_C) -mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, +mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve, size_t byte_length ) { switch( curve ) { - case PSA_ECC_CURVE_SECP_R1: + case PSA_ECC_FAMILY_SECP_R1: switch( byte_length ) { case PSA_BITS_TO_BYTES( 192 ): @@ -398,7 +393,7 @@ mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, } break; - case PSA_ECC_CURVE_BRAINPOOL_P_R1: + case PSA_ECC_FAMILY_BRAINPOOL_P_R1: switch( byte_length ) { case PSA_BITS_TO_BYTES( 256 ): @@ -412,7 +407,7 @@ mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, } break; - case PSA_ECC_CURVE_MONTGOMERY: + case PSA_ECC_FAMILY_MONTGOMERY: switch( byte_length ) { case PSA_BITS_TO_BYTES( 255 ): @@ -424,7 +419,7 @@ mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, } break; - case PSA_ECC_CURVE_SECP_K1: + case PSA_ECC_FAMILY_SECP_K1: switch( byte_length ) { case PSA_BITS_TO_BYTES( 192 ): @@ -444,9 +439,8 @@ mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve, } #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 ) +static psa_status_t validate_unstructured_key_bit_size( psa_key_type_t type, + size_t bits ) { /* Check that the bit size is acceptable for the key type */ switch( type ) @@ -493,18 +487,12 @@ static psa_status_t prepare_raw_data_slot( psa_key_type_t type, 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) +#if defined(MBEDTLS_RSA_C) + +#if 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 @@ -526,79 +514,227 @@ static psa_status_t psa_check_rsa_key_byte_aligned( mbedtls_mpi_free( &n ); return( status ); } +#endif /* MBEDTLS_PK_PARSE_C */ -static psa_status_t psa_import_rsa_key( psa_key_type_t type, - const uint8_t *data, - size_t data_length, - mbedtls_rsa_context **p_rsa ) +/** Load the contents of a key buffer into an internal RSA representation + * + * \param[in] type The type of key contained in \p data. + * \param[in] data The buffer from which to load the representation. + * \param[in] data_length The size in bytes of \p data. + * \param[out] p_rsa Returns a pointer to an RSA context on success. + * The caller is responsible for freeing both the + * contents of the context and the context itself + * when done. + */ +static psa_status_t psa_load_rsa_representation( psa_key_type_t type, + const uint8_t *data, + size_t data_length, + mbedtls_rsa_context **p_rsa ) { +#if defined(MBEDTLS_PK_PARSE_C) psa_status_t status; - mbedtls_pk_context pk; - mbedtls_rsa_context *rsa; + mbedtls_pk_context ctx; size_t bits; - - mbedtls_pk_init( &pk ); + mbedtls_pk_init( &ctx ); /* Parse the data. */ if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) ) status = mbedtls_to_psa_error( - mbedtls_pk_parse_key( &pk, data, data_length, NULL, 0 ) ); + mbedtls_pk_parse_key( &ctx, data, data_length, NULL, 0 ) ); else status = mbedtls_to_psa_error( - mbedtls_pk_parse_public_key( &pk, data, data_length ) ); + mbedtls_pk_parse_public_key( &ctx, data, data_length ) ); if( status != PSA_SUCCESS ) goto exit; /* We have something that the pkparse module recognizes. If it is a * valid RSA key, store it. */ - if( mbedtls_pk_get_type( &pk ) != MBEDTLS_PK_RSA ) + if( mbedtls_pk_get_type( &ctx ) != MBEDTLS_PK_RSA ) { status = PSA_ERROR_INVALID_ARGUMENT; goto exit; } - 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. */ - bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( rsa ) ); + bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( mbedtls_pk_rsa( ctx ) ) ); if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS ) { status = PSA_ERROR_NOT_SUPPORTED; goto exit; } - status = psa_check_rsa_key_byte_aligned( rsa ); + status = psa_check_rsa_key_byte_aligned( mbedtls_pk_rsa( ctx ) ); + if( status != PSA_SUCCESS ) + goto exit; + + /* Copy out the pointer to the RSA context, and reset the PK context + * such that pk_free doesn't free the RSA context we just grabbed. */ + *p_rsa = mbedtls_pk_rsa( ctx ); + ctx.pk_info = NULL; exit: - /* Free the content of the pk object only on error. */ + mbedtls_pk_free( &ctx ); + return( status ); +#else + (void) data; + (void) data_length; + (void) type; + (void) rsa; + return( PSA_ERROR_NOT_SUPPORTED ); +#endif /* MBEDTLS_PK_PARSE_C */ +} + +/** Export an RSA key to export representation + * + * \param[in] type The type of key (public/private) to export + * \param[in] rsa The internal RSA representation from which to export + * \param[out] data The buffer to export to + * \param[in] data_size The length of the buffer to export to + * \param[out] data_length The amount of bytes written to \p data + */ +static psa_status_t psa_export_rsa_key( psa_key_type_t type, + mbedtls_rsa_context *rsa, + uint8_t *data, + size_t data_size, + size_t *data_length ) +{ +#if defined(MBEDTLS_PK_WRITE_C) + int ret; + mbedtls_pk_context pk; + uint8_t *pos = data + data_size; + + mbedtls_pk_init( &pk ); + pk.pk_info = &mbedtls_rsa_info; + pk.pk_ctx = rsa; + + /* PSA Crypto API defines the format of an RSA key as a DER-encoded + * representation of the non-encrypted PKCS#1 RSAPrivateKey for a + * private key and of the RFC3279 RSAPublicKey for a public key. */ + if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) ) + ret = mbedtls_pk_write_key_der( &pk, data, data_size ); + else + ret = mbedtls_pk_write_pubkey( &pos, data, &pk ); + + if( ret < 0 ) + { + /* Clean up in case pk_write failed halfway through. */ + 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 + (void) type; + (void) rsa; + (void) data; + (void) data_size; + (void) data_length; + return( PSA_ERROR_NOT_SUPPORTED ); +#endif /* MBEDTLS_PK_WRITE_C */ +} + +/** Import an RSA key from import representation to a slot + * + * \param[in,out] slot The slot where to store the export representation to + * \param[in] data The buffer containing the import representation + * \param[in] data_length The amount of bytes in \p data + */ +static psa_status_t psa_import_rsa_key( psa_key_slot_t *slot, + const uint8_t *data, + size_t data_length ) +{ + psa_status_t status; + uint8_t* output = NULL; + mbedtls_rsa_context *rsa = NULL; + + /* Parse input */ + status = psa_load_rsa_representation( slot->attr.type, + data, + data_length, + &rsa ); + if( status != PSA_SUCCESS ) + goto exit; + + slot->attr.bits = (psa_key_bits_t) PSA_BYTES_TO_BITS( + mbedtls_rsa_get_len( rsa ) ); + + /* Re-export the data to PSA export format, such that we can store export + * representation in the key slot. Export representation in case of RSA is + * the smallest representation that's allowed as input, so a straight-up + * allocation of the same size as the input buffer will be large enough. */ + output = mbedtls_calloc( 1, data_length ); + if( output == NULL ) + { + status = PSA_ERROR_INSUFFICIENT_MEMORY; + goto exit; + } + + status = psa_export_rsa_key( slot->attr.type, + rsa, + output, + data_length, + &data_length); +exit: + /* Always free the RSA object */ + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + + /* Free the allocated buffer only on error. */ if( status != PSA_SUCCESS ) { - mbedtls_pk_free( &pk ); + mbedtls_free( output ); return( status ); } - /* On success, store the content of the object in the RSA context. */ - *p_rsa = rsa; + /* On success, store the allocated export-formatted key. */ + slot->data.key.data = output; + slot->data.key.bytes = data_length; return( PSA_SUCCESS ); } -#endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) */ +#endif /* defined(MBEDTLS_RSA_C) */ #if defined(MBEDTLS_ECP_C) -static psa_status_t psa_prepare_import_ec_key( psa_ecc_curve_t curve, - size_t data_length, - int is_public, - mbedtls_ecp_keypair **p_ecp ) +/** Load the contents of a key buffer into an internal ECP representation + * + * \param[in] type The type of key contained in \p data. + * \param[in] data The buffer from which to load the representation. + * \param[in] data_length The size in bytes of \p data. + * \param[out] p_ecp Returns a pointer to an ECP context on success. + * The caller is responsible for freeing both the + * contents of the context and the context itself + * when done. + */ +static psa_status_t psa_load_ecp_representation( psa_key_type_t type, + const uint8_t *data, + size_t data_length, + mbedtls_ecp_keypair **p_ecp ) { mbedtls_ecp_group_id grp_id = MBEDTLS_ECP_DP_NONE; - *p_ecp = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) ); - if( *p_ecp == NULL ) - return( PSA_ERROR_INSUFFICIENT_MEMORY ); - mbedtls_ecp_keypair_init( *p_ecp ); + psa_status_t status; + mbedtls_ecp_keypair *ecp = NULL; + size_t curve_size = data_length; - if( is_public ) + if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) && + PSA_KEY_TYPE_ECC_GET_FAMILY( type ) != PSA_ECC_FAMILY_MONTGOMERY ) { - /* A public key is represented as: + /* A Weierstrass public key is represented as: * - The byte 0x04; * - `x_P` as a `ceiling(m/8)`-byte string, big-endian; * - `y_P` as a `ceiling(m/8)`-byte string, big-endian. @@ -606,101 +742,195 @@ static psa_status_t psa_prepare_import_ec_key( psa_ecc_curve_t curve, */ if( ( data_length & 1 ) == 0 ) return( PSA_ERROR_INVALID_ARGUMENT ); - data_length = data_length / 2; + curve_size = data_length / 2; + + /* Montgomery public keys are represented in compressed format, meaning + * their curve_size is equal to the amount of input. */ + + /* Private keys are represented in uncompressed private random integer + * format, meaning their curve_size is equal to the amount of input. */ } + /* Allocate and initialize a key representation. */ + ecp = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) ); + if( ecp == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); + mbedtls_ecp_keypair_init( ecp ); + /* Load the group. */ - grp_id = mbedtls_ecc_group_of_psa( curve, data_length ); + grp_id = mbedtls_ecc_group_of_psa( PSA_KEY_TYPE_ECC_GET_FAMILY( type ), + curve_size ); if( grp_id == MBEDTLS_ECP_DP_NONE ) - return( PSA_ERROR_INVALID_ARGUMENT ); - return( mbedtls_to_psa_error( - mbedtls_ecp_group_load( &( *p_ecp )->grp, grp_id ) ) ); -} - -/* Import a public key given as the uncompressed representation defined by SEC1 - * 2.3.3 as the content of an ECPoint. */ -static psa_status_t psa_import_ec_public_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_CORRUPTION_DETECTED; - mbedtls_ecp_keypair *ecp = NULL; - - status = psa_prepare_import_ec_key( curve, data_length, 1, &ecp ); - if( status != PSA_SUCCESS ) + { + status = PSA_ERROR_INVALID_ARGUMENT; goto exit; + } - /* Load the public value. */ status = mbedtls_to_psa_error( - mbedtls_ecp_point_read_binary( &ecp->grp, &ecp->Q, - data, data_length ) ); + mbedtls_ecp_group_load( &ecp->grp, grp_id ) ); if( status != PSA_SUCCESS ) goto exit; - /* Check that the point is on the curve. */ - status = mbedtls_to_psa_error( - mbedtls_ecp_check_pubkey( &ecp->grp, &ecp->Q ) ); - if( status != PSA_SUCCESS ) - goto exit; + /* Load the key material. */ + if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ) + { + /* Load the public value. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_point_read_binary( &ecp->grp, &ecp->Q, + data, + data_length ) ); + if( status != PSA_SUCCESS ) + goto exit; + + /* Check that the point is on the curve. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_check_pubkey( &ecp->grp, &ecp->Q ) ); + if( status != PSA_SUCCESS ) + goto exit; + } + else + { + /* Load and validate the secret value. */ + status = mbedtls_to_psa_error( + mbedtls_ecp_read_key( ecp->grp.id, + ecp, + data, + data_length ) ); + if( status != PSA_SUCCESS ) + goto exit; + } *p_ecp = ecp; - return( PSA_SUCCESS ); - exit: - if( ecp != NULL ) + if( status != PSA_SUCCESS ) { mbedtls_ecp_keypair_free( ecp ); mbedtls_free( ecp ); } + return( status ); } -/* 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 ) +/** Export an ECP key to export representation + * + * \param[in] type The type of key (public/private) to export + * \param[in] ecp The internal ECP representation from which to export + * \param[out] data The buffer to export to + * \param[in] data_size The length of the buffer to export to + * \param[out] data_length The amount of bytes written to \p data + */ +static psa_status_t psa_export_ecp_key( psa_key_type_t type, + mbedtls_ecp_keypair *ecp, + uint8_t *data, + size_t data_size, + size_t *data_length ) { - psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED; + psa_status_t status; + + if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ) + { + /* Check whether the public part is loaded */ + if( mbedtls_ecp_is_zero( &ecp->Q ) ) + { + /* Calculate the public 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 ) + return( status ); + } + + status = mbedtls_to_psa_error( + mbedtls_ecp_point_write_binary( &ecp->grp, &ecp->Q, + MBEDTLS_ECP_PF_UNCOMPRESSED, + data_length, + data, + data_size ) ); + if( status != PSA_SUCCESS ) + memset( data, 0, data_size ); + + return( status ); + } + else + { + if( data_size < PSA_BITS_TO_BYTES( ecp->grp.nbits ) ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + + status = mbedtls_to_psa_error( + mbedtls_ecp_write_key( ecp, + data, + PSA_BITS_TO_BYTES( ecp->grp.nbits ) ) ); + if( status == PSA_SUCCESS ) + *data_length = PSA_BITS_TO_BYTES( ecp->grp.nbits ); + else + memset( data, 0, data_size ); + + return( status ); + } +} + +/** Import an ECP key from import representation to a slot + * + * \param[in,out] slot The slot where to store the export representation to + * \param[in] data The buffer containing the import representation + * \param[in] data_length The amount of bytes in \p data + */ +static psa_status_t psa_import_ecp_key( psa_key_slot_t *slot, + const uint8_t *data, + size_t data_length ) +{ + psa_status_t status; + uint8_t* output = NULL; mbedtls_ecp_keypair *ecp = NULL; - status = psa_prepare_import_ec_key( curve, data_length, 0, &ecp ); + /* Parse input */ + status = psa_load_ecp_representation( slot->attr.type, + data, + data_length, + &ecp ); 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; + if( PSA_KEY_TYPE_ECC_GET_FAMILY( slot->attr.type ) == PSA_ECC_FAMILY_MONTGOMERY) + slot->attr.bits = (psa_key_bits_t) ecp->grp.nbits + 1; + else + slot->attr.bits = (psa_key_bits_t) ecp->grp.nbits; - *p_ecp = ecp; - return( PSA_SUCCESS ); - -exit: - if( ecp != NULL ) + /* Re-export the data to PSA export format. There is currently no support + * for other input formats then the export format, so this is a 1-1 + * copy operation. */ + output = mbedtls_calloc( 1, data_length ); + if( output == NULL ) { - mbedtls_ecp_keypair_free( ecp ); - mbedtls_free( ecp ); + status = PSA_ERROR_INSUFFICIENT_MEMORY; + goto exit; } - return( status ); + + status = psa_export_ecp_key( slot->attr.type, + ecp, + output, + data_length, + &data_length); +exit: + /* Always free the PK object (will also free contained ECP context) */ + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + + /* Free the allocated buffer only on error. */ + if( status != PSA_SUCCESS ) + { + mbedtls_free( output ); + return( status ); + } + + /* On success, store the allocated export-formatted key. */ + slot->data.key.data = output; + slot->data.key.bytes = data_length; + + return( PSA_SUCCESS ); } #endif /* defined(MBEDTLS_ECP_C) */ - /** Return the size of the key in the given slot, in bits. * * \param[in] slot A key slot. @@ -712,30 +942,30 @@ static inline size_t psa_get_key_slot_bits( const psa_key_slot_t *slot ) return( slot->attr.bits ); } -/** Calculate the size of the key in the given slot, in bits. +/** Try to allocate a buffer to an empty key slot. * - * \param[in] slot A key slot containing a transparent key. + * \param[in,out] slot Key slot to attach buffer to. + * \param[in] buffer_length Requested size of the buffer. * - * \return The key size in bits, calculated from the key data. + * \retval #PSA_SUCCESS + * The buffer has been successfully allocated. + * \retval #PSA_ERROR_INSUFFICIENT_MEMORY + * Not enough memory was available for allocation. + * \retval #PSA_ERROR_ALREADY_EXISTS + * Trying to allocate a buffer to a non-empty key slot. */ -static psa_key_bits_t psa_calculate_key_bits( const psa_key_slot_t *slot ) +static psa_status_t psa_allocate_buffer_to_slot( psa_key_slot_t *slot, + size_t buffer_length ) { - size_t bits = 0; /* return 0 on an empty slot */ + if( slot->data.key.data != NULL ) + return( PSA_ERROR_ALREADY_EXISTS ); - if( key_type_is_raw_bytes( slot->attr.type ) ) - bits = PSA_BYTES_TO_BITS( slot->data.raw.bytes ); -#if defined(MBEDTLS_RSA_C) - else if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) - bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( slot->data.rsa ) ); -#endif /* defined(MBEDTLS_RSA_C) */ -#if defined(MBEDTLS_ECP_C) - else if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) ) - bits = slot->data.ecp->grp.pbits; -#endif /* defined(MBEDTLS_ECP_C) */ + slot->data.key.data = mbedtls_calloc( 1, buffer_length ); + if( slot->data.key.data == NULL ) + return( PSA_ERROR_INSUFFICIENT_MEMORY ); - /* We know that the size fits in psa_key_bits_t thanks to checks - * when the key was created. */ - return( (psa_key_bits_t) bits ); + slot->data.key.bytes = buffer_length; + return( PSA_SUCCESS ); } /** Import key data into a slot. `slot->attr.type` must have been set @@ -747,60 +977,68 @@ psa_status_t psa_import_key_into_slot( psa_key_slot_t *slot, { psa_status_t status = PSA_SUCCESS; + /* zero-length keys are never supported. */ + if( data_length == 0 ) + return( PSA_ERROR_NOT_SUPPORTED ); + if( key_type_is_raw_bytes( slot->attr.type ) ) { size_t bit_size = PSA_BYTES_TO_BITS( data_length ); - /* Ensure that the bytes-to-bit conversion didn't overflow. */ + + /* Ensure that the bytes-to-bits conversion hasn't overflown. */ if( data_length > SIZE_MAX / 8 ) return( PSA_ERROR_NOT_SUPPORTED ); + /* Enforce a size limit, and in particular ensure that the bit * size fits in its representation type. */ if( bit_size > PSA_MAX_KEY_BITS ) return( PSA_ERROR_NOT_SUPPORTED ); - status = prepare_raw_data_slot( slot->attr.type, bit_size, - &slot->data.raw ); + + status = validate_unstructured_key_bit_size( slot->attr.type, bit_size ); 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_KEY_PAIR( slot->attr.type ) ) - { - status = psa_import_ec_private_key( PSA_KEY_TYPE_GET_CURVE( slot->attr.type ), - data, data_length, - &slot->data.ecp ); - } - else if( PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY( slot->attr.type ) ) - { - status = psa_import_ec_public_key( - PSA_KEY_TYPE_GET_CURVE( slot->attr.type ), - data, data_length, - &slot->data.ecp ); - } - else -#endif /* MBEDTLS_ECP_C */ -#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) - if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) - { - status = psa_import_rsa_key( slot->attr.type, - data, data_length, - &slot->data.rsa ); - } - else -#endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) */ - { - return( PSA_ERROR_NOT_SUPPORTED ); - } - if( status == PSA_SUCCESS ) - { + /* Allocate memory for the key */ + status = psa_allocate_buffer_to_slot( slot, data_length ); + if( status != PSA_SUCCESS ) + return( status ); + + /* copy key into allocated buffer */ + memcpy( slot->data.key.data, data, data_length ); + /* Write the actual key size to the slot. * psa_start_key_creation() wrote the size declared by the * caller, which may be 0 (meaning unspecified) or wrong. */ - slot->attr.bits = psa_calculate_key_bits( slot ); + slot->attr.bits = (psa_key_bits_t) bit_size; } + else if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) ) + { +#if defined(MBEDTLS_ECP_C) + status = psa_import_ecp_key( slot, + data, data_length ); +#else + /* No drivers have been implemented yet, so without mbed TLS backing + * there's no way to do ECP with the current library. */ + return( PSA_ERROR_NOT_SUPPORTED ); +#endif /* defined(MBEDTLS_ECP_C) */ + } + else if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) + { +#if defined(MBEDTLS_RSA_C) + status = psa_import_rsa_key( slot, + data, data_length ); +#else + /* No drivers have been implemented yet, so without mbed TLS backing + * there's no way to do RSA with the current library. */ + status = PSA_ERROR_NOT_SUPPORTED; +#endif /* defined(MBEDTLS_RSA_C) */ + } + else + { + /* Unknown key type */ + return( PSA_ERROR_NOT_SUPPORTED ); + } + return( status ); } @@ -964,35 +1202,14 @@ static psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot ) } else #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ - if( slot->attr.type == PSA_KEY_TYPE_NONE ) { - /* No key material to clean. */ - } - else if( key_type_is_raw_bytes( slot->attr.type ) ) - { - mbedtls_free( slot->data.raw.data ); - } - else -#if defined(MBEDTLS_RSA_C) - if( PSA_KEY_TYPE_IS_RSA( slot->attr.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->attr.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_CORRUPTION_DETECTED ); + /* Data pointer will always be either a valid pointer or NULL in an + * initialized slot, so we can just free it. */ + if( slot->data.key.data != NULL ) + mbedtls_platform_zeroize( slot->data.key.data, slot->data.key.bytes); + mbedtls_free( slot->data.key.data ); + slot->data.key.data = NULL; + slot->data.key.bytes = 0; } return( PSA_SUCCESS ); @@ -1228,7 +1445,21 @@ psa_status_t psa_get_key_attributes( psa_key_handle_t handle, if( psa_key_slot_is_external( slot ) ) break; #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ - status = psa_get_rsa_public_exponent( slot->data.rsa, attributes ); + { + mbedtls_rsa_context *rsa = NULL; + + status = psa_load_rsa_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + break; + + status = psa_get_rsa_public_exponent( rsa, + attributes ); + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + } break; #endif /* MBEDTLS_RSA_C */ default: @@ -1256,21 +1487,19 @@ psa_status_t psa_get_key_slot_number( } #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ -#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECP_C) -static int pk_write_pubkey_simple( mbedtls_pk_context *key, - unsigned char *buf, size_t size ) +static psa_status_t psa_internal_export_key_buffer( const psa_key_slot_t *slot, + uint8_t *data, + size_t data_size, + size_t *data_length ) { - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - unsigned char *c; - size_t len = 0; - - c = buf + size; - - MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) ); - - return( (int) len ); + if( slot->data.key.bytes > data_size ) + return( PSA_ERROR_BUFFER_TOO_SMALL ); + memcpy( data, slot->data.key.data, slot->data.key.bytes ); + memset( data + slot->data.key.bytes, 0, + data_size - slot->data.key.bytes ); + *data_length = slot->data.key.bytes; + return( PSA_SUCCESS ); } -#endif /* defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECP_C) */ static psa_status_t psa_internal_export_key( const psa_key_slot_t *slot, uint8_t *data, @@ -1313,97 +1542,86 @@ static psa_status_t psa_internal_export_key( const psa_key_slot_t *slot, if( key_type_is_raw_bytes( slot->attr.type ) ) { - if( slot->data.raw.bytes > data_size ) - return( PSA_ERROR_BUFFER_TOO_SMALL ); - 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 ); + return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) ); } -#if defined(MBEDTLS_ECP_C) - if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( slot->attr.type ) && !export_public_key ) + else if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) || + PSA_KEY_TYPE_IS_ECC( slot->attr.type ) ) { - psa_status_t status; - - size_t bytes = PSA_BITS_TO_BYTES( slot->attr.bits ); - 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->attr.type ) || - PSA_KEY_TYPE_IS_ECC( slot->attr.type ) ) + if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) ) + { + /* Exporting public -> public */ + return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) ); + } + else if( !export_public_key ) + { + /* Exporting private -> private */ + return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) ); + } + /* Need to export the public part of a private key, + * so conversion is needed */ + if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) { - mbedtls_pk_context pk; - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) - { #if defined(MBEDTLS_RSA_C) - mbedtls_pk_init( &pk ); - pk.pk_info = &mbedtls_rsa_info; - pk.pk_ctx = slot->data.rsa; + mbedtls_rsa_context *rsa = NULL; + psa_status_t status = psa_load_rsa_representation( + slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + return( status ); + + status = psa_export_rsa_key( PSA_KEY_TYPE_RSA_PUBLIC_KEY, + rsa, + data, + data_size, + data_length ); + + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + + return( status ); #else - return( PSA_ERROR_NOT_SUPPORTED ); + /* We don't know how to convert a private RSA key to public. */ + 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->attr.type ) ) - { - ret = pk_write_pubkey_simple( &pk, data, data_size ); - } - else - { - ret = mbedtls_pk_write_key_der( &pk, data, data_size ); - } - if( ret < 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. */ +#if defined(MBEDTLS_ECP_C) + mbedtls_ecp_keypair *ecp = NULL; + psa_status_t status = psa_load_ecp_representation( + slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &ecp ); + if( status != PSA_SUCCESS ) + return( status ); + + status = psa_export_ecp_key( PSA_KEY_TYPE_ECC_PUBLIC_KEY( + PSA_KEY_TYPE_ECC_GET_FAMILY( + slot->attr.type ) ), + ecp, + data, + data_size, + data_length ); + + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + return( status ); +#else + /* We don't know how to convert a private ECC key to public */ return( PSA_ERROR_NOT_SUPPORTED ); +#endif } } + else + { + /* 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_handle_t handle, @@ -1498,16 +1716,17 @@ static psa_status_t psa_validate_key_attributes( const psa_key_attributes_t *attributes, psa_se_drv_table_entry_t **p_drv ) { - psa_status_t status; + psa_status_t status = PSA_ERROR_INVALID_ARGUMENT; - if( attributes->core.lifetime != PSA_KEY_LIFETIME_VOLATILE ) - { - status = psa_validate_persistent_key_parameters( - attributes->core.lifetime, attributes->core.id, - p_drv, 1 ); - if( status != PSA_SUCCESS ) - return( status ); - } + status = psa_validate_key_location( psa_get_key_lifetime( attributes ), + p_drv ); + if( status != PSA_SUCCESS ) + return( status ); + + status = psa_validate_key_persistence( psa_get_key_lifetime( attributes ), + psa_get_key_id( attributes ) ); + if( status != PSA_SUCCESS ) + return( status ); status = psa_validate_key_policy( &attributes->core.policy ); if( status != PSA_SUCCESS ) @@ -1593,11 +1812,14 @@ static psa_status_t psa_start_key_creation( #if defined(MBEDTLS_PSA_CRYPTO_SE_C) /* For a key in a secure element, we need to do three things - * when creating or registering a key: + * when creating or registering a persistent key: * create the key file in internal storage, create the * key inside the secure element, and update the driver's - * persistent data. Start a transaction that will encompass these - * three actions. */ + * persistent data. This is done by starting a transaction that will + * encompass these three actions. + * For registering a volatile key, we just need to find an appropriate + * slot number inside the SE. Since the key is designated volatile, creating + * a transaction is not required. */ /* The first thing to do is to find a slot number for the new key. * We save the slot number in persistent storage as part of the * transaction data. It will be needed to recover if the power @@ -1612,15 +1834,19 @@ static psa_status_t psa_start_key_creation( &slot->data.se.slot_number ); if( status != PSA_SUCCESS ) return( status ); - psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY ); - psa_crypto_transaction.key.lifetime = slot->attr.lifetime; - psa_crypto_transaction.key.slot = slot->data.se.slot_number; - psa_crypto_transaction.key.id = slot->attr.id; - status = psa_crypto_save_transaction( ); - if( status != PSA_SUCCESS ) + + if( ! PSA_KEY_LIFETIME_IS_VOLATILE( attributes->core.lifetime ) ) { - (void) psa_crypto_stop_transaction( ); - return( status ); + psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY ); + psa_crypto_transaction.key.lifetime = slot->attr.lifetime; + psa_crypto_transaction.key.slot = slot->data.se.slot_number; + psa_crypto_transaction.key.id = slot->attr.id; + status = psa_crypto_save_transaction( ); + if( status != PSA_SUCCESS ) + { + (void) psa_crypto_stop_transaction( ); + return( status ); + } } } @@ -1660,7 +1886,7 @@ static psa_status_t psa_finish_key_creation( (void) driver; #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) - if( slot->attr.lifetime != PSA_KEY_LIFETIME_VOLATILE ) + if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) ) { #if defined(MBEDTLS_PSA_CRYPTO_SE_C) if( driver != NULL ) @@ -1708,8 +1934,8 @@ static psa_status_t psa_finish_key_creation( /* Finish the transaction for a key creation. This does not * happen when registering an existing key. Detect this case * by checking whether a transaction is in progress (actual - * creation of a key in a secure element requires a transaction, - * but registration doesn't use one). */ + * creation of a persistent key in a secure element requires a transaction, + * but registration or volatile key creation doesn't use one). */ if( driver != NULL && psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY ) { @@ -1792,12 +2018,24 @@ static psa_status_t psa_validate_optional_attributes( #if defined(MBEDTLS_RSA_C) if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) { + mbedtls_rsa_context *rsa = NULL; mbedtls_mpi actual, required; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + + psa_status_t status = psa_load_rsa_representation( + slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + return( status ); + mbedtls_mpi_init( &actual ); mbedtls_mpi_init( &required ); - ret = mbedtls_rsa_export( slot->data.rsa, + ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &actual ); + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); if( ret != 0 ) goto rsa_exit; ret = mbedtls_mpi_read_binary( &required, @@ -2716,7 +2954,7 @@ static int psa_cmac_setup( psa_mac_operation_t *operation, return( ret ); ret = mbedtls_cipher_cmac_starts( &operation->ctx.cmac, - slot->data.raw.data, + slot->data.key.data, key_bits ); return( ret ); } @@ -2780,7 +3018,7 @@ static psa_status_t psa_hmac_setup_internal( psa_hmac_internal_data *hmac, status = psa_hash_update( &hmac->hash_ctx, ipad, block_size ); cleanup: - mbedtls_platform_zeroize( ipad, sizeof(ipad) ); + mbedtls_platform_zeroize( ipad, sizeof( ipad ) ); return( status ); } @@ -2860,8 +3098,8 @@ static psa_status_t psa_mac_setup( psa_mac_operation_t *operation, } status = psa_hmac_setup_internal( &operation->ctx.hmac, - slot->data.raw.data, - slot->data.raw.bytes, + slot->data.key.data, + slot->data.key.bytes, hash_alg ); } else @@ -3371,6 +3609,14 @@ static psa_status_t psa_ecdsa_verify( mbedtls_ecp_keypair *ecp, signature + curve_bytes, curve_bytes ) ); + /* Check whether the public part is loaded. If not, load it. */ + if( mbedtls_ecp_is_zero( &ecp->Q ) ) + { + MBEDTLS_MPI_CHK( + mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G, + mbedtls_ctr_drbg_random, &global_data.ctr_drbg ) ); + } + ret = mbedtls_ecdsa_verify( &ecp->grp, hash, hash_length, &ecp->Q, &r, &s ); @@ -3434,11 +3680,23 @@ psa_status_t psa_sign_hash( psa_key_handle_t handle, #if defined(MBEDTLS_RSA_C) if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR ) { - status = psa_rsa_sign( slot->data.rsa, + mbedtls_rsa_context *rsa = NULL; + + status = psa_load_rsa_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + goto exit; + + status = psa_rsa_sign( rsa, alg, hash, hash_length, signature, signature_size, signature_length ); + + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); } else #endif /* defined(MBEDTLS_RSA_C) */ @@ -3453,11 +3711,22 @@ psa_status_t psa_sign_hash( psa_key_handle_t handle, PSA_ALG_IS_RANDOMIZED_ECDSA( alg ) #endif ) - status = psa_ecdsa_sign( slot->data.ecp, + { + mbedtls_ecp_keypair *ecp = NULL; + status = psa_load_ecp_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &ecp ); + if( status != PSA_SUCCESS ) + goto exit; + status = psa_ecdsa_sign( ecp, alg, hash, hash_length, signature, signature_size, signature_length ); + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + } else #endif /* defined(MBEDTLS_ECDSA_C) */ { @@ -3520,10 +3789,22 @@ psa_status_t psa_verify_hash( psa_key_handle_t handle, #if defined(MBEDTLS_RSA_C) if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) { - return( psa_rsa_verify( slot->data.rsa, - alg, - hash, hash_length, - signature, signature_length ) ); + mbedtls_rsa_context *rsa = NULL; + + status = psa_load_rsa_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + return( status ); + + status = psa_rsa_verify( rsa, + alg, + hash, hash_length, + signature, signature_length ); + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + return( status ); } else #endif /* defined(MBEDTLS_RSA_C) */ @@ -3532,9 +3813,21 @@ psa_status_t psa_verify_hash( psa_key_handle_t handle, { #if defined(MBEDTLS_ECDSA_C) if( PSA_ALG_IS_ECDSA( alg ) ) - return( psa_ecdsa_verify( slot->data.ecp, - hash, hash_length, - signature, signature_length ) ); + { + mbedtls_ecp_keypair *ecp = NULL; + status = psa_load_ecp_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &ecp ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_ecdsa_verify( ecp, + hash, hash_length, + signature, signature_length ); + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + return( status ); + } else #endif /* defined(MBEDTLS_ECDSA_C) */ { @@ -3593,20 +3886,30 @@ psa_status_t psa_asymmetric_encrypt( psa_key_handle_t handle, #if defined(MBEDTLS_RSA_C) if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ) { - mbedtls_rsa_context *rsa = slot->data.rsa; - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + mbedtls_rsa_context *rsa = NULL; + status = psa_load_rsa_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + goto rsa_exit; + if( output_size < mbedtls_rsa_get_len( rsa ) ) - return( PSA_ERROR_BUFFER_TOO_SMALL ); + { + status = PSA_ERROR_BUFFER_TOO_SMALL; + goto rsa_exit; + } #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 ); + status = mbedtls_to_psa_error( + 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 */ @@ -3614,23 +3917,29 @@ psa_status_t psa_asymmetric_encrypt( psa_key_handle_t handle, 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 ); + status = mbedtls_to_psa_error( + 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 ); + status = PSA_ERROR_INVALID_ARGUMENT; + goto rsa_exit; } - if( ret == 0 ) +rsa_exit: + if( status == PSA_SUCCESS ) *output_length = mbedtls_rsa_get_len( rsa ); - return( mbedtls_to_psa_error( ret ) ); + + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + return( status ); } else #endif /* defined(MBEDTLS_RSA_C) */ @@ -3672,23 +3981,32 @@ psa_status_t psa_asymmetric_decrypt( psa_key_handle_t handle, #if defined(MBEDTLS_RSA_C) if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR ) { - mbedtls_rsa_context *rsa = slot->data.rsa; - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; + mbedtls_rsa_context *rsa = NULL; + status = psa_load_rsa_representation( slot->attr.type, + slot->data.key.data, + slot->data.key.bytes, + &rsa ); + if( status != PSA_SUCCESS ) + return( status ); if( input_length != mbedtls_rsa_get_len( rsa ) ) - return( PSA_ERROR_INVALID_ARGUMENT ); + { + status = PSA_ERROR_INVALID_ARGUMENT; + goto rsa_exit; + } #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 ); + status = mbedtls_to_psa_error( + 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 */ @@ -3696,23 +4014,27 @@ psa_status_t psa_asymmetric_decrypt( psa_key_handle_t handle, 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 ); + status = mbedtls_to_psa_error( + 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 ); + status = PSA_ERROR_INVALID_ARGUMENT; } - return( mbedtls_to_psa_error( ret ) ); +rsa_exit: + mbedtls_rsa_free( rsa ); + mbedtls_free( rsa ); + return( status ); } else #endif /* defined(MBEDTLS_RSA_C) */ @@ -3793,8 +4115,8 @@ static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation, { /* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */ uint8_t keys[24]; - memcpy( keys, slot->data.raw.data, 16 ); - memcpy( keys + 16, slot->data.raw.data, 8 ); + memcpy( keys, slot->data.key.data, 16 ); + memcpy( keys + 16, slot->data.key.data, 8 ); ret = mbedtls_cipher_setkey( &operation->ctx.cipher, keys, 192, cipher_operation ); @@ -3803,7 +4125,7 @@ static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation, #endif { ret = mbedtls_cipher_setkey( &operation->ctx.cipher, - slot->data.raw.data, + slot->data.key.data, (int) key_bits, cipher_operation ); } if( ret != 0 ) @@ -4135,7 +4457,7 @@ static psa_status_t psa_aead_setup( aead_operation_t *operation, mbedtls_ccm_init( &operation->ctx.ccm ); status = mbedtls_to_psa_error( mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id, - operation->slot->data.raw.data, + operation->slot->data.key.data, (unsigned int) key_bits ) ); if( status != 0 ) goto cleanup; @@ -4154,7 +4476,7 @@ static psa_status_t psa_aead_setup( aead_operation_t *operation, mbedtls_gcm_init( &operation->ctx.gcm ); status = mbedtls_to_psa_error( mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id, - operation->slot->data.raw.data, + operation->slot->data.key.data, (unsigned int) key_bits ) ); if( status != 0 ) goto cleanup; @@ -4171,7 +4493,7 @@ static psa_status_t psa_aead_setup( aead_operation_t *operation, mbedtls_chachapoly_init( &operation->ctx.chachapoly ); status = mbedtls_to_psa_error( mbedtls_chachapoly_setkey( &operation->ctx.chachapoly, - operation->slot->data.raw.data ) ); + operation->slot->data.key.data ) ); if( status != 0 ) goto cleanup; break; @@ -4475,7 +4797,7 @@ psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_ if( operation->alg == 0 ) { /* This is a blank key derivation operation. */ - return PSA_ERROR_BAD_STATE; + return( PSA_ERROR_BAD_STATE ); } *capacity = operation->capacity; @@ -4722,7 +5044,7 @@ psa_status_t psa_key_derivation_output_bytes( if( operation->alg == 0 ) { /* This is a blank operation. */ - return PSA_ERROR_BAD_STATE; + return( PSA_ERROR_BAD_STATE ); } if( output_length > operation->capacity ) @@ -5244,8 +5566,8 @@ psa_status_t psa_key_derivation_input_key( return( psa_key_derivation_input_internal( operation, step, slot->attr.type, - slot->data.raw.data, - slot->data.raw.bytes ) ); + slot->data.key.data, + slot->data.key.bytes ) ); } @@ -5266,12 +5588,13 @@ static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key, mbedtls_ecdh_context ecdh; psa_status_t status; size_t bits = 0; - psa_ecc_curve_t curve = mbedtls_ecc_group_to_psa( our_key->grp.id, &bits ); + psa_ecc_family_t curve = mbedtls_ecc_group_to_psa( our_key->grp.id, &bits ); mbedtls_ecdh_init( &ecdh ); - status = psa_import_ec_public_key( curve, - peer_key, peer_key_length, - &their_key ); + status = psa_load_ecp_representation( PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve), + peer_key, + peer_key_length, + &their_key ); if( status != PSA_SUCCESS ) goto exit; @@ -5301,6 +5624,7 @@ exit: mbedtls_ecdh_free( &ecdh ); mbedtls_ecp_keypair_free( their_key ); mbedtls_free( their_key ); + return( status ); } #endif /* MBEDTLS_ECDH_C */ @@ -5321,10 +5645,21 @@ static psa_status_t psa_key_agreement_raw_internal( psa_algorithm_t alg, case PSA_ALG_ECDH: if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( private_key->attr.type ) ) return( PSA_ERROR_INVALID_ARGUMENT ); - return( psa_key_agreement_ecdh( peer_key, peer_key_length, - private_key->data.ecp, - shared_secret, shared_secret_size, - shared_secret_length ) ); + mbedtls_ecp_keypair *ecp = NULL; + psa_status_t status = psa_load_ecp_representation( + private_key->attr.type, + private_key->data.key.data, + private_key->data.key.bytes, + &ecp ); + if( status != PSA_SUCCESS ) + return( status ); + status = psa_key_agreement_ecdh( peer_key, peer_key_length, + ecp, + shared_secret, shared_secret_size, + shared_secret_length ); + mbedtls_ecp_keypair_free( ecp ); + mbedtls_free( ecp ); + return( status ); #endif /* MBEDTLS_ECDH_C */ default: (void) private_key; @@ -5523,17 +5858,26 @@ static psa_status_t psa_generate_key_internal( if( key_type_is_raw_bytes( type ) ) { psa_status_t status; - status = prepare_raw_data_slot( type, bits, &slot->data.raw ); + + status = validate_unstructured_key_bit_size( slot->attr.type, bits ); if( status != PSA_SUCCESS ) return( status ); - status = psa_generate_random( slot->data.raw.data, - slot->data.raw.bytes ); + + /* Allocate memory for the key */ + status = psa_allocate_buffer_to_slot( slot, PSA_BITS_TO_BYTES( bits ) ); if( status != PSA_SUCCESS ) return( status ); + + status = psa_generate_random( slot->data.key.data, + slot->data.key.bytes ); + if( status != PSA_SUCCESS ) + return( status ); + + slot->attr.bits = (psa_key_bits_t) bits; #if defined(MBEDTLS_DES_C) if( type == PSA_KEY_TYPE_DES ) - psa_des_set_key_parity( slot->data.raw.data, - slot->data.raw.bytes ); + psa_des_set_key_parity( slot->data.key.data, + slot->data.key.bytes ); #endif /* MBEDTLS_DES_C */ } else @@ -5541,7 +5885,7 @@ static psa_status_t psa_generate_key_internal( #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME) if ( type == PSA_KEY_TYPE_RSA_KEY_PAIR ) { - mbedtls_rsa_context *rsa; + mbedtls_rsa_context rsa; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; int exponent; psa_status_t status; @@ -5556,22 +5900,34 @@ static psa_status_t psa_generate_key_internal( &exponent ); if( status != PSA_SUCCESS ) return( status ); - 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_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 ) ); + + /* Make sure to always have an export representation available */ + size_t bytes = PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE( bits ); + + status = psa_allocate_buffer_to_slot( slot, bytes ); + if( status != PSA_SUCCESS ) + { + mbedtls_rsa_free( &rsa ); + return( status ); } - slot->data.rsa = rsa; + + status = psa_export_rsa_key( type, + &rsa, + slot->data.key.data, + bytes, + &slot->data.key.bytes ); + mbedtls_rsa_free( &rsa ); + if( status != PSA_SUCCESS ) + psa_remove_key_data_from_memory( slot ); + return( status ); } else #endif /* MBEDTLS_RSA_C && MBEDTLS_GENPRIME */ @@ -5579,12 +5935,12 @@ static psa_status_t psa_generate_key_internal( #if defined(MBEDTLS_ECP_C) if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) ) { - psa_ecc_curve_t curve = PSA_KEY_TYPE_GET_CURVE( type ); + psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY( type ); mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve, PSA_BITS_TO_BYTES( bits ) ); const mbedtls_ecp_curve_info *curve_info = mbedtls_ecp_curve_info_from_grp_id( grp_id ); - mbedtls_ecp_keypair *ecp; + mbedtls_ecp_keypair ecp; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( domain_parameters_size != 0 ) return( PSA_ERROR_NOT_SUPPORTED ); @@ -5592,25 +5948,41 @@ static psa_status_t psa_generate_key_internal( 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_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 ); + mbedtls_ecp_keypair_free( &ecp ); return( mbedtls_to_psa_error( ret ) ); } - slot->data.ecp = ecp; + + + /* Make sure to always have an export representation available */ + size_t bytes = PSA_BITS_TO_BYTES( bits ); + psa_status_t status = psa_allocate_buffer_to_slot( slot, bytes ); + if( status != PSA_SUCCESS ) + { + mbedtls_ecp_keypair_free( &ecp ); + return( status ); + } + + status = mbedtls_to_psa_error( + mbedtls_ecp_write_key( &ecp, slot->data.key.data, bytes ) ); + + mbedtls_ecp_keypair_free( &ecp ); + if( status != PSA_SUCCESS ) { + memset( slot->data.key.data, 0, bytes ); + psa_remove_key_data_from_memory( slot ); + } + return( status ); } else #endif /* MBEDTLS_ECP_C */ - + { return( PSA_ERROR_NOT_SUPPORTED ); + } return( PSA_SUCCESS ); } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_core.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_core.h index edf3ab6031..9a61babb50 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_core.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_core.h @@ -1,7 +1,8 @@ /* * PSA crypto core internal interfaces */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +16,6 @@ * 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_CORE_H @@ -31,9 +30,6 @@ #include "psa/crypto.h" #include "psa/crypto_se_driver.h" -#include "mbedtls/ecp.h" -#include "mbedtls/rsa.h" - /** The data structure representing a key slot, containing key material * and metadata for one key. */ @@ -42,20 +38,13 @@ typedef struct psa_core_key_attributes_t attr; union { - /* Raw-data key (key_type_is_raw_bytes() in psa_crypto.c) */ - struct raw_data + /* Dynamically allocated key data buffer. + * Format as specified in psa_export_key(). */ + struct key_data { uint8_t *data; size_t bytes; - } raw; -#if defined(MBEDTLS_RSA_C) - /* RSA public key or key pair */ - mbedtls_rsa_context *rsa; -#endif /* MBEDTLS_RSA_C */ -#if defined(MBEDTLS_ECP_C) - /* EC public key or key pair */ - mbedtls_ecp_keypair *ecp; -#endif /* MBEDTLS_ECP_C */ + } key; #if defined(MBEDTLS_PSA_CRYPTO_SE_C) /* Any key type in a secure element */ struct se diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_invasive.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_invasive.h index 642652a479..c609c777ed 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_invasive.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_invasive.h @@ -9,7 +9,7 @@ * integrations except when building the library for testing. */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -23,8 +23,6 @@ * 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_INVASIVE_H diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_its.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_its.h index 3809787607..93c4ce981c 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_its.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_its.h @@ -1,7 +1,8 @@ /** \file psa_crypto_its.h * \brief Interface of trusted storage that crypto is built on. */ -/* Copyright (C) 2019, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.c index b7fa0c5c5e..56678d6a90 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.c @@ -1,7 +1,8 @@ /* * PSA crypto support for secure element drivers */ -/* Copyright (C) 2019, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +16,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PSA_CRYPTO_SE_C) @@ -64,16 +59,16 @@ typedef struct uintptr_t transient_data; } psa_drv_se_internal_context_t; -typedef struct psa_se_drv_table_entry_s +struct psa_se_drv_table_entry_s { - psa_key_lifetime_t lifetime; + psa_key_location_t location; const psa_drv_se_t *methods; union { psa_drv_se_internal_context_t internal; psa_drv_se_context_t context; - }; -} psa_se_drv_table_entry_t; + } u; +}; static psa_se_drv_table_entry_t driver_table[PSA_MAX_SE_DRIVERS]; @@ -81,15 +76,16 @@ psa_se_drv_table_entry_t *psa_get_se_driver_entry( psa_key_lifetime_t lifetime ) { size_t i; - /* In the driver table, lifetime=0 means an entry that isn't used. - * No driver has a lifetime of 0 because it's a reserved value - * (which designates volatile keys). Make sure we never return - * a driver entry for lifetime 0. */ - if( lifetime == 0 ) + psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION( lifetime ); + /* In the driver table, location=0 means an entry that isn't used. + * No driver has a location of 0 because it's a reserved value + * (which designates transparent keys). Make sure we never return + * a driver entry for location 0. */ + if( location == 0 ) return( NULL ); for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ ) { - if( driver_table[i].lifetime == lifetime ) + if( driver_table[i].location == location ) return( &driver_table[i] ); } return( NULL ); @@ -104,7 +100,7 @@ const psa_drv_se_t *psa_get_se_driver_methods( psa_drv_se_context_t *psa_get_se_driver_context( psa_se_drv_table_entry_t *driver ) { - return( &driver->context ); + return( &driver->u.context ); } int psa_get_se_driver( psa_key_lifetime_t lifetime, @@ -115,7 +111,7 @@ int psa_get_se_driver( psa_key_lifetime_t lifetime, if( p_methods != NULL ) *p_methods = ( driver ? driver->methods : NULL ); if( p_drv_context != NULL ) - *p_drv_context = ( driver ? &driver->context : NULL ); + *p_drv_context = ( driver ? &driver->u.context : NULL ); return( driver != NULL ); } @@ -129,17 +125,17 @@ static psa_status_t psa_get_se_driver_its_file_uid( const psa_se_drv_table_entry_t *driver, psa_storage_uid_t *uid ) { - if( driver->lifetime > PSA_MAX_SE_LIFETIME ) + if( driver->location > PSA_MAX_SE_LOCATION ) return( PSA_ERROR_NOT_SUPPORTED ); #if SIZE_MAX > UINT32_MAX /* ITS file sizes are limited to 32 bits. */ - if( driver->internal.persistent_data_size > UINT32_MAX ) + if( driver->u.internal.persistent_data_size > UINT32_MAX ) return( PSA_ERROR_NOT_SUPPORTED ); #endif /* See the documentation of PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE. */ - *uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + driver->lifetime; + *uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + driver->location; return( PSA_SUCCESS ); } @@ -162,8 +158,8 @@ psa_status_t psa_load_se_persistent_data( * persistent_data_size is in range, but compilers don't know that, * so cast to reassure them. */ return( psa_its_get( uid, 0, - (uint32_t) driver->internal.persistent_data_size, - driver->internal.persistent_data, + (uint32_t) driver->u.internal.persistent_data_size, + driver->u.internal.persistent_data, &length ) ); } @@ -181,17 +177,17 @@ psa_status_t psa_save_se_persistent_data( * persistent_data_size is in range, but compilers don't know that, * so cast to reassure them. */ return( psa_its_set( uid, - (uint32_t) driver->internal.persistent_data_size, - driver->internal.persistent_data, + (uint32_t) driver->u.internal.persistent_data_size, + driver->u.internal.persistent_data, 0 ) ); } -psa_status_t psa_destroy_se_persistent_data( psa_key_lifetime_t lifetime ) +psa_status_t psa_destroy_se_persistent_data( psa_key_location_t location ) { psa_storage_uid_t uid; - if( lifetime > PSA_MAX_SE_LIFETIME ) + if( location > PSA_MAX_SE_LOCATION ) return( PSA_ERROR_NOT_SUPPORTED ); - uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + lifetime; + uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + location; return( psa_its_remove( uid ) ); } @@ -202,9 +198,11 @@ psa_status_t psa_find_se_slot_for_key( psa_key_slot_number_t *slot_number ) { psa_status_t status; + psa_key_location_t key_location = + PSA_KEY_LIFETIME_GET_LOCATION( psa_get_key_lifetime( attributes ) ); - /* If the lifetime is wrong, it's a bug in the library. */ - if( driver->lifetime != psa_get_key_lifetime( attributes ) ) + /* If the location is wrong, it's a bug in the library. */ + if( driver->location != key_location ) return( PSA_ERROR_CORRUPTION_DETECTED ); /* If the driver doesn't support key creation in any way, give up now. */ @@ -221,8 +219,8 @@ psa_status_t psa_find_se_slot_for_key( driver->methods->key_management->p_validate_slot_number; if( p_validate_slot_number == NULL ) return( PSA_ERROR_NOT_SUPPORTED ); - status = p_validate_slot_number( &driver->context, - driver->internal.persistent_data, + status = p_validate_slot_number( &driver->u.context, + driver->u.internal.persistent_data, attributes, method, *slot_number ); } @@ -240,8 +238,8 @@ psa_status_t psa_find_se_slot_for_key( driver->methods->key_management->p_allocate; if( p_allocate == NULL ) return( PSA_ERROR_NOT_SUPPORTED ); - status = p_allocate( &driver->context, - driver->internal.persistent_data, + status = p_allocate( &driver->u.context, + driver->u.internal.persistent_data, attributes, method, slot_number ); } @@ -265,8 +263,8 @@ psa_status_t psa_destroy_se_key( psa_se_drv_table_entry_t *driver, driver->methods->key_management->p_destroy == NULL ) return( PSA_ERROR_NOT_PERMITTED ); status = driver->methods->key_management->p_destroy( - &driver->context, - driver->internal.persistent_data, + &driver->u.context, + driver->u.internal.persistent_data, slot_number ); storage_status = psa_save_se_persistent_data( driver ); return( status == PSA_SUCCESS ? storage_status : status ); @@ -278,15 +276,15 @@ psa_status_t psa_init_all_se_drivers( void ) for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ ) { psa_se_drv_table_entry_t *driver = &driver_table[i]; - if( driver->lifetime == 0 ) + if( driver->location == 0 ) continue; /* skipping unused entry */ const psa_drv_se_t *methods = psa_get_se_driver_methods( driver ); if( methods->p_init != NULL ) { psa_status_t status = methods->p_init( - &driver->context, - driver->internal.persistent_data, - driver->lifetime ); + &driver->u.context, + driver->u.internal.persistent_data, + driver->location ); if( status != PSA_SUCCESS ) return( status ); status = psa_save_se_persistent_data( driver ); @@ -304,7 +302,7 @@ psa_status_t psa_init_all_se_drivers( void ) /****************************************************************/ psa_status_t psa_register_se_driver( - psa_key_lifetime_t lifetime, + psa_key_location_t location, const psa_drv_se_t *methods) { size_t i; @@ -313,42 +311,39 @@ psa_status_t psa_register_se_driver( if( methods->hal_version != PSA_DRV_SE_HAL_VERSION ) return( PSA_ERROR_NOT_SUPPORTED ); /* Driver table entries are 0-initialized. 0 is not a valid driver - * lifetime because it means a volatile key. */ + * location because it means a transparent key. */ #if defined(static_assert) - static_assert( PSA_KEY_LIFETIME_VOLATILE == 0, - "Secure element support requires 0 to mean a volatile key" ); + static_assert( PSA_KEY_LOCATION_LOCAL_STORAGE == 0, + "Secure element support requires 0 to mean a local key" ); #endif - if( lifetime == PSA_KEY_LIFETIME_VOLATILE || - lifetime == PSA_KEY_LIFETIME_PERSISTENT ) - { + if( location == PSA_KEY_LOCATION_LOCAL_STORAGE ) return( PSA_ERROR_INVALID_ARGUMENT ); - } - if( lifetime > PSA_MAX_SE_LIFETIME ) + if( location > PSA_MAX_SE_LOCATION ) return( PSA_ERROR_NOT_SUPPORTED ); for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ ) { - if( driver_table[i].lifetime == 0 ) + if( driver_table[i].location == 0 ) break; - /* Check that lifetime isn't already in use up to the first free + /* Check that location isn't already in use up to the first free * entry. Since entries are created in order and never deleted, * there can't be a used entry after the first free entry. */ - if( driver_table[i].lifetime == lifetime ) + if( driver_table[i].location == location ) return( PSA_ERROR_ALREADY_EXISTS ); } if( i == PSA_MAX_SE_DRIVERS ) return( PSA_ERROR_INSUFFICIENT_MEMORY ); - driver_table[i].lifetime = lifetime; + driver_table[i].location = location; driver_table[i].methods = methods; - driver_table[i].internal.persistent_data_size = + driver_table[i].u.internal.persistent_data_size = methods->persistent_data_size; if( methods->persistent_data_size != 0 ) { - driver_table[i].internal.persistent_data = + driver_table[i].u.internal.persistent_data = mbedtls_calloc( 1, methods->persistent_data_size ); - if( driver_table[i].internal.persistent_data == NULL ) + if( driver_table[i].u.internal.persistent_data == NULL ) { status = PSA_ERROR_INSUFFICIENT_MEMORY; goto error; @@ -373,8 +368,8 @@ void psa_unregister_all_se_drivers( void ) size_t i; for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ ) { - if( driver_table[i].internal.persistent_data != NULL ) - mbedtls_free( driver_table[i].internal.persistent_data ); + if( driver_table[i].u.internal.persistent_data != NULL ) + mbedtls_free( driver_table[i].u.internal.persistent_data ); } memset( driver_table, 0, sizeof( driver_table ) ); } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.h index 86bf7a7b1a..a464232563 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_se.h @@ -1,7 +1,8 @@ /* * PSA crypto support for secure element drivers */ -/* Copyright (C) 2019, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +16,6 @@ * 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_SE_H @@ -31,31 +30,30 @@ #include "psa/crypto.h" #include "psa/crypto_se_driver.h" -/** The maximum lifetime value that this implementation supports +/** The maximum location value that this implementation supports * for a secure element. * * This is not a characteristic that each PSA implementation has, but a * limitation of the current implementation due to the constraints imposed * by storage. See #PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE. * - * The minimum lifetime value for a secure element is 2, like on any - * PSA implementation (0=volatile and 1=internal-storage are taken). + * The minimum location value for a secure element is 1, like on any + * PSA implementation (0 means a transparent key). */ -#define PSA_MAX_SE_LIFETIME 255 +#define PSA_MAX_SE_LOCATION 255 /** The base of the range of ITS file identifiers for secure element * driver persistent data. * * We use a slice of the implemenation reserved range 0xffff0000..0xffffffff, * specifically the range 0xfffffe00..0xfffffeff. The length of this range - * drives the value of #PSA_MAX_SE_LIFETIME. - * The identifiers 0xfffffe00 and 0xfffffe01 are actually not used since - * they correspond to #PSA_KEY_LIFETIME_VOLATILE and - * #PSA_KEY_LIFETIME_PERSISTENT which don't have a driver. + * drives the value of #PSA_MAX_SE_LOCATION. The identifier 0xfffffe00 is + * actually not used since it corresponds to #PSA_KEY_LOCATION_LOCAL_STORAGE + * which doesn't have a driver. */ #define PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE ( (psa_key_id_t) 0xfffffe00 ) -/** The maximum number of registered secure element driver lifetimes. */ +/** The maximum number of registered secure element driver locations. */ #define PSA_MAX_SE_DRIVERS 4 /** Unregister all secure element drivers. @@ -173,10 +171,10 @@ psa_status_t psa_save_se_persistent_data( * * This is currently only used for testing. * - * \param[in] lifetime The driver lifetime whose persistent data should - * be erased. + * \param[in] location The location identifier for the driver whose + * persistent data is to be erased. */ -psa_status_t psa_destroy_se_persistent_data( psa_key_lifetime_t lifetime ); +psa_status_t psa_destroy_se_persistent_data( psa_key_location_t location ); /** The storage representation of a key whose data is in a secure element. diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_service_integration.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_service_integration.h index 938bfe1dec..87889af49c 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_service_integration.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_service_integration.h @@ -1,4 +1,5 @@ -/* Copyright (C) 2019, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -12,8 +13,6 @@ * 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_SERVICE_INTEGRATION_H diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.c index 6cd6a1135b..a32a027980 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.c @@ -1,7 +1,8 @@ /* * PSA crypto layer on top of Mbed TLS crypto */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,15 +16,9 @@ * 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 +#include "common.h" #if defined(MBEDTLS_PSA_CRYPTO_C) @@ -183,36 +178,53 @@ static int psa_is_key_id_valid( psa_key_file_id_t file_id, } #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */ -psa_status_t psa_validate_persistent_key_parameters( - psa_key_lifetime_t lifetime, - psa_key_file_id_t id, - psa_se_drv_table_entry_t **p_drv, - int creating ) +psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime, + psa_se_drv_table_entry_t **p_drv ) { - if( p_drv != NULL ) - *p_drv = NULL; -#if defined(MBEDTLS_PSA_CRYPTO_SE_C) - if( psa_key_lifetime_is_external( lifetime ) ) + if ( psa_key_lifetime_is_external( lifetime ) ) { - *p_drv = psa_get_se_driver_entry( lifetime ); - if( *p_drv == NULL ) +#if defined(MBEDTLS_PSA_CRYPTO_SE_C) + psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry( lifetime ); + if( driver == NULL ) return( PSA_ERROR_INVALID_ARGUMENT ); + else + { + if (p_drv != NULL) + *p_drv = driver; + return( PSA_SUCCESS ); + } +#else + (void) p_drv; + return( PSA_ERROR_INVALID_ARGUMENT ); +#endif /* MBEDTLS_PSA_CRYPTO_SE_C */ } else -#endif /* MBEDTLS_PSA_CRYPTO_SE_C */ - if( lifetime != PSA_KEY_LIFETIME_PERSISTENT ) - return( PSA_ERROR_INVALID_ARGUMENT ); + /* Local/internal keys are always valid */ + return( PSA_SUCCESS ); +} +psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime, + psa_key_id_t key_id ) +{ + if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) ) + { + /* Volatile keys are always supported */ + return( PSA_SUCCESS ); + } + else + { + /* Persistent keys require storage support */ #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) - if( ! psa_is_key_id_valid( id, ! creating ) ) - return( PSA_ERROR_INVALID_ARGUMENT ); - return( PSA_SUCCESS ); - + if( psa_is_key_id_valid( key_id, + psa_key_lifetime_is_external( lifetime ) ) ) + return( PSA_SUCCESS ); + else + return( PSA_ERROR_INVALID_ARGUMENT ); #else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */ - (void) id; - (void) creating; - return( PSA_ERROR_NOT_SUPPORTED ); + (void) key_id; + return( PSA_ERROR_NOT_SUPPORTED ); #endif /* !MBEDTLS_PSA_CRYPTO_STORAGE_C */ + } } psa_status_t psa_open_key( psa_key_file_id_t id, psa_key_handle_t *handle ) @@ -223,10 +235,8 @@ psa_status_t psa_open_key( psa_key_file_id_t id, psa_key_handle_t *handle ) *handle = 0; - status = psa_validate_persistent_key_parameters( - PSA_KEY_LIFETIME_PERSISTENT, id, NULL, 0 ); - if( status != PSA_SUCCESS ) - return( status ); + if( ! psa_is_key_id_valid( id, 1 ) ) + return( PSA_ERROR_INVALID_ARGUMENT ); status = psa_get_empty_key_slot( handle, &slot ); if( status != PSA_SUCCESS ) diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.h index 472253dd9b..676a77e5a0 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_slot_management.h @@ -1,7 +1,8 @@ /* * PSA crypto layer on top of Mbed TLS crypto */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +16,6 @@ * 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_SLOT_MANAGEMENT_H @@ -88,42 +87,40 @@ psa_status_t psa_get_empty_key_slot( psa_key_handle_t *handle, */ static inline int psa_key_lifetime_is_external( psa_key_lifetime_t lifetime ) { - return( lifetime != PSA_KEY_LIFETIME_VOLATILE && - lifetime != PSA_KEY_LIFETIME_PERSISTENT ); + return( PSA_KEY_LIFETIME_GET_LOCATION( lifetime ) + != PSA_KEY_LOCATION_LOCAL_STORAGE ); } -/** Test whether the given parameters are acceptable for a persistent key. +/** Validate a key's location. * - * This function does not access the storage in any way. It only tests - * whether the parameters are meaningful and permitted by general policy. - * It does not test whether the a file by the given id exists or could be - * created. + * This function checks whether the key's attributes point to a location that + * is known to the PSA Core, and returns the driver function table if the key + * is to be found in an external location. * - * If the key is in external storage, this function returns the corresponding - * driver. + * \param[in] lifetime The key lifetime attribute. + * \param[out] p_drv On success, when a key is located in external + * storage, returns a pointer to the driver table + * associated with the key's storage location. * - * \param lifetime The lifetime to test. - * \param id The key id to test. - * \param[out] p_drv On output, if \p lifetime designates a key - * in an external processor, \c *p_drv is a pointer - * to the driver table entry fot this lifetime. - * If \p lifetime designates a transparent key, - * \c *p_drv is \c NULL. - * \param creating 0 if attempting to open an existing key. - * Nonzero if attempting to create a key. - * - * \retval PSA_SUCCESS - * The given parameters are valid. - * \retval PSA_ERROR_INVALID_ARGUMENT - * \p lifetime is volatile or is invalid. - * \retval PSA_ERROR_INVALID_ARGUMENT - * \p id is invalid. + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_INVALID_ARGUMENT */ -psa_status_t psa_validate_persistent_key_parameters( - psa_key_lifetime_t lifetime, - psa_key_file_id_t id, - psa_se_drv_table_entry_t **p_drv, - int creating ); +psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime, + psa_se_drv_table_entry_t **p_drv ); + +/** Validate that a key's persistence attributes are valid. + * + * This function checks whether a key's declared persistence level and key ID + * attributes are valid and known to the PSA Core in its actual configuration. + * + * \param[in] lifetime The key lifetime attribute. + * \param[in] key_id The key ID attribute + * + * \retval #PSA_SUCCESS + * \retval #PSA_ERROR_INVALID_ARGUMENT + */ +psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime, + psa_key_id_t key_id ); #endif /* PSA_CRYPTO_SLOT_MANAGEMENT_H */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.c index fa1214c86d..103c9bbb8e 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.c @@ -1,7 +1,8 @@ /* * PSA persistent key storage */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +16,6 @@ * 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) @@ -175,7 +174,13 @@ static psa_status_t psa_crypto_storage_store( const psa_key_file_id_t key, exit: if( status != PSA_SUCCESS ) - psa_its_remove( data_identifier ); + { + /* Remove the file in case we managed to create it but something + * went wrong. It's ok if the file doesn't exist. If the file exists + * but the removal fails, we're already reporting an error so there's + * nothing else we can do. */ + (void) psa_its_remove( data_identifier ); + } return( status ); } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.h index 1b7dbd67c7..debc742bd1 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_crypto_storage.h @@ -4,7 +4,7 @@ * \brief PSA cryptography module: Mbed TLS key storage */ /* - * Copyright (C) 2018, ARM Limited, All Rights Reserved + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -18,8 +18,6 @@ * 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 diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_its_file.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_its_file.c index 0935b2780c..2fbff20ef9 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_its_file.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/mbedtls/psa_its_file.c @@ -1,7 +1,8 @@ /* * PSA ITS simulator over stdio files. */ -/* Copyright (C) 2018, ARM Limited, All Rights Reserved +/* + * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -15,8 +16,6 @@ * 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) @@ -234,7 +233,12 @@ exit: if( rename_replace_existing( PSA_ITS_STORAGE_TEMP, filename ) != 0 ) status = PSA_ERROR_STORAGE_FAILURE; } - remove( PSA_ITS_STORAGE_TEMP ); + /* The temporary file may still exist, but only in failure cases where + * we're already reporting an error. So there's nothing we can do on + * failure. If the function succeeded, and in some error cases, the + * temporary file doesn't exist and so remove() is expected to fail. + * Thus we just ignore the return status of remove(). */ + (void) remove( PSA_ITS_STORAGE_TEMP ); return( status ); } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/CMakeLists.txt b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/CMakeLists.txt index 0608fb1c94..9413529dff 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/CMakeLists.txt +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/CMakeLists.txt @@ -5,6 +5,6 @@ if("TFM_V1_0" IN_LIST MBED_TARGET_LABELS) add_subdirectory(TARGET_TFM_V1_0) endif() -if("TFM_V1_1" IN_LIST MBED_TARGET_LABELS) - add_subdirectory(TARGET_TFM_V1_1) +if("TFM_LATEST" IN_LIST MBED_TARGET_LABELS) + add_subdirectory(TARGET_TFM_LATEST) endif() diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/CMakeLists.txt b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/CMakeLists.txt similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/CMakeLists.txt rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/CMakeLists.txt diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/platform_multicore.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/platform_multicore.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/platform_multicore.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/platform_multicore.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/platform_ns_mailbox.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/platform_ns_mailbox.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/platform_ns_mailbox.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/platform_ns_mailbox.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_mbed_boot.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_mbed_boot.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_mbed_boot.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_mbed_boot.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_multi_core_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_multi_core_api.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_multi_core_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_multi_core_api.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_multi_core_psa_ns_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_multi_core_psa_ns_api.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_multi_core_psa_ns_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_multi_core_psa_ns_api.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_ns_mailbox.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_ns_mailbox.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_DUALCPU/src/tfm_ns_mailbox.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_DUALCPU/src/tfm_ns_mailbox.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/cmsis_nvic_virtual.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/cmsis_nvic_virtual.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/cmsis_nvic_virtual.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/cmsis_nvic_virtual.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_mbed_boot.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_mbed_boot.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_mbed_boot.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_mbed_boot.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_ns_interface.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_ns_interface.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_ns_interface.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_ns_interface.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_psa_ns_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_psa_ns_api.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/TARGET_TFM_V8M/src/tfm_psa_ns_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/TARGET_TFM_V8M/src/tfm_psa_ns_api.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/VERSION.txt b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/VERSION.txt new file mode 100644 index 0000000000..e3904faf6b --- /dev/null +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/VERSION.txt @@ -0,0 +1 @@ +f17ce5d3dc6a diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/cmsis_nvic_virtual.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/cmsis_nvic_virtual.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/cmsis_nvic_virtual.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/cmsis_nvic_virtual.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/ns_ipc_config.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/ns_ipc_config.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/ns_ipc_config.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/ns_ipc_config.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/platform_multicore.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/platform_multicore.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/platform_multicore.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/platform_multicore.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/client.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/client.h similarity index 98% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/client.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/client.h index 4115f930e9..a5e851803f 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/client.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/client.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018-2019, Arm Limited. All rights reserved. + * Copyright (c) 2018-2020, Arm Limited. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * @@ -126,7 +126,7 @@ psa_handle_t psa_connect(uint32_t sid, uint32_t version); * \brief Call an RoT Service on an established connection. * * \param[in] handle A handle to an established connection. - * \param[in] type The reuqest type. + * \param[in] type The request type. * Must be zero( \ref PSA_IPC_CALL) or positive. * \param[in] in_vec Array of input \ref psa_invec structures. * \param[in] in_len Number of input \ref psa_invec structures. diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto.h similarity index 99% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto.h index 14591957b8..c58abda240 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto.h @@ -723,11 +723,12 @@ psa_status_t psa_import_key(const psa_key_attributes_t *attributes, * 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. + * `PSA_ECC_FAMILY_CURVEXXX`), and in big-endian order for Weierstrass + * curves (curve types `PSA_ECC_FAMILY_SECTXXX`, `PSA_ECC_FAMILY_SECPXXX` + * and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`). + * For Weierstrass curves, this is the content of the `privateKey` field of + * the `ECPrivateKey` format defined by RFC 5915. For Montgomery curves, + * the format is defined by RFC 7748, and output is masked according to §5. * - For Diffie-Hellman key exchange key pairs (key types for which * #PSA_KEY_TYPE_IS_DH_KEY_PAIR is true), the * format is the representation of the private key `x` as a big-endian byte @@ -920,7 +921,7 @@ psa_status_t psa_hash_compare(psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *hash, - const size_t hash_length); + size_t hash_length); /** The type of the state data structure for multipart hash operations. * @@ -1288,7 +1289,7 @@ psa_status_t psa_mac_verify(psa_key_handle_t handle, const uint8_t *input, size_t input_length, const uint8_t *mac, - const size_t mac_length); + size_t mac_length); /** The type of the state data structure for multipart MAC operations. * @@ -3490,10 +3491,10 @@ psa_status_t psa_key_derivation_output_bytes( * length is determined by the curve, and sets the mandatory bits * accordingly. That is: * - * - #PSA_ECC_CURVE_CURVE25519: draw a 32-byte string - * and process it as specified in RFC 7748 §5. - * - #PSA_ECC_CURVE_CURVE448: draw a 56-byte string - * and process it as specified in RFC 7748 §5. + * - Curve25519 (#PSA_ECC_FAMILY_MONTGOMERY, 255 bits): draw a 32-byte + * string and process it as specified in RFC 7748 §5. + * - Curve448 (#PSA_ECC_FAMILY_MONTGOMERY, 448 bits): draw a 56-byte + * string and process it as specified in RFC 7748 §5. * * - For key types for which the key is represented by a single sequence of * \p bits bits with constraints as to which bit sequences are acceptable, diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_client_struct.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_client_struct.h similarity index 97% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_client_struct.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_client_struct.h index 1d919b051f..ae92bdb3df 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_client_struct.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_client_struct.h @@ -31,13 +31,13 @@ extern "C" { * data structure internally. */ struct psa_client_key_attributes_s { - uint32_t type; uint32_t lifetime; uint32_t id; uint32_t alg; uint32_t alg2; uint32_t usage; - uint16_t bits; + size_t bits; + uint16_t type; }; #define PSA_CLIENT_KEY_ATTRIBUTES_INIT {0, 0, 0, 0, 0, 0, 0} diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_compat.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_compat.h new file mode 100644 index 0000000000..26c205ac9b --- /dev/null +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_compat.h @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2019-2020, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + */ +/** + * \file psa/crypto_compat.h + * + * \brief PSA cryptography module: Backward compatibility aliases + * + * This header declares alternative names for macro and functions. + * New application code should not use these names. + * These names may be removed in a future version of Mbed Crypto. + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + */ + +#ifndef PSA_CRYPTO_COMPAT_H +#define PSA_CRYPTO_COMPAT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) + +/* + * Mechanism for declaring deprecated values + */ +#if defined(MBEDTLS_DEPRECATED_WARNING) && !defined(MBEDTLS_PSA_DEPRECATED) +#define MBEDTLS_PSA_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_PSA_DEPRECATED +#endif + +typedef MBEDTLS_PSA_DEPRECATED size_t mbedtls_deprecated_size_t; +typedef MBEDTLS_PSA_DEPRECATED psa_status_t mbedtls_deprecated_psa_status_t; +typedef MBEDTLS_PSA_DEPRECATED psa_key_usage_t mbedtls_deprecated_psa_key_usage_t; +typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t mbedtls_deprecated_psa_ecc_family_t; +typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t mbedtls_deprecated_psa_dh_family_t; +typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t psa_ecc_curve_t; +typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t psa_dh_group_t; + +#define PSA_KEY_TYPE_GET_CURVE PSA_KEY_TYPE_ECC_GET_FAMILY +#define PSA_KEY_TYPE_GET_GROUP PSA_KEY_TYPE_DH_GET_FAMILY + +#define MBEDTLS_DEPRECATED_CONSTANT( type, value ) \ + ( (mbedtls_deprecated_##type) ( value ) ) + +/* + * Deprecated PSA Crypto error code definitions (PSA Crypto API <= 1.0 beta2) + */ +#define PSA_ERROR_UNKNOWN_ERROR \ + MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_GENERIC_ERROR ) +#define PSA_ERROR_OCCUPIED_SLOT \ + MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_ALREADY_EXISTS ) +#define PSA_ERROR_EMPTY_SLOT \ + MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_DOES_NOT_EXIST ) +#define PSA_ERROR_INSUFFICIENT_CAPACITY \ + MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_INSUFFICIENT_DATA ) +#define PSA_ERROR_TAMPERING_DETECTED \ + MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_CORRUPTION_DETECTED ) + +/* + * Deprecated PSA Crypto numerical encodings (PSA Crypto API <= 1.0 beta3) + */ +#define PSA_KEY_USAGE_SIGN \ + MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_SIGN_HASH ) +#define PSA_KEY_USAGE_VERIFY \ + MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_VERIFY_HASH ) + +/* + * Deprecated PSA Crypto size calculation macros (PSA Crypto API <= 1.0 beta3) + */ +#define PSA_ASYMMETRIC_SIGNATURE_MAX_SIZE \ + MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGNATURE_MAX_SIZE ) +#define PSA_ASYMMETRIC_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) \ + MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) ) + +/* + * Deprecated PSA Crypto function names (PSA Crypto API <= 1.0 beta3) + */ +MBEDTLS_PSA_DEPRECATED psa_status_t psa_asymmetric_sign( psa_key_handle_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 ); + +MBEDTLS_PSA_DEPRECATED psa_status_t psa_asymmetric_verify( psa_key_handle_t key, + psa_algorithm_t alg, + const uint8_t *hash, + size_t hash_length, + const uint8_t *signature, + size_t signature_length ); + +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/* + * Size-specific elliptic curve families. + */ +#define PSA_ECC_CURVE_SECP160K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP192K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP224K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP256K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP160R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP192R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP224R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP256R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP384R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP521R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP160R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) +#define PSA_ECC_CURVE_SECT163K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT233K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT239K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT283K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT409K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT571K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT163R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT193R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT233R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT283R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT409R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT571R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT163R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) +#define PSA_ECC_CURVE_SECT193R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) +#define PSA_ECC_CURVE_BRAINPOOL_P256R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) +#define PSA_ECC_CURVE_BRAINPOOL_P384R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) +#define PSA_ECC_CURVE_BRAINPOOL_P512R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) +#define PSA_ECC_CURVE_CURVE25519 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) +#define PSA_ECC_CURVE_CURVE448 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) + +/* + * Curves that changed name due to PSA specification. + */ +#define PSA_ECC_CURVE_SECP_K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) +#define PSA_ECC_CURVE_SECP_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) +#define PSA_ECC_CURVE_SECP_R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) +#define PSA_ECC_CURVE_SECT_K1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) +#define PSA_ECC_CURVE_SECT_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) +#define PSA_ECC_CURVE_SECT_R2 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) +#define PSA_ECC_CURVE_BRAINPOOL_P_R1 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) +#define PSA_ECC_CURVE_MONTGOMERY \ + MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) + +/* + * Finite-field Diffie-Hellman families. + */ +#define PSA_DH_GROUP_FFDHE2048 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_FFDHE3072 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_FFDHE4096 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_FFDHE6144 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_FFDHE8192 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) + +/* + * Diffie-Hellman families that changed name due to PSA specification. + */ +#define PSA_DH_GROUP_RFC7919 \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) +#define PSA_DH_GROUP_CUSTOM \ + MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_CUSTOM ) + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_COMPAT_H */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_extra.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_extra.h new file mode 100644 index 0000000000..7bdb49b86e --- /dev/null +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_extra.h @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2018-2020, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + */ +/** + * \file psa/crypto_extra.h + * + * \brief PSA cryptography module: vendor extensions + * + * \note This file may not be included directly. Applications must + * include psa/crypto.h. + * + * This file is reserved for vendor-specific definitions. + */ + +#ifndef PSA_CRYPTO_EXTRA_H +#define PSA_CRYPTO_EXTRA_H + +#include "psa/crypto_compat.h" + +#include "platform/mbed_toolchain.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \addtogroup crypto_types + * @{ + */ + +/** DSA public key. + * + * The import and export format is the + * representation of the public key `y = g^x mod p` as a big-endian byte + * string. The length of the byte string is the length of the base prime `p` + * in bytes. + */ +#define PSA_KEY_TYPE_DSA_PUBLIC_KEY ((psa_key_type_t)0x4002) + +/** DSA key pair (private and public key). + * + * The import and export format is the + * representation of the private key `x` as a big-endian byte string. The + * length of the byte string is the private key size in bytes (leading zeroes + * are not stripped). + * + * Determinstic DSA key derivation with psa_generate_derived_key follows + * FIPS 186-4 §B.1.2: interpret the byte string as integer + * in big-endian order. Discard it if it is not in the range + * [0, *N* - 2] where *N* is the boundary of the private key domain + * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA, + * or the order of the curve's base point for ECC). + * Add 1 to the resulting integer and use this as the private key *x*. + * + */ +#define PSA_KEY_TYPE_DSA_KEY_PAIR ((psa_key_type_t)0x7002) + +/**@}*/ + +#if defined(MBEDTLS_ECP_C) +#include + +/** Convert an ECC curve identifier from the Mbed TLS encoding to PSA. + * + * \note This function is provided solely for the convenience of + * Mbed TLS and may be removed at any time without notice. + * + * \param grpid An Mbed TLS elliptic curve identifier + * (`MBEDTLS_ECP_DP_xxx`). + * \param[out] bits On success, the bit size of the curve. + * + * \return The corresponding PSA elliptic curve identifier + * (`PSA_ECC_FAMILY_xxx`). + * \return \c 0 on failure (\p grpid is not recognized). + */ +static inline psa_ecc_family_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid, + size_t *bits ) +{ + switch( grpid ) + { + case MBEDTLS_ECP_DP_SECP192R1: + *bits = 192; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP224R1: + *bits = 224; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP256R1: + *bits = 256; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP384R1: + *bits = 384; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP521R1: + *bits = 521; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_BP256R1: + *bits = 256; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_BP384R1: + *bits = 384; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_BP512R1: + *bits = 512; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_CURVE25519: + *bits = 255; + return( PSA_ECC_FAMILY_MONTGOMERY ); + case MBEDTLS_ECP_DP_SECP192K1: + *bits = 192; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_SECP224K1: + *bits = 224; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_SECP256K1: + *bits = 256; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_CURVE448: + *bits = 448; + return( PSA_ECC_FAMILY_MONTGOMERY ); + default: + *bits = 0; + return( 0 ); + } +} + +#endif /* MBEDTLS_ECP_C */ + +/** \brief Declare the enrollment algorithm for a key. + * + * An operation on a key may indifferently use the algorithm set with + * psa_set_key_algorithm() or with this function. + * + * \param[out] attributes The attribute structure to write to. + * \param alg2 A second algorithm that the key may be used + * for, in addition to the algorithm set with + * psa_set_key_algorithm(). + * + * \deprecated This is for backward compatibility only. + * Setting an enrollment algorithm is not recommended, because + * using the same key with different algorithms can allow some + * attacks based on arithmetic relations between different + * computations made with the same key, or can escalate harmless + * side channels into exploitable ones. Use this function only + * if it is necessary to support a protocol for which it has been + * verified that the usage of the key with multiple algorithms + * is safe. + */ +MBED_DEPRECATED("Setting enrollment algorithm is for backward compatibility and not recommended.") +static inline void psa_set_key_enrollment_algorithm( + psa_key_attributes_t *attributes, + psa_algorithm_t alg2) +{ + attributes->alg2 = alg2; +} + +/** Retrieve the enrollment algorithm policy from key attributes. + * + * \param[in] attributes The key attribute structure to query. + * + * \return The enrollment algorithm stored in the attribute structure. + + * \deprecated This is for backward compatibility only. + * Deprecated along with psa_set_key_enrollment_algorithm(). + */ +MBED_DEPRECATED("Getting enrollment algorithm is for backward compatibility and not recommended.") +static inline psa_algorithm_t psa_get_key_enrollment_algorithm( + const psa_key_attributes_t *attributes) +{ + return attributes->alg2; +} + +#ifdef __cplusplus +} +#endif + +#endif /* PSA_CRYPTO_EXTRA_H */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_platform.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_platform.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_platform.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_platform.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_sizes.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_sizes.h similarity index 91% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_sizes.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_sizes.h index 4f67501b56..cbdf59716a 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_sizes.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_sizes.h @@ -133,51 +133,9 @@ * 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. */ +/* The maximum size of an ECC key on this implementation, in bits */ #define PSA_VENDOR_ECC_MAX_CURVE_BITS 521 -/** Bit size associated with an elliptic curve. - * - * \param curve An elliptic curve (value of type #psa_ecc_curve_t). - * - * \return The size associated with \p curve, in bits. - * This may be 0 if the implementation does not support - * the specified curve. - */ -#define PSA_ECC_CURVE_BITS(curve) \ - ((curve) == PSA_ECC_CURVE_SECT163K1 ? 163 : \ - (curve) == PSA_ECC_CURVE_SECT163R1 ? 163 : \ - (curve) == PSA_ECC_CURVE_SECT163R2 ? 163 : \ - (curve) == PSA_ECC_CURVE_SECT193R1 ? 193 : \ - (curve) == PSA_ECC_CURVE_SECT193R2 ? 193 : \ - (curve) == PSA_ECC_CURVE_SECT233K1 ? 233 : \ - (curve) == PSA_ECC_CURVE_SECT233R1 ? 233 : \ - (curve) == PSA_ECC_CURVE_SECT239K1 ? 239 : \ - (curve) == PSA_ECC_CURVE_SECT283K1 ? 283 : \ - (curve) == PSA_ECC_CURVE_SECT283R1 ? 283 : \ - (curve) == PSA_ECC_CURVE_SECT409K1 ? 409 : \ - (curve) == PSA_ECC_CURVE_SECT409R1 ? 409 : \ - (curve) == PSA_ECC_CURVE_SECT571K1 ? 571 : \ - (curve) == PSA_ECC_CURVE_SECT571R1 ? 571 : \ - (curve) == PSA_ECC_CURVE_SECP160K1 ? 160 : \ - (curve) == PSA_ECC_CURVE_SECP160R1 ? 160 : \ - (curve) == PSA_ECC_CURVE_SECP160R2 ? 160 : \ - (curve) == PSA_ECC_CURVE_SECP192K1 ? 192 : \ - (curve) == PSA_ECC_CURVE_SECP192R1 ? 192 : \ - (curve) == PSA_ECC_CURVE_SECP224K1 ? 224 : \ - (curve) == PSA_ECC_CURVE_SECP224R1 ? 224 : \ - (curve) == PSA_ECC_CURVE_SECP256K1 ? 256 : \ - (curve) == PSA_ECC_CURVE_SECP256R1 ? 256 : \ - (curve) == PSA_ECC_CURVE_SECP384R1 ? 384 : \ - (curve) == PSA_ECC_CURVE_SECP521R1 ? 521 : \ - (curve) == PSA_ECC_CURVE_BRAINPOOL_P256R1 ? 256 : \ - (curve) == PSA_ECC_CURVE_BRAINPOOL_P384R1 ? 384 : \ - (curve) == PSA_ECC_CURVE_BRAINPOOL_P512R1 ? 512 : \ - (curve) == PSA_ECC_CURVE_CURVE25519 ? 255 : \ - (curve) == PSA_ECC_CURVE_CURVE448 ? 448 : \ - 0) - /** \def PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN * * This macro returns the maximum length of the PSK supported @@ -419,7 +377,7 @@ * \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. + * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that @@ -438,9 +396,9 @@ /** Sufficient output buffer size for psa_asymmetric_decrypt(). * - * This macro returns a sufficient buffer size for a ciphertext produced using + * This macro returns a sufficient buffer size for a plaintext 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 + * Note that the actual size of the plaintext may be smaller, depending * on the algorithm. * * \warning This function may call its arguments multiple times or @@ -450,7 +408,7 @@ * \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. + * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_struct.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_struct.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_struct.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_struct.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_types.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_types.h similarity index 57% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_types.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_types.h index 6ac95a8d9f..540e49aead 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_types.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_types.h @@ -55,85 +55,29 @@ typedef uint16_t psa_key_handle_t; /** \brief Encoding of a key type. */ -typedef uint32_t psa_key_type_t; +typedef uint16_t psa_key_type_t; -/** The type of PSA elliptic curve identifiers. +/** The type of PSA elliptic curve family identifiers. * * The curve identifier is required to create an ECC key using the * PSA_KEY_TYPE_ECC_KEY_PAIR() or PSA_KEY_TYPE_ECC_PUBLIC_KEY() * macros. * - * The encoding of curve identifiers is taken from 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 - * - * This specification defines identifiers for some of the curves in the IANA - * registry. Implementations that support other curves that are in the IANA - * registry should use the IANA value and a implementation-specific identifier. - * Implemenations that support non-IANA curves should use one of the following - * approaches for allocating a key type: - * - * 1. Select a ::psa_ecc_curve_t value in the range #PSA_ECC_CURVE_VENDOR_MIN to - * #PSA_ECC_CURVE_VENDOR_MAX, which is a subset of the IANA private use - * range. - * 2. Use a ::psa_key_type_t value that is vendor-defined. - * - * The first option is recommended. + * Values defined by this standard will never be in the range 0x80-0xff. + * Vendors who define additional families must use an encoding in this range. */ -typedef uint16_t psa_ecc_curve_t; +typedef uint8_t psa_ecc_family_t; -/** The type of PSA Diffie-Hellman group identifiers. +/** The type of PSA Diffie-Hellman group family identifiers. * * The group identifier is required to create an Diffie-Hellman key using the * PSA_KEY_TYPE_DH_KEY_PAIR() or PSA_KEY_TYPE_DH_PUBLIC_KEY() * macros. * - * The encoding of group identifiers is taken from 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 - * - * This specification defines identifiers for some of the groups in the IANA - * registry. Implementations that support other groups that are in the IANA - * registry should use the IANA value and a implementation-specific identifier. - * Implemenations that support non-IANA groups should use one of the following - * approaches for allocating a key type: - * - * 1. Select a ::psa_dh_group_t value in the range #PSA_DH_GROUP_VENDOR_MIN to - * #PSA_DH_GROUP_VENDOR_MAX, which is a subset of the IANA private use - * range. - * 2. Select a ::psa_dh_group_t value from the named groups allocated for - * GREASE in the IETF draft specification. The GREASE specification and - * values are listed below. - * 3. Use a ::psa_key_type_t value that is vendor-defined. - * - * Option 1 or 2 are recommended. - * - * The current draft of the GREASE specification is - * https://datatracker.ietf.org/doc/draft-ietf-tls-grease - * - * The following GREASE values are allocated for named groups: - * \code - * 0x0A0A - * 0x1A1A - * 0x2A2A - * 0x3A3A - * 0x4A4A - * 0x5A5A - * 0x6A6A - * 0x7A7A - * 0x8A8A - * 0x9A9A - * 0xAAAA - * 0xBABA - * 0xCACA - * 0xDADA - * 0xEAEA - * 0xFAFA - * \endcode + * Values defined by this standard will never be in the range 0x80-0xff. + * Vendors who define additional families must use an encoding in this range. */ -typedef uint16_t psa_dh_group_t; +typedef uint8_t psa_dh_family_t; /** \brief Encoding of a cryptographic algorithm. * @@ -156,18 +100,117 @@ typedef uint32_t psa_algorithm_t; * The lifetime of a key indicates where it is stored and what system actions * may create and destroy it. * - * Keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE are automatically - * destroyed when the application terminates or on a power reset. + * Lifetime values have the following structure: + * - Bits 0-7 (#PSA_KEY_LIFETIME_GET_PERSISTENCE(\c lifetime)): + * persistence level. This value indicates what device management + * actions can cause it to be destroyed. In particular, it indicates + * whether the key is _volatile_ or _persistent_. + * See ::psa_key_persistence_t for more information. + * - Bits 8-31 (#PSA_KEY_LIFETIME_GET_LOCATION(\c lifetime)): + * location indicator. This value indicates where the key is stored + * and where operations on the key are performed. + * See ::psa_key_location_t for more information. + * + * Volatile keys are automatically destroyed when the application instance + * terminates or on a power reset of the device. Persistent keys are + * preserved until the application explicitly destroys them or until an + * implementation-specific device management event occurs (for example, + * a factory reset). * - * Keys with a lifetime other than #PSA_KEY_LIFETIME_VOLATILE are said - * to be _persistent_. - * Persistent keys are preserved if the application or the system restarts. * Persistent keys have a key identifier of type #psa_key_id_t. + * This identifier remains valid throughout the lifetime of the key, + * even if the application instance that created the key terminates. * The application can call psa_open_key() to open a persistent key that * it created previously. + * + * This specification defines two basic lifetime values: + * - Keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE are volatile. + * All implementations should support this lifetime. + * - Keys with the lifetime #PSA_KEY_LIFETIME_PERSISTENT are persistent. + * All implementations that have access to persistent storage with + * appropriate security guarantees should support this lifetime. */ typedef uint32_t psa_key_lifetime_t; +/** Encoding of key persistence levels. + * + * What distinguishes different persistence levels is what device management + * events may cause keys to be destroyed. _Volatile_ keys are destroyed + * by a power reset. Persistent keys may be destroyed by events such as + * a transfer of ownership or a factory reset. What management events + * actually affect persistent keys at different levels is outside the + * scope of the PSA Cryptography specification. + * + * This specification defines the following values of persistence levels: + * - \c 0 = #PSA_KEY_PERSISTENCE_VOLATILE: volatile key. + * A volatile key is automatically destroyed by the implementation when + * the application instance terminates. In particular, a volatile key + * is automatically destroyed on a power reset of the device. + * - \c 1 = #PSA_KEY_PERSISTENCE_DEFAULT: + * persistent key with a default lifetime. + * Implementations should support this value if they support persistent + * keys at all. + * Applications should use this value if they have no specific needs that + * are only met by implementation-specific features. + * - \c 2-127: persistent key with a PSA-specified lifetime. + * The PSA Cryptography specification does not define the meaning of these + * values, but other PSA specifications may do so. + * - \c 128-254: persistent key with a vendor-specified lifetime. + * No PSA specification will define the meaning of these values, so + * implementations may choose the meaning freely. + * As a guideline, higher persistence levels should cause a key to survive + * more management events than lower levels. + * - \c 255 = #PSA_KEY_PERSISTENCE_READ_ONLY: + * read-only or write-once key. + * A key with this persistence level cannot be destroyed. + * Implementations that support such keys may either allow their creation + * through the PSA Cryptography API, preferably only to applications with + * the appropriate privilege, or only expose keys created through + * implementation-specific means such as a factory ROM engraving process. + * Note that keys that are read-only due to policy restrictions + * rather than due to physical limitations should not have this + * persistence levels. + * + * \note Key persistence levels are 8-bit values. Key management + * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which + * encode the persistence as the lower 8 bits of a 32-bit value. + */ +typedef uint8_t psa_key_persistence_t; + +/** Encoding of key location indicators. + * + * If an implementation of this API can make calls to external + * cryptoprocessors such as secure elements, the location of a key + * indicates which secure element performs the operations on the key. + * If an implementation offers multiple physical locations for persistent + * storage, the location indicator reflects at which physical location + * the key is stored. + * + * This specification defines the following values of location indicators: + * - \c 0: primary local storage. + * All implementations should support this value. + * The primary local storage is typically the same storage area that + * contains the key metadata. + * - \c 1: primary secure element. + * Implementations should support this value if there is a secure element + * attached to the operating environment. + * As a guideline, secure elements may provide higher resistance against + * side channel and physical attacks than the primary local storage, but may + * have restrictions on supported key types, sizes, policies and operations + * and may have different performance characteristics. + * - \c 2-0x7fffff: other locations defined by a PSA specification. + * The PSA Cryptography API does not currently assign any meaning to these + * locations, but future versions of this specification or other PSA + * specifications may do so. + * - \c 0x800000-0xffffff: vendor-defined locations. + * No PSA specification will assign a meaning to locations in this range. + * + * \note Key location indicators are 24-bit values. Key management + * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which + * encode the location as the upper 24 bits of a 32-bit value. + */ +typedef uint32_t psa_key_location_t; + /** Encoding of identifiers of persistent keys. * * - Applications may freely choose key identifiers in the range diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_values.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_values.h similarity index 87% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_values.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_values.h index e21ef273e9..75e30505d4 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_values.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/crypto_values.h @@ -272,7 +272,7 @@ * * Zero is not the encoding of any key type. */ -#define PSA_KEY_TYPE_NONE ((psa_key_type_t)0x00000000) +#define PSA_KEY_TYPE_NONE ((psa_key_type_t)0x0000) /** Vendor-defined key type flag. * @@ -281,15 +281,15 @@ * 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_VENDOR_FLAG ((psa_key_type_t)0x8000) -#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_MASK ((psa_key_type_t)0x7000) +#define PSA_KEY_TYPE_CATEGORY_RAW ((psa_key_type_t)0x1000) +#define PSA_KEY_TYPE_CATEGORY_SYMMETRIC ((psa_key_type_t)0x2000) +#define PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY ((psa_key_type_t)0x4000) +#define PSA_KEY_TYPE_CATEGORY_KEY_PAIR ((psa_key_type_t)0x7000) -#define PSA_KEY_TYPE_CATEGORY_FLAG_PAIR ((psa_key_type_t)0x10000000) +#define PSA_KEY_TYPE_CATEGORY_FLAG_PAIR ((psa_key_type_t)0x3000) /** Whether a key type is vendor-defined. * @@ -303,8 +303,8 @@ * 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) + (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_RAW || \ + ((type) & PSA_KEY_TYPE_CATEGORY_MASK) == 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) \ @@ -347,7 +347,7 @@ * * 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) +#define PSA_KEY_TYPE_RAW_DATA ((psa_key_type_t)0x1001) /** HMAC key. * @@ -357,21 +357,21 @@ * 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) +#define PSA_KEY_TYPE_HMAC ((psa_key_type_t)0x1100) /** 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) +#define PSA_KEY_TYPE_DERIVE ((psa_key_type_t)0x1200) /** Key for a 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) +#define PSA_KEY_TYPE_AES ((psa_key_type_t)0x2400) /** Key for a cipher or MAC algorithm based on DES or 3DES (Triple-DES). * @@ -382,17 +382,17 @@ * 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) +#define PSA_KEY_TYPE_DES ((psa_key_type_t)0x2301) /** Key for a cipher, AEAD or MAC algorithm based on the * Camellia block cipher. */ -#define PSA_KEY_TYPE_CAMELLIA ((psa_key_type_t)0x40000003) +#define PSA_KEY_TYPE_CAMELLIA ((psa_key_type_t)0x2403) /** 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) +#define PSA_KEY_TYPE_ARC4 ((psa_key_type_t)0x2002) /** Key for the ChaCha20 stream cipher or the Chacha20-Poly1305 AEAD algorithm. * @@ -401,30 +401,30 @@ * Implementations must support 12-byte nonces, may support 8-byte nonces, * and should reject other sizes. */ -#define PSA_KEY_TYPE_CHACHA20 ((psa_key_type_t)0x40000005) +#define PSA_KEY_TYPE_CHACHA20 ((psa_key_type_t)0x2004) /** RSA public key. */ -#define PSA_KEY_TYPE_RSA_PUBLIC_KEY ((psa_key_type_t)0x60010000) +#define PSA_KEY_TYPE_RSA_PUBLIC_KEY ((psa_key_type_t)0x4001) /** RSA key pair (private and public key). */ -#define PSA_KEY_TYPE_RSA_KEY_PAIR ((psa_key_type_t)0x70010000) +#define PSA_KEY_TYPE_RSA_KEY_PAIR ((psa_key_type_t)0x7001) /** 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_KEY_PAIR(type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY) -#define PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((psa_key_type_t)0x60030000) -#define PSA_KEY_TYPE_ECC_KEY_PAIR_BASE ((psa_key_type_t)0x70030000) -#define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t)0x0000ffff) +#define PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((psa_key_type_t)0x4100) +#define PSA_KEY_TYPE_ECC_KEY_PAIR_BASE ((psa_key_type_t)0x7100) +#define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t)0x00ff) /** Elliptic curve key pair. * - * \param curve A value of type ::psa_ecc_curve_t that identifies the - * ECC curve to be used. + * \param curve A value of type ::psa_ecc_family_t that + * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_KEY_PAIR(curve) \ (PSA_KEY_TYPE_ECC_KEY_PAIR_BASE | (curve)) /** Elliptic curve public key. * - * \param curve A value of type ::psa_ecc_curve_t that identifies the - * ECC curve to be used. + * \param curve A value of type ::psa_ecc_family_t that + * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve) \ (PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve)) @@ -443,85 +443,97 @@ PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) /** 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) ? \ +#define PSA_KEY_TYPE_ECC_GET_FAMILY(type) \ + ((psa_ecc_family_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) -/** Curve25519. +/** SEC Koblitz curves over prime fields. * - * This is the curve defined in Bernstein et al., - * _Curve25519: new Diffie-Hellman speed records_, LNCS 3958, 2006. - * The algorithm #PSA_ALG_ECDH performs X25519 when used with this curve. + * This family comprises the following curves: + * secp192k1, secp224k1, secp256k1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_CURVE25519 ((psa_ecc_curve_t) 0x001d) -/** Curve448 - * - * This is the curve defined in Hamburg, - * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. - * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve. - */ -#define PSA_ECC_CURVE_CURVE448 ((psa_ecc_curve_t) 0x001e) +#define PSA_ECC_FAMILY_SECP_K1 ((psa_ecc_family_t) 0x17) -/** Minimum value for a vendor-defined ECC curve identifier +/** SEC random curves over prime fields. * - * The range for vendor-defined curve identifiers is a subset of the IANA - * registry private use range, `0xfe00` - `0xfeff`. + * This family comprises the following curves: + * secp192k1, secp224r1, secp256r1, secp384r1, secp521r1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf */ -#define PSA_ECC_CURVE_VENDOR_MIN ((psa_ecc_curve_t) 0xfe00) -/** Maximum value for a vendor-defined ECC curve identifier - * - * The range for vendor-defined curve identifiers is a subset of the IANA - * registry private use range, `0xfe00` - `0xfeff`. - */ -#define PSA_ECC_CURVE_VENDOR_MAX ((psa_ecc_curve_t) 0xfe7f) +#define PSA_ECC_FAMILY_SECP_R1 ((psa_ecc_family_t) 0x12) +/* SECP160R2 (SEC2 v1, obsolete) */ +#define PSA_ECC_FAMILY_SECP_R2 ((psa_ecc_family_t) 0x1b) -#define PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE ((psa_key_type_t)0x60040000) -#define PSA_KEY_TYPE_DH_KEY_PAIR_BASE ((psa_key_type_t)0x70040000) -#define PSA_KEY_TYPE_DH_GROUP_MASK ((psa_key_type_t)0x0000ffff) +/** SEC Koblitz curves over binary fields. + * + * This family comprises the following curves: + * sect163k1, sect233k1, sect239k1, sect283k1, sect409k1, sect571k1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECT_K1 ((psa_ecc_family_t) 0x27) + +/** SEC random curves over binary fields. + * + * This family comprises the following curves: + * sect163r1, sect233r1, sect283r1, sect409r1, sect571r1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECT_R1 ((psa_ecc_family_t) 0x22) + +/** SEC additional random curves over binary fields. + * + * This family comprises the following curve: + * sect163r2. + * It is defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECT_R2 ((psa_ecc_family_t) 0x2b) + +/** Brainpool P random curves. + * + * This family comprises the following curves: + * brainpoolP160r1, brainpoolP192r1, brainpoolP224r1, brainpoolP256r1, + * brainpoolP320r1, brainpoolP384r1, brainpoolP512r1. + * It is defined in RFC 5639. + */ +#define PSA_ECC_FAMILY_BRAINPOOL_P_R1 ((psa_ecc_family_t) 0x30) + +/** Curve25519 and Curve448. + * + * This family comprises the following Montgomery curves: + * - 255-bit: Bernstein et al., + * _Curve25519: new Diffie-Hellman speed records_, LNCS 3958, 2006. + * The algorithm #PSA_ALG_ECDH performs X25519 when used with this curve. + * - 448-bit: Hamburg, + * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. + * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve. + */ +#define PSA_ECC_FAMILY_MONTGOMERY ((psa_ecc_family_t) 0x41) + +#define PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE ((psa_key_type_t)0x4200) +#define PSA_KEY_TYPE_DH_KEY_PAIR_BASE ((psa_key_type_t)0x7200) +#define PSA_KEY_TYPE_DH_GROUP_MASK ((psa_key_type_t)0x00ff) /** Diffie-Hellman key pair. * - * \param group A value of type ::psa_dh_group_t that identifies the + * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_KEY_PAIR(group) \ (PSA_KEY_TYPE_DH_KEY_PAIR_BASE | (group)) /** Diffie-Hellman public key. * - * \param group A value of type ::psa_dh_group_t that identifies the + * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_PUBLIC_KEY(group) \ @@ -541,35 +553,21 @@ PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE) /** Extract the group from a Diffie-Hellman key type. */ -#define PSA_KEY_TYPE_GET_GROUP(type) \ - ((psa_dh_group_t) (PSA_KEY_TYPE_IS_DH(type) ? \ +#define PSA_KEY_TYPE_DH_GET_FAMILY(type) \ + ((psa_dh_family_t) (PSA_KEY_TYPE_IS_DH(type) ? \ ((type) & PSA_KEY_TYPE_DH_GROUP_MASK) : \ 0)) -/* The encoding of group 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 7919. */ -#define PSA_DH_GROUP_FFDHE2048 ((psa_dh_group_t) 0x0100) -#define PSA_DH_GROUP_FFDHE3072 ((psa_dh_group_t) 0x0101) -#define PSA_DH_GROUP_FFDHE4096 ((psa_dh_group_t) 0x0102) -#define PSA_DH_GROUP_FFDHE6144 ((psa_dh_group_t) 0x0103) -#define PSA_DH_GROUP_FFDHE8192 ((psa_dh_group_t) 0x0104) - -/** Minimum value for a vendor-defined Diffie Hellman group identifier +/** Diffie-Hellman groups defined in RFC 7919 Appendix A. * - * The range for vendor-defined group identifiers is a subset of the IANA - * registry private use range, `0x01fc` - `0x01ff`. + * This family includes groups with the following key sizes (in bits): + * 2048, 3072, 4096, 6144, 8192. A given implementation may support + * all of these sizes or only a subset. */ -#define PSA_DH_GROUP_VENDOR_MIN ((psa_dh_group_t) 0x01fc) -/** Maximum value for a vendor-defined Diffie Hellman group identifier - * - * The range for vendor-defined group identifiers is a subset of the IANA - * registry private use range, `0x01fc` - `0x01ff`. - */ -#define PSA_DH_GROUP_VENDOR_MAX ((psa_dh_group_t) 0x01fd) +#define PSA_DH_FAMILY_RFC7919 ((psa_dh_family_t) 0x03) +#define PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) \ + (((type) >> 8) & 7) /** The block size of a block cipher. * * \param type A cipher key type (value of type #psa_key_type_t). @@ -589,13 +587,9 @@ * \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 : \ - (type) == PSA_KEY_TYPE_CHACHA20 ? 1 : \ - 0) + (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC ? \ + 1u << PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) : \ + 0u) /** Vendor-defined algorithm flag. * @@ -668,22 +662,24 @@ #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. +/** Whether the specified algorithm is an asymmetric signature algorithm, + * also known as 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. + * \return 1 if \p alg is an asymmetric 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. +/** Whether the specified algorithm is an asymmetric encryption algorithm, + * also known as 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. + * \return 1 if \p alg is an asymmetric encryption algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ @@ -1201,9 +1197,9 @@ /** Whether the specified algorithm is a hash-and-sign algorithm. * - * Hash-and-sign algorithms are public-key signature algorithms structured - * in two parts: first the calculation of a hash in a way that does not - * depend on the key, then the calculation of a signature from the + * Hash-and-sign algorithms are asymmetric (public-key) signature algorithms + * structured in two parts: first the calculation of a hash in a way that + * does not depend on the key, then the calculation of a signature from the * hash value and the key. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). @@ -1255,7 +1251,7 @@ * #PSA_ALG_IS_HASH(\p hash_alg) is true) to use * for MGF1. * - * \return The corresponding RSA OAEP signature algorithm. + * \return The corresponding RSA OAEP encryption algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ @@ -1477,17 +1473,17 @@ * 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`), + * - For Montgomery curves (curve types `PSA_ECC_FAMILY_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`), + * `PSA_ECC_FAMILY_SECPXXX` and `PSA_ECC_FAMILY_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`), + * `PSA_ECC_FAMILY_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}`. @@ -1535,12 +1531,20 @@ * @{ */ -/** A volatile key only exists as long as the handle to it is not closed. +/** The default lifetime for volatile keys. + * + * A volatile key only exists as long as the handle to it is not closed. * The key material is guaranteed to be erased on a power reset. + * + * A key with this lifetime is typically stored in the RAM area of the + * PSA Crypto subsystem. However this is an implementation choice. + * If an implementation stores data about the key in a non-volatile memory, + * it must release all the resources associated with the key and erase the + * key material if the calling application terminates. */ #define PSA_KEY_LIFETIME_VOLATILE ((psa_key_lifetime_t)0x00000000) -/** The default storage area for persistent keys. +/** The default lifetime for persistent keys. * * A persistent key remains in storage until it is explicitly destroyed or * until the corresponding storage area is wiped. This specification does @@ -1551,9 +1555,77 @@ * This lifetime value is the default storage area for the calling * application. Implementations may offer other storage areas designated * by other lifetime values as implementation-specific extensions. + * See ::psa_key_lifetime_t for more information. */ #define PSA_KEY_LIFETIME_PERSISTENT ((psa_key_lifetime_t)0x00000001) +/** The persistence level of volatile keys. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_VOLATILE ((psa_key_persistence_t)0x00) + +/** The default persistence level for persistent keys. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_DEFAULT ((psa_key_persistence_t)0x01) + +/** A persistence level indicating that a key is never destroyed. + * + * See ::psa_key_persistence_t for more information. + */ +#define PSA_KEY_PERSISTENCE_READ_ONLY ((psa_key_persistence_t)0xff) + +#define PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) \ + ((psa_key_persistence_t)((lifetime) & 0x000000ff)) + +#define PSA_KEY_LIFETIME_GET_LOCATION(lifetime) \ + ((psa_key_location_t)((lifetime) >> 8)) + +/** Whether a key lifetime indicates that the key is volatile. + * + * A volatile key is automatically destroyed by the implementation when + * the application instance terminates. In particular, a volatile key + * is automatically destroyed on a power reset of the device. + * + * A key that is not volatile is persistent. Persistent keys are + * preserved until the application explicitly destroys them or until an + * implementation-specific device management event occurs (for example, + * a factory reset). + * + * \param lifetime The lifetime value to query (value of type + * ::psa_key_lifetime_t). + * + * \return \c 1 if the key is volatile, otherwise \c 0. + */ +#define PSA_KEY_LIFETIME_IS_VOLATILE(lifetime) \ + (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \ + PSA_KEY_PERSISTENCE_VOLATILE) + +/** Construct a lifetime from a persistence level and a location. + * + * \param persistence The persistence level + * (value of type ::psa_key_persistence_t). + * \param location The location indicator + * (value of type ::psa_key_location_t). + * + * \return The constructed lifetime value. + */ +#define PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(persistence, location) \ + ((location) << 8 | (persistence)) + +/** The local storage area for persistent keys. + * + * This storage area is available on all systems that can store persistent + * keys without delegating the storage to a third-party cryptoprocessor. + * + * See ::psa_key_location_t for more information. + */ +#define PSA_KEY_LOCATION_LOCAL_STORAGE ((psa_key_location_t)0x000000) + +#define PSA_KEY_LOCATION_VENDOR_FLAG ((psa_key_location_t)0x800000) + /** The minimum value for a key identifier chosen by the application. */ #define PSA_KEY_ID_USER_MIN ((psa_key_id_t)0x00000001) diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/error.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/error.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/error.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/error.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/initial_attestation.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/initial_attestation.h similarity index 97% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/initial_attestation.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/initial_attestation.h index c125a4d6f4..50dd479c62 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/initial_attestation.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/initial_attestation.h @@ -216,10 +216,10 @@ psa_initial_attest_get_token_size(size_t challenge_size, * \return Returns error code as specified in \ref psa_status_t */ psa_status_t -tfm_initial_attest_get_public_key(uint8_t *public_key, - size_t public_key_buf_size, - size_t *public_key_len, - psa_ecc_curve_t *elliptic_curve_type); +tfm_initial_attest_get_public_key(uint8_t *public_key, + size_t public_key_buf_size, + size_t *public_key_len, + psa_ecc_family_t *elliptic_curve_type); #ifdef __cplusplus } diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/internal_trusted_storage.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/internal_trusted_storage.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/internal_trusted_storage.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/internal_trusted_storage.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/protected_storage.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/protected_storage.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/protected_storage.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/protected_storage.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/storage_common.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/storage_common.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/storage_common.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa/storage_common.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_api.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_api.h new file mode 100644 index 0000000000..d55a0572ac --- /dev/null +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_api.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2018-2019, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + */ + +#ifndef __PSA_AUDIT_API__ +#define __PSA_AUDIT_API__ + +/** + * \brief PSA AUDIT API version + */ +#define PSA_AUDIT_API_VERSION_MAJOR (0) +#define PSA_AUDIT_API_VERSION_MINOR (1) + +#include "psa_audit_defs.h" +#include "psa/error.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Retrieves a record at the specified index + * + * \details The function retrieves an item specified by index and returns + * it on the buffer provided. The token is passed as a challenge + * value for the encryption scheme + * + * \note Currently the cryptography support is not yet enabled, so the + * token value is not used and must be passed as NULL, with 0 size + * + * \param[in] record_index Index of the record to retrieve + * \param[in] buffer_size Size in bytes of the provided buffer + * \param[in] token Must be set to NULL. Token used as a challenge + * for encryption, to protect against rollback + * attacks + * \param[in] token_size Must be set to 0. Size in bytes of the token + * used as challenge + * \param[out] buffer Buffer used to store the retrieved record + * \param[out] record_size Size in bytes of the retrieved record + * + * \return Returns values as specified by the \ref psa_status_t + * + */ +psa_status_t psa_audit_retrieve_record(const uint32_t record_index, + const uint32_t buffer_size, + const uint8_t *token, + const uint32_t token_size, + uint8_t *buffer, + uint32_t *record_size); +/** + * \brief Returns the total number and size of the records stored + * + * \details The function returns the total size in bytes and the + * total number of records stored + * + * \param[out] num_records Total number of records stored + * \param[out] size Total size of the records stored, in bytes + * + * \return Returns values as specified by the \ref psa_status_t + * + */ +psa_status_t psa_audit_get_info(uint32_t *num_records, uint32_t *size); + +/** + * \brief Returns the size of the record at the specified index + * + * \details The function returns the size of the record at the given index + * provided as input + * + * \param[in] record_index Index of the record to return the size + * \param[out] size Size of the specified record, in bytes + * + * \return Returns values as specified by the \ref psa_status_t + * + */ +psa_status_t psa_audit_get_record_info(const uint32_t record_index, + uint32_t *size); + +/** + * \brief Deletes a record at the specified index + * + * \details The function removes a record at the specified index. It passes + * an authorisation token for removal which is a MAC of the plain text + * + * \note Currently the cryptography support is not yet enabled, so the + * token value is not used and must be passed as NULL, with 0 size + * + * \note This is an experimental API function + * + * \param[in] record_index Index of the record to be removed. Currently, only + * the removal of the oldest entry, i.e. record_index 0 + * is supported + * \param[in] token Must be set to NULL. Token used as authorisation for + * removal of the specified record_index + * \param[in] token_size Must be set to 0. Size in bytes of the token used as + * authorisation for removal + * + * \return Returns values as specified by the \ref psa_status_t + * + */ +psa_status_t psa_audit_delete_record(const uint32_t record_index, + const uint8_t *token, + const uint32_t token_size); +/** + * \brief Adds a record + * + * \details This function adds a record. This is a Secure only callable function + * + * \note This is a Secure only callable API, Non-Secure calls will + * always return error + * + * \param[in] record Pointer to the memory buffer containing the record + * to be added + * + * \return Returns values as specified by the \ref psa_status_t + * + */ +psa_status_t psa_audit_add_record(const struct psa_audit_record *record); + +#ifdef __cplusplus +} +#endif + +#endif /* __PSA_AUDIT_API__ */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_defs.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_defs.h new file mode 100644 index 0000000000..479d76d54d --- /dev/null +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_audit_defs.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2018-2019, Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + * + */ + +#ifndef __PSA_AUDIT_DEFS_H__ +#define __PSA_AUDIT_DEFS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "tfm_api.h" + +/*! + * \struct psa_audit_record + * + * \brief This structure contains the record that is added to the audit log + * by the requesting secure service + */ +struct psa_audit_record { + uint32_t size; /*!< Size in bytes of the id and payload fields */ + uint32_t id; /*!< ID of the record */ + uint8_t payload[]; /*!< Flexible array member for payload */ +}; + +#ifdef __cplusplus +} +#endif + +#endif /* __PSA_AUDIT_DEFS_H__ */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa_manifest/sid.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_manifest/sid.h similarity index 95% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa_manifest/sid.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_manifest/sid.h index f9bdf7cf37..87d6186be3 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa_manifest/sid.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/psa_manifest/sid.h @@ -134,12 +134,6 @@ extern "C" { #define TFM_SECURE_CLIENT_2_SID (0x0000F0E0U) #define TFM_SECURE_CLIENT_2_VERSION (1U) -/******** TFM_SP_MULTI_CORE_TEST ********/ -#define MULTI_CORE_MULTI_CLIENT_CALL_TEST_0_SID (0x0000F100U) -#define MULTI_CORE_MULTI_CLIENT_CALL_TEST_0_VERSION (1U) -#define MULTI_CORE_MULTI_CLIENT_CALL_TEST_1_SID (0x0000F101U) -#define MULTI_CORE_MULTI_CLIENT_CALL_TEST_1_VERSION (1U) - #ifdef __cplusplus } #endif diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_api.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_api.h similarity index 98% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_api.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_api.h index 09abc399b1..883eb5b8c9 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_api.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_api.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019, Arm Limited. All rights reserved. + * Copyright (c) 2017-2020, Arm Limited. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * @@ -112,7 +112,7 @@ psa_handle_t tfm_psa_connect_veneer(uint32_t sid, uint32_t version); * \brief Call a secure function referenced by a connection handle. * * \param[in] handle Handle to connection. - * \param[in] ctrl_param Parameter structure, includes reuqest type, + * \param[in] ctrl_param Parameter structure, includes request type, * in_num and out_num. * \param[in] in_vec Array of input \ref psa_invec structures. * \param[in/out] out_vec Array of output \ref psa_outvec structures. diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_crypto_defs.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_crypto_defs.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_crypto_defs.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_crypto_defs.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_mailbox.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_mailbox.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_mailbox.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_mailbox.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_multi_core_api.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_multi_core_api.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_multi_core_api.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_multi_core_api.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_interface.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_interface.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_interface.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_interface.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_mailbox.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_mailbox.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_mailbox.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_mailbox.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_svc.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_svc.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_ns_svc.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_ns_svc.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_platform_api.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_platform_api.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_platform_api.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_platform_api.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_veneers.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_veneers.h similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/tfm_veneers.h rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/include/tfm_veneers.h diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_crypto_ipc_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_crypto_ipc_api.c similarity index 97% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_crypto_ipc_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_crypto_ipc_api.c index 70b3a0dfe5..1e4df7c02d 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_crypto_ipc_api.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_crypto_ipc_api.c @@ -735,6 +735,78 @@ psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation, #endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ } +psa_status_t psa_hash_compute(psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + uint8_t *hash, + size_t hash_size, + size_t *hash_length) +{ +#ifdef TFM_CRYPTO_HASH_MODULE_DISABLED + return PSA_ERROR_NOT_SUPPORTED; +#else + psa_status_t status; + struct tfm_crypto_pack_iovec iov = { + .sfn_id = TFM_CRYPTO_HASH_COMPUTE_SID, + .alg = alg, + }; + + psa_invec in_vec[] = { + {.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)}, + {.base = input, .len = input_length}, + }; + + psa_outvec out_vec[] = { + {.base = hash, .len = hash_size} + }; + + PSA_CONNECT(TFM_CRYPTO); + + status = API_DISPATCH(tfm_crypto_hash_compute, + TFM_CRYPTO_HASH_COMPUTE); + + *hash_length = out_vec[0].len; + + PSA_CLOSE(); + + return status; +#endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ +} + +psa_status_t psa_hash_compare(psa_algorithm_t alg, + const uint8_t *input, + size_t input_length, + const uint8_t *hash, + size_t hash_length) +{ +#ifdef TFM_CRYPTO_HASH_MODULE_DISABLED + return PSA_ERROR_NOT_SUPPORTED; +#else + psa_status_t status; + struct tfm_crypto_pack_iovec iov = { + .sfn_id = TFM_CRYPTO_HASH_COMPARE_SID, + .alg = alg, + }; + + psa_invec in_vec[] = { + {.base = &iov, .len = sizeof(struct tfm_crypto_pack_iovec)}, + {.base = input, .len = input_length}, + {.base = hash, .len = hash_length}, + }; + + PSA_CONNECT(TFM_CRYPTO); + + status = API_DISPATCH_NO_OUTVEC(tfm_crypto_hash_compare, + TFM_CRYPTO_HASH_COMPARE); + + PSA_CLOSE(); + + return status; +#endif /* TFM_CRYPTO_HASH_MODULE_DISABLED */ +} + + + psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation, psa_key_handle_t handle, psa_algorithm_t alg) @@ -1507,19 +1579,6 @@ psa_status_t psa_get_key_domain_parameters( return status; } -psa_status_t psa_hash_compare(psa_algorithm_t alg, - const uint8_t *input, - size_t input_length, - const uint8_t *hash, - const size_t hash_length) -{ - psa_status_t status; - - status = PSA_ERROR_NOT_SUPPORTED; - - return status; -} - psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation, const uint8_t *input, size_t input_length) @@ -1790,20 +1849,6 @@ psa_status_t psa_key_derivation_output_key( #endif /* TFM_CRYPTO_GENERATOR_MODULE_DISABLED */ } -psa_status_t psa_hash_compute(psa_algorithm_t alg, - const uint8_t *input, - size_t input_length, - uint8_t *hash, - size_t hash_size, - size_t *hash_length) -{ - psa_status_t status; - - status = PSA_ERROR_NOT_SUPPORTED; - - return status; -} - psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation, psa_key_handle_t handle, psa_algorithm_t alg) diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_initial_attestation_ipc_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_initial_attestation_ipc_api.c similarity index 90% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_initial_attestation_ipc_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_initial_attestation_ipc_api.c index 78f9dec6f4..b4a8f379e3 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_initial_attestation_ipc_api.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_initial_attestation_ipc_api.c @@ -76,10 +76,10 @@ psa_initial_attest_get_token_size(size_t challenge_size, } psa_status_t -tfm_initial_attest_get_public_key(uint8_t *public_key, - size_t public_key_buf_size, - size_t *public_key_len, - psa_ecc_curve_t *elliptic_curve_type) +tfm_initial_attest_get_public_key(uint8_t *public_key, + size_t public_key_buf_size, + size_t *public_key_len, + psa_ecc_family_t *elliptic_curve_type) { psa_handle_t handle = PSA_NULL_HANDLE; psa_status_t status; diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_its_ipc_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_its_ipc_api.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_its_ipc_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_its_ipc_api.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_platform_ipc_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_platform_ipc_api.c similarity index 99% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_platform_ipc_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_platform_ipc_api.c index c43fe8bf39..0c1edf463f 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_platform_ipc_api.c +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_platform_ipc_api.c @@ -75,3 +75,4 @@ tfm_platform_ioctl(tfm_platform_ioctl_req_t request, return (enum tfm_platform_err_t) status; } } + diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_ps_ipc_api.c b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_ps_ipc_api.c similarity index 100% rename from platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/src/tfm_ps_ipc_api.c rename to platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/src/tfm_ps_ipc_api.c diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_extra.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_extra.h index 33c9c0537a..e24f94a27b 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_extra.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_extra.h @@ -50,6 +50,91 @@ static inline void psa_set_key_enrollment_algorithm( attributes->core.policy.alg2 = alg2; } +#if defined(MBEDTLS_ECP_C) +#include + +/** Convert an ECC curve identifier from the Mbed TLS encoding to PSA. + * + * \note This function is provided solely for the convenience of + * Mbed TLS and may be removed at any time without notice. + * + * \param grpid An Mbed TLS elliptic curve identifier + * (`MBEDTLS_ECP_DP_xxx`). + * \param[out] bits On success, the bit size of the curve. + * + * \return The corresponding PSA elliptic curve identifier + * (`PSA_ECC_FAMILY_xxx`). + * \return \c 0 on failure (\p grpid is not recognized). + */ +static inline psa_ecc_family_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid, + size_t *bits ) +{ + switch( grpid ) + { + case MBEDTLS_ECP_DP_SECP192R1: + *bits = 192; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP224R1: + *bits = 224; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP256R1: + *bits = 256; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP384R1: + *bits = 384; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_SECP521R1: + *bits = 521; + return( PSA_ECC_FAMILY_SECP_R1 ); + case MBEDTLS_ECP_DP_BP256R1: + *bits = 256; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_BP384R1: + *bits = 384; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_BP512R1: + *bits = 512; + return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); + case MBEDTLS_ECP_DP_CURVE25519: + *bits = 255; + return( PSA_ECC_FAMILY_MONTGOMERY ); + case MBEDTLS_ECP_DP_SECP192K1: + *bits = 192; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_SECP224K1: + *bits = 224; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_SECP256K1: + *bits = 256; + return( PSA_ECC_FAMILY_SECP_K1 ); + case MBEDTLS_ECP_DP_CURVE448: + *bits = 448; + return( PSA_ECC_FAMILY_MONTGOMERY ); + default: + *bits = 0; + return( 0 ); + } +} + +/** Convert an ECC curve identifier from the PSA encoding to Mbed TLS. + * + * \note This function is provided solely for the convenience of + * Mbed TLS and may be removed at any time without notice. + * + * \param curve A PSA elliptic curve identifier + * (`PSA_ECC_FAMILY_xxx`). + * \param byte_length The byte-length of a private key on \p curve. + * + * \return The corresponding Mbed TLS elliptic curve identifier + * (`MBEDTLS_ECP_DP_xxx`). + * \return #MBEDTLS_ECP_DP_NONE if \c curve is not recognized. + * \return #MBEDTLS_ECP_DP_NONE if \p byte_length is not + * correct for \p curve. + */ +//mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve, +// size_t byte_length ); +#endif /* MBEDTLS_ECP_C */ + #ifdef __cplusplus } #endif diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_types.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_types.h index 690999f79c..b8cc71e4d4 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_types.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_types.h @@ -53,6 +53,17 @@ typedef int32_t psa_status_t; */ typedef uint32_t psa_key_type_t; +/** The type of PSA elliptic curve family identifiers. + * + * The curve identifier is required to create an ECC key using the + * PSA_KEY_TYPE_ECC_KEY_PAIR() or PSA_KEY_TYPE_ECC_PUBLIC_KEY() + * macros. + * + * Values defined by this standard will never be in the range 0x80-0xff. + * Vendors who define additional families must use an encoding in this range. + */ +typedef uint8_t psa_ecc_family_t; + /** The type of PSA elliptic curve identifiers. * * The curve identifier is required to create an ECC key using the diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_values.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_values.h index 7fde07385f..d8a575bb8a 100644 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_values.h +++ b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_0/include/psa/crypto_values.h @@ -1696,6 +1696,85 @@ */ #define PSA_KEY_DERIVATION_INPUT_SEED ((psa_key_derivation_step_t)0x0204) +/** Extract the curve from an elliptic curve key type. */ +#define PSA_KEY_TYPE_ECC_GET_FAMILY(type) \ + ((psa_ecc_family_t) (PSA_KEY_TYPE_IS_ECC(type) ? \ + ((type) & PSA_KEY_TYPE_ECC_CURVE_MASK) : \ + 0)) + + +/** SEC Koblitz curves over prime fields. + * + * This family comprises the following curves: + * secp192k1, secp224k1, secp256k1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECP_K1 ((psa_ecc_family_t) 0x17) + +/** SEC random curves over prime fields. + * + * This family comprises the following curves: + * secp192k1, secp224r1, secp256r1, secp384r1, secp521r1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECP_R1 ((psa_ecc_family_t) 0x12) +/* SECP160R2 (SEC2 v1, obsolete) */ +#define PSA_ECC_FAMILY_SECP_R2 ((psa_ecc_family_t) 0x1b) + +/** SEC Koblitz curves over binary fields. + * + * This family comprises the following curves: + * sect163k1, sect233k1, sect239k1, sect283k1, sect409k1, sect571k1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECT_K1 ((psa_ecc_family_t) 0x27) + +/** SEC random curves over binary fields. + * + * This family comprises the following curves: + * sect163r1, sect233r1, sect283r1, sect409r1, sect571r1. + * They are defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ +#define PSA_ECC_FAMILY_SECT_R1 ((psa_ecc_family_t) 0x22) + +/** SEC additional random curves over binary fields. + * + * This family comprises the following curve: + * sect163r2. + * It is defined in _Standards for Efficient Cryptography_, + * _SEC 2: Recommended Elliptic Curve Domain Parameters_. + * https://www.secg.org/sec2-v2.pdf + */ /**@}*/ +#define PSA_ECC_FAMILY_SECT_R2 ((psa_ecc_family_t) 0x2b) + +/** Brainpool P random curves. + * + * This family comprises the following curves: + * brainpoolP160r1, brainpoolP192r1, brainpoolP224r1, brainpoolP256r1, + * brainpoolP320r1, brainpoolP384r1, brainpoolP512r1. + * It is defined in RFC 5639. + */ +#define PSA_ECC_FAMILY_BRAINPOOL_P_R1 ((psa_ecc_family_t) 0x30) + +/** Curve25519 and Curve448. + * + * This family comprises the following Montgomery curves: + * - 255-bit: Bernstein et al., + * _Curve25519: new Diffie-Hellman speed records_, LNCS 3958, 2006. + * The algorithm #PSA_ALG_ECDH performs X25519 when used with this curve. + * - 448-bit: Hamburg, + * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. + * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve. + */ +#define PSA_ECC_FAMILY_MONTGOMERY ((psa_ecc_family_t) 0x41) #endif /* PSA_CRYPTO_VALUES_H */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/VERSION.txt b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/VERSION.txt deleted file mode 100644 index 54d3b4275b..0000000000 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/VERSION.txt +++ /dev/null @@ -1 +0,0 @@ -a630d86e91a8 diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_compat.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_compat.h deleted file mode 100644 index 518008b8a7..0000000000 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_compat.h +++ /dev/null @@ -1,111 +0,0 @@ -/** - * \file psa/crypto_compat.h - * - * \brief PSA cryptography module: Backward compatibility aliases - * - * This header declares alternative names for macro and functions. - * New application code should not use these names. - * These names may be removed in a future version of Mbed Crypto. - * - * \note This file may not be included directly. Applications must - * include psa/crypto.h. - */ -/* - * Copyright (C) 2019-2020, 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_COMPAT_H -#define PSA_CRYPTO_COMPAT_H - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(MBEDTLS_DEPRECATED_REMOVED) - -/* - * Mechanism for declaring deprecated values - */ -#if defined(MBEDTLS_DEPRECATED_WARNING) && !defined(MBEDTLS_PSA_DEPRECATED) -#define MBEDTLS_PSA_DEPRECATED __attribute__((deprecated)) -#else -#define MBEDTLS_PSA_DEPRECATED -#endif - -typedef MBEDTLS_PSA_DEPRECATED size_t mbedtls_deprecated_size_t; -typedef MBEDTLS_PSA_DEPRECATED psa_status_t mbedtls_deprecated_psa_status_t; -typedef MBEDTLS_PSA_DEPRECATED psa_key_usage_t mbedtls_deprecated_psa_key_usage_t; - -#define MBEDTLS_DEPRECATED_CONSTANT( type, value ) \ - ( (mbedtls_deprecated_##type) ( value ) ) - -/* - * Deprecated PSA Crypto error code definitions (PSA Crypto API <= 1.0 beta2) - */ -#define PSA_ERROR_UNKNOWN_ERROR \ - MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_GENERIC_ERROR ) -#define PSA_ERROR_OCCUPIED_SLOT \ - MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_ALREADY_EXISTS ) -#define PSA_ERROR_EMPTY_SLOT \ - MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_DOES_NOT_EXIST ) -#define PSA_ERROR_INSUFFICIENT_CAPACITY \ - MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_INSUFFICIENT_DATA ) -#define PSA_ERROR_TAMPERING_DETECTED \ - MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_CORRUPTION_DETECTED ) - -/* - * Deprecated PSA Crypto numerical encodings (PSA Crypto API <= 1.0 beta3) - */ -#define PSA_KEY_USAGE_SIGN \ - MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_SIGN_HASH ) -#define PSA_KEY_USAGE_VERIFY \ - MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_VERIFY_HASH ) - -/* - * Deprecated PSA Crypto size calculation macros (PSA Crypto API <= 1.0 beta3) - */ -#define PSA_ASYMMETRIC_SIGNATURE_MAX_SIZE \ - MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGNATURE_MAX_SIZE ) -#define PSA_ASYMMETRIC_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) \ - MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) ) - -/* - * Deprecated PSA Crypto function names (PSA Crypto API <= 1.0 beta3) - */ -MBEDTLS_PSA_DEPRECATED psa_status_t psa_asymmetric_sign( psa_key_handle_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 ); - -MBEDTLS_PSA_DEPRECATED psa_status_t psa_asymmetric_verify( psa_key_handle_t key, - psa_algorithm_t alg, - const uint8_t *hash, - size_t hash_length, - const uint8_t *signature, - size_t signature_length ); - -#endif /* MBEDTLS_DEPRECATED_REMOVED */ - -#ifdef __cplusplus -} -#endif - -#endif /* PSA_CRYPTO_COMPAT_H */ diff --git a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_extra.h b/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_extra.h deleted file mode 100644 index d658b7664c..0000000000 --- a/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_V1_1/include/psa/crypto_extra.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2018-2020, Arm Limited. All rights reserved. - * - * SPDX-License-Identifier: BSD-3-Clause - * - */ -/** - * \file psa/crypto_extra.h - * - * \brief PSA cryptography module: vendor extensions - * - * \note This file may not be included directly. Applications must - * include psa/crypto.h. - * - * This file is reserved for vendor-specific definitions. - */ - -#ifndef PSA_CRYPTO_EXTRA_H -#define PSA_CRYPTO_EXTRA_H - -#include "psa/crypto_compat.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** \addtogroup crypto_types - * @{ - */ - -/** DSA public key. - * - * The import and export format is the - * representation of the public key `y = g^x mod p` as a big-endian byte - * string. The length of the byte string is the length of the base prime `p` - * in bytes. - */ -#define PSA_KEY_TYPE_DSA_PUBLIC_KEY ((psa_key_type_t)0x60020000) - -/** DSA key pair (private and public key). - * - * The import and export format is the - * representation of the private key `x` as a big-endian byte string. The - * length of the byte string is the private key size in bytes (leading zeroes - * are not stripped). - * - * Determinstic DSA key derivation with psa_generate_derived_key follows - * FIPS 186-4 §B.1.2: interpret the byte string as integer - * in big-endian order. Discard it if it is not in the range - * [0, *N* - 2] where *N* is the boundary of the private key domain - * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA, - * or the order of the curve's base point for ECC). - * Add 1 to the resulting integer and use this as the private key *x*. - * - */ -#define PSA_KEY_TYPE_DSA_KEY_PAIR ((psa_key_type_t)0x70020000) - -/**@}*/ - -/** \brief Declare the enrollment algorithm for a key. - * - * An operation on a key may indifferently use the algorithm set with - * psa_set_key_algorithm() or with this function. - * - * \param[out] attributes The attribute structure to write to. - * \param alg2 A second algorithm that the key may be used - * for, in addition to the algorithm set with - * psa_set_key_algorithm(). - * - * \warning Setting an enrollment algorithm is not recommended, because - * using the same key with different algorithms can allow some - * attacks based on arithmetic relations between different - * computations made with the same key, or can escalate harmless - * side channels into exploitable ones. Use this function only - * if it is necessary to support a protocol for which it has been - * verified that the usage of the key with multiple algorithms - * is safe. - */ -static inline void psa_set_key_enrollment_algorithm( - psa_key_attributes_t *attributes, - psa_algorithm_t alg2) -{ - attributes->alg2 = alg2; -} - -/** Retrieve the enrollment algorithm policy from key attributes. - * - * \param[in] attributes The key attribute structure to query. - * - * \return The enrollment algorithm stored in the attribute structure. - */ -static inline psa_algorithm_t psa_get_key_enrollment_algorithm( - const psa_key_attributes_t *attributes) -{ - return attributes->alg2; -} - -#ifdef __cplusplus -} -#endif - -#endif /* PSA_CRYPTO_EXTRA_H */ diff --git a/storage/kvstore/kv_config/global/mbed_lib.json b/storage/kvstore/kv_config/global/mbed_lib.json index b15e4bfda9..d129fecc4f 100644 --- a/storage/kvstore/kv_config/global/mbed_lib.json +++ b/storage/kvstore/kv_config/global/mbed_lib.json @@ -38,9 +38,6 @@ "LPC55S69_S": { "storage_type": "TDB_INTERNAL" }, - "ARM_MUSCA_A1_S": { - "storage_type": "TDB_INTERNAL" - }, "ARM_MUSCA_B1_S": { "storage_type": "TDB_INTERNAL" }, diff --git a/storage/kvstore/kv_config/tdb_internal/mbed_lib.json b/storage/kvstore/kv_config/tdb_internal/mbed_lib.json index 42518aaed1..1fee13eba9 100644 --- a/storage/kvstore/kv_config/tdb_internal/mbed_lib.json +++ b/storage/kvstore/kv_config/tdb_internal/mbed_lib.json @@ -23,10 +23,6 @@ "internal_size": "2*FLASH_SECTOR_SIZE", "internal_base_address": "0x080C0000" }, - "ARM_MUSCA_A1_S": { - "internal_size": "0x8000", - "internal_base_address": "0x00420000" - }, "ARM_MUSCA_B1_S": { "internal_size": "0x8000", "internal_base_address": "0x10000000" diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/CMakeLists.txt b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/CMakeLists.txt index cca16e643c..6d2116cde2 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/CMakeLists.txt +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/CMakeLists.txt @@ -44,9 +44,6 @@ target_sources(mbed-arm-musca-b1 device/drivers/timer_gp_drv.c device/drivers/uart_pl011_drv.c - partition/image_macros_preprocessed_ns.c - partition/image_macros_preprocessed_s.c - ${STARTUP_FILE} ) @@ -55,10 +52,3 @@ target_link_libraries(mbed-arm-musca-b1 ${CMAKE_CURRENT_SOURCE_DIR}/s_veneers.o mbed-arm-ssg ) - -add_library(mbed-arm-musca-b1-ns INTERFACE) - -target_link_libraries(mbed-arm-musca-b1-ns - INTERFACE - mbed-arm-musca-b1 -) diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/bl2.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/bl2.bin new file mode 100644 index 0000000000..13aef1e7aa Binary files /dev/null and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/bl2.bin differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/mcuboot.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/mcuboot.bin deleted file mode 100644 index e3d3a9e3ff..0000000000 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/mcuboot.bin and /dev/null differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/.mbedignore b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/.mbedignore new file mode 100644 index 0000000000..f977b62810 --- /dev/null +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/.mbedignore @@ -0,0 +1,2 @@ +signing_layout_ns.c +signing_layout_s.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/flash_layout.h b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/flash_layout.h index 65cd3aaa6f..6b7a67abad 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/flash_layout.h +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/flash_layout.h @@ -1,5 +1,6 @@ /* - * Copyright (c) 2018-2020 Arm Limited. All rights reserved. + * Copyright (c) 2018-2021 Arm Limited. All rights reserved. + * Copyright (c) 2020 Cypress Semiconductor Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -19,7 +20,19 @@ #ifndef __FLASH_LAYOUT_H__ #define __FLASH_LAYOUT_H__ -/* Flash layout on Musca-B1 with BL2(single image boot, boot from eFlash 0): +/* Flash layout on Musca-B1 with BL2 (multiple image boot, boot from eFlash 0): + * + * 0x0A00_0000 BL2 - MCUBoot (128 KB) + * 0x0A02_0000 Secure image primary slot (384 KB) + * 0x0A08_0000 Non-secure image primary slot (512 KB) + * 0x0A10_0000 Secure image secondary slot (384 KB) + * 0x0A16_0000 Non-secure image secondary slot (512 KB) + * 0x0A1E_0000 Scratch area (64 KB) + * 0x0A1F_0000 Internal Trusted Storage Area (32 KB) + * 0x0A1F_8000 NV counters area (16 KB) + * 0x0A1F_C000 Unused (32 KB) + * + * Flash layout on Musca-B1 with BL2 (single image boot): * * 0x0A00_0000 BL2 - MCUBoot (128 KB) * 0x0A02_0000 Primary image area (896 KB): @@ -28,18 +41,20 @@ * 0x0A10_0000 Secondary image area (896 KB): * 0x0A10_0000 Secure image secondary (384 KB) * 0x0A16_0000 Non-secure image secondary (512 KB) - * 0x0A1E_0000 Internal Trusted Storage Area (32 KB) - * 0x0A1E_8000 NV counters area (16 KB) + * 0x0A1E_0000 Scratch area (64 KB) + * 0x0A1F_0000 Internal Trusted Storage Area (32 KB) + * 0x0A1F_8000 NV counters area (16 KB) + * 0x0A1F_C000 Unused (32 KB) * * Note: As eFlash is written at runtime, the eFlash driver code is placed - * in code sram to avoid any interference. + * in code SRAM to avoid any interference. * * Flash layout on Musca-B1 without BL2: * 0x0A00_0000 Secure image - * 0x0A07_0000 Non-secure image + * 0x0A08_0000 Non-secure image * * QSPI Flash layout - * 0x0000_0000 Secure Storage Area (20 KB) + * 0x0000_0000 Protected Storage Area (20 KB) */ /* This header file is included from linker scatter file as well, where only a @@ -88,12 +103,14 @@ #define FLASH_AREA_2_OFFSET (FLASH_AREA_0_OFFSET + FLASH_AREA_0_SIZE) #define FLASH_AREA_2_SIZE (FLASH_S_PARTITION_SIZE + \ FLASH_NS_PARTITION_SIZE) -/* Not used, only the Non-swapping firmware upgrade operation - * is supported on Musca-B1. - */ +/* Scratch area */ #define FLASH_AREA_SCRATCH_ID (FLASH_AREA_2_ID + 1) #define FLASH_AREA_SCRATCH_OFFSET (FLASH_AREA_2_OFFSET + FLASH_AREA_2_SIZE) -#define FLASH_AREA_SCRATCH_SIZE (0) +#define FLASH_AREA_SCRATCH_SIZE (4 * FLASH_AREA_IMAGE_SECTOR_SIZE) +/* The maximum number of status entries supported by the bootloader. */ +#define MCUBOOT_STATUS_MAX_ENTRIES ((FLASH_S_PARTITION_SIZE + \ + FLASH_NS_PARTITION_SIZE) / \ + FLASH_AREA_SCRATCH_SIZE) /* Maximum number of image sectors supported by the bootloader. */ #define MCUBOOT_MAX_IMG_SECTORS ((FLASH_S_PARTITION_SIZE + \ FLASH_NS_PARTITION_SIZE) / \ @@ -115,12 +132,13 @@ #define FLASH_AREA_3_ID (FLASH_AREA_2_ID + 1) #define FLASH_AREA_3_OFFSET (FLASH_AREA_2_OFFSET + FLASH_AREA_2_SIZE) #define FLASH_AREA_3_SIZE (FLASH_NS_PARTITION_SIZE) -/* Not used, only the Non-swapping firmware upgrade operation - * is supported on Musca-B1. - */ +/* Scratch area */ #define FLASH_AREA_SCRATCH_ID (FLASH_AREA_3_ID + 1) #define FLASH_AREA_SCRATCH_OFFSET (FLASH_AREA_3_OFFSET + FLASH_AREA_3_SIZE) -#define FLASH_AREA_SCRATCH_SIZE (0) +#define FLASH_AREA_SCRATCH_SIZE (4 * FLASH_AREA_IMAGE_SECTOR_SIZE) +/* The maximum number of status entries supported by the bootloader. */ +#define MCUBOOT_STATUS_MAX_ENTRIES (FLASH_MAX_PARTITION_SIZE / \ + FLASH_AREA_SCRATCH_SIZE) /* Maximum number of image sectors supported by the bootloader. */ #define MCUBOOT_MAX_IMG_SECTORS (FLASH_MAX_PARTITION_SIZE / \ FLASH_AREA_IMAGE_SECTOR_SIZE) @@ -128,12 +146,6 @@ #error "Only MCUBOOT_IMAGE_NUMBER 1 and 2 are supported!" #endif /* MCUBOOT_IMAGE_NUMBER */ -/* Not used, only the Non-swapping firmware upgrade operation - * is supported on Musca-B1. The maximum number of status entries - * supported by the bootloader. - */ -#define MCUBOOT_STATUS_MAX_ENTRIES (0) - /* Internal Trusted Storage (ITS) Service definitions (32 KB) */ #define FLASH_ITS_AREA_OFFSET (FLASH_AREA_SCRATCH_OFFSET + \ FLASH_AREA_SCRATCH_SIZE) @@ -152,38 +164,35 @@ SECURE_IMAGE_MAX_SIZE) #define NON_SECURE_IMAGE_MAX_SIZE FLASH_NS_PARTITION_SIZE -/* Secure Storage (SST) Service definitions size is 20 KB. */ +/* Protected Storage (PS) Service definitions size is 20 KB. */ /* Same as MUSCA_B1_QSPI_FLASH_S_BASE */ #define QSPI_FLASH_BASE_ADDRESS (0x10000000) -#define FLASH_SST_AREA_OFFSET (0x0) -#define FLASH_SST_AREA_SIZE (5 * QSPI_FLASH_AREA_IMAGE_SECTOR_SIZE) +#define FLASH_PS_AREA_OFFSET (0x0) +#define FLASH_PS_AREA_SIZE (5 * QSPI_FLASH_AREA_IMAGE_SECTOR_SIZE) /* Flash device name used by BL2 * Name is defined in flash driver file: Driver_Flash.c */ #define FLASH_DEV_NAME Driver_EFLASH0 -/* Secure Storage (SST) Service definitions +/* Protected Storage (PS) Service definitions * Note: Further documentation of these definitions can be found in the - * TF-M SST Integration Guide. + * TF-M PS Integration Guide. */ -#define SST_FLASH_DEV_NAME Driver_QSPI_FLASH0 +#define PS_FLASH_DEV_NAME Driver_QSPI_FLASH0 /* In this target the CMSIS driver requires only the offset from the base * address instead of the full memory address. */ -#define SST_FLASH_AREA_ADDR FLASH_SST_AREA_OFFSET -/* Dedicated flash area for SST */ -#define SST_FLASH_AREA_SIZE FLASH_SST_AREA_SIZE -#define SST_SECTOR_SIZE QSPI_FLASH_AREA_IMAGE_SECTOR_SIZE -/* Number of SST_SECTOR_SIZE per block */ -#define SST_SECTORS_PER_BLOCK (0x1) +#define PS_FLASH_AREA_ADDR FLASH_PS_AREA_OFFSET +/* Dedicated flash area for PS */ +#define PS_FLASH_AREA_SIZE FLASH_PS_AREA_SIZE +#define PS_RAM_FS_SIZE PS_FLASH_AREA_SIZE +#define PS_SECTOR_SIZE QSPI_FLASH_AREA_IMAGE_SECTOR_SIZE +/* Number of PS_SECTOR_SIZE per block */ +#define PS_SECTORS_PER_BLOCK (0x1) /* Specifies the smallest flash programmable unit in bytes */ -#define SST_FLASH_PROGRAM_UNIT (0x4) -/* The maximum asset size to be stored in the SST area */ -#define SST_MAX_ASSET_SIZE (2048) -/* The maximum number of assets to be stored in the SST area */ -#define SST_NUM_ASSETS (10) +#define PS_FLASH_PROGRAM_UNIT (0x1) /* Internal Trusted Storage (ITS) Service definitions * Note: Further documentation of these definitions can be found in the @@ -199,15 +208,12 @@ #define ITS_FLASH_AREA_ADDR FLASH_ITS_AREA_OFFSET /* Dedicated flash area for ITS */ #define ITS_FLASH_AREA_SIZE FLASH_ITS_AREA_SIZE +#define ITS_RAM_FS_SIZE ITS_FLASH_AREA_SIZE #define ITS_SECTOR_SIZE FLASH_AREA_IMAGE_SECTOR_SIZE /* Number of ITS_SECTOR_SIZE per block */ #define ITS_SECTORS_PER_BLOCK (0x1) /* Specifies the smallest flash programmable unit in bytes */ #define ITS_FLASH_PROGRAM_UNIT (0x4) -/* The maximum asset size to be stored in the ITS area */ -#define ITS_MAX_ASSET_SIZE (512) -/* The maximum number of assets to be stored in the ITS area */ -#define ITS_NUM_ASSETS (10) /* NV Counters definitions */ #define TFM_NV_COUNTERS_AREA_ADDR FLASH_NV_COUNTERS_AREA_OFFSET diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/region_defs.h b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/region_defs.h index 442cf5f61e..291c9489d3 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/region_defs.h +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/region_defs.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2020 Arm Limited. All rights reserved. + * Copyright (c) 2017-2021 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -21,6 +21,10 @@ #include "flash_layout.h" +#ifndef BL2 +#define BL2 +#endif + #define BL2_HEAP_SIZE (0x0001000) #define BL2_MSP_STACK_SIZE (0x0001800) @@ -30,8 +34,8 @@ #define S_PSP_STACK_SIZE (0x0000800) #define NS_HEAP_SIZE (0x0001000) -#define NS_MSP_STACK_SIZE (0x0000400) -#define NS_PSP_STACK_SIZE (0x0000C00) +#define NS_MSP_STACK_SIZE (0x00000A0) +#define NS_PSP_STACK_SIZE (0x0000140) /* This size of buffer is big enough to store an attestation * token produced by initial attestation service @@ -73,11 +77,11 @@ */ #ifdef BL2 #define BL2_HEADER_SIZE (0x400) /* 1 KB */ -#define BL2_TRAILER_SIZE (0x400) /* 1 KB */ +#define BL2_TRAILER_SIZE (0x800) /* 2 KB */ #else /* No header if no bootloader, but keep IMAGE_CODE_SIZE the same */ #define BL2_HEADER_SIZE (0x0) -#define BL2_TRAILER_SIZE (0x800) +#define BL2_TRAILER_SIZE (0xC00) #endif /* BL2 */ #define IMAGE_S_CODE_SIZE \ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/image_macros_preprocessed_ns.c b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/signing_layout_ns.c similarity index 100% rename from targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/image_macros_preprocessed_ns.c rename to targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/signing_layout_ns.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/image_macros_preprocessed_s.c b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/signing_layout_s.c similarity index 100% rename from targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/image_macros_preprocessed_s.c rename to targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/partition/signing_layout_s.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/s_veneers.o b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/s_veneers.o index 94b09968af..aaf402176f 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/s_veneers.o and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/s_veneers.o differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.axf b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.axf index 4510935285..3ec463e9bc 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.axf and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.axf differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.bin index 6a8937f366..aac62a264e 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.bin and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/tfm_s.bin differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/CMakeLists.txt b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/CMakeLists.txt index e7d3b0fc51..13309e20e0 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/CMakeLists.txt +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/CMakeLists.txt @@ -50,9 +50,6 @@ target_sources(mbed-arm-musca-s1 Libraries/mt25ql_flash_lib.c - partition/image_macros_preprocessed_ns.c - partition/image_macros_preprocessed_s.c - ${STARTUP_FILE} ) @@ -61,10 +58,3 @@ target_link_libraries(mbed-arm-musca-s1 ${CMAKE_CURRENT_SOURCE_DIR}/s_veneers.o mbed-arm-ssg ) - -add_library(mbed-arm-musca-s1-ns INTERFACE) - -target_link_libraries(mbed-arm-musca-s1-ns - INTERFACE - mbed-arm-musca-s1 -) diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/bl2.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/bl2.bin new file mode 100644 index 0000000000..654e712e48 Binary files /dev/null and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/bl2.bin differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/device/cmsis.h b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/device/cmsis.h index 22a3aada8a..dbf0f53cde 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/device/cmsis.h +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/device/cmsis.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Arm Limited. All rights reserved. + * Copyright (c) 2017-2021 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -83,4 +83,6 @@ #warning Not supported compiler type #endif +#include "cmsis_nvic.h" + #endif /*__MUSCA_S1_CMSIS_H__ */ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/mcuboot.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/mcuboot.bin deleted file mode 100644 index ed2cb0a0e2..0000000000 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/mcuboot.bin and /dev/null differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/.mbedignore b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/.mbedignore new file mode 100644 index 0000000000..f977b62810 --- /dev/null +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/.mbedignore @@ -0,0 +1,2 @@ +signing_layout_ns.c +signing_layout_s.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/flash_layout.h b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/flash_layout.h index 9ebc41f24c..5317e2ccce 100644 --- a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/flash_layout.h +++ b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/flash_layout.h @@ -1,5 +1,6 @@ /* - * Copyright (c) 2018-2020 Arm Limited. All rights reserved. + * Copyright (c) 2018-2021 Arm Limited. All rights reserved. + * Copyright (c) 2020 Cypress Semiconductor Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -21,15 +22,18 @@ /* Flash layout on Musca-S1 with BL2(multiple image boot, boot from MRAM): * 0x0A00_0000 BL2 - MCUBoot(128 KB) - * 0x0A02_0000 Secure image primary (320 KB) - * 0x0A07_0000 Non-secure image primary (512 KB) - * 0x0A0F_0000 Secure image secondary (320 KB) - * 0x0A14_0000 Non-secure image secondary (512 KB) - * 0x0A1C_0000 Scratch Area (16 KB) - * 0x0A1C_4000 Secure Storage Area (20 KB) - * 0x0A1C_9000 Internal Trusted Storage Area (16 KB) - * 0x0A1C_D000 NV counters area (4 KB) - * 0x0A1C_E000 Unused + * 0x0A02_0000 Secure image primary (384 KB) + * 0x0A08_0000 Non-secure image primary (512 KB) + * 0x0A10_0000 Secure image secondary (384 KB) + * 0x0A16_0000 Non-secure image secondary (512 KB) + * 0x0A1E_0000 Scratch Area (16 KB) + * 0x0A1E_4000 Protected Storage Area (20 KB) + * 0x0A1E_9000 Internal Trusted Storage Area (16 KB) + * 0x0A1E_D000 NV counters area (4 KB) + * 0x0A1E_E000 TF-M key area (256 bytes) This area is referred to in + * /lib/ext/cryptocell-312-runtime/shared/hw/include/musca_s1/ \ + * dx_reg_base_host.h Do not change one without changing the other. + * 0x0A1E_E100 Unused * * Flash layout on Musca-S1 with BL2(single image boot): * 0x0A00_0000 BL2 - MCUBoot(128 KB) @@ -39,17 +43,18 @@ * 0x0A10_0000 Secondary image area (896 KB): * 0x0A10_0000 Secure image secondary (384 KB) * 0x0A16_0000 Non-secure image secondary (512 KB) - * 0x0A1E_0000 Secure Storage Area (20 KB) - * 0x0A1E_5000 Internal Trusted Storage Area (16 KB) - * 0x0A1E_9000 NV counters area (4 KB) - * 0x0A1E_A000 TF-M key area (256 bytes) This area is referred to in + * 0x0A1E_0000 Scratch Area (16 KB) + * 0x0A1E_4000 Protected Storage Area (20 KB) + * 0x0A1E_9000 Internal Trusted Storage Area (16 KB) + * 0x0A1E_D000 NV counters area (4 KB) + * 0x0A1E_E000 TF-M key area (256 bytes) This area is referred to in * /lib/ext/cryptocell-312-runtime/shared/hw/include/musca_s1/ \ * dx_reg_base_host.h Do not change one without changing the other. - * 0x0A1E_A100 Unused + * 0x0A1E_E100 Unused * * Flash layout on Musca-S1 without BL2: * 0x0A00_0000 Secure image - * 0x0A07_0000 Non-secure image + * 0x0A08_0000 Non-secure image */ /* This header file is included from linker scatter file as well, where only a @@ -137,17 +142,17 @@ #error "Only MCUBOOT_IMAGE_NUMBER 1 and 2 are supported!" #endif /* MCUBOOT_IMAGE_NUMBER */ -/* Note: FLASH_SST_AREA_OFFSET, FLASH_ITS_AREA_OFFSET and +/* Note: FLASH_PS_AREA_OFFSET, FLASH_ITS_AREA_OFFSET and * FLASH_NV_COUNTERS_AREA_OFFSET point to offsets in flash, but reads and writes * to these addresses are redirected to Code SRAM by Driver_Flash.c. */ -#define FLASH_SST_AREA_OFFSET (FLASH_AREA_SCRATCH_OFFSET + \ +#define FLASH_PS_AREA_OFFSET (FLASH_AREA_SCRATCH_OFFSET + \ FLASH_AREA_SCRATCH_SIZE) -#define FLASH_SST_AREA_SIZE (0x5000) /* 20 KB */ +#define FLASH_PS_AREA_SIZE (0x5000) /* 20 KB */ /* Internal Trusted Storage (ITS) Service definitions */ -#define FLASH_ITS_AREA_OFFSET (FLASH_SST_AREA_OFFSET + \ - FLASH_SST_AREA_SIZE) +#define FLASH_ITS_AREA_OFFSET (FLASH_PS_AREA_OFFSET + \ + FLASH_PS_AREA_SIZE) #define FLASH_ITS_AREA_SIZE (0x4000) /* 16 KB */ /* NV Counters definitions */ @@ -173,27 +178,24 @@ */ #define FLASH_DEV_NAME Driver_FLASH0 -/* Secure Storage (SST) Service definitions +/* Protected Storage (PS) Service definitions * Note: Further documentation of these definitions can be found in the - * TF-M SST Integration Guide. + * TF-M PS Integration Guide. */ -#define SST_FLASH_DEV_NAME Driver_FLASH0 +#define PS_FLASH_DEV_NAME Driver_FLASH0 /* In this target the CMSIS driver requires only the offset from the base * address instead of the full memory address. */ -#define SST_FLASH_AREA_ADDR FLASH_SST_AREA_OFFSET -/* Dedicated flash area for SST */ -#define SST_FLASH_AREA_SIZE FLASH_SST_AREA_SIZE -#define SST_SECTOR_SIZE FLASH_AREA_IMAGE_SECTOR_SIZE -/* Number of SST_SECTOR_SIZE per block */ -#define SST_SECTORS_PER_BLOCK (0x1) +#define PS_FLASH_AREA_ADDR FLASH_PS_AREA_OFFSET +/* Dedicated flash area for PS */ +#define PS_FLASH_AREA_SIZE FLASH_PS_AREA_SIZE +#define PS_RAM_FS_SIZE PS_FLASH_AREA_SIZE +#define PS_SECTOR_SIZE FLASH_AREA_IMAGE_SECTOR_SIZE +/* Number of PS_SECTOR_SIZE per block */ +#define PS_SECTORS_PER_BLOCK (0x1) /* Specifies the smallest flash programmable unit in bytes */ -#define SST_FLASH_PROGRAM_UNIT (0x1) -/* The maximum asset size to be stored in the SST area */ -#define SST_MAX_ASSET_SIZE (2048) -/* The maximum number of assets to be stored in the SST area */ -#define SST_NUM_ASSETS (10) +#define PS_FLASH_PROGRAM_UNIT (0x1) /* Internal Trusted Storage (ITS) Service definitions * Note: Further documentation of these definitions can be found in the @@ -209,15 +211,12 @@ #define ITS_FLASH_AREA_ADDR FLASH_ITS_AREA_OFFSET /* Dedicated flash area for ITS */ #define ITS_FLASH_AREA_SIZE FLASH_ITS_AREA_SIZE +#define ITS_RAM_FS_SIZE ITS_FLASH_AREA_SIZE #define ITS_SECTOR_SIZE FLASH_AREA_IMAGE_SECTOR_SIZE /* Number of ITS_SECTOR_SIZE per block */ #define ITS_SECTORS_PER_BLOCK (0x1) /* Specifies the smallest flash programmable unit in bytes */ #define ITS_FLASH_PROGRAM_UNIT (0x1) -/* The maximum asset size to be stored in the ITS area */ -#define ITS_MAX_ASSET_SIZE (512) -/* The maximum number of assets to be stored in the ITS area */ -#define ITS_NUM_ASSETS (10) /* NV Counters definitions */ #define TFM_NV_COUNTERS_AREA_ADDR FLASH_NV_COUNTERS_AREA_OFFSET diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/image_macros_preprocessed_ns.c b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/signing_layout_ns.c similarity index 100% rename from targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/image_macros_preprocessed_ns.c rename to targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/signing_layout_ns.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/image_macros_preprocessed_s.c b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/signing_layout_s.c similarity index 100% rename from targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/image_macros_preprocessed_s.c rename to targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/partition/signing_layout_s.c diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/s_veneers.o b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/s_veneers.o index 94b09968af..aaf402176f 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/s_veneers.o and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/s_veneers.o differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.axf b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.axf index 33fdcfffd7..ecc1cc9478 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.axf and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.axf differ diff --git a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.bin b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.bin index 3fffbc5af3..7a661bb32b 100644 Binary files a/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.bin and b/targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/tfm_s.bin differ diff --git a/targets/targets.json b/targets/targets.json index 4cea53d70f..32711baa82 100644 --- a/targets/targets.json +++ b/targets/targets.json @@ -144,7 +144,7 @@ ], "extra_labels": [ "TFM", - "TFM_V1_1", + "TFM_LATEST", "TFM_V8M" ], "device_has": [ @@ -4815,18 +4815,18 @@ "CMSIS_NVIC_VIRTUAL", "LPTICKER_DELAY_TICKS=3", "MBED_MPU_CUSTOM", - "BL2" + "BL2", + "MCUBOOT_IMAGE_NUMBER=2" ], "extra_labels_add": [ "ARM_SSG", - "MUSCA_B1", - "MUSCA_B1_NS" + "MUSCA_B1" ], "post_binary_hook": { "function": "ArmMuscaB1Code.binary_hook" }, "secure_image_filename": "tfm_s.bin", - "tfm_target_name": "MUSCA_B1", + "tfm_target_name": "musca_b1", "tfm_bootloader_supported": true, "tfm_default_toolchain": "ARMCLANG", "tfm_supported_toolchains": [ @@ -4835,11 +4835,6 @@ ], "tfm_delivery_dir": "TARGET_ARM_SSG/TARGET_MUSCA_B1" }, - "ARM_MUSCA_B1_NS": { - "inherits": [ - "ARM_MUSCA_B1" - ] - }, "ARM_MUSCA_S1": { "inherits": [ "PSA_V8_M" @@ -4872,18 +4867,18 @@ "CMSIS_NVIC_VIRTUAL", "LPTICKER_DELAY_TICKS=3", "MBED_MPU_CUSTOM", - "BL2" + "BL2", + "MCUBOOT_IMAGE_NUMBER=2" ], "extra_labels_add": [ "ARM_SSG", - "MUSCA_S1", - "MUSCA_S1_NS" + "MUSCA_S1" ], "post_binary_hook": { "function": "ArmMuscaS1Code.binary_hook" }, "secure_image_filename": "tfm_s.bin", - "tfm_target_name": "MUSCA_S1", + "tfm_target_name": "musca_s1", "tfm_bootloader_supported": true, "tfm_default_toolchain": "ARMCLANG", "tfm_supported_toolchains": [ @@ -4895,11 +4890,6 @@ "5009" ] }, - "ARM_MUSCA_S1_NS": { - "inherits": [ - "ARM_MUSCA_S1" - ] - }, "RZ_A1XX": { "inherits": [ "Target" diff --git a/tools/cmake/README.md b/tools/cmake/README.md index 830d23c2cc..34a324f163 100644 --- a/tools/cmake/README.md +++ b/tools/cmake/README.md @@ -41,7 +41,7 @@ LPC546XX, FF_LPC546XX, CY8CKIT064B0S2_4343W, CYTFM_064B0S2_4343W, CYSBSYSKIT_01. The following Mbed boards do not have post build operations support as TFM is not yet supported: -ARM_MUSCA_B1, ARM_MUSCA_B1_NS, ARM_MUSCA_S1, ARM_MUSCA_S1_NS. +ARM_MUSCA_B1, ARM_MUSCA_S1. ### Supported toolchains diff --git a/tools/psa/tfm/bin_utils/assemble.py b/tools/psa/tfm/bin_utils/assemble.py old mode 100644 new mode 100755 index 5a75424699..e6b5625189 --- a/tools/psa/tfm/bin_utils/assemble.py +++ b/tools/psa/tfm/bin_utils/assemble.py @@ -3,6 +3,8 @@ # Copyright 2017 Linaro Limited # Copyright (c) 2017-2019, Arm Limited. # +# 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 diff --git a/tools/psa/tfm/bin_utils/imgtool.py b/tools/psa/tfm/bin_utils/imgtool.py old mode 100644 new mode 100755 index b5242456f0..e29e224d8c --- a/tools/psa/tfm/bin_utils/imgtool.py +++ b/tools/psa/tfm/bin_utils/imgtool.py @@ -1,7 +1,8 @@ #! /usr/bin/env python3 # # Copyright 2017 Linaro Limited -# Copyright (c) 2018-2019, Arm Limited. +# +# 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. @@ -15,240 +16,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import print_function -import os -import re -import argparse -from imgtool_lib import keys -from imgtool_lib import image -from imgtool_lib import version -import sys -import macro_parser -import fileinput - -sign_bin_size_re = re.compile(r"^\s*RE_SIGN_BIN_SIZE\s*=\s*(.*)") -image_load_address_re = re.compile(r"^\s*RE_IMAGE_LOAD_ADDRESS\s*=\s*(.*)") - -# Returns the last version number if present, or None if not -def get_last_version(path): - if (os.path.isfile(path) == False): # Version file not present - return None - else: # Version file is present, check it has a valid number inside it - with open(path, "r") as oldFile: - fileContents = oldFile.read() - if version.version_re.match(fileContents): # number is valid - return version.decode_version(fileContents) - else: - return None - -def next_version_number(args, defaultVersion, path): - newVersion = None - versionProvided = False - if (version.compare(args.version, defaultVersion) == 0): # Default version - lastVersion = get_last_version(path) - if (lastVersion is not None): - newVersion = version.increment_build_num(lastVersion) - else: - newVersion = version.increment_build_num(defaultVersion) - else: # Version number has been explicitly provided (not using the default) - versionProvided = True - newVersion = args.version - versionString = "{a}.{b}.{c}+{d}".format( - a=str(newVersion.major), - b=str(newVersion.minor), - c=str(newVersion.revision), - d=str(newVersion.build) - ) - if not versionProvided: - with open(path, "w") as newFile: - newFile.write(versionString) - print("**[INFO]** Image version number set to " + versionString) - return newVersion - -def gen_rsa2048(args): - keys.RSAutil.generate().export_private(args.key) - -def gen_rsa3072(args): - keys.RSAutil.generate(key_size=3072).export_private(args.key) - -keygens = { - 'rsa-2048': gen_rsa2048, - 'rsa-3072': gen_rsa3072, } - -def do_keygen(args): - if args.type not in keygens: - msg = "Unexpected key type: {}".format(args.type) - raise argparse.ArgumentTypeError(msg) - keygens[args.type](args) - -def do_getpub(args): - key = keys.load(args.key) - if args.lang == 'c': - key.emit_c() - else: - msg = "Unsupported language, valid are: c" - raise argparse.ArgumentTypeError(msg) - -def do_sign(args): - if args.rsa_pkcs1_15: - keys.sign_rsa_pss = False - - version_num = next_version_number(args, - version.decode_version("0"), - "lastVerNum.txt") - - if args.security_counter is None: - # Security counter has not been explicitly provided, - # generate it from the version number - args.security_counter = ((version_num.major << 24) - + (version_num.minor << 16) - + version_num.revision) - - if "_s.c" in args.layout: - sw_type = "SPE" - elif "_ns.c" in args.layout: - sw_type = "NSPE" - else: - sw_type = "NSPE_SPE" - - pad_size = macro_parser.evaluate_macro(args.layout, sign_bin_size_re, 0, 1) - img = image.Image.load(args.infile, - version=version_num, - header_size=args.header_size, - security_cnt=args.security_counter, - included_header=args.included_header, - pad=pad_size) - key = keys.load(args.key, args.public_key_format) if args.key else None - ram_load_address = macro_parser.evaluate_macro(args.layout, image_load_address_re, 0, 1) - img.sign(sw_type, key, ram_load_address, args.dependencies) - - if pad_size: - img.pad_to(pad_size, args.align) - - img.save(args.outfile) - -def do_flash(args): - image_value_re = re.compile(r"^\s*"+args.macro+"\s*=\s*(.*)") - value = macro_parser.evaluate_macro(args.layout, image_value_re, 0, 1, - True) - if args.setting == 1: - begin_line="set "+args.begin - else: - begin_line=args.begin - - for line in fileinput.input(args.infile, inplace=True): - if line.startswith(begin_line): - if args.division: - value = int(value/int(args.division)) - if args.phexa == 0: - line = begin_line+"="+str(value)+"\n" - else: - line = begin_line+"="+hex(value)+"\n" - sys.stdout.write(line) - -subcmds = { - 'keygen': do_keygen, - 'getpub': do_getpub, - 'sign': do_sign, - 'flash': do_flash, } - - -def get_dependencies(text): - if text is not None: - versions = [] - images = re.findall(r"\((\d+)", text) - if len(images) == 0: - msg = "Image dependency format is invalid: {}".format(text) - raise argparse.ArgumentTypeError(msg) - raw_versions = re.findall(r",\s*([0-9.+]+)\)", text) - if len(images) != len(raw_versions): - msg = '''There's a mismatch between the number of dependency images - and versions in: {}'''.format(text) - raise argparse.ArgumentTypeError(msg) - for raw_version in raw_versions: - try: - versions.append(version.decode_version(raw_version)) - except ValueError as e: - print(e) - dependencies = dict() - dependencies[image.DEP_IMAGES_KEY] = images - dependencies[image.DEP_VERSIONS_KEY] = versions - return dependencies - - -def alignment_value(text): - value = int(text) - if value not in [1, 2, 4, 8]: - msg = "{} must be one of 1, 2, 4 or 8".format(value) - raise argparse.ArgumentTypeError(msg) - return value - -def intparse(text): - """Parse a command line argument as an integer. - - Accepts 0x and other prefixes to allow other bases to be used.""" - return int(text, 0) - -def args(): - parser = argparse.ArgumentParser() - subs = parser.add_subparsers(help='subcommand help', dest='subcmd') - - keygenp = subs.add_parser('keygen', help='Generate pub/private keypair') - keygenp.add_argument('-k', '--key', metavar='filename', required=True) - keygenp.add_argument('-t', '--type', metavar='type', - choices=keygens.keys(), required=True) - - getpub = subs.add_parser('getpub', help='Get public key from keypair') - getpub.add_argument('-k', '--key', metavar='filename', required=True) - getpub.add_argument('-l', '--lang', metavar='lang', default='c') - - sign = subs.add_parser('sign', help='Sign an image with a private key') - sign.add_argument('-l', '--layout', required=True, - help='Location of the file that contains preprocessed macros') - sign.add_argument('-k', '--key', metavar='filename') - sign.add_argument("-K", "--public-key-format", - help='In what format to add the public key to the image manifest: full or hash', - metavar='pub_key_format', choices=['full', 'hash'], default='hash') - sign.add_argument("--align", type=alignment_value, required=True) - sign.add_argument("-v", "--version", type=version.decode_version, - default="0.0.0+0") - sign.add_argument("-d", "--dependencies", type=get_dependencies, - required=False, help='''Add dependence on another image, - format: "(,), ... "''') - sign.add_argument("-s", "--security-counter", type=intparse, - help='Specify explicitly the security counter value') - sign.add_argument("-H", "--header-size", type=intparse, required=True) - sign.add_argument("--included-header", default=False, action='store_true', - help='Image has gap for header') - sign.add_argument("--rsa-pkcs1-15", - help='Use old PKCS#1 v1.5 signature algorithm', - default=False, action='store_true') - sign.add_argument("infile") - sign.add_argument("outfile") - - flash = subs.add_parser('flash', help='modify flash script') - flash.add_argument("infile") - flash.add_argument('-l', '--layout', required=True, - help='Location of the file that contains preprocessed macros') - flash.add_argument('-m', '--macro', required =True, - help='macro symbol string to grep in preprocessed file') - flash.add_argument('-b', '--begin', required=True, - help='begin of line to replace ') - flash.add_argument('-s', '--setting',type=intparse,required=False,default=0, - help='search for window batch set variable') - flash.add_argument('-d', '--division', - required=False,type=intparse,default=0, - help='search for window batch set variable') - flash.add_argument('-p', '--phexa', - required=False,type=intparse,default=1, - help='print value in hexa') - - args = parser.parse_args() - if args.subcmd is None: - print('Must specify a subcommand', file=sys.stderr) - sys.exit(1) - - subcmds[args.subcmd](args) +from imgtool import main if __name__ == '__main__': - args() + main.imgtool() diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/__init__.py b/tools/psa/tfm/bin_utils/imgtool/__init__.py similarity index 76% rename from tools/psa/tfm/bin_utils/imgtool_lib/__init__.py rename to tools/psa/tfm/bin_utils/imgtool/__init__.py index fd240440dc..3f67eed488 100644 --- a/tools/psa/tfm/bin_utils/imgtool_lib/__init__.py +++ b/tools/psa/tfm/bin_utils/imgtool/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2017 Linaro Limited +# Copyright 2017-2020 Linaro Limited +# +# 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. @@ -12,7 +14,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This file is intentionally empty. -# -# The __init__.py files are required to make Python treat the directories as -# containing packages. \ No newline at end of file +imgtool_version = "1.7.0rc1" diff --git a/tools/psa/tfm/bin_utils/imgtool/boot_record.py b/tools/psa/tfm/bin_utils/imgtool/boot_record.py new file mode 100644 index 0000000000..ac433aa099 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/boot_record.py @@ -0,0 +1,49 @@ +# Copyright (c) 2019, Arm Limited. +# Copyright (c) 2020, Linaro Limited +# +# 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. + +from enum import Enum +import cbor + + +class SwComponent(int, Enum): + """ + Software component property IDs specified by + Arm's PSA Attestation API 1.0 document. + """ + TYPE = 1 + MEASUREMENT_VALUE = 2 + VERSION = 4 + SIGNER_ID = 5 + MEASUREMENT_DESCRIPTION = 6 + + +def create_sw_component_data(sw_type, sw_version, sw_measurement_description, + sw_measurement_value, sw_signer_id): + + # List of software component properties (Key ID + value) + properties = { + SwComponent.TYPE: sw_type, + SwComponent.VERSION: sw_version, + SwComponent.SIGNER_ID: sw_signer_id, + SwComponent.MEASUREMENT_DESCRIPTION: sw_measurement_description, + } + + # Note: The measurement value must be the last item of the property + # list because later it will be modified by the bootloader. + properties[SwComponent.MEASUREMENT_VALUE] = sw_measurement_value + + return cbor.dumps(properties) diff --git a/tools/psa/tfm/bin_utils/imgtool/image.py b/tools/psa/tfm/bin_utils/imgtool/image.py new file mode 100644 index 0000000000..7d7f2bac01 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/image.py @@ -0,0 +1,576 @@ +# Copyright 2018 Nordic Semiconductor ASA +# Copyright 2017-2020 Linaro Limited +# Copyright 2019-2020 Arm Limited +# +# 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. + +""" +Image signing and management. +""" + +from . import version as versmod +from .boot_record import create_sw_component_data +import click +from enum import Enum +from intelhex import IntelHex +import hashlib +import struct +import os.path +from .keys import rsa, ecdsa, x25519 +from cryptography.hazmat.primitives.asymmetric import ec, padding +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.kdf.hkdf import HKDF +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes, hmac +from cryptography.exceptions import InvalidSignature + +IMAGE_MAGIC = 0x96f3b83d +IMAGE_HEADER_SIZE = 32 +BIN_EXT = "bin" +INTEL_HEX_EXT = "hex" +DEFAULT_MAX_SECTORS = 128 +MAX_ALIGN = 8 +DEP_IMAGES_KEY = "images" +DEP_VERSIONS_KEY = "versions" +MAX_SW_TYPE_LENGTH = 12 # Bytes + +# Image header flags. +IMAGE_F = { + 'PIC': 0x0000001, + 'NON_BOOTABLE': 0x0000010, + 'RAM_LOAD': 0x0000020, + 'ENCRYPTED': 0x0000004, +} + +TLV_VALUES = { + 'KEYHASH': 0x01, + 'PUBKEY': 0x02, + 'SHA256': 0x10, + 'RSA2048': 0x20, + 'ECDSA224': 0x21, + 'ECDSA256': 0x22, + 'RSA3072': 0x23, + 'ED25519': 0x24, + 'ENCRSA2048': 0x30, + 'ENCKW128': 0x31, + 'ENCEC256': 0x32, + 'ENCX25519': 0x33, + 'DEPENDENCY': 0x40, + 'SEC_CNT': 0x50, + 'BOOT_RECORD': 0x60, +} + +TLV_SIZE = 4 +TLV_INFO_SIZE = 4 +TLV_INFO_MAGIC = 0x6907 +TLV_PROT_INFO_MAGIC = 0x6908 + +boot_magic = bytes([ + 0x77, 0xc2, 0x95, 0xf3, + 0x60, 0xd2, 0xef, 0x7f, + 0x35, 0x52, 0x50, 0x0f, + 0x2c, 0xb6, 0x79, 0x80, ]) + +STRUCT_ENDIAN_DICT = { + 'little': '<', + 'big': '>' +} + +VerifyResult = Enum('VerifyResult', + """ + OK INVALID_MAGIC INVALID_TLV_INFO_MAGIC INVALID_HASH + INVALID_SIGNATURE + """) + + +class TLV(): + def __init__(self, endian, magic=TLV_INFO_MAGIC): + self.magic = magic + self.buf = bytearray() + self.endian = endian + + def __len__(self): + return TLV_INFO_SIZE + len(self.buf) + + def add(self, kind, payload): + """ + Add a TLV record. Kind should be a string found in TLV_VALUES above. + """ + e = STRUCT_ENDIAN_DICT[self.endian] + if isinstance(kind, int): + buf = struct.pack(e + 'BBH', kind, 0, len(payload)) + else: + buf = struct.pack(e + 'BBH', TLV_VALUES[kind], 0, len(payload)) + self.buf += buf + self.buf += payload + + def get(self): + if len(self.buf) == 0: + return bytes() + e = STRUCT_ENDIAN_DICT[self.endian] + header = struct.pack(e + 'HH', self.magic, len(self)) + return header + bytes(self.buf) + + +class Image(): + + def __init__(self, version=None, header_size=IMAGE_HEADER_SIZE, + pad_header=False, pad=False, confirm=False, align=1, + slot_size=0, max_sectors=DEFAULT_MAX_SECTORS, + overwrite_only=False, endian="little", load_addr=0, + erased_val=None, save_enctlv=False, security_counter=None): + self.version = version or versmod.decode_version("0") + self.header_size = header_size + self.pad_header = pad_header + self.pad = pad + self.confirm = confirm + self.align = align + self.slot_size = slot_size + self.max_sectors = max_sectors + self.overwrite_only = overwrite_only + self.endian = endian + self.base_addr = None + self.load_addr = 0 if load_addr is None else load_addr + self.erased_val = 0xff if erased_val is None else int(erased_val, 0) + self.payload = [] + self.enckey = None + self.save_enctlv = save_enctlv + self.enctlv_len = 0 + + if security_counter == 'auto': + # Security counter has not been explicitly provided, + # generate it from the version number + self.security_counter = ((self.version.major << 24) + + (self.version.minor << 16) + + self.version.revision) + else: + self.security_counter = security_counter + + def __repr__(self): + return "".format( + self.version, + self.header_size, + self.security_counter, + self.base_addr if self.base_addr is not None else "N/A", + self.load_addr, + self.align, + self.slot_size, + self.max_sectors, + self.overwrite_only, + self.endian, + self.__class__.__name__, + len(self.payload)) + + def load(self, path): + """Load an image from a given file""" + ext = os.path.splitext(path)[1][1:].lower() + try: + if ext == INTEL_HEX_EXT: + ih = IntelHex(path) + self.payload = ih.tobinarray() + self.base_addr = ih.minaddr() + else: + with open(path, 'rb') as f: + self.payload = f.read() + except FileNotFoundError: + raise click.UsageError("Input file not found") + + # Add the image header if needed. + if self.pad_header and self.header_size > 0: + if self.base_addr: + # Adjust base_addr for new header + self.base_addr -= self.header_size + self.payload = bytes([self.erased_val] * self.header_size) + \ + self.payload + + self.check_header() + + def save(self, path, hex_addr=None): + """Save an image from a given file""" + ext = os.path.splitext(path)[1][1:].lower() + if ext == INTEL_HEX_EXT: + # input was in binary format, but HEX needs to know the base addr + if self.base_addr is None and hex_addr is None: + raise click.UsageError("No address exists in input file " + "neither was it provided by user") + h = IntelHex() + if hex_addr is not None: + self.base_addr = hex_addr + h.frombytes(bytes=self.payload, offset=self.base_addr) + if self.pad: + trailer_size = self._trailer_size(self.align, self.max_sectors, + self.overwrite_only, + self.enckey, + self.save_enctlv, + self.enctlv_len) + trailer_addr = (self.base_addr + self.slot_size) - trailer_size + padding = bytearray([self.erased_val] * + (trailer_size - len(boot_magic))) + if self.confirm and not self.overwrite_only: + padding[-MAX_ALIGN] = 0x01 # image_ok = 0x01 + padding += boot_magic + h.puts(trailer_addr, bytes(padding)) + h.tofile(path, 'hex') + else: + if self.pad: + self.pad_to(self.slot_size) + with open(path, 'wb') as f: + f.write(self.payload) + + def check_header(self): + if self.header_size > 0 and not self.pad_header: + if any(v != 0 for v in self.payload[0:self.header_size]): + raise click.UsageError("Header padding was not requested and " + "image does not start with zeros") + + def check_trailer(self): + if self.slot_size > 0: + tsize = self._trailer_size(self.align, self.max_sectors, + self.overwrite_only, self.enckey, + self.save_enctlv, self.enctlv_len) + padding = self.slot_size - (len(self.payload) + tsize) + if padding < 0: + msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds " \ + "requested size 0x{:x}".format( + len(self.payload), tsize, self.slot_size) + raise click.UsageError(msg) + + def ecies_hkdf(self, enckey, plainkey): + if isinstance(enckey, ecdsa.ECDSA256P1Public): + newpk = ec.generate_private_key(ec.SECP256R1(), default_backend()) + shared = newpk.exchange(ec.ECDH(), enckey._get_public()) + else: + newpk = X25519PrivateKey.generate() + shared = newpk.exchange(enckey._get_public()) + derived_key = HKDF( + algorithm=hashes.SHA256(), length=48, salt=None, + info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) + encryptor = Cipher(algorithms.AES(derived_key[:16]), + modes.CTR(bytes([0] * 16)), + backend=default_backend()).encryptor() + cipherkey = encryptor.update(plainkey) + encryptor.finalize() + mac = hmac.HMAC(derived_key[16:], hashes.SHA256(), + backend=default_backend()) + mac.update(cipherkey) + ciphermac = mac.finalize() + if isinstance(enckey, ecdsa.ECDSA256P1Public): + pubk = newpk.public_key().public_bytes( + encoding=Encoding.X962, + format=PublicFormat.UncompressedPoint) + else: + pubk = newpk.public_key().public_bytes( + encoding=Encoding.Raw, + format=PublicFormat.Raw) + return cipherkey, ciphermac, pubk + + def create(self, key, public_key_format, enckey, dependencies=None, + sw_type=None, custom_tlvs=None): + self.enckey = enckey + + # Calculate the hash of the public key + if key is not None: + pub = key.get_public_bytes() + sha = hashlib.sha256() + sha.update(pub) + pubbytes = sha.digest() + else: + pubbytes = bytes(hashlib.sha256().digest_size) + + protected_tlv_size = 0 + + if self.security_counter is not None: + # Size of the security counter TLV: header ('HH') + payload ('I') + # = 4 + 4 = 8 Bytes + protected_tlv_size += TLV_SIZE + 4 + + if sw_type is not None: + if len(sw_type) > MAX_SW_TYPE_LENGTH: + msg = "'{}' is too long ({} characters) for sw_type. Its " \ + "maximum allowed length is 12 characters.".format( + sw_type, len(sw_type)) + raise click.UsageError(msg) + + image_version = (str(self.version.major) + '.' + + str(self.version.minor) + '.' + + str(self.version.revision)) + + # The image hash is computed over the image header, the image + # itself and the protected TLV area. However, the boot record TLV + # (which is part of the protected area) should contain this hash + # before it is even calculated. For this reason the script fills + # this field with zeros and the bootloader will insert the right + # value later. + digest = bytes(hashlib.sha256().digest_size) + + # Create CBOR encoded boot record + boot_record = create_sw_component_data(sw_type, image_version, + "SHA256", digest, + pubbytes) + + protected_tlv_size += TLV_SIZE + len(boot_record) + + if dependencies is not None: + # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') + # = 4 + 12 = 16 Bytes + dependencies_num = len(dependencies[DEP_IMAGES_KEY]) + protected_tlv_size += (dependencies_num * 16) + + if custom_tlvs is not None: + for value in custom_tlvs.values(): + protected_tlv_size += TLV_SIZE + len(value) + + if protected_tlv_size != 0: + # Add the size of the TLV info header + protected_tlv_size += TLV_INFO_SIZE + + # At this point the image is already on the payload + # + # This adds the padding if image is not aligned to the 16 Bytes + # in encrypted mode + if self.enckey is not None: + pad_len = len(self.payload) % 16 + if pad_len > 0: + self.payload += bytes(16 - pad_len) + + # This adds the header to the payload as well + self.add_header(enckey, protected_tlv_size) + + prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) + + # Protected TLVs must be added first, because they are also included + # in the hash calculation + protected_tlv_off = None + if protected_tlv_size != 0: + + e = STRUCT_ENDIAN_DICT[self.endian] + + if self.security_counter is not None: + payload = struct.pack(e + 'I', self.security_counter) + prot_tlv.add('SEC_CNT', payload) + + if sw_type is not None: + prot_tlv.add('BOOT_RECORD', boot_record) + + if dependencies is not None: + for i in range(dependencies_num): + payload = struct.pack( + e + 'B3x'+'BBHI', + int(dependencies[DEP_IMAGES_KEY][i]), + dependencies[DEP_VERSIONS_KEY][i].major, + dependencies[DEP_VERSIONS_KEY][i].minor, + dependencies[DEP_VERSIONS_KEY][i].revision, + dependencies[DEP_VERSIONS_KEY][i].build + ) + prot_tlv.add('DEPENDENCY', payload) + + if custom_tlvs is not None: + for tag, value in custom_tlvs.items(): + prot_tlv.add(tag, value) + + protected_tlv_off = len(self.payload) + self.payload += prot_tlv.get() + + tlv = TLV(self.endian) + + # Note that ecdsa wants to do the hashing itself, which means + # we get to hash it twice. + sha = hashlib.sha256() + sha.update(self.payload) + digest = sha.digest() + + tlv.add('SHA256', digest) + + if key is not None: + if public_key_format == 'hash': + tlv.add('KEYHASH', pubbytes) + else: + tlv.add('PUBKEY', pub) + + # `sign` expects the full image payload (sha256 done internally), + # while `sign_digest` expects only the digest of the payload + + if hasattr(key, 'sign'): + sig = key.sign(bytes(self.payload)) + else: + sig = key.sign_digest(digest) + tlv.add(key.sig_tlv(), sig) + + # At this point the image was hashed + signed, we can remove the + # protected TLVs from the payload (will be re-added later) + if protected_tlv_off is not None: + self.payload = self.payload[:protected_tlv_off] + + if enckey is not None: + plainkey = os.urandom(16) + + if isinstance(enckey, rsa.RSAPublic): + cipherkey = enckey._get_public().encrypt( + plainkey, padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None)) + self.enctlv_len = len(cipherkey) + tlv.add('ENCRSA2048', cipherkey) + elif isinstance(enckey, (ecdsa.ECDSA256P1Public, + x25519.X25519Public)): + cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) + enctlv = pubk + mac + cipherkey + self.enctlv_len = len(enctlv) + if isinstance(enckey, ecdsa.ECDSA256P1Public): + tlv.add('ENCEC256', enctlv) + else: + tlv.add('ENCX25519', enctlv) + + nonce = bytes([0] * 16) + cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), + backend=default_backend()) + encryptor = cipher.encryptor() + img = bytes(self.payload[self.header_size:]) + self.payload[self.header_size:] = \ + encryptor.update(img) + encryptor.finalize() + + self.payload += prot_tlv.get() + self.payload += tlv.get() + + self.check_trailer() + + def add_header(self, enckey, protected_tlv_size): + """Install the image header.""" + + flags = 0 + if enckey is not None: + flags |= IMAGE_F['ENCRYPTED'] + if self.load_addr != 0: + # Indicates that this image should be loaded into RAM + # instead of run directly from flash. + flags |= IMAGE_F['RAM_LOAD'] + + e = STRUCT_ENDIAN_DICT[self.endian] + fmt = (e + + # type ImageHdr struct { + 'I' + # Magic uint32 + 'I' + # LoadAddr uint32 + 'H' + # HdrSz uint16 + 'H' + # PTLVSz uint16 + 'I' + # ImgSz uint32 + 'I' + # Flags uint32 + 'BBHI' + # Vers ImageVersion + 'I' # Pad1 uint32 + ) # } + assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE + header = struct.pack(fmt, + IMAGE_MAGIC, + self.load_addr, + self.header_size, + protected_tlv_size, # TLV Info header + Protected TLVs + len(self.payload) - self.header_size, # ImageSz + flags, + self.version.major, + self.version.minor or 0, + self.version.revision or 0, + self.version.build or 0, + 0) # Pad1 + self.payload = bytearray(self.payload) + self.payload[:len(header)] = header + + def _trailer_size(self, write_size, max_sectors, overwrite_only, enckey, + save_enctlv, enctlv_len): + # NOTE: should already be checked by the argument parser + magic_size = 16 + if overwrite_only: + return MAX_ALIGN * 2 + magic_size + else: + if write_size not in set([1, 2, 4, 8]): + raise click.BadParameter("Invalid alignment: {}".format( + write_size)) + m = DEFAULT_MAX_SECTORS if max_sectors is None else max_sectors + trailer = m * 3 * write_size # status area + if enckey is not None: + if save_enctlv: + # TLV saved by the bootloader is aligned + keylen = (int((enctlv_len - 1) / MAX_ALIGN) + 1) * MAX_ALIGN + else: + keylen = 16 + trailer += keylen * 2 # encryption keys + trailer += MAX_ALIGN * 4 # image_ok/copy_done/swap_info/swap_size + trailer += magic_size + return trailer + + def pad_to(self, size): + """Pad the image to the given size, with the given flash alignment.""" + tsize = self._trailer_size(self.align, self.max_sectors, + self.overwrite_only, self.enckey, + self.save_enctlv, self.enctlv_len) + padding = size - (len(self.payload) + tsize) + pbytes = bytearray([self.erased_val] * padding) + pbytes += bytearray([self.erased_val] * (tsize - len(boot_magic))) + if self.confirm and not self.overwrite_only: + pbytes[-MAX_ALIGN] = 0x01 # image_ok = 0x01 + pbytes += boot_magic + self.payload += pbytes + + @staticmethod + def verify(imgfile, key): + with open(imgfile, "rb") as f: + b = f.read() + + magic, _, header_size, _, img_size = struct.unpack('IIHHI', b[:16]) + version = struct.unpack('BBHI', b[20:28]) + + if magic != IMAGE_MAGIC: + return VerifyResult.INVALID_MAGIC, None, None + + tlv_info = b[header_size+img_size:header_size+img_size+TLV_INFO_SIZE] + magic, tlv_tot = struct.unpack('HH', tlv_info) + if magic != TLV_INFO_MAGIC: + return VerifyResult.INVALID_TLV_INFO_MAGIC, None, None + + sha = hashlib.sha256() + sha.update(b[:header_size+img_size]) + digest = sha.digest() + + tlv_off = header_size + img_size + tlv_end = tlv_off + tlv_tot + tlv_off += TLV_INFO_SIZE # skip tlv info + while tlv_off < tlv_end: + tlv = b[tlv_off:tlv_off+TLV_SIZE] + tlv_type, _, tlv_len = struct.unpack('BBH', tlv) + if tlv_type == TLV_VALUES["SHA256"]: + off = tlv_off + TLV_SIZE + if digest == b[off:off+tlv_len]: + if key is None: + return VerifyResult.OK, version, digest + else: + return VerifyResult.INVALID_HASH, None, None + elif key is not None and tlv_type == TLV_VALUES[key.sig_tlv()]: + off = tlv_off + TLV_SIZE + tlv_sig = b[off:off+tlv_len] + payload = b[:header_size+img_size] + try: + if hasattr(key, 'verify'): + key.verify(tlv_sig, payload) + else: + key.verify_digest(tlv_sig, digest) + return VerifyResult.OK, version, digest + except InvalidSignature: + # continue to next TLV + pass + tlv_off += TLV_SIZE + tlv_len + return VerifyResult.INVALID_SIGNATURE, None, None diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/__init__.py b/tools/psa/tfm/bin_utils/imgtool/keys/__init__.py new file mode 100644 index 0000000000..dfd101dd66 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/__init__.py @@ -0,0 +1,96 @@ +# Copyright 2017 Linaro Limited +# +# 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. + +""" +Cryptographic key management for imgtool. +""" + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPrivateKey, RSAPublicKey) +from cryptography.hazmat.primitives.asymmetric.ec import ( + EllipticCurvePrivateKey, EllipticCurvePublicKey) +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, Ed25519PublicKey) +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey, X25519PublicKey) + +from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES +from .ecdsa import ECDSA256P1, ECDSA256P1Public, ECDSAUsageError +from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError +from .x25519 import X25519, X25519Public, X25519UsageError + + +class PasswordRequired(Exception): + """Raised to indicate that the key is password protected, but a + password was not specified.""" + pass + + +def load(path, passwd=None): + """Try loading a key from the given path. Returns None if the password wasn't specified.""" + with open(path, 'rb') as f: + raw_pem = f.read() + try: + pk = serialization.load_pem_private_key( + raw_pem, + password=passwd, + backend=default_backend()) + # Unfortunately, the crypto library raises unhelpful exceptions, + # so we have to look at the text. + except TypeError as e: + msg = str(e) + if "private key is encrypted" in msg: + return None + raise e + except ValueError: + # This seems to happen if the key is a public key, let's try + # loading it as a public key. + pk = serialization.load_pem_public_key( + raw_pem, + backend=default_backend()) + + if isinstance(pk, RSAPrivateKey): + if pk.key_size not in RSA_KEY_SIZES: + raise Exception("Unsupported RSA key size: " + pk.key_size) + return RSA(pk) + elif isinstance(pk, RSAPublicKey): + if pk.key_size not in RSA_KEY_SIZES: + raise Exception("Unsupported RSA key size: " + pk.key_size) + return RSAPublic(pk) + elif isinstance(pk, EllipticCurvePrivateKey): + if pk.curve.name != 'secp256r1': + raise Exception("Unsupported EC curve: " + pk.curve.name) + if pk.key_size != 256: + raise Exception("Unsupported EC size: " + pk.key_size) + return ECDSA256P1(pk) + elif isinstance(pk, EllipticCurvePublicKey): + if pk.curve.name != 'secp256r1': + raise Exception("Unsupported EC curve: " + pk.curve.name) + if pk.key_size != 256: + raise Exception("Unsupported EC size: " + pk.key_size) + return ECDSA256P1Public(pk) + elif isinstance(pk, Ed25519PrivateKey): + return Ed25519(pk) + elif isinstance(pk, Ed25519PublicKey): + return Ed25519Public(pk) + elif isinstance(pk, X25519PrivateKey): + return X25519(pk) + elif isinstance(pk, X25519PublicKey): + return X25519Public(pk) + else: + raise Exception("Unknown key type: " + str(type(pk))) diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa.py b/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa.py new file mode 100644 index 0000000000..56222d8f27 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa.py @@ -0,0 +1,174 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +ECDSA key management +""" + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.hashes import SHA256 + +from .general import KeyClass + +class ECDSAUsageError(Exception): + pass + +class ECDSA256P1Public(KeyClass): + def __init__(self, key): + self.key = key + + def shortname(self): + return "ecdsa" + + def _unsupported(self, name): + raise ECDSAUsageError("Operation {} requires private key".format(name)) + + def _get_public(self): + return self.key + + def get_public_bytes(self): + # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format + return self._get_public().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + + def get_private_bytes(self, minimal): + self._unsupported('get_private_bytes') + + def export_private(self, path, passwd=None): + self._unsupported('export_private') + + def export_public(self, path): + """Write the public key to the given file.""" + pem = self._get_public().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + with open(path, 'wb') as f: + f.write(pem) + + def sig_type(self): + return "ECDSA256_SHA256" + + def sig_tlv(self): + return "ECDSA256" + + def sig_len(self): + # Early versions of MCUboot (< v1.5.0) required ECDSA + # signatures to be padded to 72 bytes. Because the DER + # encoding is done with signed integers, the size of the + # signature will vary depending on whether the high bit is set + # in each value. This padding was done in a + # not-easily-reversible way (by just adding zeros). + # + # The signing code no longer requires this padding, and newer + # versions of MCUboot don't require it. But, continue to + # return the total length so that the padding can be done if + # requested. + return 72 + + def verify(self, signature, payload): + # strip possible paddings added during sign + signature = signature[:signature[1] + 2] + k = self.key + if isinstance(self.key, ec.EllipticCurvePrivateKey): + k = self.key.public_key() + return k.verify(signature=signature, data=payload, + signature_algorithm=ec.ECDSA(SHA256())) + + +class ECDSA256P1(ECDSA256P1Public): + """ + Wrapper around an ECDSA private key. + """ + + def __init__(self, key): + """key should be an instance of EllipticCurvePrivateKey""" + self.key = key + self.pad_sig = False + + @staticmethod + def generate(): + pk = ec.generate_private_key( + ec.SECP256R1(), + backend=default_backend()) + return ECDSA256P1(pk) + + def _get_public(self): + return self.key.public_key() + + def _build_minimal_ecdsa_privkey(self, der): + ''' + Builds a new DER that only includes the EC private key, removing the + public key that is added as an "optional" BITSTRING. + ''' + offset_PUB = 68 + EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" + if der[offset_PUB] != 0xa1: + raise ECDSAUsageError(EXCEPTION_TEXT) + len_PUB = der[offset_PUB + 1] + b = bytearray(der[:-offset_PUB]) + offset_SEQ = 29 + if b[offset_SEQ] != 0x30: + raise ECDSAUsageError(EXCEPTION_TEXT) + b[offset_SEQ + 1] -= len_PUB + offset_OCT_STR = 27 + if b[offset_OCT_STR] != 0x04: + raise ECDSAUsageError(EXCEPTION_TEXT) + b[offset_OCT_STR + 1] -= len_PUB + if b[0] != 0x30 or b[1] != 0x81: + raise ECDSAUsageError(EXCEPTION_TEXT) + b[2] -= len_PUB + return b + + def get_private_bytes(self, minimal): + priv = self.key.private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption()) + if minimal: + priv = self._build_minimal_ecdsa_privkey(priv) + return priv + + def export_private(self, path, passwd=None): + """Write the private key to the given file, protecting it with the optional password.""" + if passwd is None: + enc = serialization.NoEncryption() + else: + enc = serialization.BestAvailableEncryption(passwd) + pem = self.key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=enc) + with open(path, 'wb') as f: + f.write(pem) + + def raw_sign(self, payload): + """Return the actual signature""" + return self.key.sign( + data=payload, + signature_algorithm=ec.ECDSA(SHA256())) + + def sign(self, payload): + sig = self.raw_sign(payload) + if self.pad_sig: + # To make fixed length, pad with one or two zeros. + sig += b'\000' * (self.sig_len() - len(sig)) + return sig + else: + return sig diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa_test.py b/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa_test.py new file mode 100644 index 0000000000..021f04073f --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/ecdsa_test.py @@ -0,0 +1,116 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +Tests for ECDSA keys +""" + +import io +import os.path +import sys +import tempfile +import unittest + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.hashes import SHA256 + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) + +from imgtool.keys import load, ECDSA256P1, ECDSAUsageError + +class EcKeyGeneration(unittest.TestCase): + + def setUp(self): + self.test_dir = tempfile.TemporaryDirectory() + + def tname(self, base): + return os.path.join(self.test_dir.name, base) + + def tearDown(self): + self.test_dir.cleanup() + + def test_keygen(self): + name1 = self.tname("keygen.pem") + k = ECDSA256P1.generate() + k.export_private(name1, b'secret') + + self.assertIsNone(load(name1)) + + k2 = load(name1, b'secret') + + pubname = self.tname('keygen-pub.pem') + k2.export_public(pubname) + pk2 = load(pubname) + + # We should be able to export the public key from the loaded + # public key, but not the private key. + pk2.export_public(self.tname('keygen-pub2.pem')) + self.assertRaises(ECDSAUsageError, + pk2.export_private, self.tname('keygen-priv2.pem')) + + def test_emit(self): + """Basic sanity check on the code emitters.""" + k = ECDSA256P1.generate() + + ccode = io.StringIO() + k.emit_c_public(ccode) + self.assertIn("ecdsa_pub_key", ccode.getvalue()) + self.assertIn("ecdsa_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k.emit_rust_public(rustcode) + self.assertIn("ECDSA_PUB_KEY", rustcode.getvalue()) + + def test_emit_pub(self): + """Basic sanity check on the code emitters.""" + pubname = self.tname("public.pem") + k = ECDSA256P1.generate() + k.export_public(pubname) + + k2 = load(pubname) + + ccode = io.StringIO() + k2.emit_c_public(ccode) + self.assertIn("ecdsa_pub_key", ccode.getvalue()) + self.assertIn("ecdsa_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k2.emit_rust_public(rustcode) + self.assertIn("ECDSA_PUB_KEY", rustcode.getvalue()) + + def test_sig(self): + k = ECDSA256P1.generate() + buf = b'This is the message' + sig = k.raw_sign(buf) + + # The code doesn't have any verification, so verify this + # manually. + k.key.public_key().verify( + signature=sig, + data=buf, + signature_algorithm=ec.ECDSA(SHA256())) + + # Modify the message to make sure the signature fails. + self.assertRaises(InvalidSignature, + k.key.public_key().verify, + signature=sig, + data=b'This is thE message', + signature_algorithm=ec.ECDSA(SHA256())) + +if __name__ == '__main__': + unittest.main() diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/ed25519.py b/tools/psa/tfm/bin_utils/imgtool/keys/ed25519.py new file mode 100644 index 0000000000..661b8857a5 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/ed25519.py @@ -0,0 +1,122 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +ED25519 key management +""" + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 + +from .general import KeyClass + + +class Ed25519UsageError(Exception): + pass + + +class Ed25519Public(KeyClass): + def __init__(self, key): + self.key = key + + def shortname(self): + return "ed25519" + + def _unsupported(self, name): + raise Ed25519UsageError("Operation {} requires private key".format(name)) + + def _get_public(self): + return self.key + + def get_public_bytes(self): + # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format + return self._get_public().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + + def get_private_bytes(self, minimal): + self._unsupported('get_private_bytes') + + def export_private(self, path, passwd=None): + self._unsupported('export_private') + + def export_public(self, path): + """Write the public key to the given file.""" + pem = self._get_public().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + with open(path, 'wb') as f: + f.write(pem) + + def sig_type(self): + return "ED25519" + + def sig_tlv(self): + return "ED25519" + + def sig_len(self): + return 64 + + +class Ed25519(Ed25519Public): + """ + Wrapper around an ED25519 private key. + """ + + def __init__(self, key): + """key should be an instance of EllipticCurvePrivateKey""" + self.key = key + + @staticmethod + def generate(): + pk = ed25519.Ed25519PrivateKey.generate() + return Ed25519(pk) + + def _get_public(self): + return self.key.public_key() + + def get_private_bytes(self, minimal): + raise Ed25519UsageError("Operation not supported with {} keys".format( + self.shortname())) + + def export_private(self, path, passwd=None): + """ + Write the private key to the given file, protecting it with the + optional password. + """ + if passwd is None: + enc = serialization.NoEncryption() + else: + enc = serialization.BestAvailableEncryption(passwd) + pem = self.key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=enc) + with open(path, 'wb') as f: + f.write(pem) + + def sign_digest(self, digest): + """Return the actual signature""" + return self.key.sign(data=digest) + + def verify_digest(self, signature, digest): + """Verify that signature is valid for given digest""" + k = self.key + if isinstance(self.key, ed25519.Ed25519PrivateKey): + k = self.key.public_key() + return k.verify(signature=signature, data=digest) diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/ed25519_test.py b/tools/psa/tfm/bin_utils/imgtool/keys/ed25519_test.py new file mode 100644 index 0000000000..d49f34aa3d --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/ed25519_test.py @@ -0,0 +1,120 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +Tests for ECDSA keys +""" + +import hashlib +import io +import os.path +import sys +import tempfile +import unittest + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric import ed25519 + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) + +from imgtool.keys import load, Ed25519, Ed25519UsageError + + +class Ed25519KeyGeneration(unittest.TestCase): + + def setUp(self): + self.test_dir = tempfile.TemporaryDirectory() + + def tname(self, base): + return os.path.join(self.test_dir.name, base) + + def tearDown(self): + self.test_dir.cleanup() + + def test_keygen(self): + name1 = self.tname("keygen.pem") + k = Ed25519.generate() + k.export_private(name1, b'secret') + + self.assertIsNone(load(name1)) + + k2 = load(name1, b'secret') + + pubname = self.tname('keygen-pub.pem') + k2.export_public(pubname) + pk2 = load(pubname) + + # We should be able to export the public key from the loaded + # public key, but not the private key. + pk2.export_public(self.tname('keygen-pub2.pem')) + self.assertRaises(Ed25519UsageError, + pk2.export_private, self.tname('keygen-priv2.pem')) + + def test_emit(self): + """Basic sanity check on the code emitters.""" + k = Ed25519.generate() + + ccode = io.StringIO() + k.emit_c_public(ccode) + self.assertIn("ed25519_pub_key", ccode.getvalue()) + self.assertIn("ed25519_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k.emit_rust_public(rustcode) + self.assertIn("ED25519_PUB_KEY", rustcode.getvalue()) + + def test_emit_pub(self): + """Basic sanity check on the code emitters.""" + pubname = self.tname("public.pem") + k = Ed25519.generate() + k.export_public(pubname) + + k2 = load(pubname) + + ccode = io.StringIO() + k2.emit_c_public(ccode) + self.assertIn("ed25519_pub_key", ccode.getvalue()) + self.assertIn("ed25519_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k2.emit_rust_public(rustcode) + self.assertIn("ED25519_PUB_KEY", rustcode.getvalue()) + + def test_sig(self): + k = Ed25519.generate() + buf = b'This is the message' + sha = hashlib.sha256() + sha.update(buf) + digest = sha.digest() + sig = k.sign_digest(digest) + + # The code doesn't have any verification, so verify this + # manually. + k.key.public_key().verify(signature=sig, data=digest) + + # Modify the message to make sure the signature fails. + sha = hashlib.sha256() + sha.update(b'This is thE message') + new_digest = sha.digest() + self.assertRaises(InvalidSignature, + k.key.public_key().verify, + signature=sig, + data=new_digest) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/general.py b/tools/psa/tfm/bin_utils/imgtool/keys/general.py new file mode 100644 index 0000000000..442b1eab8b --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/general.py @@ -0,0 +1,62 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +"""General key class.""" + +import sys + +AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */" + +class KeyClass(object): + def _emit(self, header, trailer, encoded_bytes, indent, file=sys.stdout, len_format=None): + print(AUTOGEN_MESSAGE, file=file) + print(header, end='', file=file) + for count, b in enumerate(encoded_bytes): + if count % 8 == 0: + print("\n" + indent, end='', file=file) + else: + print(" ", end='', file=file) + print("0x{:02x},".format(b), end='', file=file) + print("\n" + trailer, file=file) + if len_format is not None: + print(len_format.format(len(encoded_bytes)), file=file) + + def emit_c_public(self, file=sys.stdout): + self._emit( + header="const unsigned char {}_pub_key[] = {{".format(self.shortname()), + trailer="};", + encoded_bytes=self.get_public_bytes(), + indent=" ", + len_format="const unsigned int {}_pub_key_len = {{}};".format(self.shortname()), + file=file) + + def emit_rust_public(self, file=sys.stdout): + self._emit( + header="static {}_PUB_KEY: &'static [u8] = &[".format(self.shortname().upper()), + trailer="];", + encoded_bytes=self.get_public_bytes(), + indent=" ", + file=file) + + def emit_private(self, minimal, file=sys.stdout): + self._emit( + header="const unsigned char enc_priv_key[] = {", + trailer="};", + encoded_bytes=self.get_private_bytes(minimal), + indent=" ", + len_format="const unsigned int enc_priv_key_len = {};", + file=file) diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/rsa.py b/tools/psa/tfm/bin_utils/imgtool/keys/rsa.py new file mode 100644 index 0000000000..a7230e30eb --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/rsa.py @@ -0,0 +1,180 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +RSA Key management +""" + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.padding import PSS, MGF1 +from cryptography.hazmat.primitives.hashes import SHA256 + +from .general import KeyClass + + +# Sizes that bootutil will recognize +RSA_KEY_SIZES = [2048, 3072] + + +class RSAUsageError(Exception): + pass + + +class RSAPublic(KeyClass): + """The public key can only do a few operations""" + def __init__(self, key): + self.key = key + + def key_size(self): + return self.key.key_size + + def shortname(self): + return "rsa" + + def _unsupported(self, name): + raise RSAUsageError("Operation {} requires private key".format(name)) + + def _get_public(self): + return self.key + + def get_public_bytes(self): + # The key embedded into MCUboot is in PKCS1 format. + return self._get_public().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.PKCS1) + + def get_private_bytes(self, minimal): + self._unsupported('get_private_bytes') + + def export_private(self, path, passwd=None): + self._unsupported('export_private') + + def export_public(self, path): + """Write the public key to the given file.""" + pem = self._get_public().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + with open(path, 'wb') as f: + f.write(pem) + + def sig_type(self): + return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size()) + + def sig_tlv(self): + return"RSA{}".format(self.key_size()) + + def sig_len(self): + return self.key_size() / 8 + + def verify(self, signature, payload): + k = self.key + if isinstance(self.key, rsa.RSAPrivateKey): + k = self.key.public_key() + return k.verify(signature=signature, data=payload, + padding=PSS(mgf=MGF1(SHA256()), salt_length=32), + algorithm=SHA256()) + + +class RSA(RSAPublic): + """ + Wrapper around an RSA key, with imgtool support. + """ + + def __init__(self, key): + """The key should be a private key from cryptography""" + self.key = key + + @staticmethod + def generate(key_size=2048): + if key_size not in RSA_KEY_SIZES: + raise RSAUsageError("Key size {} is not supported by MCUboot" + .format(key_size)) + pk = rsa.generate_private_key( + public_exponent=65537, + key_size=key_size, + backend=default_backend()) + return RSA(pk) + + def _get_public(self): + return self.key.public_key() + + def _build_minimal_rsa_privkey(self, der): + ''' + Builds a new DER that only includes N/E/D/P/Q RSA parameters; + standard DER private bytes provided by OpenSSL also includes + CRT params (DP/DQ/QP) which can be removed. + ''' + OFFSET_N = 7 # N is always located at this offset + b = bytearray(der) + off = OFFSET_N + if b[off + 1] != 0x82: + raise RSAUsageError("Error parsing N while minimizing") + len_N = (b[off + 2] << 8) + b[off + 3] + 4 + off += len_N + if b[off + 1] != 0x03: + raise RSAUsageError("Error parsing E while minimizing") + len_E = b[off + 2] + 4 + off += len_E + if b[off + 1] != 0x82: + raise RSAUsageError("Error parsing D while minimizing") + len_D = (b[off + 2] << 8) + b[off + 3] + 4 + off += len_D + if b[off + 1] != 0x81: + raise RSAUsageError("Error parsing P while minimizing") + len_P = b[off + 2] + 3 + off += len_P + if b[off + 1] != 0x81: + raise RSAUsageError("Error parsing Q while minimizing") + len_Q = b[off + 2] + 3 + off += len_Q + # adjust DER size for removed elements + b[2] = (off - 4) >> 8 + b[3] = (off - 4) & 0xff + return b[:off] + + def get_private_bytes(self, minimal): + priv = self.key.private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption()) + if minimal: + priv = self._build_minimal_rsa_privkey(priv) + return priv + + def export_private(self, path, passwd=None): + """Write the private key to the given file, protecting it with the + optional password.""" + if passwd is None: + enc = serialization.NoEncryption() + else: + enc = serialization.BestAvailableEncryption(passwd) + pem = self.key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=enc) + with open(path, 'wb') as f: + f.write(pem) + + def sign(self, payload): + # The verification code only allows the salt length to be the + # same as the hash length, 32. + return self.key.sign( + data=payload, + padding=PSS(mgf=MGF1(SHA256()), salt_length=32), + algorithm=SHA256()) diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/rsa_test.py b/tools/psa/tfm/bin_utils/imgtool/keys/rsa_test.py new file mode 100644 index 0000000000..722a444603 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/rsa_test.py @@ -0,0 +1,132 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +Tests for RSA keys +""" + +import io +import os +import sys +import tempfile +import unittest + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric.padding import PSS, MGF1 +from cryptography.hazmat.primitives.hashes import SHA256 + +# Setup sys path so 'imgtool' is in it. +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), + '../..'))) + +from imgtool.keys import load, RSA, RSAUsageError +from imgtool.keys.rsa import RSA_KEY_SIZES + + +class KeyGeneration(unittest.TestCase): + + def setUp(self): + self.test_dir = tempfile.TemporaryDirectory() + + def tname(self, base): + return os.path.join(self.test_dir.name, base) + + def tearDown(self): + self.test_dir.cleanup() + + def test_keygen(self): + # Try generating a RSA key with non-supported size + with self.assertRaises(RSAUsageError): + RSA.generate(key_size=1024) + + for key_size in RSA_KEY_SIZES: + name1 = self.tname("keygen.pem") + k = RSA.generate(key_size=key_size) + k.export_private(name1, b'secret') + + # Try loading the key without a password. + self.assertIsNone(load(name1)) + + k2 = load(name1, b'secret') + + pubname = self.tname('keygen-pub.pem') + k2.export_public(pubname) + pk2 = load(pubname) + + # We should be able to export the public key from the loaded + # public key, but not the private key. + pk2.export_public(self.tname('keygen-pub2.pem')) + self.assertRaises(RSAUsageError, pk2.export_private, + self.tname('keygen-priv2.pem')) + + def test_emit(self): + """Basic sanity check on the code emitters.""" + for key_size in RSA_KEY_SIZES: + k = RSA.generate(key_size=key_size) + + ccode = io.StringIO() + k.emit_c_public(ccode) + self.assertIn("rsa_pub_key", ccode.getvalue()) + self.assertIn("rsa_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k.emit_rust_public(rustcode) + self.assertIn("RSA_PUB_KEY", rustcode.getvalue()) + + def test_emit_pub(self): + """Basic sanity check on the code emitters, from public key.""" + pubname = self.tname("public.pem") + for key_size in RSA_KEY_SIZES: + k = RSA.generate(key_size=key_size) + k.export_public(pubname) + + k2 = load(pubname) + + ccode = io.StringIO() + k2.emit_c_public(ccode) + self.assertIn("rsa_pub_key", ccode.getvalue()) + self.assertIn("rsa_pub_key_len", ccode.getvalue()) + + rustcode = io.StringIO() + k2.emit_rust_public(rustcode) + self.assertIn("RSA_PUB_KEY", rustcode.getvalue()) + + def test_sig(self): + for key_size in RSA_KEY_SIZES: + k = RSA.generate(key_size=key_size) + buf = b'This is the message' + sig = k.sign(buf) + + # The code doesn't have any verification, so verify this + # manually. + k.key.public_key().verify( + signature=sig, + data=buf, + padding=PSS(mgf=MGF1(SHA256()), salt_length=32), + algorithm=SHA256()) + + # Modify the message to make sure the signature fails. + self.assertRaises(InvalidSignature, + k.key.public_key().verify, + signature=sig, + data=b'This is thE message', + padding=PSS(mgf=MGF1(SHA256()), salt_length=32), + algorithm=SHA256()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/psa/tfm/bin_utils/imgtool/keys/x25519.py b/tools/psa/tfm/bin_utils/imgtool/keys/x25519.py new file mode 100644 index 0000000000..32751163d3 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/keys/x25519.py @@ -0,0 +1,124 @@ +# Original code taken from mcuboot project at: +# https://github.com/mcu-tools/mcuboot +# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f +# +# 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. +""" +X25519 key management +""" + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import x25519 + +from .general import KeyClass + + +class X25519UsageError(Exception): + pass + + +class X25519Public(KeyClass): + def __init__(self, key): + self.key = key + + def shortname(self): + return "x25519" + + def _unsupported(self, name): + raise X25519UsageError("Operation {} requires private key".format(name)) + + def _get_public(self): + return self.key + + def get_public_bytes(self): + # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format + return self._get_public().public_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + + def get_private_bytes(self, minimal): + self._unsupported('get_private_bytes') + + def export_private(self, path, passwd=None): + self._unsupported('export_private') + + def export_public(self, path): + """Write the public key to the given file.""" + pem = self._get_public().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo) + with open(path, 'wb') as f: + f.write(pem) + + def sig_type(self): + return "X25519" + + def sig_tlv(self): + return "X25519" + + def sig_len(self): + return 32 + + +class X25519(X25519Public): + """ + Wrapper around an X25519 private key. + """ + + def __init__(self, key): + """key should be an instance of EllipticCurvePrivateKey""" + self.key = key + + @staticmethod + def generate(): + pk = x25519.X25519PrivateKey.generate() + return X25519(pk) + + def _get_public(self): + return self.key.public_key() + + def get_private_bytes(self, minimal): + return self.key.private_bytes( + encoding=serialization.Encoding.DER, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption()) + + def export_private(self, path, passwd=None): + """ + Write the private key to the given file, protecting it with the + optional password. + """ + if passwd is None: + enc = serialization.NoEncryption() + else: + enc = serialization.BestAvailableEncryption(passwd) + pem = self.key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=enc) + with open(path, 'wb') as f: + f.write(pem) + + def sign_digest(self, digest): + """Return the actual signature""" + return self.key.sign(data=digest) + + def verify_digest(self, signature, digest): + """Verify that signature is valid for given digest""" + k = self.key + if isinstance(self.key, x25519.X25519PrivateKey): + k = self.key.public_key() + return k.verify(signature=signature, data=digest) diff --git a/tools/psa/tfm/bin_utils/imgtool/main.py b/tools/psa/tfm/bin_utils/imgtool/main.py new file mode 100755 index 0000000000..46be8a8271 --- /dev/null +++ b/tools/psa/tfm/bin_utils/imgtool/main.py @@ -0,0 +1,388 @@ +#! /usr/bin/env python3 +# +# Copyright 2017-2020 Linaro Limited +# Copyright 2019-2020 Arm Limited +# +# 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. + +import re +import click +import getpass +import imgtool.keys as keys +import sys +from imgtool import image, imgtool_version +from imgtool.version import decode_version +from .keys import ( + RSAUsageError, ECDSAUsageError, Ed25519UsageError, X25519UsageError) + +MIN_PYTHON_VERSION = (3, 6) +if sys.version_info < MIN_PYTHON_VERSION: + sys.exit("Python %s.%s or newer is required by imgtool." + % MIN_PYTHON_VERSION) + + +def gen_rsa2048(keyfile, passwd): + keys.RSA.generate().export_private(path=keyfile, passwd=passwd) + + +def gen_rsa3072(keyfile, passwd): + keys.RSA.generate(key_size=3072).export_private(path=keyfile, + passwd=passwd) + + +def gen_ecdsa_p256(keyfile, passwd): + keys.ECDSA256P1.generate().export_private(keyfile, passwd=passwd) + + +def gen_ecdsa_p224(keyfile, passwd): + print("TODO: p-224 not yet implemented") + + +def gen_ed25519(keyfile, passwd): + keys.Ed25519.generate().export_private(path=keyfile, passwd=passwd) + + +def gen_x25519(keyfile, passwd): + keys.X25519.generate().export_private(path=keyfile, passwd=passwd) + + +valid_langs = ['c', 'rust'] +keygens = { + 'rsa-2048': gen_rsa2048, + 'rsa-3072': gen_rsa3072, + 'ecdsa-p256': gen_ecdsa_p256, + 'ecdsa-p224': gen_ecdsa_p224, + 'ed25519': gen_ed25519, + 'x25519': gen_x25519, +} + + +def load_key(keyfile): + # TODO: better handling of invalid pass-phrase + key = keys.load(keyfile) + if key is not None: + return key + passwd = getpass.getpass("Enter key passphrase: ").encode('utf-8') + return keys.load(keyfile, passwd) + + +def get_password(): + while True: + passwd = getpass.getpass("Enter key passphrase: ") + passwd2 = getpass.getpass("Reenter passphrase: ") + if passwd == passwd2: + break + print("Passwords do not match, try again") + + # Password must be bytes, always use UTF-8 for consistent + # encoding. + return passwd.encode('utf-8') + + +@click.option('-p', '--password', is_flag=True, + help='Prompt for password to protect key') +@click.option('-t', '--type', metavar='type', required=True, + type=click.Choice(keygens.keys()), prompt=True, + help='{}'.format('One of: {}'.format(', '.join(keygens.keys())))) +@click.option('-k', '--key', metavar='filename', required=True) +@click.command(help='Generate pub/private keypair') +def keygen(type, key, password): + password = get_password() if password else None + keygens[type](key, password) + + +@click.option('-l', '--lang', metavar='lang', default=valid_langs[0], + type=click.Choice(valid_langs)) +@click.option('-k', '--key', metavar='filename', required=True) +@click.command(help='Dump public key from keypair') +def getpub(key, lang): + key = load_key(key) + if key is None: + print("Invalid passphrase") + elif lang == 'c': + key.emit_c_public() + elif lang == 'rust': + key.emit_rust_public() + else: + raise ValueError("BUG: should never get here!") + + +@click.option('--minimal', default=False, is_flag=True, + help='Reduce the size of the dumped private key to include only ' + 'the minimum amount of data required to decrypt. This ' + 'might require changes to the build config. Check the docs!' + ) +@click.option('-k', '--key', metavar='filename', required=True) +@click.command(help='Dump private key from keypair') +def getpriv(key, minimal): + key = load_key(key) + if key is None: + print("Invalid passphrase") + try: + key.emit_private(minimal) + except (RSAUsageError, ECDSAUsageError, Ed25519UsageError, + X25519UsageError) as e: + raise click.UsageError(e) + + +@click.argument('imgfile') +@click.option('-k', '--key', metavar='filename') +@click.command(help="Check that signed image can be verified by given key") +def verify(key, imgfile): + key = load_key(key) if key else None + ret, version, digest = image.Image.verify(imgfile, key) + if ret == image.VerifyResult.OK: + print("Image was correctly validated") + print("Image version: {}.{}.{}+{}".format(*version)) + print("Image digest: {}".format(digest.hex())) + return + elif ret == image.VerifyResult.INVALID_MAGIC: + print("Invalid image magic; is this an MCUboot image?") + elif ret == image.VerifyResult.INVALID_TLV_INFO_MAGIC: + print("Invalid TLV info magic; is this an MCUboot image?") + elif ret == image.VerifyResult.INVALID_HASH: + print("Image has an invalid sha256 digest") + elif ret == image.VerifyResult.INVALID_SIGNATURE: + print("No signature found for the given key") + else: + print("Unknown return code: {}".format(ret)) + sys.exit(1) + + +def validate_version(ctx, param, value): + try: + decode_version(value) + return value + except ValueError as e: + raise click.BadParameter("{}".format(e)) + + +def validate_security_counter(ctx, param, value): + if value is not None: + if value.lower() == 'auto': + return 'auto' + else: + try: + return int(value, 0) + except ValueError: + raise click.BadParameter( + "{} is not a valid integer. Please use code literals " + "prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary." + .format(value)) + + +def validate_header_size(ctx, param, value): + min_hdr_size = image.IMAGE_HEADER_SIZE + if value < min_hdr_size: + raise click.BadParameter( + "Minimum value for -H/--header-size is {}".format(min_hdr_size)) + return value + + +def get_dependencies(ctx, param, value): + if value is not None: + versions = [] + images = re.findall(r"\((\d+)", value) + if len(images) == 0: + raise click.BadParameter( + "Image dependency format is invalid: {}".format(value)) + raw_versions = re.findall(r",\s*([0-9.+]+)\)", value) + if len(images) != len(raw_versions): + raise click.BadParameter( + '''There's a mismatch between the number of dependency images + and versions in: {}'''.format(value)) + for raw_version in raw_versions: + try: + versions.append(decode_version(raw_version)) + except ValueError as e: + raise click.BadParameter("{}".format(e)) + dependencies = dict() + dependencies[image.DEP_IMAGES_KEY] = images + dependencies[image.DEP_VERSIONS_KEY] = versions + return dependencies + + +class BasedIntParamType(click.ParamType): + name = 'integer' + + def convert(self, value, param, ctx): + try: + return int(value, 0) + except ValueError: + self.fail('%s is not a valid integer. Please use code literals ' + 'prefixed with 0b/0B, 0o/0O, or 0x/0X as necessary.' + % value, param, ctx) + + +@click.argument('outfile') +@click.argument('infile') +@click.option('--custom-tlv', required=False, nargs=2, default=[], + multiple=True, metavar='[tag] [value]', + help='Custom TLV that will be placed into protected area. ' + 'Add "0x" prefix if the value should be interpreted as an ' + 'integer, otherwise it will be interpreted as a string. ' + 'Specify the option multiple times to add multiple TLVs.') +@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']), + required=False, + help='The value that is read back from erased flash.') +@click.option('-x', '--hex-addr', type=BasedIntParamType(), required=False, + help='Adjust address in hex output file.') +@click.option('-L', '--load-addr', type=BasedIntParamType(), required=False, + help='Load address for image when it should run from RAM.') +@click.option('--save-enctlv', default=False, is_flag=True, + help='When upgrading, save encrypted key TLVs instead of plain ' + 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option ' + 'was set.') +@click.option('-E', '--encrypt', metavar='filename', + help='Encrypt image using the provided public key. ' + '(Not supported in direct-xip or ram-load mode.)') +@click.option('-e', '--endian', type=click.Choice(['little', 'big']), + default='little', help="Select little or big endian") +@click.option('--overwrite-only', default=False, is_flag=True, + help='Use overwrite-only instead of swap upgrades') +@click.option('--boot-record', metavar='sw_type', help='Create CBOR encoded ' + 'boot record TLV. The sw_type represents the role of the ' + 'software component (e.g. CoFM for coprocessor firmware). ' + '[max. 12 characters]') +@click.option('-M', '--max-sectors', type=int, + help='When padding allow for this amount of sectors (defaults ' + 'to 128)') +@click.option('--confirm', default=False, is_flag=True, + help='When padding the image, mark it as confirmed (implies ' + '--pad)') +@click.option('--pad', default=False, is_flag=True, + help='Pad image to --slot-size bytes, adding trailer magic') +@click.option('-S', '--slot-size', type=BasedIntParamType(), required=True, + help='Size of the slot. If the slots have different sizes, use ' + 'the size of the secondary slot.') +@click.option('--pad-header', default=False, is_flag=True, + help='Add --header-size zeroed bytes at the beginning of the ' + 'image') +@click.option('-H', '--header-size', callback=validate_header_size, + type=BasedIntParamType(), required=True) +@click.option('--pad-sig', default=False, is_flag=True, + help='Add 0-2 bytes of padding to ECDSA signature ' + '(for mcuboot <1.5)') +@click.option('-d', '--dependencies', callback=get_dependencies, + required=False, help='''Add dependence on another image, format: + "(,), ... "''') +@click.option('-s', '--security-counter', callback=validate_security_counter, + help='Specify the value of security counter. Use the `auto` ' + 'keyword to automatically generate it from the image version.') +@click.option('-v', '--version', callback=validate_version, required=True) +@click.option('--align', type=click.Choice(['1', '2', '4', '8']), + required=True) +@click.option('--public-key-format', type=click.Choice(['hash', 'full']), + default='hash', help='In what format to add the public key to ' + 'the image manifest: full key or hash of the key.') +@click.option('-k', '--key', metavar='filename') +@click.command(help='''Create a signed or unsigned image\n + INFILE and OUTFILE are parsed as Intel HEX if the params have + .hex extension, otherwise binary format is used''') +def sign(key, public_key_format, align, version, pad_sig, header_size, + pad_header, slot_size, pad, confirm, max_sectors, overwrite_only, + endian, encrypt, infile, outfile, dependencies, load_addr, hex_addr, + erased_val, save_enctlv, security_counter, boot_record, custom_tlv): + + if confirm: + # Confirmed but non-padded images don't make much sense, because + # otherwise there's no trailer area for writing the confirmed status. + pad = True + img = image.Image(version=decode_version(version), header_size=header_size, + pad_header=pad_header, pad=pad, confirm=confirm, + align=int(align), slot_size=slot_size, + max_sectors=max_sectors, overwrite_only=overwrite_only, + endian=endian, load_addr=load_addr, erased_val=erased_val, + save_enctlv=save_enctlv, + security_counter=security_counter) + img.load(infile) + key = load_key(key) if key else None + enckey = load_key(encrypt) if encrypt else None + if enckey and key: + if ((isinstance(key, keys.ECDSA256P1) and + not isinstance(enckey, keys.ECDSA256P1Public)) + or (isinstance(key, keys.RSA) and + not isinstance(enckey, keys.RSAPublic))): + # FIXME + raise click.UsageError("Signing and encryption must use the same " + "type of key") + + if pad_sig and hasattr(key, 'pad_sig'): + key.pad_sig = True + + # Get list of custom protected TLVs from the command-line + custom_tlvs = {} + for tlv in custom_tlv: + tag = int(tlv[0], 0) + if tag in custom_tlvs: + raise click.UsageError('Custom TLV %s already exists.' % hex(tag)) + if tag in image.TLV_VALUES.values(): + raise click.UsageError( + 'Custom TLV %s conflicts with predefined TLV.' % hex(tag)) + + value = tlv[1] + if value.startswith('0x'): + if len(value[2:]) % 2: + raise click.UsageError('Custom TLV length is odd.') + custom_tlvs[tag] = bytes.fromhex(value[2:]) + else: + custom_tlvs[tag] = value.encode('utf-8') + + img.create(key, public_key_format, enckey, dependencies, boot_record, + custom_tlvs) + img.save(outfile, hex_addr) + + +class AliasesGroup(click.Group): + + _aliases = { + "create": "sign", + } + + def list_commands(self, ctx): + cmds = [k for k in self.commands] + aliases = [k for k in self._aliases] + return sorted(cmds + aliases) + + def get_command(self, ctx, cmd_name): + rv = click.Group.get_command(self, ctx, cmd_name) + if rv is not None: + return rv + if cmd_name in self._aliases: + return click.Group.get_command(self, ctx, self._aliases[cmd_name]) + return None + + +@click.command(help='Print imgtool version information') +def version(): + print(imgtool_version) + + +@click.command(cls=AliasesGroup, + context_settings=dict(help_option_names=['-h', '--help'])) +def imgtool(): + pass + + +imgtool.add_command(keygen) +imgtool.add_command(getpub) +imgtool.add_command(getpriv) +imgtool.add_command(verify) +imgtool.add_command(sign) +imgtool.add_command(version) + + +if __name__ == '__main__': + imgtool() diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/version.py b/tools/psa/tfm/bin_utils/imgtool/version.py similarity index 59% rename from tools/psa/tfm/bin_utils/imgtool_lib/version.py rename to tools/psa/tfm/bin_utils/imgtool/version.py index d1d45f0385..6e38f445bb 100644 --- a/tools/psa/tfm/bin_utils/imgtool_lib/version.py +++ b/tools/psa/tfm/bin_utils/imgtool/version.py @@ -1,5 +1,6 @@ # Copyright 2017 Linaro Limited -# Copyright (c) 2018, Arm Limited. +# +# 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. @@ -16,37 +17,23 @@ """ Semi Semantic Versioning -Implements a subset of semantic versioning that is supportable by the image header. +Implements a subset of semantic versioning that is supportable by the image +header. """ -import argparse from collections import namedtuple import re -SemiSemVersion = namedtuple('SemiSemVersion', ['major', 'minor', 'revision', 'build']) +SemiSemVersion = namedtuple('SemiSemVersion', ['major', 'minor', 'revision', + 'build']) -def increment_build_num(lastVer): - newVer = SemiSemVersion(lastVer.major, lastVer.minor, lastVer.revision, lastVer.build + 1) - return newVer +version_re = re.compile( + r"""^([1-9]\d*|0)(\.([1-9]\d*|0)(\.([1-9]\d*|0)(\+([1-9]\d*|0))?)?)?$""") -# -1 if a is older than b; 0 if they're the same version; 1 if a is newer than b -def compare(a, b): - if (a.major > b.major): return 1 - elif (a.major < b.major): return -1 - else: - if (a.minor > b.minor): return 1 - elif (a.minor < b.minor): return -1 - else: - if (a.revision > b.revision): return 1 - elif (a.revision < b.revision): return -1 - else: - if (a.build > b.build): return 1 - elif (a.build < b.build): return -1 - else: return 0 -version_re = re.compile(r"""^([1-9]\d*|0)(\.([1-9]\d*|0)(\.([1-9]\d*|0)(\+([1-9]\d*|0))?)?)?$""") def decode_version(text): - """Decode the version string, which should be of the form maj.min.rev+build""" + """Decode the version string, which should be of the form maj.min.rev+build + """ m = version_re.match(text) if m: result = SemiSemVersion( @@ -56,8 +43,10 @@ def decode_version(text): int(m.group(7)) if m.group(7) else 0) return result else: - msg = "Invalid version number, should be maj.min.rev+build with later parts optional" - raise argparse.ArgumentTypeError(msg) + msg = "Invalid version number, should be maj.min.rev+build with later " + msg += "parts optional" + raise ValueError(msg) + if __name__ == '__main__': print(decode_version("1.2")) diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/boot_record.py b/tools/psa/tfm/bin_utils/imgtool_lib/boot_record.py deleted file mode 100644 index 76eed98ce0..0000000000 --- a/tools/psa/tfm/bin_utils/imgtool_lib/boot_record.py +++ /dev/null @@ -1,79 +0,0 @@ - -# Copyright (c) 2019, Arm Limited. -# -# 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. - -import os -import sys -import cbor - - -# SW component IDs -SW_COMPONENT_RANGE = 0 -SW_COMPONENT_TYPE = SW_COMPONENT_RANGE + 1 -MEASUREMENT_VALUE = SW_COMPONENT_RANGE + 2 -SW_COMPONENT_VERSION = SW_COMPONENT_RANGE + 4 -SIGNER_ID = SW_COMPONENT_RANGE + 5 -MEASUREMENT_DESCRIPTION = SW_COMPONENT_RANGE + 6 - - -def create_sw_component_data(sw_type, sw_version, sw_measurement_type, - sw_measurement_value, sw_signer_id): - - # List of SW component claims (key ID + value) - key_value_list = [ - SW_COMPONENT_TYPE, sw_type, - SW_COMPONENT_VERSION, sw_version, - SIGNER_ID, sw_signer_id, - MEASUREMENT_DESCRIPTION, sw_measurement_type, - MEASUREMENT_VALUE, sw_measurement_value - ] - # The measurement value should be the last item (key + value) in the list - # to make it easier to modify its value later in the bootloader. - # A dictionary would be the best suited data structure to store these - # key-value pairs (claims), however dictionaries are not sorted, but for - # example the lists do keep to order of items which we care about now. - # An ordered dictionary could be used instead, but it would be converted - # to a dict before the encoding and this conversion may not keep the order - # of the items. - - if (len(key_value_list) % 2) != 0: - print('Error: The length of the sw component claim list must ' - 'be even (key + value).', file=sys.stderr) - sys.exit(1) - else: - claim_number = (int)(len(key_value_list) / 2) - - # The output of this function must be a CBOR encoded map (dictionary) of - # the SW component claims. The CBOR representation of an array and a map - # (dictionary) is quite similar. To convert the encoded list to a map, it - # is enough to modify the first byte (CBOR data item header) of the - # data. This applies up to 23 items (11 claims in this case) - until the 5 - # lower bits of the item header are used as an item count specifier. - - if claim_number > 11: - print('Error: There are more than 11 claims in the ' - 'list of sw component claims.', file=sys.stderr) - sys.exit(1) - - record_array = bytearray(cbor.dumps(key_value_list)) - # Modify the CBOR data item header (from array to map) - # 7..5 bits : Major type - # Array - 0x80 - # Map - 0xA0 - # 4..0 bits : Number of items - record_array[0] = 0xA0 + claim_number - - return bytes(record_array) diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/image.py b/tools/psa/tfm/bin_utils/imgtool_lib/image.py deleted file mode 100644 index d790a75f7e..0000000000 --- a/tools/psa/tfm/bin_utils/imgtool_lib/image.py +++ /dev/null @@ -1,267 +0,0 @@ -# Copyright 2017 Linaro Limited -# Copyright (c) 2018-2019, Arm Limited. -# -# 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. - -""" -Image signing and management. -""" - -from . import version as versmod -from . import boot_record as br -import hashlib -import struct - -IMAGE_MAGIC = 0x96f3b83d -IMAGE_HEADER_SIZE = 32 -TLV_HEADER_SIZE = 4 -PAYLOAD_DIGEST_SIZE = 32 # SHA256 hash -KEYHASH_SIZE = 32 -DEP_IMAGES_KEY = "images" -DEP_VERSIONS_KEY = "versions" - -# Image header flags. -IMAGE_F = { - 'PIC': 0x0000001, - 'NON_BOOTABLE': 0x0000010, - 'RAM_LOAD': 0x0000020, } -TLV_VALUES = { - 'KEYHASH': 0x01, - 'KEY' : 0x02, - 'SHA256' : 0x10, - 'RSA2048': 0x20, - 'RSA3072': 0x23, - 'DEPENDENCY': 0x40, - 'SEC_CNT': 0x50, - 'BOOT_RECORD': 0x60, } - -TLV_INFO_SIZE = 4 -TLV_INFO_MAGIC = 0x6907 -TLV_PROT_INFO_MAGIC = 0x6908 - -# Sizes of the image trailer, depending on flash write size. -trailer_sizes = { - write_size: 128 * 3 * write_size + 8 * 2 + 16 - for write_size in [1, 2, 4, 8] -} - -boot_magic = bytearray([ - 0x77, 0xc2, 0x95, 0xf3, - 0x60, 0xd2, 0xef, 0x7f, - 0x35, 0x52, 0x50, 0x0f, - 0x2c, 0xb6, 0x79, 0x80, ]) - -class TLV(): - def __init__(self, magic=TLV_INFO_MAGIC): - self.magic = magic - self.buf = bytearray() - - def __len__(self): - return TLV_INFO_SIZE + len(self.buf) - - def add(self, kind, payload): - """ - Add a TLV record. Kind should be a string found in TLV_VALUES above. - """ - buf = struct.pack(' 0: - obj.payload = (b'\000' * obj.header_size) + obj.payload - - obj.check() - return obj - - def __init__(self, version, header_size=IMAGE_HEADER_SIZE, security_cnt=0, - pad=0): - self.version = version - self.header_size = header_size or IMAGE_HEADER_SIZE - self.security_cnt = security_cnt - self.pad = pad - - def __repr__(self): - return "".format( - self.version, - self.header_size, - self.security_cnt, - self.pad, - len(self.payload)) - - def save(self, path): - with open(path, 'wb') as f: - f.write(self.payload) - - def check(self): - """Perform some sanity checking of the image.""" - # If there is a header requested, make sure that the image - # starts with all zeros. - if self.header_size > 0: - if any(v != 0 and v != b'\000' for v in self.payload[0:self.header_size]): - raise Exception("Padding requested, but image does not start with zeros") - - def sign(self, sw_type, key, ramLoadAddress, dependencies=None): - image_version = (str(self.version.major) + '.' - + str(self.version.minor) + '.' - + str(self.version.revision)) - - # Calculate the hash of the public key - if key is not None: - pub = key.get_public_bytes() - sha = hashlib.sha256() - sha.update(pub) - pubbytes = sha.digest() - else: - pubbytes = bytes(KEYHASH_SIZE) - - # The image hash is computed over the image header, the image itself - # and the protected TLV area. However, the boot record TLV (which is - # part of the protected area) should contain this hash before it is - # even calculated. For this reason the script fills this field with - # zeros and the bootloader will insert the right value later. - image_hash = bytes(PAYLOAD_DIGEST_SIZE) - - # Create CBOR encoded boot record - boot_record = br.create_sw_component_data(sw_type, image_version, - "SHA256", image_hash, - pubbytes) - - # Mandatory protected TLV area: TLV info header - # + security counter TLV - # + boot record TLV - # Size of the security counter TLV: header ('BBH') + payload ('I') - # = 8 Bytes - protected_tlv_size = TLV_INFO_SIZE + 8 + TLV_HEADER_SIZE \ - + len(boot_record) - - if dependencies is None: - dependencies_num = 0 - else: - # Size of a dependency TLV: - # header ('BBH') + payload('IBBHI') = 16 Bytes - dependencies_num = len(dependencies[DEP_IMAGES_KEY]) - protected_tlv_size += (dependencies_num * 16) - - # At this point the image is already on the payload, this adds - # the header to the payload as well - self.add_header(key, protected_tlv_size, ramLoadAddress) - - prot_tlv = TLV(TLV_PROT_INFO_MAGIC) - - # Protected TLVs must be added first, because they are also included - # in the hash calculation - payload = struct.pack('I', self.security_cnt) - prot_tlv.add('SEC_CNT', payload) - prot_tlv.add('BOOT_RECORD', boot_record) - - if dependencies_num != 0: - for i in range(dependencies_num): - payload = struct.pack( - '<'+'B3x'+'BBHI', - int(dependencies[DEP_IMAGES_KEY][i]), - dependencies[DEP_VERSIONS_KEY][i].major, - dependencies[DEP_VERSIONS_KEY][i].minor, - dependencies[DEP_VERSIONS_KEY][i].revision, - dependencies[DEP_VERSIONS_KEY][i].build - ) - prot_tlv.add('DEPENDENCY', payload) - - self.payload += prot_tlv.get() - - sha = hashlib.sha256() - sha.update(self.payload) - image_hash = sha.digest() - - tlv = TLV() - - tlv.add('SHA256', image_hash) - - if key is not None: - if key.get_public_key_format() == 'hash': - tlv.add('KEYHASH', pubbytes) - else: - tlv.add('KEY', pub) - - sig = key.sign(self.payload) - tlv.add(key.sig_tlv(), sig) - - self.payload += tlv.get() - - def add_header(self, key, protected_tlv_size, ramLoadAddress): - """Install the image header. - - The key is needed to know the type of signature, and - approximate the size of the signature.""" - - flags = 0 - if ramLoadAddress is not None: - # add the load address flag to the header to indicate that an SRAM - # load address macro has been defined - flags |= IMAGE_F["RAM_LOAD"] - - fmt = ('<' + - # type ImageHdr struct { - 'I' + # Magic uint32 - 'I' + # LoadAddr uint32 - 'H' + # HdrSz uint16 - 'H' + # PTLVSz uint16 - 'I' + # ImgSz uint32 - 'I' + # Flags uint32 - 'BBHI' + # Vers ImageVersion - 'I' # Pad1 uint32 - ) # } - assert struct.calcsize(fmt) == IMAGE_HEADER_SIZE - header = struct.pack(fmt, - IMAGE_MAGIC, - 0 if (ramLoadAddress is None) else ramLoadAddress, # LoadAddr - self.header_size, - protected_tlv_size, # TLV info header + Protected TLVs - len(self.payload) - self.header_size, # ImageSz - flags, - self.version.major, - self.version.minor or 0, - self.version.revision or 0, - self.version.build or 0, - 0) # Pad1 - self.payload = bytearray(self.payload) - self.payload[:len(header)] = header - - def pad_to(self, size, align): - """Pad the image to the given size, with the given flash alignment.""" - tsize = trailer_sizes[align] - padding = size - (len(self.payload) + tsize) - if padding < 0: - msg = "Image size (0x{:x}) + trailer (0x{:x}) exceeds requested size 0x{:x}".format( - len(self.payload), tsize, size) - raise Exception(msg) - pbytes = b'\xff' * padding - pbytes += b'\xff' * (tsize - len(boot_magic)) - pbytes += boot_magic - self.payload += pbytes diff --git a/tools/psa/tfm/bin_utils/imgtool_lib/keys.py b/tools/psa/tfm/bin_utils/imgtool_lib/keys.py deleted file mode 100644 index d129116b0e..0000000000 --- a/tools/psa/tfm/bin_utils/imgtool_lib/keys.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) 2017,2019 Linaro Limited. -# Copyright (c) 2017-2019, Arm Limited. -# -# 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. - -""" -Cryptographic key management for imgtool. -""" - -from __future__ import print_function -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import serialization -from cryptography.hazmat.primitives.hashes import SHA256 -from cryptography.hazmat.primitives.asymmetric import rsa -from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15 -from cryptography.hazmat.primitives.asymmetric.padding import MGF1 -import hashlib -from pyasn1.type import namedtype, univ -from pyasn1.codec.der.encoder import encode - -# Sizes that bootutil will recognize -RSA_KEY_SIZES = [2048, 3072] - -# Public exponent -PUBLIC_EXPONENT = 65537 - -# By default, we use RSA-PSS (PKCS 2.1). That can be overridden on -# the command line to support the older (less secure) PKCS1.5 -sign_rsa_pss = True - -AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */" - -class RSAUsageError(Exception): - pass - -class RSAutil(): - def __init__(self, key, public_key_format='hash'): - """Construct an RSA key with the given key data""" - self.key = key - self.public_key_format = public_key_format - - def key_size(self): - return self.key.key_size - - def get_public_key_format(self): - return self.public_key_format - - @staticmethod - def generate(key_size=2048): - if key_size not in RSA_KEY_SIZES: - raise RSAUsageError("Key size {} is not supported by MCUboot" - .format(key_size)) - return RSAutil(rsa.generate_private_key( - public_exponent=PUBLIC_EXPONENT, - key_size=key_size, - backend=default_backend())) - - def export_private(self, path): - with open(path, 'wb') as f: - f.write(self.key.private_bytes( - encoding=serialization.Encoding.PEM, - format=serialization.PrivateFormat.TraditionalOpenSSL, - encryption_algorithm=serialization.NoEncryption())) - - def get_public_bytes(self): - return self.key.public_key().public_bytes( - encoding=serialization.Encoding.DER, - format=serialization.PublicFormat.PKCS1) - - def emit_c(self): - print(AUTOGEN_MESSAGE) - print("const unsigned char rsa_pub_key[] = {", end='') - encoded = self.get_public_bytes() - for count, b in enumerate(encoded): - if count % 8 == 0: - print("\n\t", end='') - else: - print(" ", end='') - print("0x{:02x},".format(b), end='') - print("\n};") - print("const unsigned int rsa_pub_key_len = {};".format(len(encoded))) - - def sig_type(self): - """Return the type of this signature (as a string)""" - if sign_rsa_pss: - return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size()) - else: - return "PKCS15_RSA{}_SHA256".format(self.key_size()) - - def sig_len(self): - return 256 if self.key_size() == 2048 else 384 - - def sig_tlv(self): - return "RSA2048" if self.key_size() == 2048 else "RSA3072" - - def sign(self, payload): - if sign_rsa_pss: - signature = self.key.sign( - data=payload, - padding=PSS( - mgf=MGF1(SHA256()), - salt_length=32 - ), - algorithm=SHA256() - ) - else: - signature = self.key.sign( - data=payload, - padding=PKCS1v15(), - algorithm=SHA256() - ) - assert len(signature) == self.sig_len() - return signature - -def load(path, public_key_format='hash'): - with open(path, 'rb') as f: - pem = f.read() - try: - key = serialization.load_pem_private_key( - pem, - password=None, - backend=default_backend() - ) - return RSAutil(key, public_key_format) - except ValueError: - raise Exception("Unsupported RSA key file") diff --git a/tools/psa/tfm/bin_utils/macro_parser.py b/tools/psa/tfm/bin_utils/macro_parser.py index 5e489a9c57..5d9418a4e8 100644 --- a/tools/psa/tfm/bin_utils/macro_parser.py +++ b/tools/psa/tfm/bin_utils/macro_parser.py @@ -47,7 +47,7 @@ def parse_and_sum(text): # Opens a file that contains the macro of interest, then finds the macro with # a regular expression, parses the expression that is defined for the given # macro. Lastly it evaluates the expression with the parse_and_sum function -def evaluate_macro(file, regexp, matchGroupKey, matchGroupData): +def evaluate_macro(file, regexp, matchGroupKey, matchGroupData, bracketless=False): regexp_compiled = re.compile(regexp) if os.path.isabs(file): @@ -59,6 +59,9 @@ def evaluate_macro(file, regexp, matchGroupKey, matchGroupData): macroValue = {} with open(configFile, 'r') as macros_preprocessed_file: for line in macros_preprocessed_file: + if bracketless: + line=line.replace("(","") + line=line.replace(")","") m = regexp_compiled.match(line) if m is not None: macroValue[m.group(matchGroupKey)] = \ diff --git a/tools/psa/tfm/bin_utils/wrapper.py b/tools/psa/tfm/bin_utils/wrapper.py new file mode 100755 index 0000000000..7799ce06da --- /dev/null +++ b/tools/psa/tfm/bin_utils/wrapper.py @@ -0,0 +1,126 @@ +#! /usr/bin/env python3 +# +# ----------------------------------------------------------------------------- +# Copyright (c) 2020, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +# +# ----------------------------------------------------------------------------- + +import re +import os +import sys +import click + +# Add the cwd to the path so that if there is a version of imgtool in there then +# it gets used over the system imgtool. Used so that imgtool from upstream +# mcuboot is preferred over system imgtool +cwd = os.getcwd() +sys.path = [cwd] + sys.path +import imgtool +import imgtool.main + +parser_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) +sys.path.append(parser_path) +import macro_parser + +sign_bin_size_re = re.compile(r"^\s*RE_SIGN_BIN_SIZE\s*=\s*(.*)") +load_addr_re = re.compile(r"^\s*RE_IMAGE_LOAD_ADDRESS\s*=\s*(.*)") + +#This works around Python 2 and Python 3 handling character encodings +#differently. More information about this issue at +#https://click.palletsprojects.com/en/5.x/python3 +os.environ['LC_ALL'] = 'C.UTF-8' +os.environ['LANG'] = 'C.UTF-8' + +@click.argument('outfile') +@click.argument('infile') +@click.option('-R', '--erased-val', type=click.Choice(['0', '0xff']), + required=False, help='The value that is read back from erased ' + 'flash.') +@click.option('-x', '--hex-addr', type=imgtool.main.BasedIntParamType(), + required=False, help='Adjust address in hex output file.') +@click.option('--save-enctlv', default=False, is_flag=True, + help='When upgrading, save encrypted key TLVs instead of plain ' + 'keys. Enable when BOOT_SWAP_SAVE_ENCTLV config option ' + 'was set.') +@click.option('-E', '--encrypt', metavar='filename', + help='Encrypt image using the provided public key') +@click.option('-e', '--endian', type=click.Choice(['little', 'big']), + default='little', help="Select little or big endian") +@click.option('--overwrite-only', default=False, is_flag=True, + help='Use overwrite-only instead of swap upgrades') +@click.option('-M', '--max-sectors', type=int, + help='When padding allow for this amount of sectors (defaults ' + 'to 128)') +@click.option('--confirm', default=False, is_flag=True, + help='When padding the image, mark it as confirmed') +@click.option('--pad', default=False, is_flag=True, + help='Pad image to the size determined by --layout, adding ' + 'trailer magic') +@click.option('-l', '--layout', help='The file containing the macros of the ' + 'slot sizes') +@click.option('--pad-header', default=False, is_flag=True, + help='Adds --erased-val (defaults to 0xff) --header-size times ' + 'at the beginning of the image') +@click.option('-H', '--header-size', + callback=imgtool.main.validate_header_size, + type=imgtool.main.BasedIntParamType(), required=True) +@click.option('-d', '--dependencies', callback=imgtool.main.get_dependencies, + required=False, help='''Add dependence on another image, format: + "(,), ... "''') +@click.option('-s', '--security-counter', + callback=imgtool.main.validate_security_counter, + help='Specify the value of security counter. Use the `auto` ' + 'keyword to automatically generate it from the image version.') +@click.option('-v', '--version', callback=imgtool.main.validate_version, + required=True) +@click.option('--align', type=click.Choice(['1', '2', '4', '8']), + required=True) +@click.option('--public-key-format', type=click.Choice(['hash', 'full']), + default='hash', help='In what format to add the public key to ' + 'the image manifest: full key or hash of the key.') +@click.option('-k', '--key', metavar='filename') +@click.command(help='''Create a signed or unsigned image\n + INFILE and OUTFILE are parsed as Intel HEX if the params have + .hex extension, otherwise binary format is used''') +def wrap(key, align, version, header_size, pad_header, layout, pad, confirm, + max_sectors, overwrite_only, endian, encrypt, infile, outfile, + dependencies, hex_addr, erased_val, save_enctlv, public_key_format, + security_counter): + + slot_size = macro_parser.evaluate_macro(layout, sign_bin_size_re, 0, 1) + load_addr = macro_parser.evaluate_macro(layout, load_addr_re, 0, 1) + + if "_s" in layout: + boot_record = "SPE" + elif "_ns" in layout: + boot_record = "NSPE" + else: + boot_record = "NSPE_SPE" + + img = imgtool.image.Image(version=imgtool.version.decode_version(version), + header_size=header_size, pad_header=pad_header, + pad=pad, confirm=confirm, align=int(align), + slot_size=slot_size, max_sectors=max_sectors, + overwrite_only=overwrite_only, endian=endian, + load_addr=load_addr, erased_val=erased_val, + save_enctlv=save_enctlv, + security_counter=security_counter) + + img.load(infile) + key = imgtool.main.load_key(key) if key else None + enckey = imgtool.main.load_key(encrypt) if encrypt else None + if enckey and key: + if (isinstance(key, imgtool.keys.RSA) and + not isinstance(enckey, imgtool.keys.RSAPublic)): + # FIXME + raise click.UsageError("Signing and encryption must use the same " + "type of key") + + img.create(key, public_key_format, enckey, dependencies, boot_record) + img.save(outfile, hex_addr) + + +if __name__ == '__main__': + wrap() diff --git a/tools/targets/ARM_MUSCA.py b/tools/targets/ARM_MUSCA.py new file mode 100644 index 0000000000..e74894f1a9 --- /dev/null +++ b/tools/targets/ARM_MUSCA.py @@ -0,0 +1,167 @@ +#!/usr/bin/python +# Copyright (c) 2017-2021 Arm Limited +# +# 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. + +import os +from os.path import abspath, basename, dirname, splitext, isdir +from os.path import join as path_join +import re +import subprocess + +SCRIPT_DIR = dirname(abspath(__file__)) +MBED_OS_ROOT = abspath(path_join(SCRIPT_DIR, os.pardir, os.pardir)) + +def musca_tfm_bin(t_self, non_secure_bin, secure_bin, target_name): + + MUSCA_BASE = path_join(MBED_OS_ROOT, 'targets', 'TARGET_ARM_SSG', ('TARGET_' + target_name)) + assert os.path.isfile(secure_bin) + assert os.path.isfile(non_secure_bin) + + build_dir = dirname(non_secure_bin) + tempdir = path_join(build_dir, 'temp') + if not isdir(tempdir): + os.makedirs(tempdir) + flash_layout = path_join(MUSCA_BASE, 'partition', 'flash_layout.h') + mcuboot_bin = path_join(MUSCA_BASE, 'bl2.bin') + image_macros_s = path_join(MUSCA_BASE, 'partition', 'signing_layout_s.c') + image_macros_ns = path_join(MUSCA_BASE, 'partition', 'signing_layout_ns.c') + s_bin_name, s_bin_ext = splitext(basename(secure_bin)) + s_signed_bin = abspath(path_join(tempdir, s_bin_name + '_signed' + s_bin_ext)) + ns_bin_name, ns_bin_ext = splitext(basename(non_secure_bin)) + ns_signed_bin = abspath(path_join(tempdir, 'tfm_' + ns_bin_name + '_signed' + ns_bin_ext)) + concatenated_bin = abspath(path_join(tempdir, s_bin_name + '_' + ns_bin_name + '_concat' + ns_bin_ext)) + + assert os.path.isfile(image_macros_s) + assert os.path.isfile(image_macros_ns) + + #1. Run wrapper to sign the TF-M secure binary + cmd = [ + "python3", + path_join(MBED_OS_ROOT, "tools", "psa","tfm", "bin_utils","wrapper.py"), + "-v", + '1.2.0', + "-k", + path_join(SCRIPT_DIR, (target_name.lower() + '-root-rsa-3072.pem')), + "--layout", + image_macros_s, + "--public-key-format", + 'full', + "--align", + '1', + "--pad", + "--pad-header", + "-H", + '0x400', + "--overwrite-only", + "-s", + 'auto', + "-d", + '(0,0.0.0+0)', + abspath(secure_bin), + s_signed_bin, + ] + + retcode = run_cmd(cmd, MBED_OS_ROOT) + if retcode: + raise Exception("Unable to sign " + target_name + + " secure binary, Error code: " + retcode) + return + + #2. Run wrapper to sign the non-secure mbed binary + cmd = [ + "python3", + path_join(MBED_OS_ROOT, "tools", "psa","tfm", "bin_utils","wrapper.py"), + "-v", + '1.2.0', + "-k", + path_join(SCRIPT_DIR, (target_name.lower() + '-root-rsa-3072_1.pem')), + "--layout", + image_macros_ns, + "--public-key-format", + 'full', + "--align", + '1', + "--pad", + "--pad-header", + "-H", + '0x400', + "--overwrite-only", + "-s", + 'auto', + "-d", + '(1,0.0.0+0)', + abspath(non_secure_bin), + ns_signed_bin, + ] + + retcode = run_cmd(cmd, MBED_OS_ROOT) + if retcode: + raise Exception("Unable to sign " + target_name + + " non-secure binary, Error code: " + retcode) + return + + #3. Concatenate signed secure TFM and non-secure mbed binaries + cmd = [ + "python3", + path_join(MBED_OS_ROOT, "tools", "psa","tfm", "bin_utils","assemble.py"), + "--layout", + image_macros_s, + "-s", + s_signed_bin, + "-n", + ns_signed_bin, + "-o", + concatenated_bin, + ] + + retcode = run_cmd(cmd, MBED_OS_ROOT) + if retcode: + raise Exception("Unable to concatenate " + target_name + + " binaries, Error code: " + retcode) + return + + #4. Concatenate mcuboot and signed binary and overwrite mbed built binary file + mcuboot_image_size = find_bl2_size(flash_layout) + with open(mcuboot_bin, "rb") as mcuboot_fh, open(concatenated_bin, "rb") as concat_fh: + with open(non_secure_bin, "w+b") as out_fh: + out_fh.write(mcuboot_fh.read()) + out_fh.seek(mcuboot_image_size) + out_fh.write(concat_fh.read()) + + +def find_bl2_size(configFile): + bl2_size_re = re.compile(r"^#define\s+FLASH_AREA_BL2_SIZE\s+\({0,1}(0x[0-9a-fA-F]+)\){0,1}") + bl2_size = None + with open(configFile, 'r') as flash_layout_file: + for line in flash_layout_file: + m = bl2_size_re.match(line) + if m is not None: + bl2_size = int(m.group(1), 0) + break + return bl2_size + +def run_cmd(cmd, directory): + + POPEN_INSTANCE = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=directory, + ) + + POPEN_INSTANCE.communicate() + return POPEN_INSTANCE.returncode + diff --git a/tools/targets/ARM_MUSCA_A1.py b/tools/targets/ARM_MUSCA_A1.py deleted file mode 100644 index de541ebe95..0000000000 --- a/tools/targets/ARM_MUSCA_A1.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# Copyright (c) 2017-2020 ARM Limited -# -# 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. - -import os -from os.path import abspath, basename, dirname, splitext, isdir -from os.path import join as path_join -import re -from argparse import Namespace -from tools.psa.tfm.bin_utils.assemble import Assembly -from tools.psa.tfm.bin_utils.imgtool import do_sign -from tools.psa.tfm.bin_utils.imgtool_lib import version - -SCRIPT_DIR = dirname(abspath(__file__)) -MBED_OS_ROOT = abspath(path_join(SCRIPT_DIR, os.pardir, os.pardir)) -MUSCA_A1_BASE = path_join(MBED_OS_ROOT, 'targets', 'TARGET_ARM_SSG', 'TARGET_MUSCA_A1') - - -def musca_tfm_bin(t_self, non_secure_bin, secure_bin): - - assert os.path.isfile(secure_bin) - assert os.path.isfile(non_secure_bin) - - build_dir = dirname(non_secure_bin) - tempdir = path_join(build_dir, 'temp') - if not isdir(tempdir): - os.makedirs(tempdir) - flash_layout = path_join(MUSCA_A1_BASE, 'partition', 'flash_layout.h') - mcuboot_bin = path_join(MUSCA_A1_BASE, 'mcuboot.bin') - image_macros = path_join(MUSCA_A1_BASE, 'partition', 'image_macros_preprocessed.c') - ns_bin_name, ns_bin_ext = splitext(basename(non_secure_bin)) - concatenated_bin = path_join(tempdir, 'tfm_' + ns_bin_name + ns_bin_ext) - signed_bin = path_join(tempdir, 'tfm_' + ns_bin_name + '_signed' + ns_bin_ext) - - assert os.path.isfile(image_macros) - - #1. Concatenate secure TFM and non-secure mbed binaries - output = Assembly(image_macros, concatenated_bin) - output.add_image(secure_bin, "SECURE") - output.add_image(non_secure_bin, "NON_SECURE") - - #2. Run imgtool to sign the concatenated binary - sign_args = Namespace( - layout=image_macros, - key=path_join(SCRIPT_DIR, 'musca_a1-root-rsa-3072.pem'), - public_key_format=None, - align=1, - dependencies=None, - version=version.decode_version('1.0'), - header_size=0x400, - pad=0x100000, - security_counter=None, - rsa_pkcs1_15=False, - included_header=False, - infile=concatenated_bin, - outfile=signed_bin - ) - do_sign(sign_args) - - #3. Concatenate mcuboot and signed binary and overwrite mbed built binary file - mcuboot_image_size = find_bl2_size(flash_layout) - with open(mcuboot_bin, "rb") as mcuboot_fh, open(signed_bin, "rb") as signed_fh: - with open(non_secure_bin, "w+b") as out_fh: - out_fh.write(mcuboot_fh.read()) - out_fh.seek(mcuboot_image_size) - out_fh.write(signed_fh.read()) - - -def find_bl2_size(configFile): - bl2_size_re = re.compile(r"^#define\s+FLASH_AREA_BL2_SIZE\s+\({0,1}(0x[0-9a-fA-F]+)\){0,1}") - bl2_size = None - with open(configFile, 'r') as flash_layout_file: - for line in flash_layout_file: - m = bl2_size_re.match(line) - if m is not None: - bl2_size = int(m.group(1), 0) - break - return bl2_size diff --git a/tools/targets/ARM_MUSCA_B1.py b/tools/targets/ARM_MUSCA_B1.py deleted file mode 100644 index 948d590f87..0000000000 --- a/tools/targets/ARM_MUSCA_B1.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# Copyright (c) 2017-2020 Arm Limited -# -# 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. - -import os -from os.path import abspath, basename, dirname, splitext, isdir -from os.path import join as path_join -import re -from argparse import Namespace -from tools.psa.tfm.bin_utils.assemble import Assembly -from tools.psa.tfm.bin_utils.imgtool import do_sign -from tools.psa.tfm.bin_utils.imgtool_lib import version - -SCRIPT_DIR = dirname(abspath(__file__)) -MBED_OS_ROOT = abspath(path_join(SCRIPT_DIR, os.pardir, os.pardir)) -MUSCA_B1_BASE = path_join(MBED_OS_ROOT, 'targets', 'TARGET_ARM_SSG', 'TARGET_MUSCA_B1') - - -def musca_tfm_bin(t_self, non_secure_bin, secure_bin): - - assert os.path.isfile(secure_bin) - assert os.path.isfile(non_secure_bin) - - build_dir = dirname(non_secure_bin) - tempdir = path_join(build_dir, 'temp') - if not isdir(tempdir): - os.makedirs(tempdir) - flash_layout = path_join(MUSCA_B1_BASE, 'partition', 'flash_layout.h') - mcuboot_bin = path_join(MUSCA_B1_BASE, 'mcuboot.bin') - image_macros_s = path_join(MUSCA_B1_BASE, 'partition', 'image_macros_preprocessed_s.c') - image_macros_ns = path_join(MUSCA_B1_BASE, 'partition', 'image_macros_preprocessed_ns.c') - s_bin_name, s_bin_ext = splitext(basename(secure_bin)) - s_signed_bin = path_join(tempdir, s_bin_name + '_signed' + s_bin_ext) - ns_bin_name, ns_bin_ext = splitext(basename(non_secure_bin)) - ns_signed_bin = path_join(tempdir, 'tfm_' + ns_bin_name + '_signed' + ns_bin_ext) - concatenated_bin = path_join(tempdir, s_bin_name + '_' + ns_bin_name + '_concat' + ns_bin_ext) - - assert os.path.isfile(image_macros_s) - assert os.path.isfile(image_macros_ns) - - #1. Run imgtool to sign the secure binary - sign_args = Namespace( - layout=image_macros_s, - key=path_join(SCRIPT_DIR, 'musca_b1-root-rsa-3072.pem'), - public_key_format=None, - align=1, - dependencies=None, - version=version.decode_version('1.0'), - header_size=0x400, - security_counter=None, - rsa_pkcs1_15=False, - included_header=False, - infile=secure_bin, - outfile=s_signed_bin - ) - do_sign(sign_args) - - #2. Run imgtool to sign the non-secure mbed binary - sign_args = Namespace( - layout=image_macros_ns, - key=path_join(SCRIPT_DIR, 'musca_b1-root-rsa-3072_1.pem'), - public_key_format=None, - align=1, - dependencies=None, - version=version.decode_version('1.0'), - header_size=0x400, - security_counter=None, - rsa_pkcs1_15=False, - included_header=False, - infile=non_secure_bin, - outfile=ns_signed_bin - ) - do_sign(sign_args) - - #1. Concatenate signed secure TFM and non-secure mbed binaries - output = Assembly(image_macros_s, concatenated_bin) - output.add_image(s_signed_bin, "SECURE") - output.add_image(ns_signed_bin, "NON_SECURE") - - #3. Concatenate mcuboot and signed binary and overwrite mbed built binary file - mcuboot_image_size = find_bl2_size(flash_layout) - with open(mcuboot_bin, "rb") as mcuboot_fh, open(concatenated_bin, "rb") as concat_fh: - with open(non_secure_bin, "w+b") as out_fh: - out_fh.write(mcuboot_fh.read()) - out_fh.seek(mcuboot_image_size) - out_fh.write(concat_fh.read()) - - -def find_bl2_size(configFile): - bl2_size_re = re.compile(r"^#define\s+FLASH_AREA_BL2_SIZE\s+\({0,1}(0x[0-9a-fA-F]+)\){0,1}") - bl2_size = None - with open(configFile, 'r') as flash_layout_file: - for line in flash_layout_file: - m = bl2_size_re.match(line) - if m is not None: - bl2_size = int(m.group(1), 0) - break - return bl2_size diff --git a/tools/targets/ARM_MUSCA_S1.py b/tools/targets/ARM_MUSCA_S1.py deleted file mode 100644 index 8a38a617a1..0000000000 --- a/tools/targets/ARM_MUSCA_S1.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# Copyright (c) 2017-2020 Arm Limited -# -# 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. - -import os -from os.path import abspath, basename, dirname, splitext, isdir -from os.path import join as path_join -import re -from argparse import Namespace -from tools.psa.tfm.bin_utils.assemble import Assembly -from tools.psa.tfm.bin_utils.imgtool import do_sign -from tools.psa.tfm.bin_utils.imgtool_lib import version - -SCRIPT_DIR = dirname(abspath(__file__)) -MBED_OS_ROOT = abspath(path_join(SCRIPT_DIR, os.pardir, os.pardir)) -MUSCA_S1_BASE = path_join(MBED_OS_ROOT, 'targets', 'TARGET_ARM_SSG', 'TARGET_MUSCA_S1') - - -def musca_tfm_bin(t_self, non_secure_bin, secure_bin): - - assert os.path.isfile(secure_bin) - assert os.path.isfile(non_secure_bin) - - build_dir = dirname(non_secure_bin) - tempdir = path_join(build_dir, 'temp') - if not isdir(tempdir): - os.makedirs(tempdir) - flash_layout = path_join(MUSCA_S1_BASE, 'partition', 'flash_layout.h') - mcuboot_bin = path_join(MUSCA_S1_BASE, 'mcuboot.bin') - image_macros_s = path_join(MUSCA_S1_BASE, 'partition', 'image_macros_preprocessed_s.c') - image_macros_ns = path_join(MUSCA_S1_BASE, 'partition', 'image_macros_preprocessed_ns.c') - s_bin_name, s_bin_ext = splitext(basename(secure_bin)) - s_signed_bin = path_join(tempdir, s_bin_name + '_signed' + s_bin_ext) - ns_bin_name, ns_bin_ext = splitext(basename(non_secure_bin)) - ns_signed_bin = path_join(tempdir, 'tfm_' + ns_bin_name + '_signed' + ns_bin_ext) - concatenated_bin = path_join(tempdir, s_bin_name + '_' + ns_bin_name + '_concat' + ns_bin_ext) - - assert os.path.isfile(image_macros_s) - assert os.path.isfile(image_macros_ns) - - #1. Run imgtool to sign the secure binary - sign_args = Namespace( - layout=image_macros_s, - key=path_join(SCRIPT_DIR, 'musca_s1-root-rsa-3072.pem'), - public_key_format=None, - align=1, - dependencies=None, - version=version.decode_version('1.0'), - header_size=0x400, - security_counter=None, - rsa_pkcs1_15=False, - included_header=False, - infile=secure_bin, - outfile=s_signed_bin - ) - do_sign(sign_args) - - #2. Run imgtool to sign the non-secure mbed binary - sign_args = Namespace( - layout=image_macros_ns, - key=path_join(SCRIPT_DIR, 'musca_s1-root-rsa-3072_1.pem'), - public_key_format=None, - align=1, - dependencies=None, - version=version.decode_version('1.0'), - header_size=0x400, - security_counter=None, - rsa_pkcs1_15=False, - included_header=False, - infile=non_secure_bin, - outfile=ns_signed_bin - ) - do_sign(sign_args) - - #1. Concatenate signed secure TFM and non-secure mbed binaries - output = Assembly(image_macros_s, concatenated_bin) - output.add_image(s_signed_bin, "SECURE") - output.add_image(ns_signed_bin, "NON_SECURE") - - #3. Concatenate mcuboot and signed binary and overwrite mbed built binary file - mcuboot_image_size = find_bl2_size(flash_layout) - with open(mcuboot_bin, "rb") as mcuboot_fh, open(concatenated_bin, "rb") as concat_fh: - with open(non_secure_bin, "w+b") as out_fh: - out_fh.write(mcuboot_fh.read()) - out_fh.seek(mcuboot_image_size) - out_fh.write(concat_fh.read()) - - -def find_bl2_size(configFile): - bl2_size_re = re.compile(r"^#define\s+FLASH_AREA_BL2_SIZE\s+\({0,1}(0x[0-9a-fA-F]+)\){0,1}") - bl2_size = None - with open(configFile, 'r') as flash_layout_file: - for line in flash_layout_file: - m = bl2_size_re.match(line) - if m is not None: - bl2_size = int(m.group(1), 0) - break - return bl2_size diff --git a/tools/targets/__init__.py b/tools/targets/__init__.py index fd843998b8..7898e357d1 100644 --- a/tools/targets/__init__.py +++ b/tools/targets/__init__.py @@ -681,26 +681,11 @@ class PSOC6Code(object): psoc6_sign_image(t_self, resources, elf, binf, m0hexf) -class ArmMuscaA1Code(object): - """Musca-A1 Hooks""" - @staticmethod - def binary_hook(t_self, resources, elf, binf): - from tools.targets.ARM_MUSCA_A1 import musca_tfm_bin - configured_secure_image_filename = t_self.target.secure_image_filename - secure_bin = find_secure_image( - t_self.notify, - resources, - binf, - configured_secure_image_filename, - FileType.BIN - ) - musca_tfm_bin(t_self, binf, secure_bin) - class ArmMuscaB1Code(object): """Musca-B1 Hooks""" @staticmethod def binary_hook(t_self, resources, elf, binf): - from tools.targets.ARM_MUSCA_B1 import musca_tfm_bin + from tools.targets.ARM_MUSCA import musca_tfm_bin configured_secure_image_filename = t_self.target.secure_image_filename secure_bin = find_secure_image( t_self.notify, @@ -709,13 +694,13 @@ class ArmMuscaB1Code(object): configured_secure_image_filename, FileType.BIN ) - musca_tfm_bin(t_self, binf, secure_bin) + musca_tfm_bin(t_self, binf, secure_bin, 'MUSCA_B1') class ArmMuscaS1Code(object): """Musca-S1 Hooks""" @staticmethod def binary_hook(t_self, resources, elf, binf): - from tools.targets.ARM_MUSCA_S1 import musca_tfm_bin + from tools.targets.ARM_MUSCA import musca_tfm_bin configured_secure_image_filename = t_self.target.secure_image_filename secure_bin = find_secure_image( t_self.notify, @@ -724,7 +709,7 @@ class ArmMuscaS1Code(object): configured_secure_image_filename, FileType.BIN ) - musca_tfm_bin(t_self, binf, secure_bin) + musca_tfm_bin(t_self, binf, secure_bin, 'MUSCA_S1') def find_secure_image(notify, resources, ns_image_path, configured_s_image_filename, image_type): diff --git a/tools/targets/musca_a1-root-rsa-3072.md b/tools/targets/musca_a1-root-rsa-3072.md deleted file mode 100644 index 0362964660..0000000000 --- a/tools/targets/musca_a1-root-rsa-3072.md +++ /dev/null @@ -1,11 +0,0 @@ -# Musca-A1 RSA keypair - -A default RSA key pair is given to the Musca-A1 target. - -Public key was pre-compiled to `targets/TARGET_ARM_SSG/TARGET_MUSCA_A1/prebuilt/mcuboot.bin` and private key is in `musca_a1-root-rsa-3072.pem`. - -DO NOT use them in production code, they are exclusively for testing! - -Private key must be stored in a safe place outside of the repository. - -`tools/psa/tfm/bin_utils/imgtool.py` can be used to generate new key pairs. diff --git a/tools/targets/musca_a1-root-rsa-3072.pem b/tools/targets/musca_a1-root-rsa-3072.pem deleted file mode 100644 index 23288bc101..0000000000 --- a/tools/targets/musca_a1-root-rsa-3072.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIG4gIBAAKCAYEAnLrCWr/MxU8gDE9vbFFPXAqrgLhrEMSbK8RSMglLOyeUah3V -TKhcoMB2lXsmBLETfngn1gy06LAtklKK+2n/QhCqVgyDyGVuug1fjvcrKZL8Qi0t -+YD1hSGH6qxAqMvQqDvi0uzwFEgOzyuKS6TNoQVbF2Yd3m5E/kajDdBpv4ytqRZo -Uet5kSDmgQMHiUBVS+vPZ/gxxxxUTlILYOiiUAfRz84SJs2Ogo1OZKn3xyGZJQfd -xdVf9GP6zCvaBlxZZ7AGNemqkkU15aAD/xwCtcdOlEturXOdzm8Js7GPYGyi+s13 -D8wn5jZYs1L3j75JmLfpYP2XV83q0wvfokL3RNOH3uAQA5Ta/LzdvpOzSitY3JYS -8m8jujs3/vwYH3V9VAEOvj0YE7MouTQs1fvFM72HvTvkHdcCPRxyZXJDQzao+uZz -LaRh6AKcOlZNHNF2nIyqXxvrHEr1ubhvQUsnh972lB/d5vGpwgLCT6P8pANa2W94 -/YTw5f09pU0brVtLAgMBAAECggGAG786mltbctEL0PIdPVV10cs3yq2bktfjys9S -Z/ZaQcpDjbfjY9NotrLsK5GmTO1WkKzQDKaqPom2P7HqVhFRdg5CQcKscAV5IWot -sT9T/mO90i9ydLoefWfOyr6dIeUXdzlG8mWtKUIKkSXZsYOnPesXUeCryA3InCXA -RzlPB3Dt68ICTQJ9vrJO7KcvJd7kWvEQAo2frmr3B/iheBInbji8LeiDMShyIu3G -Y67tpWzu0m3+lsAsYTV0GMJosniVulaZ3hYQQazHUk+zDzMSC7zryICrpjEbgzWU -HZI9EGi1B890nwUtdhlCpkr8zoWDb0BjawpftiGz7fRm7q2TQkYAWGzNKm3DZlIS -4LsRACvHnPZ17wUSze9tqP14Pb593WR3nOTiVjrJWm+4Z5hgV3QfoEqW5swOAYl4 -6QmKZsCXAfGkozJiHnYcyaULkGBVegn1LQ5rcb8JUMribQddrHZxCVHrbgwh2zm/ -v9CYfTtpWCnKHq+wF3mwjl6w7m4JAoHBALolVbgs919Dx0xjcPnW5MSxW3ctflI9 -2ZE1BOH/Rtg5gfBwR/aToUM3a/ZgIJHQYhVty2TzUVtthtmLNTRKu2FSqWN8//GJ -wmj4bcNBshMgniHEfkutlBiP9exhdvCZX4bYpdTkJAyvOmUGjEM8QBFsod60u0z7 -Bd0EIXs7PIURP0fNAUXCgSHMPjdICLljhwHinr31VEIU2/xehw8DBIJwkR/rCsPq -xBmlIwPWVjzCRTnYUxQuxCAYf+qvgNylKQKBwQDXi3UGI7t30rYNMdIjMn1GPkhW -o62BOJNCusoXiGnbVOkj8qBayf7kPu10ONBzHcYL7+SQYeVVXQY+DH033ji8oa0J -p1xMGIlx4JZEduQYlk0ke4hUNrcBQczTRA47DmMm2kIdWlaTHtB7aCJNx72IrwWn -lVTY9TWm6+yOPcpV5JfyCMM6GqoRycikgNS5IQug5hl2pFVLw+UTfxo6msYaAOnp -ICUjoeDUKS0Z8+FtzGhAkWTk8GXIiPbfu7RoN1MCgcAcah6Poq2QKTR/AJ76REdf -jwM7SgKCY1aWx9Ua+nDCCOVA4qLZjOeM7yTX0wyltX2Db+MgYdQFdM6k3o8ckFvS -G2AoA6i+Ih0/EM0QhTK9oLkCxo/Q1YpJxY/wqWASkhb26pNF0B2Aoi7zxPAcQ1I0 -VrTO3h/JPHhEqKDDwuMWHO/f8fdDwtEba6YDokdSpVKygvlgXdaiz7RU7ckIDZne -n3hHuwVFqsyMbZzOtSUs2SrgDZmA9zKRA6xjEq9E/yECgcAnm7XecfSCGVNg61XN -J/sDTHCokx1QEKBm88ItPuEM7/aDp5M1+8Z+FN43rDUJ4l/BU8zxhzvISvbZshvU -h15vs1oD2yBHz356UaXrYNmbdwsn+BdeOku4zGmiLPBcg9FOk27wy+f60v/GnaUo -G9tFYbwtRnC4CZ9ZVCM9JDepPv9494lAhSPZbvYS3KW6e0sSvxXQynPuH0paIdIl -EMn0f1R8hW6ttJKHCiYCjeFP9u71ZoJe25oolpqfFHQbbocCgcAuBR4w3Qmnbscm -3b7fyy8n3AXa1gIfYjjPpR35qyp1K9thiLyj66YZIl0ACC/dt08lmI9/lguRoNIQ -AfjzZ8DByZa0caiSiFIMlgNZXdh7N3BUNNbIQk98Wd91gBlWDAiFEhrJKFPpRkmv -FySATPYcq0lcrjJb3IW2GDK4uo/jb4Nb7Cfog95W6T76XcSKHS5O8k1aI4kFPRsr -1wGZw64OkA8VXVaCaEBQ4brZ1YKB3mx4/tDqwn0I6bqkGRX3RJg= ------END RSA PRIVATE KEY----- diff --git a/tools/targets/musca_b1-root-rsa-3072.md b/tools/targets/musca_b1-root-rsa-3072.md index 76596759a1..a48b77a6fc 100644 --- a/tools/targets/musca_b1-root-rsa-3072.md +++ b/tools/targets/musca_b1-root-rsa-3072.md @@ -2,7 +2,7 @@ A default RSA key pair is given to the Musca-B1 target. -Public keys were pre-compiled to `targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/prebuilt/mcuboot.bin` and private key is in `musca_b1-root-rsa-3072.pem` for Secure image and `musca_b1-root-rsa-3072_1.pem` for Non-Secure image. +Public keys were pre-compiled to `targets/TARGET_ARM_SSG/TARGET_MUSCA_B1/bl2.bin` and private key is in `musca_b1-root-rsa-3072.pem` for Secure image and `musca_b1-root-rsa-3072_1.pem` for Non-Secure image. DO NOT use them in production code, they are exclusively for testing! diff --git a/tools/targets/musca_s1-root-rsa-3072.md b/tools/targets/musca_s1-root-rsa-3072.md index c7cccb8090..638f2f192d 100644 --- a/tools/targets/musca_s1-root-rsa-3072.md +++ b/tools/targets/musca_s1-root-rsa-3072.md @@ -2,7 +2,7 @@ A default RSA key pair is given to the Musca-S1 target. -Public keys were pre-compiled to `targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/prebuilt/mcuboot.bin` and private key is in `musca_s1-root-rsa-3072.pem` for Secure image and `musca_s1-root-rsa-3072_1.pem` for Non-Secure image. +Public keys were pre-compiled to `targets/TARGET_ARM_SSG/TARGET_MUSCA_S1/bl2.bin` and private key is in `musca_s1-root-rsa-3072.pem` for Secure image and `musca_s1-root-rsa-3072_1.pem` for Non-Secure image. DO NOT use them in production code, they are exclusively for testing!