Merge branch 'development' into mbedtls_x509_crt_parse_path-qemu-bug

Signed-off-by: Dave Rodgman <dave.rodgman@arm.com>
This commit is contained in:
Dave Rodgman 2023-07-07 15:11:35 +01:00 committed by GitHub
commit 8abb3497ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
531 changed files with 29377 additions and 10523 deletions

View File

@ -4,7 +4,9 @@ Please write a few sentences describing the overall goals of the pull request's
## Gatekeeper checklist
## PR checklist
Please tick as appropriate and edit the reasons (e.g.: "backport: not needed because this is a new feature")
- [ ] **changelog** provided, or not required
- [ ] **backport** done, or not required
@ -16,4 +18,3 @@ Please write a few sentences describing the overall goals of the pull request's
Please refer to the [contributing guidelines](https://github.com/Mbed-TLS/mbedtls/blob/development/CONTRIBUTING.md), especially the
checklist for PR contributors.

6
.gitignore vendored
View File

@ -28,6 +28,9 @@ massif-*
.project
/.settings
# Unix-like build artifacts:
*.o
# MSVC build artifacts:
*.exe
*.pdb
@ -57,3 +60,6 @@ massif-*
/TAGS
/cscope*.out
/tags
# Clangd compilation database
compile_commands.json

View File

@ -12,8 +12,14 @@ build:
python: "3.9"
jobs:
pre_build:
- make apidoc
- breathe-apidoc -o docs/api apidoc/xml
- ./scripts/apidoc_full.sh
- breathe-apidoc -o docs/api apidoc/xml
post_build:
- |
# Work around Readthedocs bug: Command parsing fails if the 'if' statement is on the first line
if [ "$READTHEDOCS_VERSION" = "development" ]; then
"$READTHEDOCS_VIRTUALENV_PATH/bin/rtd" projects "Mbed TLS API" redirects sync --wet-run -f docs/redirects.yaml
fi
# Build documentation in the docs/ directory with Sphinx
sphinx:

View File

@ -1,2 +1 @@
*.o
Makefile

View File

@ -1,6 +1,7 @@
/*
* Implementation of curve P-256 (ECDH and ECDSA)
*
* Copyright The Mbed TLS Contributors
* Author: Manuel Pégourié-Gonnard.
* SPDX-License-Identifier: Apache-2.0
*/

View File

@ -1,6 +1,7 @@
/*
* Interface of curve P-256 (ECDH and ECDSA)
*
* Copyright The Mbed TLS Contributors
* Author: Manuel Pégourié-Gonnard.
* SPDX-License-Identifier: Apache-2.0
*/

View File

@ -34,9 +34,9 @@ cmake_policy(SET CMP0011 NEW)
cmake_policy(SET CMP0012 NEW)
if(TEST_CPP)
project("mbed TLS" C CXX)
project("mbed TLS" LANGUAGES C CXX)
else()
project("mbed TLS" C)
project("mbed TLS" LANGUAGES C)
endif()
include(GNUInstallDirs)
@ -245,7 +245,7 @@ if(MBEDTLS_FATAL_WARNINGS)
endif(CMAKE_COMPILER_IS_CLANG OR CMAKE_COMPILER_IS_GNU)
if (CMAKE_COMPILER_IS_IAR)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --warning_are_errors")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --warnings_are_errors")
endif(CMAKE_COMPILER_IS_IAR)
endif(MBEDTLS_FATAL_WARNINGS)

View File

@ -0,0 +1,14 @@
New deprecations
* PSA_WANT_KEY_TYPE_xxx_KEY_PAIR and
MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR, where xxx is either ECC or RSA,
are now being deprecated in favor of PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_yyy and
MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR_yyy. Here yyy can be: USE, IMPORT,
EXPORT, GENERATE, DERIVE. The goal is to have a finer detail about the
capabilities of the PSA side for either key.
Features
* New symbols PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_yyy and
MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR_yyy (where xxx is either ECC, RSA
or DH) were introduced in order to have finer accuracy in defining the
PSA capabilities for each key. These capabilities, named yyy above, can be
any of: USE, IMPORT, EXPORT, GENERATE, DERIVE.

View File

@ -0,0 +1,3 @@
Features
* When parsing X.509 certificates, support the extensions
SignatureKeyIdentifier and AuthorityKeyIdentifier.

View File

@ -0,0 +1,4 @@
Features
* Add support to restrict AES to 128-bit keys in order to save code size.
A new configuration option, MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH, can be
used to enable this feature.

View File

@ -0,0 +1,2 @@
Features
* Add support for PBKDF2-HMAC through the PSA API.

View File

@ -0,0 +1,3 @@
Features
* Don't include the PSA dispatch functions for PAKEs (psa_pake_setup() etc)
if no PAKE algorithms are requested

View File

@ -0,0 +1,6 @@
Features
* It is now possible to generate certificates with SubjectAltNames.
Currently supported subtypes: DnsName, UniformResourceIdentifier,
IP address, OtherName, and DirectoryName, as defined in RFC 5280.
See mbedtls_x509write_crt_set_subject_alternative_name for
more information.

7
ChangeLog.d/aes-perf.txt Normal file
View File

@ -0,0 +1,7 @@
Features
* AES performance improvements. Uplift varies by platform,
toolchain, optimisation flags and mode.
Aarch64, gcc -Os and CCM, GCM and XTS benefit the most.
On Aarch64, uplift is typically around 20 - 110%.
When compiling with gcc -Os on Aarch64, AES-XTS improves
by 4.5x.

View File

@ -0,0 +1,7 @@
Bugfix
* Fix clang and armclang compilation error when targeting certain Arm
M-class CPUs (Cortex-M0, Cortex-M0+, Cortex-M1, Cortex-M23,
SecurCore SC000). Fixes #1077.
Changes
* Enable Arm / Thumb bignum assembly for most Arm platforms when
compiling with gcc, clang or armclang and -O0.

View File

@ -0,0 +1,4 @@
Features
* X.509 hostname verification now partially supports URI Subject Alternate
Names. Only exact matching, without any normalization procedures
described in 7.4 of RFC5280, will result in a positive URI verification.

View File

@ -0,0 +1,3 @@
Bugfix
* Fixed an issue that caused compile errors when using CMake and the IAR
toolchain.

View File

@ -0,0 +1,3 @@
Features
* Add a driver dispatch layer for FFDH keys, enabling alternative
implementations of FFDH through the driver entry points.

View File

@ -0,0 +1,6 @@
Features
* Add support for FFDH key exchange in TLS 1.3.
This is automatically enabled as soon as PSA_WANT_ALG_FFDH
and the ephemeral or psk-ephemeral key exchange mode are enabled.
By default, all groups are offered; the list of groups can be
configured using the existing API function mbedtls_ssl_conf_groups().

View File

@ -0,0 +1,4 @@
Bugfix
* Fix crypt_and_hash decryption fail when used with a stream cipher
mode of operation due to the input not being multiple of block size.
Resolves #7417.

View File

@ -0,0 +1,4 @@
Bugfix
* Fix a compilation failure in the constant_time module when
building for arm64_32 (e.g., for watchos). Reported by Paulo
Coutinho in #7787.

View File

@ -0,0 +1,3 @@
Bugfix
* Fix a bug in which mbedtls_x509_string_to_names() would return success
when given a invalid name string if it did not contain '=' or ','.

View File

@ -0,0 +1,5 @@
Bugfix
* Fix compilation warnings in aes.c, which prevented the
example TF-M configuration in configs/ from building cleanly:
tfm_mbedcrypto_config_profile_medium.h with
crypto_config_profile_medium.h.

View File

@ -0,0 +1,4 @@
Bugfix
* Fix "unterminated '#pragma clang attribute push'" in sha256/sha512.c when
built with MBEDTLS_SHAxxx_USE_A64_CRYPTO_IF_PRESENT but don't have a
way to detect the crypto extensions required. A warning is still issued.

View File

@ -0,0 +1,3 @@
Features
* Improve mbedtls_x509_time performance and reduce memory use.
* Reduce syscalls to time() during certificate verification.

View File

@ -0,0 +1,3 @@
Features
* Add function mbedtls_oid_from_numeric_string() to parse an OID from a
string to a DER-encoded mbedtls_asn1_buf.

View File

@ -0,0 +1,2 @@
Requirement changes
* Officially require Python 3.8 now that earlier versions are out of support.

3
ChangeLog.d/rfc8410.txt Normal file
View File

@ -0,0 +1,3 @@
Features
* Add support for reading and writing X25519 and X448
public and private keys in RFC 8410 format using the existing PK APIs.

3
ChangeLog.d/sha3.txt Normal file
View File

@ -0,0 +1,3 @@
Features
* Add SHA-3 family hash functions.

View File

@ -0,0 +1,3 @@
Bugfix
* Fix very high stack usage in SSL debug code. Reported by Maximilian
Gerhardt in #7804.

View File

@ -48,7 +48,7 @@ You need the following tools to build the library with the provided makefiles:
* GNU Make 3.82 or a build tool that CMake supports.
* A C99 toolchain (compiler, linker, archiver). We actively test with GCC 5.4, Clang 3.8, IAR 8 and Visual Studio 2013. More recent versions should work. Slightly older versions may work.
* Python 3.6 to generate the test code, and to generate sample programs in the development branch.
* Python 3.8 to generate the test code. Python is also needed to integrate PSA drivers and to build the development branch (see next section).
* Perl to run the tests, and to generate some source files in the development branch.
* CMake 3.10.2 or later (if using CMake).
* Microsoft Visual Studio 2013 or later (if using Visual Studio).
@ -61,7 +61,7 @@ The source code of Mbed TLS includes some files that are automatically generated
The following tools are required:
* Perl, for some library source files and for Visual Studio build files.
* Python 3 and some Python packages, for some library source files, sample programs and test data. To install the necessary packages, run:
* Python 3.8 and some Python packages, for some library source files, sample programs and test data. To install the necessary packages, run:
```
python3 -m pip install --user -r scripts/basic.requirements.txt
```
@ -293,14 +293,16 @@ However, it does not aim to implement the whole specification; in particular it
The X.509 and TLS code can use PSA cryptography for most operations. To enable this support, activate the compilation option `MBEDTLS_USE_PSA_CRYPTO` in `mbedtls_config.h`. Note that TLS 1.3 uses PSA cryptography for most operations regardless of this option. See `docs/use-psa-crypto.md` for details.
### Upcoming features
### PSA drivers
Future releases of this library will include:
Mbed TLS supports drivers for cryptographic accelerators, secure elements and random generators. This is work in progress. Please note that the driver interfaces are not fully stable yet and may change without notice. We intend to preserve backward compatibility for application code (using the PSA Crypto API), but the code of the drivers may have to change in future minor releases of Mbed TLS.
* A driver programming interface, which makes it possible to use hardware accelerators instead of the default software implementation for chosen algorithms.
* Support for external keys to be stored and manipulated exclusively in a separate cryptoprocessor.
* A configuration mechanism to compile only the algorithms you need for your application.
* A wider set of cryptographic algorithms.
Please see the [PSA driver example and guide](docs/psa-driver-example-and-guide.md) for information on writing a driver.
When using drivers, you will generally want to enable two compilation options (see the reference manual for more information):
* `MBEDTLS_USE_PSA_CRYPTO` is necessary so that the X.509 and TLS code calls the PSA drivers rather than the built-in software implementation.
* `MBEDTLS_PSA_CRYPTO_CONFIG` allows you to enable PSA cryptographic mechanisms without including the code of the corresponding software implementation. This is not yet supported for all mechanisms.
License
-------

View File

@ -25,7 +25,7 @@
#define MBEDTLS_HAVE_TIME
#define MBEDTLS_HAVE_TIME_DATE
/* Mbed Crypto feature support */
/* Mbed TLS feature support */
#define MBEDTLS_CIPHER_MODE_CBC
#define MBEDTLS_CIPHER_MODE_CFB
#define MBEDTLS_CIPHER_MODE_CTR
@ -42,7 +42,7 @@
#define MBEDTLS_USE_PSA_CRYPTO
#define MBEDTLS_VERSION_FEATURES
/* Mbed Crypto modules */
/* Mbed TLS modules */
#define MBEDTLS_AES_C
#define MBEDTLS_ASN1_PARSE_C
#define MBEDTLS_ASN1_WRITE_C

View File

@ -0,0 +1,119 @@
/*
* Copyright (c) 2018-2022, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
/**
* \file psa/crypto_config.h
* \brief PSA crypto configuration options (set of defines)
*
*/
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
/**
* When #MBEDTLS_PSA_CRYPTO_CONFIG is enabled in mbedtls_config.h,
* this file determines which cryptographic mechanisms are enabled
* through the PSA Cryptography API (\c psa_xxx() functions).
*
* To enable a cryptographic mechanism, uncomment the definition of
* the corresponding \c PSA_WANT_xxx preprocessor symbol.
* To disable a cryptographic mechanism, comment out the definition of
* the corresponding \c PSA_WANT_xxx preprocessor symbol.
* The names of cryptographic mechanisms correspond to values
* defined in psa/crypto_values.h, with the prefix \c PSA_WANT_ instead
* of \c PSA_.
*
* Note that many cryptographic mechanisms involve two symbols: one for
* the key type (\c PSA_WANT_KEY_TYPE_xxx) and one for the algorithm
* (\c PSA_WANT_ALG_xxx). Mechanisms with additional parameters may involve
* additional symbols.
*/
#else
/**
* When \c MBEDTLS_PSA_CRYPTO_CONFIG is disabled in mbedtls_config.h,
* this file is not used, and cryptographic mechanisms are supported
* through the PSA API if and only if they are supported through the
* mbedtls_xxx API.
*/
#endif
#ifndef PROFILE_M_PSA_CRYPTO_CONFIG_H
#define PROFILE_M_PSA_CRYPTO_CONFIG_H
/*
* CBC-MAC is not yet supported via the PSA API in Mbed TLS.
*/
//#define PSA_WANT_ALG_CBC_MAC 1
//#define PSA_WANT_ALG_CBC_NO_PADDING 1
//#define PSA_WANT_ALG_CBC_PKCS7 1
#define PSA_WANT_ALG_CCM 1
//#define PSA_WANT_ALG_CMAC 1
//#define PSA_WANT_ALG_CFB 1
//#define PSA_WANT_ALG_CHACHA20_POLY1305 1
//#define PSA_WANT_ALG_CTR 1
#define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1
//#define PSA_WANT_ALG_ECB_NO_PADDING 1
#define PSA_WANT_ALG_ECDH 1
#define PSA_WANT_ALG_ECDSA 1
//#define PSA_WANT_ALG_GCM 1
#define PSA_WANT_ALG_HKDF 1
#define PSA_WANT_ALG_HMAC 1
//#define PSA_WANT_ALG_MD5 1
//#define PSA_WANT_ALG_OFB 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_PBKDF2_HMAC 1
//#define PSA_WANT_ALG_RIPEMD160 1
//#define PSA_WANT_ALG_RSA_OAEP 1
//#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
//#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1
//#define PSA_WANT_ALG_RSA_PSS 1
//#define PSA_WANT_ALG_SHA_1 1
#define PSA_WANT_ALG_SHA_224 1
#define PSA_WANT_ALG_SHA_256 1
//#define PSA_WANT_ALG_SHA_384 1
//#define PSA_WANT_ALG_SHA_512 1
//#define PSA_WANT_ALG_STREAM_CIPHER 1
#define PSA_WANT_ALG_TLS12_PRF 1
#define PSA_WANT_ALG_TLS12_PSK_TO_MS 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_XTS 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1
//#define PSA_WANT_ECC_MONTGOMERY_255 1
//#define PSA_WANT_ECC_MONTGOMERY_448 1
//#define PSA_WANT_ECC_SECP_K1_192 1
/*
* SECP224K1 is buggy via the PSA API in Mbed TLS
* (https://github.com/Mbed-TLS/mbedtls/issues/3541). Thus, do not enable it by
* default.
*/
//#define PSA_WANT_ECC_SECP_K1_224 1
//#define PSA_WANT_ECC_SECP_K1_256 1
//#define PSA_WANT_ECC_SECP_R1_192 1
//#define PSA_WANT_ECC_SECP_R1_224 1
#define PSA_WANT_ECC_SECP_R1_256 1
//#define PSA_WANT_ECC_SECP_R1_384 1
//#define PSA_WANT_ECC_SECP_R1_521 1
#define PSA_WANT_KEY_TYPE_DERIVE 1
#define PSA_WANT_KEY_TYPE_HMAC 1
#define PSA_WANT_KEY_TYPE_AES 1
//#define PSA_WANT_KEY_TYPE_ARIA 1
//#define PSA_WANT_KEY_TYPE_CAMELLIA 1
//#define PSA_WANT_KEY_TYPE_CHACHA20 1
//#define PSA_WANT_KEY_TYPE_DES 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_RAW_DATA 1
//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1
//#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
#endif /* PROFILE_M_PSA_CRYPTO_CONFIG_H */

View File

@ -0,0 +1,629 @@
/**
* \file config.h
*
* \brief Configuration options (set of defines)
*
* This set of compile-time options may be used to enable
* or disable features selectively, and reduce the global
* memory footprint.
*/
/*
* Copyright (C) 2006-2022, 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 PROFILE_M_MBEDTLS_CONFIG_H
#define PROFILE_M_MBEDTLS_CONFIG_H
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
/**
* \name SECTION: System support
*
* This section sets system specific settings.
* \{
*/
/**
* \def MBEDTLS_HAVE_ASM
*
* The compiler has support for asm().
*
* Requires support for asm() in compiler.
*
* Used in:
* library/aria.c
* library/timing.c
* include/mbedtls/bn_mul.h
*
* Required by:
* MBEDTLS_AESNI_C
* MBEDTLS_PADLOCK_C
*
* Comment to disable the use of assembly code.
*/
#define MBEDTLS_HAVE_ASM
/**
* \def MBEDTLS_PLATFORM_MEMORY
*
* Enable the memory allocation layer.
*
* By default mbed TLS uses the system-provided calloc() and free().
* This allows different allocators (self-implemented or provided) to be
* provided to the platform abstraction layer.
*
* Enabling MBEDTLS_PLATFORM_MEMORY without the
* MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide
* "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and
* free() function pointer at runtime.
*
* Enabling MBEDTLS_PLATFORM_MEMORY and specifying
* MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the
* alternate function at compile time.
*
* Requires: MBEDTLS_PLATFORM_C
*
* Enable this layer to allow use of alternative memory allocators.
*/
#define MBEDTLS_PLATFORM_MEMORY
/* \} name SECTION: System support */
/**
* \name SECTION: mbed TLS feature support
*
* This section sets support for features that are or are not needed
* within the modules that are enabled.
* \{
*/
/**
* \def MBEDTLS_MD2_PROCESS_ALT
*
* MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you
* alternate core implementation of symmetric crypto or hash function. Keep in
* mind that function prototypes should remain the same.
*
* This replaces only one function. The header file from mbed TLS is still
* used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags.
*
* Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will
* no longer provide the mbedtls_sha1_process() function, but it will still provide
* the other function (using your mbedtls_sha1_process() function) and the definition
* of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible
* with this definition.
*
* \note Because of a signature change, the core AES encryption and decryption routines are
* currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt,
* respectively. When setting up alternative implementations, these functions should
* be overridden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt
* must stay untouched.
*
* \note If you use the AES_xxx_ALT macros, then is is recommended to also set
* MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
* tables.
*
* Uncomment a macro to enable alternate implementation of the corresponding
* function.
*
* \warning MD2, MD4, MD5, DES and SHA-1 are considered weak and their use
* constitutes a security risk. If possible, we recommend avoiding
* dependencies on them, and considering stronger message digests
* and ciphers instead.
*
*/
#define MBEDTLS_AES_SETKEY_DEC_ALT
#define MBEDTLS_AES_DECRYPT_ALT
/**
* \def MBEDTLS_AES_ROM_TABLES
*
* Use precomputed AES tables stored in ROM.
*
* Uncomment this macro to use precomputed AES tables stored in ROM.
* Comment this macro to generate AES tables in RAM at runtime.
*
* Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb
* (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the
* initialization time before the first AES operation can be performed.
* It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c
* MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded
* performance if ROM access is slower than RAM access.
*
* This option is independent of \c MBEDTLS_AES_FEWER_TABLES.
*
*/
#define MBEDTLS_AES_ROM_TABLES
/**
* \def MBEDTLS_AES_FEWER_TABLES
*
* Use less ROM/RAM for AES tables.
*
* Uncommenting this macro omits 75% of the AES tables from
* ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES)
* by computing their values on the fly during operations
* (the tables are entry-wise rotations of one another).
*
* Tradeoff: Uncommenting this reduces the RAM / ROM footprint
* by ~6kb but at the cost of more arithmetic operations during
* runtime. Specifically, one has to compare 4 accesses within
* different tables to 4 accesses with additional arithmetic
* operations within the same table. The performance gain/loss
* depends on the system and memory details.
*
* This option is independent of \c MBEDTLS_AES_ROM_TABLES.
*
*/
#define MBEDTLS_AES_FEWER_TABLES
/**
* \def MBEDTLS_ECP_NIST_OPTIM
*
* Enable specific 'modulo p' routines for each NIST prime.
* Depending on the prime and architecture, makes operations 4 to 8 times
* faster on the corresponding curve.
*
* Comment this macro to disable NIST curves optimisation.
*/
#define MBEDTLS_ECP_NIST_OPTIM
/**
* \def MBEDTLS_ERROR_STRERROR_DUMMY
*
* Enable a dummy error function to make use of mbedtls_strerror() in
* third party libraries easier when MBEDTLS_ERROR_C is disabled
* (no effect when MBEDTLS_ERROR_C is enabled).
*
* You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're
* not using mbedtls_strerror() or error_strerror() in your application.
*
* Disable if you run into name conflicts and want to really remove the
* mbedtls_strerror()
*/
#define MBEDTLS_ERROR_STRERROR_DUMMY
/**
* \def MBEDTLS_NO_PLATFORM_ENTROPY
*
* Do not use built-in platform entropy functions.
* This is useful if your platform does not support
* standards like the /dev/urandom or Windows CryptoAPI.
*
* Uncomment this macro to disable the built-in platform entropy functions.
*/
#define MBEDTLS_NO_PLATFORM_ENTROPY
/**
* \def MBEDTLS_ENTROPY_NV_SEED
*
* Enable the non-volatile (NV) seed file-based entropy source.
* (Also enables the NV seed read/write functions in the platform layer)
*
* This is crucial (if not required) on systems that do not have a
* cryptographic entropy source (in hardware or kernel) available.
*
* Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C
*
* \note The read/write functions that are used by the entropy source are
* determined in the platform layer, and can be modified at runtime and/or
* compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used.
*
* \note If you use the default implementation functions that read a seedfile
* with regular fopen(), please make sure you make a seedfile with the
* proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at
* least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from
* and written to or you will get an entropy source error! The default
* implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE
* bytes from the file.
*
* \note The entropy collector will write to the seed file before entropy is
* given to an external source, to update it.
*/
// This macro is enabled in TFM Medium but is disabled here because it is
// incompatible with baremetal builds in Mbed TLS.
//#define MBEDTLS_ENTROPY_NV_SEED
/* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
*
* Enable key identifiers that encode a key owner identifier.
*
* This is only meaningful when building the library as part of a
* multi-client service. When you activate this option, you must provide an
* implementation of the type mbedtls_key_owner_id_t and a translation from
* mbedtls_svc_key_id_t to file name in all the storage backends that you
* you wish to support.
*
* Note that while this define has been removed from TF-M's copy of this config
* file, TF-M still passes this option to Mbed TLS during the build via CMake.
* Therefore we keep it in our copy. See discussion on PR #7426 for more info.
*
*/
#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
/**
* \def MBEDTLS_PSA_CRYPTO_SPM
*
* When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is built for SPM (Secure
* Partition Manager) integration which separates the code into two parts: a
* NSPE (Non-Secure Process Environment) and an SPE (Secure Process
* Environment).
*
* Module: library/psa_crypto.c
* Requires: MBEDTLS_PSA_CRYPTO_C
*
*/
#define MBEDTLS_PSA_CRYPTO_SPM
/**
* \def MBEDTLS_SHA256_SMALLER
*
* Enable an implementation of SHA-256 that has lower ROM footprint but also
* lower performance.
*
* The default implementation is meant to be a reasonnable compromise between
* performance and size. This version optimizes more aggressively for size at
* the expense of performance. Eg on Cortex-M4 it reduces the size of
* mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about
* 30%.
*
* Uncomment to enable the smaller implementation of SHA256.
*/
#define MBEDTLS_SHA256_SMALLER
/**
* \def MBEDTLS_PSA_CRYPTO_CONFIG
*
* This setting allows support for cryptographic mechanisms through the PSA
* API to be configured separately from support through the mbedtls API.
*
* When this option is disabled, the PSA API exposes the cryptographic
* mechanisms that can be implemented on top of the `mbedtls_xxx` API
* configured with `MBEDTLS_XXX` symbols.
*
* When this option is enabled, the PSA API exposes the cryptographic
* mechanisms requested by the `PSA_WANT_XXX` symbols defined in
* include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are
* automatically enabled if required (i.e. if no PSA driver provides the
* mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols
* in mbedtls_config.h.
*
* If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies
* an alternative header to include instead of include/psa/crypto_config.h.
*
* This feature is still experimental and is not ready for production since
* it is not completed.
*/
#define MBEDTLS_PSA_CRYPTO_CONFIG
/* \} name SECTION: mbed TLS feature support */
/**
* \name SECTION: mbed TLS modules
*
* This section enables or disables entire modules in mbed TLS
* \{
*/
/**
* \def MBEDTLS_AES_C
*
* Enable the AES block cipher.
*
* Module: library/aes.c
* Caller: library/cipher.c
* library/pem.c
* library/ctr_drbg.c
*
* This module is required to support the TLS ciphersuites that use the AES
* cipher.
*
* PEM_PARSE uses AES for decrypting encrypted keys.
*/
#define MBEDTLS_AES_C
/**
* \def MBEDTLS_CIPHER_C
*
* Enable the generic cipher layer.
*
* Module: library/cipher.c
*
* Uncomment to enable generic cipher wrappers.
*/
#define MBEDTLS_CIPHER_C
/**
* \def MBEDTLS_CTR_DRBG_C
*
* Enable the CTR_DRBG AES-based random generator.
* The CTR_DRBG generator uses AES-256 by default.
* To use AES-128 instead, enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY below.
*
* Module: library/ctr_drbg.c
* Caller:
*
* Requires: MBEDTLS_AES_C
*
* This module provides the CTR_DRBG AES random number generator.
*/
#define MBEDTLS_CTR_DRBG_C
/**
* \def MBEDTLS_ENTROPY_C
*
* Enable the platform-specific entropy code.
*
* Module: library/entropy.c
* Caller:
*
* Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C
*
* This module provides a generic entropy pool
*/
#define MBEDTLS_ENTROPY_C
/**
* \def MBEDTLS_ERROR_C
*
* Enable error code to error string conversion.
*
* Module: library/error.c
* Caller:
*
* This module enables mbedtls_strerror().
*/
#define MBEDTLS_ERROR_C
/**
* \def MBEDTLS_HKDF_C
*
* Enable the HKDF algorithm (RFC 5869).
*
* Module: library/hkdf.c
* Caller:
*
* Requires: MBEDTLS_MD_C
*
* This module adds support for the Hashed Message Authentication Code
* (HMAC)-based key derivation function (HKDF).
*/
#define MBEDTLS_HKDF_C /* Used for HUK deriviation */
/**
* \def MBEDTLS_MEMORY_BUFFER_ALLOC_C
*
* Enable the buffer allocator implementation that makes use of a (stack)
* based buffer to 'allocate' dynamic memory. (replaces calloc() and free()
* calls)
*
* Module: library/memory_buffer_alloc.c
*
* Requires: MBEDTLS_PLATFORM_C
* MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS)
*
* Enable this module to enable the buffer memory allocator.
*/
#define MBEDTLS_MEMORY_BUFFER_ALLOC_C
/**
* \def MBEDTLS_PK_C
*
* Enable the generic public (asymetric) key layer.
*
* Module: library/pk.c
*
* Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C
*
* Uncomment to enable generic public key wrappers.
*/
#define MBEDTLS_PK_C
/**
* \def MBEDTLS_PK_PARSE_C
*
* Enable the generic public (asymetric) key parser.
*
* Module: library/pkparse.c
*
* Requires: MBEDTLS_PK_C
*
* Uncomment to enable generic public key parse functions.
*/
#define MBEDTLS_PK_PARSE_C
/**
* \def MBEDTLS_PK_WRITE_C
*
* Enable the generic public (asymetric) key writer.
*
* Module: library/pkwrite.c
*
* Requires: MBEDTLS_PK_C
*
* Uncomment to enable generic public key write functions.
*/
#define MBEDTLS_PK_WRITE_C
/**
* \def MBEDTLS_PLATFORM_C
*
* Enable the platform abstraction layer that allows you to re-assign
* functions like calloc(), free(), snprintf(), printf(), fprintf(), exit().
*
* Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT
* or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned
* above to be specified at runtime or compile time respectively.
*
* \note This abstraction layer must be enabled on Windows (including MSYS2)
* as other module rely on it for a fixed snprintf implementation.
*
* Module: library/platform.c
* Caller: Most other .c files
*
* This module enables abstraction of common (libc) functions.
*/
#define MBEDTLS_PLATFORM_C
/**
* \def MBEDTLS_PSA_CRYPTO_C
*
* Enable the Platform Security Architecture cryptography API.
*
* Module: library/psa_crypto.c
*
* Requires: MBEDTLS_CTR_DRBG_C, MBEDTLS_ENTROPY_C
*
*/
#define MBEDTLS_PSA_CRYPTO_C
/**
* \def MBEDTLS_PSA_CRYPTO_STORAGE_C
*
* Enable the Platform Security Architecture persistent key storage.
*
* Module: library/psa_crypto_storage.c
*
* Requires: MBEDTLS_PSA_CRYPTO_C,
* either MBEDTLS_PSA_ITS_FILE_C or a native implementation of
* the PSA ITS interface
*/
// This macro is enabled in TFM Medium but is disabled here because it is
// incompatible with baremetal builds in Mbed TLS.
//#define MBEDTLS_PSA_CRYPTO_STORAGE_C
/* \} name SECTION: mbed TLS modules */
/**
* \name SECTION: General configuration options
*
* This section contains Mbed TLS build settings that are not associated
* with a particular module.
*
* \{
*/
/**
* \def MBEDTLS_CONFIG_FILE
*
* If defined, this is a header which will be included instead of
* `"mbedtls/mbedtls_config.h"`.
* This header file specifies the compile-time configuration of Mbed TLS.
* Unlike other configuration options, this one must be defined on the
* compiler command line: a definition in `mbedtls_config.h` would have
* no effect.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h"
/**
* \def MBEDTLS_USER_CONFIG_FILE
*
* If defined, this is a header which will be included after
* `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE.
* This allows you to modify the default configuration, including the ability
* to undefine options that are enabled by default.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_USER_CONFIG_FILE "/dev/null"
/**
* \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE
*
* If defined, this is a header which will be included instead of
* `"psa/crypto_config.h"`.
* This header file specifies which cryptographic mechanisms are available
* through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and
* is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h"
/**
* \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE
*
* If defined, this is a header which will be included after
* `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE.
* This allows you to modify the default configuration, including the ability
* to undefine options that are enabled by default.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null"
/** \} name SECTION: General configuration options */
/**
* \name SECTION: Module configuration options
*
* This section allows for the setting of module specific sizes and
* configuration options. The default values are already present in the
* relevant header files and should suffice for the regular use cases.
*
* Our advice is to enable options and change their values here
* only if you have a good reason and know the consequences.
*
* Please check the respective header file for documentation on these
* parameters (to prevent duplicate documentation).
* \{
*/
/* ECP options */
#define MBEDTLS_ECP_FIXED_POINT_OPTIM 0 /**< Disable fixed-point speed-up */
/* \} name SECTION: Customisation configuration options */
#if CRYPTO_NV_SEED
#include "tfm_mbedcrypto_config_extra_nv_seed.h"
#endif /* CRYPTO_NV_SEED */
#if !defined(CRYPTO_HW_ACCELERATOR) && defined(MBEDTLS_ENTROPY_NV_SEED)
#include "mbedtls_entropy_nv_seed_config.h"
#endif
#ifdef CRYPTO_HW_ACCELERATOR
#include "mbedtls_accelerator_config.h"
#endif
#endif /* PROFILE_M_MBEDTLS_CONFIG_H */

View File

@ -3,10 +3,18 @@ PANDOC = pandoc
default: all
all_markdown = \
mbed-crypto-storage-specification.md \
testing/driver-interface-test-strategy.md \
testing/invasive-testing.md \
testing/test-framework.md \
alternative-implementations.md \
mbed-crypto-storage-specification.md \
psa-crypto-implementation-structure.md \
psa-migration/psa-limitations.md \
psa-migration/strategy.md \
psa-migration/tasks-g2.md \
psa-migration/testing.md \
testing/driver-interface-test-strategy.md \
testing/invasive-testing.md \
testing/psa-storage-format-testing.md \
testing/test-framework.md \
tls13-support.md \
# This line is intentionally left blank
html: $(all_markdown:.md=.html)

View File

@ -1,7 +1,9 @@
Mbed Crypto storage specification
Mbed TLS storage specification
=================================
This document specifies how Mbed Crypto uses storage.
This document specifies how Mbed TLS uses storage.
Key storage was originally introduced in a product called Mbed Crypto, which was re-distributed via Mbed TLS and has since been merged into Mbed TLS.
This document contains historical information both from before and after this merge.
Mbed Crypto may be upgraded on an existing device with the storage preserved. Therefore:

View File

@ -71,3 +71,105 @@ In case of any error occurring at step 3 or 4, psa_fail_key_creation() is called
A driver of the Mbed TLS PSA Cryptography API implementation (Mbed TLS PSA driver in the following) is a driver in the sense that it is compliant with the PSA driver interface specification. But it is not an actual driver that drives some hardware. It implements cryptographic operations purely in software.
An Mbed TLS PSA driver C file is named psa_crypto_<driver_name>.c and its associated header file psa_crypto_<driver_name>.h. The functions implementing a driver entry point as defined in the PSA driver interface specification are named as mbedtls_psa_<driver name>_<entry point>(). As an example, the psa_crypto_rsa.c and psa_crypto_rsa.h are the files containing the Mbed TLS PSA driver implementing RSA cryptographic operations. This RSA driver implements among other entry points the "import_key" entry point. The function implementing this entry point is named mbedtls_psa_rsa_import_key().
## How to implement a new cryptographic mechanism
Summary of files to modify when adding a new algorithm or key type:
* [ ] PSA Crypto API draft, if not already done — [PSA standardization](#psa-standardization)
* [ ] `include/psa/crypto_values.h` or `include/psa/crypto_extra.h` — [New functions and macros](#new-functions-and-macros)
* [ ] `include/psa/crypto_config.h`, `tests/include/test/drivers/crypto_config_test_driver_extension.h` — [Preprocessor symbols](#preprocessor-symbols)
* Occasionally `library/check_crypto_config.h` — [Preprocessor symbols](#preprocessor-symbols)
* [ ] `include/mbedtls/config_psa.h` — [Preprocessor symbols](#preprocessor-symbols)
* [ ] `library/psa_crypto.c`, `library/psa_crypto_*.[hc]` — [Implementation of the mechanisms](#implementation-of-the-mechanisms)
* [ ] `include/psa/crypto_builtin_*.h` — [Translucent data structures](#translucent-data-structures)
* [ ] `tests/suites/test_suite_psa_crypto_metadata.data` — [New functions and macros](#new-functions-and-macros)
* (If adding `PSA_IS_xxx`) `tests/suites/test_suite_psa_crypto_metadata.function` — [New functions and macros](#new-functions-and-macros)
* [ ] `tests/suites/test_suite_psa_crypto*.data`, `tests/suites/test_suite_psa_crypto*.function` — [Unit tests](#unit-tests)
* [ ] `scripts/mbedtls_dev/crypto_knowledge.py`, `scripts/mbedtls_dev/asymmetric_key_data.py` — [Unit tests](#unit-tests)
* [ ] `ChangeLog.d/*.txt` — changelog entry
Summary of files to modify when adding new API functions:
* [ ] `include/psa/crypto.h` and `include/psa/crypto_sizes.h`, or `include/psa/crypto_extra.h` — [New functions and macros](#new-functions-and-macros)
* [ ] `library/psa_crypto.c`, `scripts/data_files/driver_templates/*.jinja` — [Implementation of the mechanisms](#implementation-of-the-mechanisms)
* [ ] If adding stateful functions: `include/psa/crypto_struct.h`, `include/psa/crypto_builtin_*.h`, `include/psa/crypto_driver_contexts_*.h` — [Translucent data structures](#translucent-data-structures)
* [ ] `tests/suites/test_suite_psa_crypto.data`, `tests/suites/test_suite_psa_crypto.function`, `tests/suites/test_suite_psa_crypto_driver_wrappers.*` — [Unit tests](#unit-tests)
Note that this is just a basic guide. In some cases, you won't need to change all the files listed here. In some cases, you may need to change other files.
### PSA standardization
Typically, if there's enough demand for a cryptographic mechanism in Mbed TLS, there's enough demand for it to be part of the official PSA Cryptography specification. Therefore the first step before implementing a new mechanism should be to approach the PSA Cryptography working group in Arm for standardization.
At the time of writing, all cryptographic mechanisms that are accessible through `psa_xxx` APIs in in Mbed TLS are current or upcoming PSA standards. Mbed TLS implements some extensions to the PSA API that offer extra integration customization or extra key policies.
Mbed TLS routinely implements cryptographic mechanisms that are not yet part of a published PSA standard, but that are scheduled to be part of a future version of the standard. The Mbed TLS implementation validates the feasibility of the upcoming PSA standard. The PSA Cryptography working group and the Mbed TLS development team communicate during the elaboration of the new interfaces.
### New functions and macros
If a mechanism requires new functions, they should follow the design guidelines in the PSA Cryptography API specification.
Functions that are part of the current or upcoming API are declared in `include/psa/crypto.h`, apart from structure accessors defined in `include/psa/crypto_struct.h`. Functions that have output buffers have associated sufficient-output-size macros in `include/psa/crypto_sizes.h`.
Constants (algorithm identifiers, key type identifiers, etc.) and associated destructor macros (e.g. `PSA_IS_xxx()`) are defined in `include/psa/crypto_values.h`.
Functions and macros that are not intended for standardization, or that are at a stage where the draft standard might still evolve significantly, are declared in `include/psa/crypto_extra.h`.
The PSA Cryptography API specification defines both names and values for certain kinds of constants: algorithms (`PSA_ALG_xxx`), key types (`PSA_KEY_TYPE_xxx`), ECC curve families (`PSA_ECC_FAMILY_xxx`), DH group families (`PSA_DH_FAMILY_xxx`). If Mbed TLS defines an algorithm or a key type that is not part of a current or upcoming PSA standard, pick a value with the `VENDOR` flag set. If Mbed TLS defines an ECC curve or DH group family that is not part of a current or upcoming PSA standard, define a vendor key type and use the family identifier only with this vendor key type.
New constants must have a test case in `tests/suites/test_suite_psa_crypto_metadata.data` that verifies that `PSA_IS_xxx` macros behave properly with the new constant. New `PSA_IS_xxx` macros must be declared in `tests/suites/test_suite_psa_crypto_metadata.function`.
### Preprocessor symbols
Each cryptographic mechanism is optional and can be selected by the application at build time. For each feature `PSA_ttt_xxx`:
* The feature is available to applications when the preprocessor symbol `PSA_WANT_ttt_xxx` is defined. These symbols are set:
* If `MBEDTLS_PSA_CRYPTO_CONFIG` is disabled: based on the available mechanisms in Mbed TLS, deduced from `mbedtls/mbedtls_config.h` by code in `include/mbedtls/config_psa.h`.
* if `MBEDTLS_PSA_CRYPTO_CONFIG` is enabled: in the application configuration file `include/psa/crypto_config.h` (or `MBEDTLS_PSA_CRYPTO_CONFIG_FILE`, plus `MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE`), with code in `include/mbedtls/config_psa.h` deducing the necessary underlying `MBEDTLS_xxx` symbols.
* For transparent keys (keys that are not in a secure element), the feature is implemented by Mbed TLS if `MBEDTLS_PSA_BUILTIN_ttt_xxx` is defined, and by an accelerator driver if `MBEDTLS_PSA_ACCEL_ttt_xxx` is defined. `MBEDTLS_PSA_BUILTIN_ttt_xxx` constants are set in `include/mbedtls/config_psa.h` based on the application requests `PSA_WANT_ttt_xxx` and the accelerator driver declarations `MBEDTLS_PSA_ACCEL_ttt_xxx`.
* For the testing of the driver dispatch code, `tests/include/test/drivers/crypto_config_test_driver_extension.h` sets additional `MBEDTLS_PSA_ACCEL_xxx` symbols.
For more details, see *[Conditional inclusion of cryptographic mechanism through the PSA API in Mbed TLS](../proposed/psa-conditional-inclusion-c.html)*.
Some mechanisms require other mechanisms. For example, you can't do GCM without a block cipher, or RSA-PSS without RSA keys. When mechanism A requires mechanism B, `include/mbedtls/config_psa.h` ensures that B is enabled whenever A is enabled. When mechanism A requires at least one of a set {B1, B2, B3, ...} but there is no particular reason why enabling A would enable any of the specific Bi's, it's up to the application to choose Bi's and the file `library/check_crypto_config.h` contains compile-time constraints to ensure that at least one Bi is enabled.
### Implementation of the mechanisms
The general structure of a cryptographic operation function is:
1. API function defined in `library/psa_crypto.c`. The entry point performs generic checks that don't depend on whether the mechanism is implemented in software or in a driver and looks up keys in the key store.
2. Driver dispatch code in `scripts/data_files/driver_templates/psa_crypto_driver_wrappers.c.jinja` or files included from there.
3. Built-in implementation in `library/psa_crypto_*.c` (with function declarations in the corresponding `.h` file). These files typically contain the implementation of modes of operation over basic building blocks that are defined elsewhere. For example, HMAC is implemented in `library/psa_crypto_mac.c` but the underlying hash functions are implemented in `library/sha*.c` and `library/md*.c`.
4. Basic cryptographic building blocks in `library/*.c`.
When implementing a new algorithm or key type, there are typically things to change in `library/crypto.c` (e.g. buffer size calculations, algorithm/key-type compatibility) and in the built-in implementation, but not in the driver dispatch code.
### Translucent data structures
Some mechanisms require state to be kept between function calls. Keys and key-like data is kept in the key store, which PSA manages internally. Other state, for example the state of multipart operations, is kept in structures allocated by the caller.
The size of operation structures needs to be known at compile time, since callers may allocate them on the stack. Therefore these structures are defined in a public header: `include/psa/crypto_struct.h` for the parts that are independent of the underlying implementation, `include/psa/crypto_builtin_*` for parts that are specific to the Mbed TLS built-in implementation, `include/psa/crypto_driver_*.h` for structures implemented by drivers.
### Unit tests
A number of unit tests are automatically generated by `tests/scripts/generate_psa_tests.py` based on the algorithms and key types declared in `include/psa/crypto_values.h` and `include/psa/crypto_extra.h`:
* Attempt to create a key with a key type that is not supported.
* Attempt to perform an operation with a combination of key type and algorithm that is not valid or not supported.
* Storage and retrieval of a persistent key.
When adding a new key type or algorithm:
* `scripts/mbedtls_dev/crypto_knowledge.py` contains knowledge about the compatibility of key types, key sizes and algorithms.
* `scripts/mbedtls_dev/asymmetric_key_data.py` contains valid key data for asymmetric key types.
Other things need to be tested manually, either in `tests/suites/test_sutie_psa_crypto.data` or in another file. For example (this is not an exhaustive list):
* Known answer tests.
* Potential edge cases (e.g. data less/equal/more than the block size, number equal to zero in asymmetric cryptography).
* Tests with invalid keys (e.g. wrong size or format).
* Tests with invalid data (e.g. wrong size or format, output buffer too small, invalid padding).
* For new functions: incorrect function call sequence, driver dispatch (in `tests/suites/test_suite_psa_crypto_driver_wrappers.*`).
* For key derivation algorithms: variation on the sequence of input steps, variation on the output size.

View File

@ -0,0 +1,536 @@
# PSA storage resilience design
## Introduction
The PSA crypto subsystem includes a persistent key store. It is possible to create a persistent key and read it back later. This must work even if the underlying storage exhibits non-nominal behavior. In this document, _resilience_ means correct behavior of the key store even under if the underlying platform behaves in a non-nominal, but still partially controlled way.
At this point, we are only concerned about one specific form of resilience: to a system crash or power loss. That is, we assume that the underlying platform behaves nominally, except that occasionally it may restart. In the field, this can happen due to a sudden loss of power.
This document explores the problem space, defines a library design and a test design.
## Resilience goals for API functions
**Goal: PSA Crypto API functions are atomic and committing.**
_Atomic_ means that when an application calls an API function, as far as the application is concerned, at any given point in time, the system is either in a state where the function has not started yet, or in a state where the function has returned. The application never needs to worry about an intermediate state.
_Committing_ means that when a function returns, the data has been written to the persistent storage. As a consequence, if the system restarts during a sequence of storage modifications $M_1, M_2, \ldots, M_n$, we know that when the system restarts, a prefix of the sequence has been performed. For example, there will never be a situation where $M_2$ has been performed but not $M_1$.
The committing property is important not only for sequences of operations, but also when reporting the result of an operation to an external system. For example, if a key creation function in the PSA Crypto API reports to the application that a key has been created, and the application reports to a server that the key has been created, it is guaranteed that the key exists even if the system restarts.
## Assumptions on the underlying file storage
PSA relies on a PSA ITS (Internal Trusted Storage) interface, which exposes a simple API. There are two functions to modify files:
* `set()` writes a whole file (either creating it, or replacing the previous content).
* `remove()` removes a file (returning a specific error code if the file does not exist).
**Assumption: the underlying ITS functions are atomic and committing.**
Since the underlying functions are atomic, the content of a file is always a version that was previously passed to `set()`. We do not try to handle the case where a file might be partially written.
## Overview of API functions
For a transparent key, all key management operations (creation or destruction) on persistent keys rely on a single call to the underlying storage (`set()` for a key creation, `remove()` for a key destruction). This also holds for an opaque key stored in a secure element that does not have its own key store: in this case, the core stores a wrapped (i.e. encrypted) copy of the key material, but this does not impact how the core interacts with the storage. Other API functions do not modify the storage.
The following case requires extra work related to resilience:
* [Key management for stateful secure element keys](#designing-key-management-for-secure-element-keys).
As a consequence, apart from the listed cases, the API calls inherit directly from the [resilience properties of the underyling storage](#assumptions-on-the-underlying-file-storage). We do not need to take any special precautions in the library design, and we do not need to perform any testing of resilience for transparent keys.
(This section was last updated for Mbed TLS 3.4.0 implementing PSA Crypto API 1.1.)
## Designing key management for secure element keys
In this section, we use “(stateful) secure element key” to mean a key stored in a stateful secure element, i.e. a secure element that stores keys. This excludes keys in a stateleess secure element for which the core stores a wrapped copy of the key. We study the problem of how key management in stateful secure elements interacts with storage and explore the design space.
### Assumptions on stateful secure elements
**Assumption: driver calls for key management in stateful secure elements are atomic and committing.**
(For stateless secure elements, this assumption is vacuously true.)
### Dual management of keys: the problem
For a secure element key, key management requires a commitment on both sites. For example, consider a successful key creation operation:
1. The core sends a request to the secure element to create a key.
2. The secure element modifies its key store to create the key.
3. The secure element reports to the core that the key has been created.
4. The core reports to the application that the key has been created.
If the core loses power between steps 1 and 2, the key does not exist yet. This is fine from an application's perspective since the core has not committed to the key's existence, but the core needs to take care not to leave resources in storage that are related to the non-existent key. If the core loses power between steps 2 and 3, the key exists in the secure element. From an application's perspective, the core may either report that the key exists or that it does not exist, but in the latter case, the core needs to free the key in the secure element, to avoid leaving behind inaccessible resources.
As a consequence, the content of the storage cannot remain the same between the end of step 1 and the end of step 3, since the core must behave differently depending on whether step 2 has taken place.
Accomplishing a transaction across system boundaries is a well-known problem in database management, with a well-known solution: two-phase commit.
### Overview of two-phase commit with stateful secure elements
With a key in a stateful secure element, a successful creation process goes as follows (see [“Key management in a secure element with storage” in the driver interface specification](../../proposed/psa-driver-interface.html#key-management-in-a-secure-element-with-storage)):
1. The core calls the driver's `"allocate_key"` entry point.
2. The driver allocates a unique identifier _D_ for the key. This is unrelated to the key identifier _A_ used by the application interface. This step must not modify the state of the secure element.
3. The core updates the storage to indicate that key identifier _A_ has the identifier _D_ in the driver, and that _A_ is in a half-created state.
4. The core calls the driver's key creation entry point, passing it the driver's chosen identifier _D_.
5. The driver creates the key in the secure element. When this happens, it concludes the voting phase of the two-phase commit: effectively, the secure element decides to commit. (It is however possible to revert this commitment by giving the secure element the order to destroy the key.)
6. The core updates the storage to indicate that _A_ is now in a fully created state. This concludes the commit phase of the two-phase commit.
If there is a loss of power:
* Before step 3: the system state has not changed at all. As far as the world is concerned, the key creation attempt never happened.
* Between step 3 and step 6: upon restart, the core needs to find out whether the secure element completed step 5 or not, and reconcile the state of the storage with the state of the secure element.
* After step 6: the key has been created successfully.
Key destruction goes as follows:
1. The core updates the storage indicating that the key is being destroyed.
2. The core calls the driver's `"destroy_key"` entry point.
3. The secure element destroys the key.
4. The core updates the storage to indicate that the key has been destroyed.
If there is a loss of power:
* Before step 1: the system state has not changed at all. As far as the world is concerned, the key destruction attempt never happened.
* Between step 1 and step 4: upon restart, the core needs to find out whether the secure element completed step 3 or not, and reconcile the state of the storage with the state of the secure element.
* After step 4: the key has been destroyed successfully.
In both cases, upon restart, the core needs to perform a transaction recovery. When a power loss happens, the core decides whether to commit or abort the transaction.
Note that the analysis in this section assumes that the driver does not update its persistent state during a key management operation (or at least not in a way that is influences the key management process — for example, it might renew an authorization token).
### Optimization considerations for transactions
We assume that power failures are rare. Therefore we will primarily optimize for the normal case. Transaction recovery needs to be practical, but does not have to be fully optimized.
The main quantity we will optimize for is the number of storage updates in the nominal case. This is good for performance because storage writes are likely to dominate the runtime in some hardware configurations where storage writes are slow and communication with the secure element is fast, for key management operations that require a small amount of computation. In addition, minimizing the number of storage updates is good for the longevity of flash media.
#### Information available during recovery
The PSA ITS API does not support enumerating files in storage: an ITS call can only access one file identifier. Therefore transaction recovery cannot be done by traversing files whose name is or encodes the key identifier. It must start by traversing a small number of files whose names are independent of the key identifiers involved.
#### Minimum effort for a transaction
Per the [assumptions on the underlying file storage](#assumptions-on-the-underlying-file-storage), each atomic operation in the internal storage concerns a single file: either removing it, or setting its content. Furthermore there is no way to enumerate the files in storage.
A key creation function must transform the internal storage from a state where file `id` does not exist, to a state where file `id` exists and has its desired final content (containing the key attributes and the driver's key identifier). The situation is similar with key destruction, except that the initial and final states are exchanged. Neither the initial state nor the final state reference `id` otherwise.
For a key that is not in a stateful element, the transaction consists of a single write operation. As discussed previously, this is not possible with a stateful secure element because the state of the internal storage needs to change both before and after the state change in the secure element. No other single-write algorithm works.
If there is a power failure around the time of changing the state of the secure element, there must be information in the internal storage that indicates that key `id` has a transaction in progress. The file `id` cannot be used for this purpose because there is no way to enumerate all keys (and even if there was, it would not be practical). Therefore the transaction will need to modify some other file `t` with a fixed name (a name that doesn't depend on the key). Since the final system state should be identical to the initial state except for the file `id`, the minimum number of storage operations for a transaction is 3:
* Write (create or update) a file `t` referencing `id`.
* Write the final state of `id`.
* Restore `t` to its initial state.
The strategies discussed in the [overview above](#overview-of-two-phase-commit-with-stateful-secure-elements) follow this pattern, with `t` being the file containing the transaction list that the recovery consults. We have just proved that this pattern is optimal.
Note that this pattern requires the state of `id` to be modified only once. In particular, if a key management involves writing an intermediate state for `id` before modifying the secure element state and writing a different state after that, this will require a total of 4 updates to internal storage. Since we want to minimize the number of storage updates, we will not explore designs that involved updating `id` twice or more.
### Recovery strategies
When the core starts, it needs to know about transaction(s) that need to be resumed. This information will be stored in a persistent “transaction list”, with one entry per key. In this section, we explore recovery strategies, and we determine what the transaction list needs to contain as well as when it needs to be updated. Other sections will explore the format of the transaction list, as well as how many keys it needs to contain.
#### Exploring the recovery decision tree
There are four cases for recovery when a transaction is in progress. In each case, the core can either decide to commit the transaction (which may require replaying the interrupted part) or abort it (which may require a rewind in the secure element). It may call the secure element driver's `"get_key_attributes"` entry point to find out whether the key is present.
* Key creation, key not present in the secure element:
* Committing means replaying the driver call in the key creation. This requires all the input, for example the data to import. This seems impractical in general. Also, the second driver call require a new call to `"allocate_key"` which will in general changing the key's driver identifier, which complicates state management in the core. Given the likely complexity, we exclude this strategy.
* Aborting means removing any trace of the key creation.
* Key creation, key present in the secure element:
* Committing means finishing the update of the core's persistent state, as would have been done if the transaction had not been interrupted.
* Aborting means destroying the key in the secure element and removing any local storage used for that key.
* Key destruction, key not present in the secure element:
* Committing means finishing the update of the core's persistent state, as would have been done if the transaction had not been interrupted, by removing any remaining local storage used for that key.
* Aborting would mean re-creating the key in the secure element, which is impossible in general since the key material is no longer present.
* Key destruction, key present in the secure element:
* Committing means finishing the update of the core's persistent state, as would have been done if the transaction had not been interrupted, by removing any remaining local storage used for that key and destroying the key in the secure element.
* Aborting means keeping the key. This requires no action on the secure element, and is only practical locally if the local storage is intact.
#### Comparing recovery strategies
From the analysis above, assuming that all keys are treated in the same way, there are 4 possible strategies.
* [Always follow the state of the secure element](#exploring-the-follow-the-secure-element-strategy). This requires the secure element driver to have a `"get_key_attributes"` entry point. Recovery means resuming the operation where it left off. For key creation, this means that the key metadata needs to be saved before calling the secure element's key creation entry point.
* Minimize the information processing: [always destroy the key](#exploring-the-always-destroy-strategy), i.e. abort all key creations and commit all key destructions. This does not require querying the state of the secure element. This does not require any special precautions to preserve information about the key during the transaction. It simplifies recovery in that the recovery process might not even need to know whether it's recovering a key creation or a key destruction.
* Follow the state of the secure element for key creation, but always go ahead with key destruction. This requires the secure element driver to have a `"get_key_attributes"` entry point. Compared to always following the state of the secure element, this has the advantage of maximizing the chance that a command to destroy key material is effective. Compared to always destroying the key, this has a performance advantage if a key creation is interrupted. These do not seem like decisive advantages, so we will not consider this strategy further.
* Always abort key creation, but follow the state of the secure element for key destruction. I can't think of a good reason to choose this strategy.
Requiring the driver to have a `"get_key_attributes"` entry point is potentially problematic because some secure elements don't have room to store key attributes: a key slot always exists, and it's up to the user to remember what, if anything, they put in it. The driver has to remember anyway, so that it can find a free slot when creating a key. But with a recovery strategy that doesn't involve a `"get_key_attributes"` entry point, the driver design is easier: the driver doesn't need to protect the information about slots in use against a power failure, the core takes care of that.
#### Exploring the follow-the-secure-element strategy
Each entry in the transaction list contains the API key identifier, the key lifetime (or at least the location), the driver key identifier (not constant-size), and an indication of whether the key is being created or destroyed.
For key creation, we have all the information to store in the key file once the `"allocate_key"` call returns. We must store all the information that will go in the key file before calling the driver's key creation entry point. Therefore the normal sequence of operations is:
1. Call the driver's `"allocate_key"` entry point.
2. Add the key to the transaction list, indicating that it is being created.
3. Write the key file.
4. Call the driver's key creation entry point.
5. Remove the key from the transaction list.
During recovery, for each key in the transaction list that was being created:
* If the key exists in the secure element, just remove it from the transaction list.
* If the key does not exist in the secure element, first remove the key file if it is present, then remove the key from the transaction list.
For key destruction, we need to preserve the key file until after the key has been destroyed. Therefore the normal sequence of operations is:
1. Add the key to the transaction list, indicating that it is being destroyed.
2. Call the driver's `"destroy_key"` entry point.
3. Remove the key file.
4. Remove the key from the transaction list.
During recovery, for each key in the transaction list that was being created:
* If the key exists in the secure element, call the driver's `"destroy_key"` entry point, then remove the key file, and finally remote the key from the transaction lits.
* If the key does not exist in the secure element, remove the key file if it is still present, then remove the key from the transaction list.
#### Exploring the always-destroy strategy
Each entry in the transaction list contains the API key identifier, the key lifetime (or at least the location), and the driver key identifier (not constant-size).
For key creation, we do not need to store the key's metadata until it has been created in the secure element. Therefore the normal sequence of operations is:
1. Call the driver's `"allocate_key"` entry point.
2. Add the key to the transaction list.
3. Call the driver's key creation entry point.
4. Write the key file.
5. Remove the key from the transaction list.
For key destruction, we can remove the key file before contacting the secure element. Therefore the normal sequence of operations is:
1. Add the key to the transaction list.
2. Remove the key file.
3. Call the driver's `"destroy_key"` entry point.
4. Remove the key from the transaction list.
Recovery means removing all traces of all keys on the transaction list. This means following the destruction process, starting after the point where the key has been added to the transaction list, and ignoring any failure of a removal action if the item to remove does not exist:
1. Remove the key file, treating `DOES_NOT_EXIST` as a success.
2. Call the driver's `"destroy_key"` entry point, treating `DOES_NOT_EXIST` as a success.
3. Remove the key from the transaction list.
#### Always-destroy strategy with a simpler transaction file
We can modify the [always-destroy strategy](#exploring-the-always-destroy-strategy) to make the transaction file simpler: if we ensure that the key file always exists if the key exists in the secure element, then the transaction list does not need to include the driver key identifier: it can be read from the key file.
For key creation, we need to store the key's metadata before creating in the secure element. Therefore the normal sequence of operations is:
1. Call the driver's `"allocate_key"` entry point.
2. Add the key to the transaction list.
3. Write the key file.
4. Call the driver's key creation entry point.
5. Remove the key from the transaction list.
For key destruction, we need to contact the secure element before removing the key file. Therefore the normal sequence of operations is:
1. Add the key to the transaction list.
2. Call the driver's `"destroy_key"` entry point.
3. Remove the key file.
4. Remove the key from the transaction list.
Recovery means removing all traces of all keys on the transaction list. This means following the destruction process, starting after the point where the key has been added to the transaction list, and ignoring any failure of a removal action if the item to remove does not exist:
1. Load the driver key identifier from the key file. If the key file does not exist, skip to step 4.
2. Call the driver's `"destroy_key"` entry point, treating `DOES_NOT_EXIST` as a success.
3. Remove the key file, treating `DOES_NOT_EXIST` as a success.
4. Remove the key from the transaction list.
Compared with the basic always-destroy strategy:
* The transaction file handling is simpler since its entries have a fixed size.
* The flow of information is somewhat different from transparent keys and keys in stateless secure elements: we aren't just replacing “create the key material” by “tell the secure element to create the key material”, those happen at different times. But there's a different flow for stateful secure elements anyway, since the call to `"allocate_key"` has no analog in the stateless secure element or transparent cases.
#### Assisting secure element drivers with recovery
The actions of the secure element driver may themselves be non-atomic. So the driver must be given a chance to perform recovery.
To simplify the design of the driver, the core should guarantee that the driver will know if a transaction was in progress and the core cannot be sure about the state of the secure element. Merely calling a read-only entry point such as `"get_key_attributes"` does not provide enough information to the driver for it to know that it should actively perform recovery related to that key.
This gives an advantage to the “always destroy” strategy. Under this strategy, if the key might be in a transitional state, the core will request a key destruction from the driver. This means that, if the driver has per-key auxiliary data to clean up, it can bundle that as part of the key's destruction.
### Testing non-atomic processes
In this section, we discuss how to test non-atomic processes that must implement an atomic and committing interface. As discussed in [“Overview of API functions”](#overview-of-api-functions), this concerns key management in stateful secure elements.
#### Naive test strategy for non-atomic processes
Non-atomic processes consist of a series of atomic, committing steps.
Our general strategy to test them is as follows: every time there is a modification of persistent state, either in storage or in the (simulated) secure element, try both the nominal case and simulating a power loss. If a power loss occurs, restart the system (i.e. clean up and call `psa_crypto_init()`), and check that the system ends up in a consistent state.
Note that this creates a binary tree of possibilities: after each state modification, there may or may not be a restart, and after that different state modifications may occur, each of which may or may not be followed by a restart.
For example, consider testing of one key creation operation (see [“Overview of two-phase commit with stateful secure elements”](#overview-of-two-phase-commit-with-stateful-secure-elements), under the simplifying assumption that each storage update step, as well as the recovery after a restart, each make a single (atomic) storage modification and no secure element access. The nominal case consists of three state modifications: storage modification (start transaction), creation on the secure element, storage modification (commit transaction). We need to test the following sequences:
* Start transaction, restart, recovery.
* Start transaction, secure element operation, restart, recovery.
* Start transaction, secure element operation, commit transaction.
If, for example, recovery consists of two atomic steps, the tree of possibilities expands and may be infinite:
* Start transaction, restart, recovery step 1, restart, recovery step 1, recovery step 2.
* Start transaction, restart, recovery step 1, restart, recovery step 1, restart, recovery step 1, recovery step 2.
* Start transaction, restart, recovery step 1, restart, recovery step 1, restart, recovery step 1, restart, recovery step 1, recovery step 2.
* etc.
* Start transaction, secure element operation, restart, ...
* Start transaction, secure element operation, commit transaction.
In order to limit the possibilities, we need to make some assumptions about the recovery step. For example, if we have confidence that recovery step 1 is idempotent (i.e. doing it twice is the same as doing it once), we don't need to test what happens in execution sequences that take recovery step 1 more than twice in a row.
### Splitting normal behavior and transaction recovery
We introduce an abstraction level in transaction recovery:
* Normal operation must maintain a certain invariant on the state of the world (internal storage and secure element).
* Transaction recovery is defined over all states of the world that satisfy this invariant.
This separation of concerns greatly facilitates testing, since it is now split into two parts:
* During the testing of normal operation, we can use read-only invasive testing to ensure that the invariant is maintained. No modification of normal behavior (such as simulated power failures) is necessary.
* Testing of transaction recovery is independent of how the system state was reached. We only need to artificially construct a representative sample of system states that match the invariant. Transaction recovery is itself an operation that must respect the invariant, and so we do not need any special testing for the case of an interrupted recovery.
Another benefit of this approach is that it is easier to specify and test what happens if the library is updated on a device with leftovers from an interrupted transaction. We will require and test that the new version of the library supports recovery of the old library's states, without worrying how those states were reached.
#### Towards an invariant for transactions
As discussed in the section [“Recovery strategies”](#recovery-strategies), the information about active transactions is stored in a transaction list file. The name of the transaction list file does not depend on the identifiers of the keys in the list, but there may be more than one transaction list, for example one per secure element. If so, each transaction list can be considered independently.
When no transaction is in progress, the transaction list does not exist, or is empty. The empty case must be supported because this is the initial state of the filesystem. When no transaction is in progress, the state of the secure element must be consistent with references to keys in that secure element contained in key files. More generally, if a key is not in the transaction list, then the key must be present in the secure element if and only if the key file is in the internal storage.
For the purposes of the state invariant, it matters whether the transaction list file contains the driver key identifier, or if the driver key identifier is only stored in the key file. This is because the core needs to know the driver key id in order to access the secure element. If the transaction list does not contain the driver key identifier, and the key file does not exist, the key must not be present in the secure element.
We thus have two scenarios, each with their own invariant: one where the transaction list contains only key identifiers, and one where it also contains the secure element's key identifier (as well as the location of the secure element if this is not encoded in the name of the transaction list file).
#### Storage invariant if the transaction list contains application key identifiers only
Invariants:
* If the file `id` does not exist, then no resources corresponding to that key are in a secure element. This holds whether `id` is in the transaction list or not.
* If `id` is not in the transaction list and the file `id` exists and references a key in a stateful secure element, then the key is present in the secure element.
If `id` is in the transaction list and the file `id` exists, the key may or may not be present in the secure element.
The invariant imposes constraints on the [order of operations for the two-phase commit](#overview-of-two-phase-commit-with-stateful-secure-elements): key creation must create `id` before calling the secure element's key creation entry point, and key destruction must remove `id` after calling the secure element's key destruction entry point.
For recovery:
* If the file `id` does not exist, then nothing needs to be done for recovery, other than removing `id` from the transaction list.
* If the file `id` exists:
* It is correct to destroy the key in the secure element (treating a `DOES_NOT_EXIST` error as a success), then remove `id`.
* It is correct to check whether the key exists in the secure element, and if it does, keep it and keep `id`. If not, remove `id` from the internal storage.
#### Storage invariant if the transaction list contains driver key identifiers
Invariants:
* If `id` is not in the transaction list and the file `id` does not exist, then no resources corresponding to that key are in a secure element.
* If `id` is not in the transaction list and the file `id` exists, then the key is present in the secure element.
If `id` is in the transaction list, neither the state of `id` in the internal storage nor the state of the key in the secure element is known.
For recovery:
* If the file `id` does not exist, then destroy the key in the secure element (treating a `DOES_NOT_EXIST` error as a success).
* If the file `id` exists:
* It is correct to destroy the key in the secure element (treating a `DOES_NOT_EXIST` error as a success), then remove `id`.
* It is correct to check whether the key exists in the secure element, and if it does, keep it and keep `id`. If not, remove `id` from the internal storage.
#### Coverage of states that respect the invariant
For a given key, we have to consider three a priori independent boolean states:
* Whether the key file exists.
* Whether the key is in the secure element.
* Whether the key is in the transaction list.
There is full coverage for one key if we have tests of recovery for the states among these $2^3 = 8$ possibilities that satisfy the storage invariant.
In addition, testing should adequately cover the case of multiple keys in the transaction list. How much coverage is adequate depends on the layout of the list as well as white-box considerations of how the list is manipulated.
### Choice of a transaction design
#### Chosen transaction algorithm
Based on [“Optimization considerations for transactions”](#optimization-considerations-for-transactions), we choose a transaction algorithm that consists in the following operations:
1. Add the key identifier to the transaction list.
2. Call the secure element's key creation or destruction entry point.
3. Remove the key identifier from the transaction list.
In addition, before or after step 2, create or remove the key file in the internal storage.
In order to conveniently support multiple transactions at the same time, we pick the simplest possible layout for the transaction list: a simple array of key identifiers. Since the transaction list does not contain the driver key identifier:
* During key creation, create the key file in internal storage in the internal storage before calling the secure element's key creation entry point.
* During key destruction, call the secure element's key destruction entry point before removing the key file in internal storage.
This choice of algorithm does not require the secure element driver to have a `"get_key_attributes"` entry point.
#### Chosen storage invariant
The [storage invariant](#storage-invariant-if-the-transaction-list-contains-application-key-identifiers-only) is as follows:
* If the file `id` does not exist, then no resources corresponding to that key are in a secure element. This holds whether `id` is in the transaction list or not.
* If `id` is not in the transaction list and the file `id` exists and references a key in a stateful secure element, then the key is present in the secure element.
* If `id` is in the transaction list and a key exists by that identifier, the key's location is a stateful secure element.
#### Chosen recovery process
To [assist secure element drivers with recovery](#assisting-secure-element-drivers-with-recovery), we pick the [always-destroy recovery strategy with a simple transaction file](#always-destroy-strategy-with-a-simpler-transaction-file). The the recovery process is as follows:
* If the file `id` does not exist, then nothing needs to be done for recovery, other than removing `id` from the transaction list.
* If the file `id` exists, call the secure element's key destruction entry point (treating a `DOES_NOT_EXIST` error as a success), then remove `id`.
## Specification of key management in stateful secure elements
This section only concerns stateful secure elements as discussed in [“Designing key management for secure element keys”](#designing-key-management-for-secure-element-keys), i.e. secure elements with an `"allocate_key"` entry point. The design follows the general principle described in [“Overview of two-phase commit with stateful secure elements”](#overview-of-two-phase-commit-with-stateful-secure-elements) and the specific choices justified in [“Choice of a transaction design”](choice-of-a-transaction-design).
### Transaction list file manipulation
The transaction list is a simple array of key identifiers.
To add a key identifier to the list:
1. Load the current list from the transaction list if it exists and it is not already cached in memory.
2. Append the key identifier to the array.
3. Write the updated list file.
To remove a key identifier from the list:
1. Load the current list if it is not already cached in memory. It is an error if the file does not exist since it must contain this identifier.
2. Remove the key identifier from the array. If it wasn't the last element in array, move array elements to fill the hole.
3. If the list is now empty, remove the transaction list file. Otherwise write the updated list to the file.
### Key creation process in the core
Let _A_ be the application key identifier.
1. Call the driver's `"allocate_key"` entry point, obtaining the driver key identifier _D_ chosen by the driver.
2. Add _A_ [to the transaction list file](#transaction-list-file-manipulation).
3. Create the key file _A_ in the internal storage. Note that this is done at a different time from what happens when creating a transparent key or a key in a stateless secure element: in those cases, creating the key file happens after the actual creation of the key material.
4. Call the secure element's key creation entry point.
5. Remove _A_ [from the transaction list file](#transaction-list-file-manipulation).
If any step fails:
* If the secure element's key creation entry point has been called and succeeded, call the secure element's destroy entry point.
* If the key file has been created in the internal storage, remove it.
* Remove the key from the transaction list.
Note that this process is identical to key destruction, except that the key is already in the transaction list.
### Key destruction process in the core
Let _A_ be the application key identifier.
We assume that the key is loaded in a key slot in memory: the core needs to know the key's location in order to determine whether the key is in a stateful secure element, and if so to know the driver key identifier. A possible optimization would be to load only that information in local variables, without occupying a key store; this has the advantage that key destruction works even if the key store is full.
1. Add _A_ [to the transaction list file](#transaction-list-file-manipulation).
2. Call the secure element's `"destroy_key"` entry point.
3. Remove the key file _A_ from the internal storage.
4. Remove _A_ [from the transaction list file](#transaction-list-file-manipulation).
5. Free the corresponding key slot in memory.
If any step fails, remember the error but continue the process, to destroy the resources associated with the key as much as is practical.
### Transaction recovery
For each key _A_ in the transaction list file, if the file _A_ exists in the internal storage:
1. Load the key into a key slot in memory (to get its location and the driver key identifier, although we could get the location from the transaction list).
2. Call the secure element's `"destroy_key"` entry point.
3. Remove the key file _A_ from the internal storage.
4. Remove _A_ [from the transaction list file](#transaction-list-file-manipulation).
5. Free the corresponding key slot in memory.
The transaction list file can be processed in any order.
It is correct to update the transaction list after recovering each key, or to only delete the transaction list file once the recovery is over.
### Concrete format of the transaction list file
The transaction list file contains a [fixed header](#transaction-list-header-format) followed by a list of [fixed-size elements](#transaction-list-element-format).
The file uid is `PSA_CRYPTO_ITS_TRANSACTION_LIST_UID` = 0xffffff53.
#### Transaction list header format
* Version (2 bytes): 0x0003. (Chosen to differ from the first two bytes of a [dynamic secure element transaction file](#dynamic-secure-element-transaction-file), to reduce the risk of a mix-up.)
* Key name size (2 bytes): `sizeof(psa_storage_uid_t)`. Storing this size avoids reading bad data if Mbed TLS is upgraded to a different integration that names keys differently.
#### Transaction list element format
In practice, there will rarely be more than one active transaction at a time, so the size of an element is not critical for efficiency. Therefore, in addition to the key identifier which is required, we add some potentially useful information in case it becomes useful later. We do not put the driver key identifier because its size is not a constant.
* Key id: `sizeof(psa_storage_uid_t)` bytes.
* Key lifetime: 4 bytes (`sizeof(psa_key_lifetime_t)`). Currently unused during recovery.
* Operation type: 1 byte. Currently unused during recovery.
* 0: destroy key.
* 1: import key.
* 2: generate key.
* 3: derive key.
* 4: import key.
* Padding: 3 bytes. Reserved for future use. Currently unused during recovery.
#### Dynamic secure element transaction file
Note that the code base already references a “transaction file” (`PSA_CRYPTO_ITS_TRANSACTION_UID` = 0xffffff54), used by dynamic secure elements (feature enabled with `MBEDTLS_PSA_CRYPTO_SE_C`). This is a deprecated feature that has not been fully implemented: when this feature is enabled, the transaction file gets written during transactions, but if it exists when PSA crypto starts, `psa_crypto_init()` fails because [recovery has never been implemented](https://github.com/ARMmbed/mbed-crypto/issues/218).
For the new kind of secure element driver, we pick a different file name to avoid any mixup.
## Testing key management in secure elements
### Instrumentation for checking the storage invariant
#### Test hook locations
When `MBEDTLS_TEST_HOOKS` is enabled, each call to `psa_its_set()` or `psa_its_remove()` also calls a test hook, passing the file UID as an argument to the hook.
When a stateful secure element driver is present in the build, we use this hook to verify that the storage respects the [storage invariant](#chosen-storage-invariant). In addition, if there is some information about key ongoing operation (set explicitly by the test function as a global variable in the test framework), the hook tests that the content of the storage is compatible with the ongoing operation.
#### Test hook behavior
The storage invariant check cannot check all keys in storage, and does not need to (for example, it would be pointless to check anything about transparent keys). It checks the following keys:
* When invoked from the test hook on a key file: on that key.
* When invoked from the test hook on the transaction file: on all the keys listed in the transaction file.
* When invoked from a test secure element: on the specified key.
#### Test hook extra data
Some tests set global variables to indicate which persistent keys they manipulate. We instrument at least some of these tests to also indicate what operation is in progress on the key. See the GitHub issues or the source code for details.
### Testing of transaction recovery
When no secure element driver is present in the build, the presence of a transaction list file during initialization is an error.
#### Recovery testing process
When the stateful test secure element driver is present in the build, we run test cases on a representative selection of states of the internal storage and the test secure element. Each test case for transaction recovery has the following form:
1. Create the initial state:
* Create a transaction list file with a certain content.
* Create key files that we want to have in the test.
* Call the secure element test driver to create keys without going throught the PSA API.
2. Call `psa_crypto_init()`. Expect success if the initial state satisfies the [storage invariant](#chosen-storage-invariant) and failure otherwise.
3. On success, check that the expected keys exist, and that keys that are expected to have been destroyed by recovery do not exist.
4. Clean up the storage and the secure element test driver's state.
#### States to test recovery on
For a given key located in a secure element, the following combination of states are possible:
* Key file: present, absent.
* Key in secure element: present, absent.
* Key in the transaction file: no, creation (import), destruction.
We test all $2 \times 2 \times 3 = 12$ possibilities, each in its own test case. In each case, call the test function that checks the storage invariant and check that its result is as expected. Then, if the storage invariant is met, follow the [recovery testing process](#recovery-testing-process).
In addition, have at least one positive test case for each creation method other than import, to ensure that we don't reject a valid value.
Note: testing of a damaged filesystem (including a filesystem that doesn't meet the invariant) is out of scope of the present document.

View File

@ -1,6 +1,6 @@
# Mbed Crypto driver interface test strategy
# Mbed TLS driver interface test strategy
This document describes the test strategy for the driver interfaces in Mbed Crypto. Mbed Crypto has interfaces for secure element drivers, accelerator drivers and entropy drivers. This document is about testing Mbed Crypto itself; testing drivers is out of scope.
This document describes the test strategy for the driver interfaces in Mbed TLS. Mbed TLS has interfaces for secure element drivers, accelerator drivers and entropy drivers. This document is about testing Mbed TLS itself; testing drivers is out of scope.
The driver interfaces are standardized through PSA Cryptography functional specifications.
@ -16,9 +16,9 @@ Drivers exposing this interface need to be registered at compile time by declari
#### Dynamic secure element driver interface
The dynamic secure element driver interface (SE interface for short) is defined by [`psa/crypto_se_driver.h`](../../../include/psa/crypto_se_driver.h). This is an interface between Mbed Crypto and one or more third-party drivers.
The dynamic secure element driver interface (SE interface for short) is defined by [`psa/crypto_se_driver.h`](../../../include/psa/crypto_se_driver.h). This is an interface between Mbed TLS and one or more third-party drivers.
The SE interface consists of one function provided by Mbed Crypto (`psa_register_se_driver`) and many functions that drivers must implement. To make a driver usable by Mbed Crypto, the initialization code must call `psa_register_se_driver` with a structure that describes the driver. The structure mostly contains function pointers, pointing to the driver's methods. All calls to a driver function are triggered by a call to a PSA crypto API function.
The SE interface consists of one function provided by Mbed TLS (`psa_register_se_driver`) and many functions that drivers must implement. To make a driver usable by Mbed TLS, the initialization code must call `psa_register_se_driver` with a structure that describes the driver. The structure mostly contains function pointers, pointing to the driver's methods. All calls to a driver function are triggered by a call to a PSA crypto API function.
### SE driver interface unit tests
@ -57,7 +57,7 @@ For each API function that can lead to a driver call (more precisely, for each d
#### SE driver outputs
For each API function that leads to a driver call, call it with parameters that cause a driver to be invoked and check how Mbed Crypto handles the outputs.
For each API function that leads to a driver call, call it with parameters that cause a driver to be invoked and check how Mbed TLS handles the outputs.
* Correct outputs.
* Incorrect outputs such as an invalid output length.

View File

@ -47,7 +47,7 @@ The PSA subsystem provides storage on top of the PSA trusted storage interface.
* [Storage transaction file](#storage-transaction-resumption).
* [Driver state files](#driver-state-files).
For a more detailed description, refer to the [Mbed Crypto storage specification](../mbed-crypto-storage-specification.md).
For a more detailed description, refer to the [Mbed TLS storage specification](../mbed-crypto-storage-specification.md).
In addition, Mbed TLS includes an implementation of the PSA trusted storage interface on top of C stdio. This document addresses the test strategy for [PSA ITS over file](#psa-its-over-file) in a separate section below.

View File

@ -80,9 +80,18 @@ If a feature is not requested for inclusion in the PSA Crypto configuration file
#### Configuration symbols for key types
For each constant or constructor macro of the form `PSA_KEY_TYPE_xxx`, the symbol **`PSA_WANT_KEY_TYPE_xxx`** indicates that support for this key type is desired.
For most constant or constructor macros of the form `PSA_KEY_TYPE_xxx`, the symbol **`PSA_WANT_KEY_TYPE_xxx`** indicates that support for this key type is desired.
For asymmetric cryptography, `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR` determines whether private-key operations are desired, and `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY` determines whether public-key operations are desired. `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR` implicitly enables `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY`: there is no way to only include private-key operations (which typically saves little code).
As an exception, starting in Mbed TLS 3.5.0, for `KEY_PAIR` types (that is, private keys for asymmetric cryptography), the feature selection is more fine-grained, with an additional suffix:
* `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_BASIC` enables basic support for the key type, and in particular support for operations with a key of that type for enabled algorithms. This is automatically enabled if any of the other `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_yyy` options is enabled.
* `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_IMPORT` enables support for `psa_import_key` to import a key of that type.
* `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_GENERATE` enables support for `psa_generate_key` to randomly generate a key of that type.
* `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_DERIVE` enables support for `psa_key_derivation_output_key` to deterministically derive a key of that type.
* `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_EXPORT` enables support for `psa_export_key` to export a key of that type.
For asymmetric cryptography, `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_BASIC` determines whether private-key operations are desired, and `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY` determines whether public-key operations are desired. `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_BASIC` implicitly enables `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY`, as well as support for `psa_export_public_key` on the private key: there is no way to only include private-key operations (which typically saves little code).
Note: the implementation is always free to include support for more than what was explicitly requested. (For example, as of Mbed TLS 3.5.0, `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_BASIC` implicitly enables import and export support for that key type, but this may not be the case in future versions.) Applications should always request support for all operations they need, rather than rely on them being implicitly enabled by the implementation. The only thing that is documented and guaranteed in the future is as follows: `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_yyy` -> `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_BASIC` -> `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY`.
#### Configuration symbols for elliptic curves

View File

@ -301,25 +301,289 @@ TODO
TODO
#### Operation family `"key_derivation"`
### Driver entry points for key derivation
This family requires the following type and entry points:
Key derivation is more complex than other multipart operations for several reasons:
* Type `"key_derivation_operation_t"`: the type of a key derivation operation context.
* `"key_derivation_setup"`: called by `psa_key_derivation_setup()`.
* `"key_derivation_set_capacity"`: called by `psa_key_derivation_set_capacity()`. The core will always enforce the capacity, therefore this function does not need to do anything for algorithms where the output stream only depends on the effective generated length and not on the capacity.
* `"key_derivation_input_bytes"`: called by `psa_key_derivation_input_bytes()` and `psa_key_derivation_input_key()`. For transparent drivers, when processing a call to `psa_key_derivation_input_key()`, the core always calls the applicable driver's `"key_derivation_input_bytes"` entry point.
* `"key_derivation_input_integer"`: called by `psa_key_derivation_input_integer()`.
* `"key_derivation_input_key"` (opaque drivers only)
* `"key_derivation_output_bytes"`: called by `psa_key_derivation_output_bytes()`; also by `psa_key_derivation_output_key()` for transparent drivers.
* `"key_derivation_output_key"`: called by `psa_key_derivation_output_key()` for transparent drivers when deriving an asymmetric key pair, and also for opaque drivers.
* `"key_derivation_verify_bytes"` (opaque drivers only).
* `"key_derivation_verify_key"` (opaque drivers only).
* `"key_derivation_abort"`: called by all key derivation functions of the PSA Cryptography API.
* There are multiple inputs and outputs.
* Multiple drivers can be involved. This happens when an operation combines a key agreement and a subsequent symmetric key derivation, each of which can have independent drivers. This also happens when deriving an asymmetric key, where processing the secret input and generating the key output might involve different drivers.
* When multiple drivers are involved, they are not always independent: if the secret input is managed by an opaque driver, it might not allow the core to retrieve the intermediate output and pass it to another driver.
* The involvement of an opaque driver cannot be determined as soon as the operation is set up (since `psa_key_derivation_setup()` does not determine the key input).
TODO: key input and output for opaque drivers; deterministic key generation for transparent drivers
#### Key derivation driver dispatch logic
TODO
The core decides whether to dispatch a key derivation operation to a driver based on the location associated with the input step `PSA_KEY_DERIVATION_INPUT_SECRET`.
1. If this step is passed via `psa_key_derivation_input_key()` for a key in a secure element:
* If the driver for this secure element implements the `"key_derivation"` family for the specified algorithm, the core calls that driver's `"key_derivation_setup"` and subsequent entry points.
Note that for all currently specified algorithms, the key type for the secret input does not matter.
* Otherwise the core calls the secure element driver's [`"export_key"`](#key-management-with-opaque-drivers) entry point.
2. Otherwise ([or on fallback?](#fallback-for-key-derivation-in-opaque-drivers)), if there is a transparent driver for the specified algorithm, the core calls that driver's `"key_derivation_setup"` and subsequent entry points.
3. Otherwise, or on fallback, the core uses its built-in implementation.
#### Summary of entry points for the operation family `"key_derivation"`
A key derivation driver has the following entry points:
* `"key_derivation_setup"` (mandatory): always the first entry point to be called. This entry point provides the [initial inputs](#key-derivation-driver-initial-inputs). See [“Key derivation driver setup”](#key-derivation-driver-setup).
* `"key_derivation_input_step"` (mandatory if the driver supports a key derivation algorithm with long inputs, otherwise ignored): provide an extra input for the key derivation. This entry point is only mandatory in drivers that support algorithms that have extra inputs. See [“Key derivation driver long inputs”](#key-derivation-driver-long-inputs).
* `"key_derivation_output_bytes"` (mandatory): derive cryptographic material and output it. See [“Key derivation driver outputs”](#key-derivation-driver-outputs).
* `"key_derivation_output_key"`, `"key_derivation_verify_bytes"`, `"key_derivation_verify_key"` (optional, opaque drivers only): derive key material which remains inside the same secure element. See [“Key derivation driver outputs”](#key-derivation-driver-outputs).
* `"key_derivation_set_capacity"` (mandatory for opaque drivers that implement `"key_derivation_output_key"` for “cooked”, i.e. non-raw-data key types; ignored for other opaque drivers; not permitted for transparent drivers): update the capacity policy on the operation. See [“Key derivation driver operation capacity”](#key-derivation-driver-operation-capacity).
* `"key_derivation_abort"` (mandatory): always the last entry point to be called.
For naming purposes, here and in the following subsection, this specification takes the example of a driver with the prefix `"acme"` that implements the `"key_derivation"` entry point family with a capability that does not use the `"names"` property to declare different type and entry point names. Such a driver must implement the following type and functions, as well as the entry points listed above and described in the following subsections:
```
typedef ... acme_key_derivation_operation_t;
psa_status_t acme_key_derivation_abort(acme_key_derivation_operation_t *operation);
```
#### Key derivation driver initial inputs
The core conveys the initial inputs for a key derivation via an opaque data structure of type `psa_crypto_driver_key_derivation_inputs_t`.
```
typedef ... psa_crypto_driver_key_derivation_inputs_t; // implementation-specific type
```
A driver receiving an argument that points to a `psa_crypto_driver_key_derivation_inputs_t` can retrieve its contents by calling one of the type-specific functions below. To determine the correct function, the driver can call `psa_crypto_driver_key_derivation_get_input_type()`.
```
enum psa_crypto_driver_key_derivation_input_type_t {
PSA_KEY_DERIVATION_INPUT_TYPE_INVALID = 0,
PSA_KEY_DERIVATION_INPUT_TYPE_OMITTED,
PSA_KEY_DERIVATION_INPUT_TYPE_BYTES,
PSA_KEY_DERIVATION_INPUT_TYPE_KEY,
PSA_KEY_DERIVATION_INPUT_TYPE_INTEGER,
// Implementations may add other values, and may freely choose the
// numerical values for each identifer except as explicitly specified
// above.
};
psa_crypto_driver_key_derivation_input_type_t psa_crypto_driver_key_derivation_get_input_type(
const psa_crypto_driver_key_derivation_inputs_t *inputs,
psa_key_derivation_step_t step);
```
The function `psa_crypto_driver_key_derivation_get_input_type()` determines whether a given step is present and how to access its value:
* `PSA_KEY_DERIVATION_INPUT_TYPE_INVALID`: the step is invalid for the algorithm of the operation that the inputs are for.
* `PSA_KEY_DERIVATION_INPUT_TYPE_OMITTED`: the step is optional for the algorithm of the operation that the inputs are for, and has been omitted.
* `PSA_KEY_DERIVATION_INPUT_TYPE_BYTES`: the step is valid and present and is a transparent byte string. Call `psa_crypto_driver_key_derivation_get_input_size()` to obtain the size of the input data. Call `psa_crypto_driver_key_derivation_get_input_bytes()` to make a copy of the input data (design note: [why a copy?](#key-derivation-inputs-and-buffer-ownership)).
* `PSA_KEY_DERIVATION_INPUT_TYPE_KEY`: the step is valid and present and is a byte string passed via a key object. Call `psa_crypto_driver_key_derivation_get_input_key()` to obtain a pointer to the key context.
* `PSA_KEY_DERIVATION_INPUT_TYPE_INTEGER`: the step is valid and present and is an integer. Call `psa_crypto_driver_key_derivation_get_input_integer()` to retrieve the integer value.
```
psa_status_t psa_crypto_driver_key_derivation_get_input_size(
const psa_crypto_driver_key_derivation_inputs_t *inputs,
psa_key_derivation_step_t step,
size_t *size);
psa_status_t psa_crypto_driver_key_derivation_get_input_bytes(
const psa_crypto_driver_key_derivation_inputs_t *inputs,
psa_key_derivation_step_t step,
uint8_t *buffer, size_t buffer_size, size_t *buffer_length);
psa_status_t psa_crypto_driver_key_derivation_get_input_key(
const psa_crypto_driver_key_derivation_inputs_t *inputs,
psa_key_derivation_step_t step,
const psa_key_attributes_t *attributes,
uint8_t** p_key_buffer, size_t *key_buffer_size);
psa_status_t psa_crypto_driver_key_derivation_get_input_integer(
const psa_crypto_driver_key_derivation_inputs_t *inputs,
psa_key_derivation_step_t step,
uint64_t *value);
```
The get-data functions take the following parameters:
* The first parameter `inputs` must be a pointer passed by the core to a key derivation driver setup entry point which has not returned yet.
* The `step` parameter indicates the input step whose content the driver wants to retrieve.
* On a successful invocation of `psa_crypto_driver_key_derivation_get_input_size`, the core sets `*size` to the size of the specified input in bytes.
* On a successful invocation of `psa_crypto_driver_key_derivation_get_input_bytes`, the core fills the first *N* bytes of `buffer` with the specified input and sets `*buffer_length` to *N*, where *N* is the length of the input in bytes. The value of `buffer_size` must be at least *N*, otherwise this function fails with the status `PSA_ERROR_BUFFER_TOO_SMALL`.
* On a successful invocation of `psa_crypto_driver_key_derivation_get_input_key`, the core sets `*key_buffer` to a pointer to a buffer containing the key context and `*key_buffer_size` to the size of the key context in bytes. The key context buffer remains valid for the duration of the driver entry point. If the driver needs to access the key context after the current entry point returns, it must make a copy of the key context.
* On a successful invocation of `psa_crypto_driver_key_derivation_get_input_integer`, the core sets `*value` to the value of the specified input.
These functions can return the following statuses:
* `PSA_SUCCESS`: the call succeeded and the requested value has been copied to the output parameter (`size`, `buffer`, `value` or `p_key_buffer`) and if applicable the size of the value has been written to the applicable parameter (`buffer_length`, `key_buffer_size`).
* `PSA_ERROR_DOES_NOT_EXIST`: the input step is valid for this particular algorithm, but it is not part of the initial inputs. This is not a fatal error. The driver will receive the input later as a [long input](#key-derivation-driver-long-inputs).
* `PSA_ERROR_INVALID_ARGUMENT`: the input type is not compatible with this function or was omitted. Call `psa_crypto_driver_key_derivation_get_input_type()` to find out the actual type of this input step. This is not a fatal error and the driver can, for example, subsequently call the appropriate function on the same step.
* `PSA_ERROR_BUFFER_TOO_SMALL` (`psa_crypto_driver_key_derivation_get_input_bytes` only): the output buffer is too small. This is not a fatal error and the driver can, for example, subsequently call the same function again with a larger buffer. Call `psa_crypto_driver_key_derivation_get_input_size` to obtain the required size.
* The core may return other errors such as `PSA_ERROR_CORRUPTION_DETECTED` or `PSA_ERROR_COMMUNICATION_FAILURE` to convey implementation-specific error conditions. Portable drivers should treat such conditions as fatal errors.
#### Key derivation driver setup
A key derivation driver must implement the following entry point:
```
psa_status_t acme_key_derivation_setup(
acme_key_derivation_operation_t *operation,
psa_algorithm_t alg,
const psa_crypto_driver_key_derivation_inputs_t *inputs);
```
* `operation` is a zero-initialized operation object.
* `alg` is the algorithm for the key derivation operation. It does not include a key agreement component.
* `inputs` is an opaque pointer to the [initial inputs](#key-derivation-driver-initial-inputs) for the key derivation.
#### Key derivation driver long inputs
Some key derivation algorithms take long inputs which it would not be practical to pass in the [initial inputs](#key-derivation-driver-initial-inputs). A driver that implements a key derivation algorithm that takes such inputs must provide a `"key_derivation_input_step"` entry point. The core calls this entry point for all the long inputs after calling `"acme_key_derivation_setup"`. A long input step may be fragmented into multiple calls of `psa_key_derivation_input_bytes()`, and the core may reassemble or refragment those fragments before passing them to the driver. Calls to this entry point for different step values occur in an unspecified order and may be interspersed.
```
psa_status_t acme_key_derivation_input_step(
acme_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
const uint8_t *input, size_t input_length);
```
At the time of writing, no standard key derivation algorithm has long inputs. It is likely that such algorithms will be added in the future.
#### Key derivation driver operation capacity
The core keeps track of an operation's capacity and enforces it. The core guarantees that it will not request output beyond the capacity of the operation, with one exception: opaque drivers that support [`"key_derivation_output_key"`](#key-derivation-driver-outputs), i.e. for key types where the derived key material is not a direct copy of the key derivation's output stream.
Such drivers must enforce the capacity limitation and must return `PSA_ERROR_INSUFFICIENT_CAPACITY` from any output request that exceeds the operation's capacity. Such drivers must provide the following entry point:
```
psa_status_t acme_key_derivation_set_capacity(
acme_key_derivation_operation_t *operation,
size_t capacity);
```
`capacity` is guaranteed to be less or equal to any value previously set through this entry point, and is guaranteed not to be `PSA_KEY_DERIVATION_UNLIMITED_CAPACITY`.
If this entry point has not been called, the operation has an unlimited capacity.
#### Key derivation driver outputs
A key derivation driver must provide the following entry point:
```
psa_status_t acme_key_derivation_output_bytes(
acme_key_derivation_operation_t *operation,
uint8_t *output, size_t length);
```
An opaque key derivation driver may provide the following entry points:
```
psa_status_t acme_key_derivation_output_key(
const psa_key_attributes_t *attributes,
acme_key_derivation_operation_t *operation,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
psa_status_t acme_key_derivation_verify_bytes(
acme_key_derivation_operation_t *operation,
const uint8_t *expected output, size_t length);
psa_status_t acme_key_derivation_verify_key(
acme_key_derivation_operation_t *operation,
uint8_t *key_buffer, size_t key_buffer_size);
```
The core calls a key derivation driver's output entry point when the application calls `psa_key_derivation_output_bytes()`, `psa_key_derivation_output_key()`, `psa_key_derivation_verify_bytes()` or `psa_key_derivation_verify_key()`.
If the key derivation's `PSA_KEY_DERIVATION_INPUT_SECRET` input is in a secure element and the derivation operation is handled by that secure element, the core performs the following steps:
* For a call to `psa_key_derivation_output_key()`:
1. If the derived key is in the same secure element, if the driver has an `"key_derivation_output_key"` entry point, call that entry point. If the driver has no such entry point, or if that entry point returns `PSA_ERROR_NOT_SUPPORTED`, continue with the following steps, otherwise stop.
1. If the driver's capabilities indicate that its `"import_key"` entry point does not support the derived key, stop and return `PSA_ERROR_NOT_SUPPORTED`.
1. Otherwise proceed as for `psa_key_derivation_output_bytes()`, then import the resulting key material.
* For a call to `psa_key_derivation_verify_key()`:
1. If the driver has a `"key_derivation_verify_key"` entry point, call it and stop.
1. Call the driver's `"export_key"` entry point on the key object that contains the expected value, then proceed as for `psa_key_derivation_verify_bytes()`.
* For a call to `psa_key_derivation_verify_bytes()`:
1. If the driver has a `"key_derivation_verify_bytes"` entry point, call that entry point on the expected output, then stop.
1. Otherwise, proceed as for `psa_key_derivation_output_bytes()`, and compare the resulting output to the expected output inside the core.
* For a call to `psa_key_derivation_output_bytes()`:
1. Call the `"key_derivation_output_bytes"` entry point. The core may call this entry point multiple times to implement a single call from the application when deriving a cooked (non-raw) key as described below, or if the output size exceeds some implementation limit.
If the key derivation operation is not handled by an opaque driver as described above, the core calls the `"key_derivation_output_bytes"` from the applicable transparent driver (or multiple drivers in succession if fallback applies). In some cases, the core then calls additional entry points in the same or another driver:
* For a call to `psa_key_derivation_output_key()` for some key types, the core calls a transparent driver's `"derive_key"` entry point. See [“Transparent cooked key derivation”](#transparent-cooked-key-derivation).
* For a call to `psa_key_derivation_output_key()` where the derived key is in a secure element, call that secure element driver's `"import_key"` entry point.
#### Transparent cooked key derivation
Key derivation is said to be *raw* for some key types, where the key material of a derived (8×*n*)-bit key consists of the next *n* bytes of output from the key derivation, and *cooked* otherwise. When deriving a raw key, the core only calls the driver's `"output_bytes"` entry point, except when deriving a key entirely inside a secure element as described in [“Key derivation driver outputs”](#key-derivation-driver-outputs). When deriving a cooked key, the core calls a transparent driver's `"derive_key"` entry point if available.
A capability for cooked key derivation contains the following properties (this is not a subset of [the usual entry point properties](#capability-syntax)):
* `"entry_points"` (mandatory, list of strings). Must be `["derive_key"]`.
* `"derived_types"` (mandatory, list of strings). Each element is a [key type specification](#key-type-specifications). This capability only applies when deriving a key of the specified type.
* `"derived_sizes"` (optional, list of integers). Each element is a size for the derived key, in bits. This capability only applies when deriving a key of the specified sizes. If absent, this capability applies to all sizes for the specified types.
* `"memory"` (optional, boolean). If present and true, the driver must define a type `"derive_key_memory_t"` and the core will allocate an object of that type as specified below.
* `"names"` (optional, object). A mapping from entry point names to C function and type names, as usual.
* `"fallback"` (optional, boolean). If present and true, the driver may return `PSA_ERROR_NOT_SUPPORTED` if it only partially supports the specified mechanism, as usual.
A transparent driver with the prefix `"acme"` that implements cooked key derivation must provide the following type and function:
```
typedef ... acme_derive_key_memory_t; // only if the "memory" property is true
psa_status_t acme_derive_key(
const psa_key_attributes_t *attributes,
const uint8_t *input, size_t input_length,
acme_derive_key_memory_t *memory, // if the "memory" property is false: void*
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
```
* `attributes` contains the attributes of the specified key. Note that only the key type and the bit-size are guaranteed to be set.
* `input` is a buffer of `input_length` bytes which contains the raw key stream, i.e. the data that `psa_key_derivation_output_bytes()` would return.
* If `"memory"` property in the driver capability is true, `memory` is a data structure that the driver may use to store data between successive calls of the `"derive_key"` entry point to derive the same key. If the `"memory"` property is false or absent, the `memory` parameter is a null pointer.
* `key_buffer` is a buffer for the output material, in the appropriate [export format](#key-format-for-transparent-drivers) for the key type. Its size is `key_buffer_size` bytes.
* On success, `*key_buffer_length` must contain the number of bytes written to `key_buffer`.
This entry point may return the following statuses:
* `PSA_SUCCESS`: a key was derived successfully. The driver has placed the representation of the key in `key_buffer`.
* `PSA_ERROR_NOT_SUPPORTED` (for the first call only) (only if fallback is enabled): the driver cannot fulfill this request, but a fallback driver might.
* `PSA_ERROR_INSUFFICIENT_DATA`: the core must call the `"derive_key"` entry point again with the same `memory` object and with subsequent data from the key stream.
* Any other error is a fatal error.
The core calls the `"derive_key"` entry point in a loop until it returns a status other than `PSA_ERROR_INSUFFICIENT_DATA`. Each call has a successive fragment of the key stream. The `memory` object is guaranteed to be the same for successive calls, but note that its address may change between calls. Before the first call, `*memory` is initialized to all-bits-zero.
For standard key types, the `"derive_key"` entry point is called with a certain input length as follows:
* `PSA_KEY_TYPE_DES`: the length of the key.
* `PSA_KEY_TYPE_ECC_KEY_PAIR(…)`, `PSA_KEY_TYPE_DH_KEY_PAIR(…)`: $m$ bytes, where the bit-size of the key $n$ satisfies $8 (m-1) < n \le 8 m$.
* `PSA_KEY_TYPE_RSA_KEY_PAIR`: an implementation-defined length. A future version of this specification may specify a length.
* Other key types: not applicable.
See [“Open questions around cooked key derivation”](#open-questions-around-cooked-key-derivation) for some points that may not be fully settled.
#### Key agreement
The core always decouples key agreement from symmetric key derivation.
To implement a call to `psa_key_derivation_key_agreement()` where the private key is in a secure element that has a `"key_agreement_to_key"` entry point which is applicable for the given key type and algorithm, the core calls the secure element driver as follows:
1. Call the `"key_agreement_to_key"` entry point to create a key object containing the shared secret. The key object is volatile and has the type `PSA_KEY_TYPE_DERIVE`.
2. Call the `"key_derivation_setup"` entry point, passing the resulting key object .
3. Perform the rest of the key derivation, up to and including the call to the `"key_derivation_abort"` entry point.
4. Call the `"destroy_key"` entry point to destroy the key containing the key object.
In other cases, the core treats `psa_key_derivation_key_agreement()` as if it was a call to `psa_raw_key_agreement()` followed by a call to `psa_key_derivation_input_bytes()` on the shared secret.
The entry points related to key agreement have the following prototypes for a driver with the prefix `"acme"`:
```
psa_status_t acme_key_agreement(psa_algorithm_t alg,
const psa_key_attributes_t *our_attributes,
const uint8_t *our_key_buffer,
size_t our_key_buffer_length,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *output,
size_t output_size,
size_t *output_length);
psa_status_t acme_key_agreement_to_key(psa_algorithm_t alg,
const psa_key_attributes_t *our_attributes,
const uint8_t *our_key_buffer,
size_t our_key_buffer_length,
const uint8_t *peer_key,
size_t peer_key_length,
const psa_key_attributes_t *shared_secret_attributes,
uint8_t *shared_secret_key_buffer,
size_t shared_secret_key_buffer_size,
size_t *shared_secret_key_buffer_length);
```
Note that unlike most other key creation entry points, in `"acme_key_agreement_to_key"`, the attributes for the shared secret are not placed near the beginning, but rather grouped with the other parameters related to the shared secret at the end of the parameter list. This is to avoid potential confusion with the attributes of the private key that is passed as an input.
### Driver entry points for PAKE
@ -506,8 +770,9 @@ psa_status_t acme_generate_key(const psa_key_attributes_t *attributes,
size_t key_buffer_size,
size_t *key_buffer_length);
```
Additionally, opaque drivers can create keys through their [`"key_derivation_output_key"`](#key-derivation-driver-outputs) and [`"key_agreement_key"`](#key-agreement) entry points. Transparent drivers can create key material through their [`"derive_key"`](#transparent-cooked-key-derivation) entry point.
TODO: derivation, copy
TODO: copy
* The key attributes (`attributes`) have the same semantics as in the PSA Cryptography application interface.
* For the `"import_key"` entry point, the input in the `data` buffer is either the export format or an implementation-specific format that the core documents as an acceptable input format for `psa_import_key()`.
@ -640,7 +905,7 @@ psa_status_t acme_import_key(const psa_key_attributes_t *attributes,
This entry point has several roles:
1. Parse the key data in the input buffer `data`. The driver must support the export format for the key types that the entry point is declared for. It may support additional formats as specified in the description of [`psa_import_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_key) in the PSA Cryptography API specification.
2. Validate the key data. The necessary validation is described in the section [“Key validation with transparent drivers”](#key-validation-with-transparent-drivers) above.
2. Validate the key data. The necessary validation is described in the section [“Key validation”](#key-validation) above.
3. [Determine the key size](#key-size-determination-on-import) and output it through `*bits`.
4. Copy the validated key data from `data` to `key_buffer`. The output must be in the canonical format documented for [`psa_export_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_key) or [`psa_export_public_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_public_key), so if the input is not in this format, the entry point must convert it.
@ -830,7 +1095,7 @@ If the key is stored in wrapped form outside the secure element, and the wrapped
Opaque drivers may provide the following key management entry points:
* `"export_key"`: called by `psa_export_key()`, or by `psa_copy_key()` when copying a key from or to a different [location](#lifetimes-and-locations).
* `"export_key"`: called by `psa_export_key()`, or by `psa_copy_key()` when copying a key from or to a different [location](#lifetimes-and-locations), or [as a fallback for key derivation](#key-derivation-driver-dispatch-logic).
* `"export_public_key"`: called by the core to obtain the public key of a key pair. The core may call this entry point at any time to obtain the public key, which can be for `psa_export_public_key()` but also at other times, including during a cryptographic operation that requires the public key such as a call to `psa_verify_message()` on a key pair object.
* `"import_key"`: called by `psa_import_key()`, or by `psa_copy_key()` when copying a key from another location.
* `"generate_key"`: called by `psa_generate_key()`.
@ -1101,6 +1366,12 @@ Should drivers really have to cope with overlap?
Should the core guarantee that the output buffer size has the size indicated by the applicable buffer size macro (which may be an overestimation)?
#### Key derivation inputs and buffer ownership
Why is `psa_crypto_driver_key_derivation_get_input_bytes` a copy, rather than giving a pointer?
The main reason is to avoid complex buffer ownership. A driver entry point does not own memory after the entry point return. This is generally necessary because an API function does not own memory after the entry point returns. In the case of key derivation inputs, this could be relaxed because the driver entry point is making callbacks to the core: these functions could return a pointer that is valid until the driver entry point returns, which would allow the driver to process the data immediately (e.g. hash it rather than copy it).
### Partial computations in drivers
#### Substitution points
@ -1144,6 +1415,18 @@ An example use case for updating the persistent state at arbitrary times is to r
`psa_crypto_driver_get_persistent_state` does not identify the calling driver, so the driver needs to remember which driver it's calling. This may require a thread-local variable in a multithreaded core. Is this ok?
#### Open questions around cooked key derivation
`"derive_key"` is not a clear name. Can we use a better one?
For the `"derive_key"` entry point, how does the core choose `input_length`? Doesn't the driver know better? Should there be a driver entry point to determine the length, or should there be a callback that allows the driver to retrieve the input? Note that for some key types, it's impossible to predict the amount of input in advance, because it depends on some complex calculation or even on random data, e.g. if doing a randomized pseudo-primality test. However, for all key types except RSA, the specification mandates how the key is derived, which practically dictates how the pseudorandom key stream is consumed. So it's probably ok.
#### Fallback for key derivation in opaque drivers
Should [dispatch to an opaque driver](#key-derivation-driver-dispatch-logic) allow fallback, so that if `"key_derivation_setup"` returns `PSA_ERROR_NOT_SUPPORTED` then the core exports the key from the secure element instead?
Should the ["`key_derivation_output_key`"](#key-derivation-driver-outputs) capability indicate which key types the driver can derive? How should fallback work? For example, consider a secure element that implements HMAC, HKDF and ECDSA, and that can derive an HMAC key from HKDF without exporting intermediate material but can only import or randomly generate ECC keys. How does this driver convey that it can't derive an ECC key with HKDF, but it can let the core do this and import the resulting key?
### Randomness
#### Input to `"add_entropy"`

11
docs/redirects.yaml Normal file
View File

@ -0,0 +1,11 @@
# Readthedocs redirects
# See https://docs.readthedocs.io/en/stable/user-defined-redirects.html
#
# Changes to this file do not take effect until they are merged into the
# 'development' branch. This is because the API token (RTD_TOKEN) is not
# made available in PR jobs - preventing bad actors from crafting PRs to
# expose it.
- type: exact
from_url: /projects/api/en/latest/$rest
to_url: /projects/api/en/development/

View File

@ -1,2 +1,3 @@
sphinx-rtd-theme
breathe
readthedocs-cli
sphinx-rtd-theme

View File

@ -14,6 +14,8 @@ certifi==2022.12.7
# via requests
charset-normalizer==3.1.0
# via requests
click==8.1.3
# via readthedocs-cli
docutils==0.17.1
# via
# breathe
@ -27,14 +29,28 @@ importlib-metadata==6.0.0
# via sphinx
jinja2==3.1.2
# via sphinx
markdown-it-py==2.2.0
# via rich
markupsafe==2.1.2
# via jinja2
mdurl==0.1.2
# via markdown-it-py
packaging==23.0
# via sphinx
pygments==2.14.0
# via sphinx
# via
# rich
# sphinx
pyyaml==6.0
# via readthedocs-cli
readthedocs-cli==4
# via -r requirements.in
requests==2.28.2
# via sphinx
# via
# readthedocs-cli
# sphinx
rich==13.3.5
# via readthedocs-cli
snowballstemmer==2.2.0
# via sphinx
sphinx==4.5.0

View File

@ -22,73 +22,10 @@
*/
/**
* @mainpage mbed TLS v3.4.0 source code documentation
* @mainpage Mbed TLS v3.4.0 API Documentation
*
* This documentation describes the internal structure of mbed TLS. It was
* This documentation describes the internal structure of Mbed TLS. It was
* automatically generated from specially formatted comment blocks in
* mbed TLS's source code using Doxygen. (See
* http://www.stack.nl/~dimitri/doxygen/ for more information on Doxygen)
*
* mbed TLS has a simple setup: it provides the ingredients for an SSL/TLS
* implementation. These ingredients are listed as modules in the
* \ref mainpage_modules "Modules section". This "Modules section" introduces
* the high-level module concepts used throughout this documentation.\n
* Some examples of mbed TLS usage can be found in the \ref mainpage_examples
* "Examples section".
*
* @section mainpage_modules Modules
*
* mbed TLS supports TLSv1.0 up to TLSv1.2 communication by providing the
* following:
* - TCP/IP communication functions: listen, connect, accept, read/write.
* - SSL/TLS communication functions: init, handshake, read/write.
* - X.509 functions: CRT, CRL and key handling
* - Random number generation
* - Hashing
* - Encryption/decryption
*
* Above functions are split up neatly into logical interfaces. These can be
* used separately to provide any of the above functions or to mix-and-match
* into an SSL server/client solution that utilises a X.509 PKI. Examples of
* such implementations are amply provided with the source code.
*
* Note that mbed TLS does not provide a control channel or (multiple) session
* handling without additional work from the developer.
*
* @section mainpage_examples Examples
*
* Example server setup:
*
* \b Prerequisites:
* - X.509 certificate and private key
* - session handling functions
*
* \b Setup:
* - Load your certificate and your private RSA key (X.509 interface)
* - Setup the listening TCP socket (TCP/IP interface)
* - Accept incoming client connection (TCP/IP interface)
* - Initialise as an SSL-server (SSL/TLS interface)
* - Set parameters, e.g. authentication, ciphers, CA-chain, key exchange
* - Set callback functions RNG, IO, session handling
* - Perform an SSL-handshake (SSL/TLS interface)
* - Read/write data (SSL/TLS interface)
* - Close and cleanup (all interfaces)
*
* Example client setup:
*
* \b Prerequisites:
* - X.509 certificate and private key
* - X.509 trusted CA certificates
*
* \b Setup:
* - Load the trusted CA certificates (X.509 interface)
* - Load your certificate and your private RSA key (X.509 interface)
* - Setup a TCP/IP connection (TCP/IP interface)
* - Initialise as an SSL-client (SSL/TLS interface)
* - Set parameters, e.g. authentication mode, ciphers, CA-chain, session
* - Set callback functions RNG, IO
* - Perform an SSL-handshake (SSL/TLS interface)
* - Verify the server certificate (SSL/TLS interface)
* - Write/read data (SSL/TLS interface)
* - Close and cleanup (all interfaces)
* Mbed TLS's source code using Doxygen. (See
* https://www.doxygen.nl for more information on Doxygen)
*/

View File

@ -76,6 +76,10 @@ typedef struct mbedtls_aes_context {
int MBEDTLS_PRIVATE(nr); /*!< The number of rounds. */
size_t MBEDTLS_PRIVATE(rk_offset); /*!< The offset in array elements to AES
round keys in the buffer. */
#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && !defined(MBEDTLS_PADLOCK_C)
uint32_t MBEDTLS_PRIVATE(buf)[44]; /*!< Aligned data buffer to hold
10 round keys for 128-bit case. */
#else
uint32_t MBEDTLS_PRIVATE(buf)[68]; /*!< Unaligned data buffer. This buffer can
hold 32 extra Bytes, which can be used for
one of the following purposes:
@ -84,6 +88,7 @@ typedef struct mbedtls_aes_context {
<li>Simplifying key expansion in the 256-bit
case by generating an extra round key.
</li></ul> */
#endif /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH && !MBEDTLS_PADLOCK_C */
}
mbedtls_aes_context;

View File

@ -163,6 +163,27 @@ int mbedtls_asn1_write_algorithm_identifier(unsigned char **p,
const char *oid, size_t oid_len,
size_t par_len);
/**
* \brief Write an AlgorithmIdentifier sequence in ASN.1 format.
*
* \note This function works backwards in data buffer.
*
* \param p The reference to the current position pointer.
* \param start The start of the buffer, for bounds-checking.
* \param oid The OID of the algorithm to write.
* \param oid_len The length of the algorithm's OID.
* \param par_len The length of the parameters, which must be already written.
* \param has_par If there are any parameters. If 0, par_len must be 0. If 1
* and \p par_len is 0, NULL parameters are added.
*
* \return The number of bytes written to \p p on success.
* \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
*/
int mbedtls_asn1_write_algorithm_identifier_ext(unsigned char **p,
const unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len, int has_par);
/**
* \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value
* in ASN.1 format.

View File

@ -594,6 +594,8 @@ int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
* \brief Perform a left-shift on an MPI: X <<= count
*
* \param X The MPI to shift. This must point to an initialized MPI.
* The MPI pointed by \p X may be resized to fit
* the resulting number.
* \param count The number of bits to shift by.
*
* \return \c 0 if successful.

View File

@ -80,6 +80,14 @@
#include MBEDTLS_USER_CONFIG_FILE
#endif
/* Auto-enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY if
* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH and MBEDTLS_CTR_DRBG_C defined
* to ensure a 128-bit key size in CTR_DRBG.
*/
#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && defined(MBEDTLS_CTR_DRBG_C)
#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
#endif
/* Auto-enable MBEDTLS_MD_C if needed by a module that didn't require it
* in a previous release, to ensure backwards compatibility.
*/
@ -87,6 +95,18 @@
#define MBEDTLS_MD_C
#endif
/* PSA crypto specific configuration options
* - If config_psa.h reads a configuration option in preprocessor directive,
* this symbol should be set before its inclusion. (e.g. MBEDTLS_MD_C)
* - If config_psa.h writes a configuration option in conditional directive,
* this symbol should be consulted after its inclusion.
* (e.g. MBEDTLS_MD_LIGHT)
*/
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* PSA_WANT_xxx influences MBEDTLS_xxx */ || \
defined(MBEDTLS_PSA_CRYPTO_C) /* MBEDTLS_xxx influences PSA_WANT_xxx */
#include "mbedtls/config_psa.h"
#endif
/* Auto-enable MBEDTLS_MD_LIGHT based on MBEDTLS_MD_C.
* This allows checking for MD_LIGHT rather than MD_LIGHT || MD_C.
*/
@ -100,18 +120,47 @@
#if defined(MBEDTLS_ECJPAKE_C) || \
defined(MBEDTLS_PEM_PARSE_C) || \
defined(MBEDTLS_ENTROPY_C) || \
defined(MBEDTLS_PK_C) || \
defined(MBEDTLS_PKCS12_C) || \
defined(MBEDTLS_RSA_C)
defined(MBEDTLS_RSA_C) || \
defined(MBEDTLS_SSL_TLS_C) || \
defined(MBEDTLS_X509_USE_C) || \
defined(MBEDTLS_X509_CREATE_C)
#define MBEDTLS_MD_LIGHT
#endif
/* MBEDTLS_ECP_C now consists of MBEDTLS_ECP_LIGHT plus functions for curve
* arithmetic. As a consequence if MBEDTLS_ECP_C is required for some reason,
* then MBEDTLS_ECP_LIGHT should be enabled as well. */
#if defined(MBEDTLS_ECP_C)
/* MBEDTLS_ECP_LIGHT is auto-enabled by the following symbols:
* - MBEDTLS_ECP_C because now it consists of MBEDTLS_ECP_LIGHT plus functions
* for curve arithmetic. As a consequence if MBEDTLS_ECP_C is required for
* some reason, then MBEDTLS_ECP_LIGHT should be enabled as well.
* - MBEDTLS_PK_PARSE_EC_EXTENDED and MBEDTLS_PK_PARSE_EC_COMPRESSED because
* these features are not supported in PSA so the only way to have them is
* to enable the built-in solution.
* Both of them are temporary dependencies:
* - PK_PARSE_EC_EXTENDED will be removed after #7779 and #7789
* - support for compressed points should also be added to PSA, but in this
* case there is no associated issue to track it yet.
* - PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE because Weierstrass key derivation
* still depends on ECP_LIGHT.
* - PK_C + USE_PSA + PSA_WANT_ALG_ECDSA is a temporary dependency which will
* be fixed by #7453.
*/
#if defined(MBEDTLS_ECP_C) || \
defined(MBEDTLS_PK_PARSE_EC_EXTENDED) || \
defined(MBEDTLS_PK_PARSE_EC_COMPRESSED) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
#define MBEDTLS_ECP_LIGHT
#endif
/* MBEDTLS_PK_PARSE_EC_COMPRESSED is introduced in MbedTLS version 3.5, while
* in previous version compressed points were automatically supported as long
* as PK_PARSE_C and ECP_C were enabled. As a consequence, for backward
* compatibility, we auto-enable PK_PARSE_EC_COMPRESSED when these conditions
* are met. */
#if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_ECP_C)
#define MBEDTLS_PK_PARSE_EC_COMPRESSED
#endif
/* If MBEDTLS_PSA_CRYPTO_C is defined, make sure MBEDTLS_PSA_CRYPTO_CLIENT
* is defined as well to include all PSA code.
*/
@ -183,13 +232,14 @@
#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED
#endif
/* Make sure all configuration symbols are set before including check_config.h,
* even the ones that are calculated programmatically. */
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* PSA_WANT_xxx influences MBEDTLS_xxx */ || \
defined(MBEDTLS_PSA_CRYPTO_C) /* MBEDTLS_xxx influences PSA_WANT_xxx */
#include "mbedtls/config_psa.h"
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
(defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED))
#define MBEDTLS_SSL_TLS1_2_SOME_ECC
#endif
/* Make sure all configuration symbols are set before including check_config.h,
* even the ones that are calculated programmatically. */
#include "mbedtls/check_config.h"
#endif /* MBEDTLS_BUILD_INFO_H */

View File

@ -279,7 +279,7 @@
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#if (defined(PSA_WANT_ALG_ECDSA) || \
defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA)) && \
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PK_HAVE_ECDSA
#endif
#else /* MBEDTLS_USE_PSA_CRYPTO */
@ -290,7 +290,7 @@
/* Helper for JPAKE dependencies, will be undefined at the end of the file */
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#if defined(PSA_WANT_ALG_JPAKE) && defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
#if defined(PSA_WANT_ALG_JPAKE) && defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PK_HAVE_JPAKE
#endif
#else /* MBEDTLS_USE_PSA_CRYPTO */
@ -301,7 +301,7 @@
/* Helper for ECDH dependencies, will be undefined at the end of the file */
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#if defined(PSA_WANT_ALG_ECDH) && defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
#if defined(PSA_WANT_ALG_ECDH) && defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PK_HAVE_ECDH
#endif
#else /* MBEDTLS_USE_PSA_CRYPTO */
@ -814,14 +814,14 @@
#endif
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
#if !( defined(PSA_WANT_ALG_ECDH) && defined(MBEDTLS_X509_CRT_PARSE_C) && \
#if !( (defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)) && defined(MBEDTLS_X509_CRT_PARSE_C) && \
( defined(MBEDTLS_PK_HAVE_ECDSA) || defined(MBEDTLS_PKCS1_V21) ) )
#error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED defined, but not all prerequisites"
#endif
#endif
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
#if !( defined(PSA_WANT_ALG_ECDH) )
#if !( defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH) )
#error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED defined, but not all prerequisites"
#endif
#endif

View File

@ -270,45 +270,58 @@ typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
* mbedtls_cipher_info_from_type(),
* mbedtls_cipher_info_from_values(),
* mbedtls_cipher_info_from_psa().
*
* \note Some fields store a value that has been right-shifted to save
* code-size, so should not be used directly. The accessor
* functions adjust for this and return the "natural" value.
*/
typedef struct mbedtls_cipher_info_t {
/** Full cipher identifier. For example,
* MBEDTLS_CIPHER_AES_256_CBC.
*/
mbedtls_cipher_type_t MBEDTLS_PRIVATE(type);
/** The cipher mode. For example, MBEDTLS_MODE_CBC. */
mbedtls_cipher_mode_t MBEDTLS_PRIVATE(mode);
/** The cipher key length, in bits. This is the
* default length for variable sized ciphers.
* Includes parity bits for ciphers like DES.
*/
unsigned int MBEDTLS_PRIVATE(key_bitlen);
/** Name of the cipher. */
const char *MBEDTLS_PRIVATE(name);
/** IV or nonce size, in Bytes.
/** The block size, in bytes. */
unsigned int MBEDTLS_PRIVATE(block_size) : 5;
/** IV or nonce size, in bytes (right shifted by #MBEDTLS_IV_SIZE_SHIFT).
* For ciphers that accept variable IV sizes,
* this is the recommended size.
*/
unsigned int MBEDTLS_PRIVATE(iv_size);
unsigned int MBEDTLS_PRIVATE(iv_size) : 3;
/** The cipher key length, in bits (right shifted by #MBEDTLS_KEY_BITLEN_SHIFT).
* This is the default length for variable sized ciphers.
* Includes parity bits for ciphers like DES.
*/
unsigned int MBEDTLS_PRIVATE(key_bitlen) : 4;
/** The cipher mode (as per mbedtls_cipher_mode_t).
* For example, MBEDTLS_MODE_CBC.
*/
unsigned int MBEDTLS_PRIVATE(mode) : 4;
/** Full cipher identifier (as per mbedtls_cipher_type_t).
* For example, MBEDTLS_CIPHER_AES_256_CBC.
*
* This could be 7 bits, but 8 bits retains byte alignment for the
* next field, which reduces code size to access that field.
*/
unsigned int MBEDTLS_PRIVATE(type) : 8;
/** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and
* MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the
* cipher supports variable IV or variable key sizes, respectively.
*/
int MBEDTLS_PRIVATE(flags);
unsigned int MBEDTLS_PRIVATE(flags) : 2;
/** The block size, in Bytes. */
unsigned int MBEDTLS_PRIVATE(block_size);
/** Struct for base cipher information and functions. */
const mbedtls_cipher_base_t *MBEDTLS_PRIVATE(base);
/** Index to LUT for base cipher information and functions. */
unsigned int MBEDTLS_PRIVATE(base_idx) : 5;
} mbedtls_cipher_info_t;
/* For internal use only.
* These are used to more compactly represent the fields above. */
#define MBEDTLS_KEY_BITLEN_SHIFT 6
#define MBEDTLS_IV_SIZE_SHIFT 2
/**
* Generic cipher context.
*/
@ -439,7 +452,7 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_info_get_type(
if (info == NULL) {
return MBEDTLS_CIPHER_NONE;
} else {
return info->MBEDTLS_PRIVATE(type);
return (mbedtls_cipher_type_t) info->MBEDTLS_PRIVATE(type);
}
}
@ -458,7 +471,7 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_info_get_mode(
if (info == NULL) {
return MBEDTLS_MODE_NONE;
} else {
return info->MBEDTLS_PRIVATE(mode);
return (mbedtls_cipher_mode_t) info->MBEDTLS_PRIVATE(mode);
}
}
@ -479,7 +492,7 @@ static inline size_t mbedtls_cipher_info_get_key_bitlen(
if (info == NULL) {
return 0;
} else {
return info->MBEDTLS_PRIVATE(key_bitlen);
return info->MBEDTLS_PRIVATE(key_bitlen) << MBEDTLS_KEY_BITLEN_SHIFT;
}
}
@ -521,7 +534,7 @@ static inline size_t mbedtls_cipher_info_get_iv_size(
return 0;
}
return (size_t) info->MBEDTLS_PRIVATE(iv_size);
return ((size_t) info->MBEDTLS_PRIVATE(iv_size)) << MBEDTLS_IV_SIZE_SHIFT;
}
/**
@ -541,7 +554,7 @@ static inline size_t mbedtls_cipher_info_get_block_size(
return 0;
}
return (size_t) info->MBEDTLS_PRIVATE(block_size);
return (size_t) (info->MBEDTLS_PRIVATE(block_size));
}
/**
@ -682,7 +695,7 @@ static inline unsigned int mbedtls_cipher_get_block_size(
return 0;
}
return ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(block_size);
return (unsigned int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(block_size);
}
/**
@ -702,7 +715,7 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode(
return MBEDTLS_MODE_NONE;
}
return ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(mode);
return (mbedtls_cipher_mode_t) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(mode);
}
/**
@ -727,7 +740,8 @@ static inline int mbedtls_cipher_get_iv_size(
return (int) ctx->MBEDTLS_PRIVATE(iv_size);
}
return (int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(iv_size);
return (int) (((int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(iv_size)) <<
MBEDTLS_IV_SIZE_SHIFT);
}
/**
@ -747,7 +761,7 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type(
return MBEDTLS_CIPHER_NONE;
}
return ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(type);
return (mbedtls_cipher_type_t) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(type);
}
/**
@ -788,7 +802,8 @@ static inline int mbedtls_cipher_get_key_bitlen(
return MBEDTLS_KEY_LENGTH_NONE;
}
return (int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(key_bitlen);
return (int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(key_bitlen) <<
MBEDTLS_KEY_BITLEN_SHIFT;
}
/**

View File

@ -42,6 +42,8 @@
#include MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE
#endif
#include "psa/crypto_legacy.h"
#ifdef __cplusplus
extern "C" {
#endif
@ -148,6 +150,13 @@ extern "C" {
#endif /* !MBEDTLS_PSA_ACCEL_ALG_ECDSA */
#endif /* PSA_WANT_ALG_ECDSA */
#if defined(PSA_WANT_ALG_FFDH)
#if !defined(MBEDTLS_PSA_ACCEL_ALG_FFDH)
#define MBEDTLS_PSA_BUILTIN_ALG_FFDH 1
#define MBEDTLS_BIGNUM_C
#endif /* !MBEDTLS_PSA_ACCEL_ALG_FFDH */
#endif /* PSA_WANT_ALG_FFDH */
#if defined(PSA_WANT_ALG_HKDF)
#if !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF)
#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
@ -261,6 +270,15 @@ extern "C" {
#define MBEDTLS_SHA512_C
#endif
#if defined(PSA_WANT_ALG_PBKDF2_HMAC)
#if !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_HMAC)
#define MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC 1
#if !defined(MBEDTLS_PSA_ACCEL_ALG_HMAC)
#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
#endif /* !MBEDTLS_PSA_ACCEL_ALG_HMAC */
#endif /* !MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
#endif /* PSA_WANT_ALG_PBKDF2_HMAC */
#if defined(PSA_WANT_ALG_TLS12_PRF)
#if !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PRF)
#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF 1
@ -279,13 +297,97 @@ extern "C" {
#endif /* !MBEDTLS_PSA_ACCEL_ALG_TLS12_ECJPAKE_TO_PMS */
#endif /* PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR 1
#define MBEDTLS_ECP_C
#define MBEDTLS_BIGNUM_C
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
#define MBEDTLS_GENPRIME
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC */
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT)
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_IMPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_IMPORT */
#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT */
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT)
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_EXPORT)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_EXPORT */
#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT */
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_GENERATE */
#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE */
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_BASIC */
#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC */
#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
@ -295,20 +397,12 @@ extern "C" {
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY */
#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR 1
#define MBEDTLS_RSA_C
#if defined(PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY)
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_PUBLIC_KEY)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY 1
#define MBEDTLS_BIGNUM_C
#define MBEDTLS_OID_C
#define MBEDTLS_GENPRIME
#define MBEDTLS_PK_PARSE_C
#define MBEDTLS_PK_WRITE_C
#define MBEDTLS_PK_C
#define MBEDTLS_ASN1_PARSE_C
#define MBEDTLS_ASN1_WRITE_C
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR */
#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_PUBLIC_KEY */
#endif /* PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY */
#if defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY)
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY)
@ -645,12 +739,40 @@ extern "C" {
#endif /* MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_ECP_C)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
/* Normally we wouldn't enable this because it's not implemented in ecp.c,
* but since it used to be available any time ECP_C was enabled, let's enable
* it anyway for the sake of backwards compatibility */
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
/* See comment for PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE above. */
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_DHM_C)
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
#define PSA_WANT_ALG_FFDH 1
#define PSA_WANT_DH_FAMILY_RFC7919 1
#define MBEDTLS_PSA_BUILTIN_ALG_FFDH 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY 1
#endif /* MBEDTLS_DHM_C */
#if defined(MBEDTLS_GCM_C)
#define MBEDTLS_PSA_BUILTIN_ALG_GCM 1
#define PSA_WANT_ALG_GCM 1
@ -712,8 +834,14 @@ extern "C" {
#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS 1
#define PSA_WANT_ALG_RSA_PSS 1
#endif /* MBEDTLS_PKCS1_V21 */
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
#endif /* MBEDTLS_RSA_C */
@ -877,6 +1005,60 @@ extern "C" {
#endif /* MBEDTLS_PSA_CRYPTO_CONFIG */
#if defined(PSA_WANT_ALG_JPAKE)
#define PSA_WANT_ALG_SOME_PAKE 1
#endif
/* Even though KEY_PAIR symbols' feature several level of support (BASIC, IMPORT,
* EXPORT, GENERATE, DERIVE) we're not planning to have support only for BASIC
* without IMPORT/EXPORT since these last 2 features are strongly used in tests.
* In general it is allowed to include more feature than what is strictly
* requested.
* As a consequence IMPORT and EXPORT features will be automatically enabled
* as soon as the BASIC one is. */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#endif
/* See description above */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#endif
/* Temporary internal migration helpers */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY
#endif
/* Temporary internal migration helpers */
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_WANT_KEY_TYPE_DH_KEY_PAIR_LEGACY
#endif
/* Temporary internal migration helpers */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_LEGACY
#endif
/* Temporary internal migration helpers */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_LEGACY
#endif
/* These features are always enabled. */
#define PSA_WANT_KEY_TYPE_DERIVE 1
#define PSA_WANT_KEY_TYPE_PASSWORD 1

View File

@ -141,15 +141,6 @@ typedef enum {
MBEDTLS_ECP_TYPE_MONTGOMERY, /* y^2 = x^3 + a x^2 + x */
} mbedtls_ecp_curve_type;
/*
* Curve modulus types
*/
typedef enum {
MBEDTLS_ECP_MOD_NONE = 0,
MBEDTLS_ECP_MOD_COORDINATE,
MBEDTLS_ECP_MOD_SCALAR
} mbedtls_ecp_modulus_type;
/**
* Curve information, for use by other modules.
*

View File

@ -73,6 +73,7 @@
* SHA1 1 0x0035-0x0035 0x0073-0x0073
* SHA256 1 0x0037-0x0037 0x0074-0x0074
* SHA512 1 0x0039-0x0039 0x0075-0x0075
* SHA-3 1 0x0076-0x0076
* CHACHA20 3 0x0051-0x0055
* POLY1305 3 0x0057-0x005B
* CHACHAPOLY 2 0x0054-0x0056

View File

@ -496,7 +496,6 @@
* performance if ROM access is slower than RAM access.
*
* This option is independent of \c MBEDTLS_AES_FEWER_TABLES.
*
*/
//#define MBEDTLS_AES_ROM_TABLES
@ -518,10 +517,26 @@
* depends on the system and memory details.
*
* This option is independent of \c MBEDTLS_AES_ROM_TABLES.
*
*/
//#define MBEDTLS_AES_FEWER_TABLES
/**
* \def MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
*
* Use only 128-bit keys in AES operations to save ROM.
*
* Uncomment this macro to remove support for AES operations that use 192-
* or 256-bit keys.
*
* Uncommenting this macro reduces the size of AES code by ~300 bytes
* on v8-M/Thumb2.
*
* Module: library/aes.c
*
* Requires: MBEDTLS_AES_C
*/
//#define MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
/**
* \def MBEDTLS_CAMELLIA_SMALL_MEMORY
*
@ -640,7 +655,8 @@
/** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
*
* Uncomment this macro to use a 128-bit key in the CTR_DRBG module.
* By default, CTR_DRBG uses a 256-bit key.
* Without this, CTR_DRBG uses a 256-bit key
* unless \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set.
*/
//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
@ -1029,6 +1045,19 @@
*/
#define MBEDTLS_PK_PARSE_EC_EXTENDED
/**
* \def MBEDTLS_PK_PARSE_EC_COMPRESSED
*
* Enable the support for parsing public keys of type Short Weierstrass
* (MBEDTLS_ECP_DP_SECP_XXX and MBEDTLS_ECP_DP_BP_XXX) which are using the
* compressed point format. This parsing is done through ECP module's functions.
*
* \note As explained in the description of MBEDTLS_ECP_PF_COMPRESSED (in ecp.h)
* the only unsupported curves are MBEDTLS_ECP_DP_SECP224R1 and
* MBEDTLS_ECP_DP_SECP224K1.
*/
#define MBEDTLS_PK_PARSE_EC_COMPRESSED
/**
* \def MBEDTLS_ERROR_STRERROR_DUMMY
*
@ -1642,7 +1671,7 @@
*
* Enable TLS 1.3 ephemeral key exchange mode.
*
* Requires: PSA_WANT_ALG_ECDH
* Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH
* MBEDTLS_X509_CRT_PARSE_C
* and at least one of:
* MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA)
@ -1660,7 +1689,7 @@
*
* Enable TLS 1.3 PSK ephemeral key exchange mode.
*
* Requires: PSA_WANT_ALG_ECDH
* Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH
*
* Comment to disable support for the PSK ephemeral key exchange mode in
* TLS 1.3. If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not
@ -2414,6 +2443,8 @@
* The CTR_DRBG generator uses AES-256 by default.
* To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above.
*
* \note AES-128 will be used if \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set.
*
* \note To achieve a 256-bit security strength with CTR_DRBG,
* you must use AES-256 *and* use sufficient entropy.
* See ctr_drbg.h for more details.
@ -3164,6 +3195,17 @@
*/
#define MBEDTLS_SHA512_C
/**
* \def MBEDTLS_SHA3_C
*
* Enable the SHA3 cryptographic hash algorithm.
*
* Module: library/sha3.c
*
* This module adds support for SHA3.
*/
#define MBEDTLS_SHA3_C
/**
* \def MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
*

View File

@ -112,6 +112,12 @@
#define MBEDTLS_MD_CAN_SHA512
#define MBEDTLS_MD_SOME_LEGACY
#endif
#if defined(MBEDTLS_SHA3_C)
#define MBEDTLS_MD_CAN_SHA3_224
#define MBEDTLS_MD_CAN_SHA3_256
#define MBEDTLS_MD_CAN_SHA3_384
#define MBEDTLS_MD_CAN_SHA3_512
#endif
#if defined(MBEDTLS_RIPEMD160_C)
#define MBEDTLS_MD_CAN_RIPEMD160
#define MBEDTLS_MD_SOME_LEGACY
@ -149,23 +155,43 @@ typedef enum {
MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */
MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */
MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */
MBEDTLS_MD_SHA3_224, /**< The SHA3-224 message digest. */
MBEDTLS_MD_SHA3_256, /**< The SHA3-256 message digest. */
MBEDTLS_MD_SHA3_384, /**< The SHA3-384 message digest. */
MBEDTLS_MD_SHA3_512, /**< The SHA3-512 message digest. */
} mbedtls_md_type_t;
#if defined(MBEDTLS_MD_CAN_SHA512)
/* Note: this should always be >= PSA_HASH_MAX_SIZE
* in all builds with both CRYPTO_C and MD_LIGHT.
*
* This is to make things easier for modules such as TLS that may define a
* buffer size using MD_MAX_SIZE in a part of the code that's common to PSA
* and legacy, then assume the buffer's size is PSA_HASH_MAX_SIZE in another
* part of the code based on PSA.
*/
#if defined(MBEDTLS_MD_CAN_SHA512) || defined(MBEDTLS_MD_CAN_SHA3_512)
#define MBEDTLS_MD_MAX_SIZE 64 /* longest known is SHA512 */
#elif defined(MBEDTLS_MD_CAN_SHA384)
#elif defined(MBEDTLS_MD_CAN_SHA384) || defined(MBEDTLS_MD_CAN_SHA3_384)
#define MBEDTLS_MD_MAX_SIZE 48 /* longest known is SHA384 */
#elif defined(MBEDTLS_MD_CAN_SHA256)
#elif defined(MBEDTLS_MD_CAN_SHA256) || defined(MBEDTLS_MD_CAN_SHA3_256)
#define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 */
#elif defined(MBEDTLS_MD_CAN_SHA224)
#elif defined(MBEDTLS_MD_CAN_SHA224) || defined(MBEDTLS_MD_CAN_SHA3_224)
#define MBEDTLS_MD_MAX_SIZE 28 /* longest known is SHA224 */
#else
#define MBEDTLS_MD_MAX_SIZE 20 /* longest known is SHA1 or RIPE MD-160
or smaller (MD5 and earlier) */
#endif
#if defined(MBEDTLS_MD_CAN_SHA512)
#if defined(MBEDTLS_MD_CAN_SHA3_224)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 144 /* the longest known is SHA3-224 */
#elif defined(MBEDTLS_MD_CAN_SHA3_256)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 136
#elif defined(MBEDTLS_MD_CAN_SHA512) || defined(MBEDTLS_MD_CAN_SHA384)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 128
#elif defined(MBEDTLS_MD_CAN_SHA3_384)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 104
#elif defined(MBEDTLS_MD_CAN_SHA3_512)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 72
#else
#define MBEDTLS_MD_MAX_BLOCK_SIZE 64
#endif
@ -310,6 +336,20 @@ int mbedtls_md_clone(mbedtls_md_context_t *dst,
*/
unsigned char mbedtls_md_get_size(const mbedtls_md_info_t *md_info);
/**
* \brief This function gives the message-digest size associated to
* message-digest type.
*
* \param md_type The message-digest type.
*
* \return The size of the message-digest output in Bytes,
* or 0 if the message-digest type is not known.
*/
static inline unsigned char mbedtls_md_get_size_from_type(mbedtls_md_type_t md_type)
{
return mbedtls_md_get_size(mbedtls_md_info_from_type(md_type));
}
/**
* \brief This function extracts the message-digest type from the
* message-digest information structure.

View File

@ -63,6 +63,11 @@
#define MBEDTLS_OID_X509_EXT_FRESHEST_CRL (1 << 14)
#define MBEDTLS_OID_X509_EXT_NS_CERT_TYPE (1 << 16)
/*
* Maximum number of OID components allowed
*/
#define MBEDTLS_OID_MAX_COMPONENTS 128
/*
* Top level OID tuples
*/
@ -90,6 +95,9 @@
#define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03"
#define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02"
#define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a"
#define MBEDTLS_OID_ORG_THAWTE "\x65" /* thawte(101) */
#define MBEDTLS_OID_THAWTE MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_ORG_THAWTE
#define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */
#define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG \
MBEDTLS_OID_ORG_CERTICOM
@ -437,6 +445,15 @@
* ecdsa-with-SHA2(3) 4 } */
#define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04"
/*
* EC key algorithms from RFC 8410
*/
#define MBEDTLS_OID_X25519 MBEDTLS_OID_THAWTE "\x6e" /**< id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 } */
#define MBEDTLS_OID_X448 MBEDTLS_OID_THAWTE "\x6f" /**< id-X448 OBJECT IDENTIFIER ::= { 1 3 101 111 } */
#define MBEDTLS_OID_ED25519 MBEDTLS_OID_THAWTE "\x70" /**< id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 } */
#define MBEDTLS_OID_ED448 MBEDTLS_OID_THAWTE "\x71" /**< id-Ed448 OBJECT IDENTIFIER ::= { 1 3 101 113 } */
#ifdef __cplusplus
extern "C" {
#endif
@ -466,6 +483,25 @@ typedef struct mbedtls_oid_descriptor_t {
*/
int mbedtls_oid_get_numeric_string(char *buf, size_t size, const mbedtls_asn1_buf *oid);
/**
* \brief Translate a string containing a dotted-decimal
* representation of an ASN.1 OID into its encoded form
* (e.g. "1.2.840.113549" into "\x2A\x86\x48\x86\xF7\x0D").
* On success, this function allocates oid->buf from the
* heap. It must be freed by the caller using mbedtls_free().
*
* \param oid #mbedtls_asn1_buf to populate with the DER-encoded OID
* \param oid_str string representation of the OID to parse
* \param size length of the OID string, not including any null terminator
*
* \return 0 if successful
* \return #MBEDTLS_ERR_ASN1_INVALID_DATA if \p oid_str does not
* represent a valid OID
* \return #MBEDTLS_ERR_ASN1_ALLOC_FAILED if the function fails to
* allocate oid->buf
*/
int mbedtls_oid_from_numeric_string(mbedtls_asn1_buf *oid, const char *oid_str, size_t size);
/**
* \brief Translate an X.509 extension OID into local values
*
@ -509,7 +545,7 @@ int mbedtls_oid_get_pk_alg(const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_al
int mbedtls_oid_get_oid_by_pk_alg(mbedtls_pk_type_t pk_alg,
const char **oid, size_t *olen);
#if defined(MBEDTLS_ECP_LIGHT)
#if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
/**
* \brief Translate NamedCurve OID into an EC group identifier
*
@ -531,7 +567,31 @@ int mbedtls_oid_get_ec_grp(const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *gr
*/
int mbedtls_oid_get_oid_by_ec_grp(mbedtls_ecp_group_id grp_id,
const char **oid, size_t *olen);
#endif /* MBEDTLS_ECP_LIGHT */
/**
* \brief Translate AlgorithmIdentifier OID into an EC group identifier,
* for curves that are directly encoded at this level
*
* \param oid OID to use
* \param grp_id place to store group id
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_ec_grp_algid(const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id);
/**
* \brief Translate EC group identifier into AlgorithmIdentifier OID,
* for curves that are directly encoded at this level
*
* \param grp_id EC group identifier
* \param oid place to store ASN.1 OID string pointer
* \param olen length of the OID
*
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_oid_by_ec_grp_algid(mbedtls_ecp_group_id grp_id,
const char **oid, size_t *olen);
#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
/**
* \brief Translate SignatureAlgorithm OID into md_type and pk_type

View File

@ -40,7 +40,7 @@
#include "mbedtls/ecdsa.h"
#endif
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_PSA_CRYPTO_C)
#include "psa/crypto.h"
#endif
@ -184,7 +184,7 @@ typedef struct mbedtls_pk_rsassa_pss_options {
#endif
#else /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(PSA_WANT_ALG_ECDSA)
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PK_CAN_ECDSA_SIGN
#endif
#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
@ -202,6 +202,35 @@ typedef struct mbedtls_pk_rsassa_pss_options {
#define MBEDTLS_PK_CAN_ECDH
#endif
/* Internal helper to define which fields in the pk_context structure below
* should be used for EC keys: legacy ecp_keypair or the raw (PSA friendly)
* format. It should be noticed that this only affect how data is stored, not
* which functions are used for various operations. The overall picture looks
* like this:
* - if USE_PSA is not defined and ECP_C is then use ecp_keypair data structure
* and legacy functions
* - if USE_PSA is defined and
* - if ECP_C then use ecp_keypair structure, convert data to a PSA friendly
* format and use PSA functions
* - if !ECP_C then use new raw data and PSA functions directly.
*
* The main reason for the "intermediate" (USE_PSA + ECP_C) above is that as long
* as ECP_C is defined mbedtls_pk_ec() gives the user a read/write access to the
* ecp_keypair structure inside the pk_context so he/she can modify it using
* ECP functions which are not under PK module's control.
*/
#if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) && \
!defined(MBEDTLS_ECP_C)
#define MBEDTLS_PK_USE_PSA_EC_DATA
#endif /* MBEDTLS_USE_PSA_CRYPTO && !MBEDTLS_ECP_C */
/* Helper symbol to state that the PK module has support for EC keys. This
* can either be provided through the legacy ECP solution or through the
* PSA friendly MBEDTLS_PK_USE_PSA_EC_DATA. */
#if defined(MBEDTLS_PK_USE_PSA_EC_DATA) || defined(MBEDTLS_ECP_C)
#define MBEDTLS_PK_HAVE_ECC_KEYS
#endif /* MBEDTLS_PK_USE_PSA_EC_DATA || MBEDTLS_ECP_C */
/**
* \brief Types for interfacing with the debug module
*/
@ -209,6 +238,7 @@ typedef enum {
MBEDTLS_PK_DEBUG_NONE = 0,
MBEDTLS_PK_DEBUG_MPI,
MBEDTLS_PK_DEBUG_ECP,
MBEDTLS_PK_DEBUG_PSA_EC,
} mbedtls_pk_debug_type;
/**
@ -232,12 +262,59 @@ typedef struct mbedtls_pk_debug_item {
*/
typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
#define MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN \
PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
/**
* \brief Public key container
*/
typedef struct mbedtls_pk_context {
const mbedtls_pk_info_t *MBEDTLS_PRIVATE(pk_info); /**< Public key information */
void *MBEDTLS_PRIVATE(pk_ctx); /**< Underlying public key context */
/* The following field is used to store the ID of a private key in the
* following cases:
* - opaque key when MBEDTLS_PSA_CRYPTO_C is defined
* - normal key when MBEDTLS_PK_USE_PSA_EC_DATA is defined. In this case:
* - the pk_ctx above is not not used to store the private key anymore.
* Actually that field not populated at all in this case because also
* the public key will be stored in raw format as explained below
* - this ID is used for all private key operations (ex: sign, check
* key pair, key write, etc) using PSA functions
*
* Note: this private key storing solution only affects EC keys, not the
* other ones. The latters still use the pk_ctx to store their own
* context.
*
* Note: this priv_id is guarded by MBEDTLS_PSA_CRYPTO_C and not by
* MBEDTLS_PK_USE_PSA_EC_DATA (as the public counterpart below) because,
* when working with opaque keys, it can be used also in
* mbedtls_pk_sign_ext for RSA keys. */
#if defined(MBEDTLS_PSA_CRYPTO_C)
mbedtls_svc_key_id_t MBEDTLS_PRIVATE(priv_id); /**< Key ID for opaque keys */
#endif /* MBEDTLS_PSA_CRYPTO_C */
/* The following fields are meant for storing the public key in raw format
* which is handy for:
* - easily importing it into the PSA context
* - reducing the ECP module dependencies in the PK one.
*
* When MBEDTLS_PK_USE_PSA_EC_DATA is enabled:
* - the pk_ctx above is not used anymore for storing the public key
* inside the ecp_keypair structure
* - the following fields are used for all public key operations: signature
* verify, key pair check and key write.
* Of course, when MBEDTLS_PK_USE_PSA_EC_DATA is not enabled, the legacy
* ecp_keypair structure is used for storing the public key and performing
* all the operations.
*
* Note: This new public key storing solution only works for EC keys, not
* other ones. The latters still use pk_ctx to store their own
* context.
*/
#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
uint8_t MBEDTLS_PRIVATE(pub_raw)[MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN]; /**< Raw public key */
size_t MBEDTLS_PRIVATE(pub_raw_len); /**< Valid bytes in "pub_raw" */
psa_ecc_family_t MBEDTLS_PRIVATE(ec_family); /**< EC family of pk */
size_t MBEDTLS_PRIVATE(ec_bits); /**< Curve's bits of pk */
#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
} mbedtls_pk_context;
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
@ -771,7 +848,7 @@ static inline mbedtls_rsa_context *mbedtls_pk_rsa(const mbedtls_pk_context pk)
}
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_LIGHT)
#if defined(MBEDTLS_ECP_C)
/**
* Quick access to an EC context inside a PK context.
*
@ -794,7 +871,7 @@ static inline mbedtls_ecp_keypair *mbedtls_pk_ec(const mbedtls_pk_context pk)
return NULL;
}
}
#endif /* MBEDTLS_ECP_LIGHT */
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_PK_PARSE_C)
/** \ingroup pk_module */

View File

@ -139,6 +139,8 @@ extern "C" {
#if defined(MBEDTLS_PLATFORM_MEMORY)
#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \
defined(MBEDTLS_PLATFORM_CALLOC_MACRO)
#undef mbedtls_free
#undef mbedtls_calloc
#define mbedtls_free MBEDTLS_PLATFORM_FREE_MACRO
#define mbedtls_calloc MBEDTLS_PLATFORM_CALLOC_MACRO
#else
@ -160,6 +162,8 @@ int mbedtls_platform_set_calloc_free(void *(*calloc_func)(size_t, size_t),
void (*free_func)(void *));
#endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */
#else /* !MBEDTLS_PLATFORM_MEMORY */
#undef mbedtls_free
#undef mbedtls_calloc
#define mbedtls_free free
#define mbedtls_calloc calloc
#endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */
@ -184,6 +188,7 @@ extern int (*mbedtls_fprintf)(FILE *stream, const char *format, ...);
int mbedtls_platform_set_fprintf(int (*fprintf_func)(FILE *stream, const char *,
...));
#else
#undef mbedtls_fprintf
#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO)
#define mbedtls_fprintf MBEDTLS_PLATFORM_FPRINTF_MACRO
#else
@ -208,6 +213,7 @@ extern int (*mbedtls_printf)(const char *format, ...);
*/
int mbedtls_platform_set_printf(int (*printf_func)(const char *, ...));
#else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
#undef mbedtls_printf
#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO)
#define mbedtls_printf MBEDTLS_PLATFORM_PRINTF_MACRO
#else
@ -243,6 +249,7 @@ extern int (*mbedtls_snprintf)(char *s, size_t n, const char *format, ...);
int mbedtls_platform_set_snprintf(int (*snprintf_func)(char *s, size_t n,
const char *format, ...));
#else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
#undef mbedtls_snprintf
#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
#define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO
#else
@ -279,6 +286,7 @@ extern int (*mbedtls_vsnprintf)(char *s, size_t n, const char *format, va_list a
int mbedtls_platform_set_vsnprintf(int (*vsnprintf_func)(char *s, size_t n,
const char *format, va_list arg));
#else /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */
#undef mbedtls_vsnprintf
#if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO)
#define mbedtls_vsnprintf MBEDTLS_PLATFORM_VSNPRINTF_MACRO
#else
@ -320,7 +328,9 @@ extern void (*mbedtls_setbuf)(FILE *stream, char *buf);
*/
int mbedtls_platform_set_setbuf(void (*setbuf_func)(
FILE *stream, char *buf));
#elif defined(MBEDTLS_PLATFORM_SETBUF_MACRO)
#else
#undef mbedtls_setbuf
#if defined(MBEDTLS_PLATFORM_SETBUF_MACRO)
/**
* \brief Macro defining the function for the library to
* call for `setbuf` functionality (changing the
@ -334,7 +344,8 @@ int mbedtls_platform_set_setbuf(void (*setbuf_func)(
#define mbedtls_setbuf MBEDTLS_PLATFORM_SETBUF_MACRO
#else
#define mbedtls_setbuf setbuf
#endif /* MBEDTLS_PLATFORM_SETBUF_ALT / MBEDTLS_PLATFORM_SETBUF_MACRO */
#endif /* MBEDTLS_PLATFORM_SETBUF_MACRO */
#endif /* MBEDTLS_PLATFORM_SETBUF_ALT */
/*
* The function pointers for exit
@ -353,6 +364,7 @@ extern void (*mbedtls_exit)(int status);
*/
int mbedtls_platform_set_exit(void (*exit_func)(int status));
#else
#undef mbedtls_exit
#if defined(MBEDTLS_PLATFORM_EXIT_MACRO)
#define mbedtls_exit MBEDTLS_PLATFORM_EXIT_MACRO
#else
@ -405,6 +417,8 @@ int mbedtls_platform_set_nv_seed(
int (*nv_seed_write_func)(unsigned char *buf, size_t buf_len)
);
#else
#undef mbedtls_nv_seed_read
#undef mbedtls_nv_seed_write
#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \
defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO)
#define mbedtls_nv_seed_read MBEDTLS_PLATFORM_NV_SEED_READ_MACRO

View File

@ -29,6 +29,8 @@
#include "mbedtls/build_info.h"
#include "mbedtls/platform_util.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#include "psa/crypto.h"
@ -38,7 +40,6 @@
#include "mbedtls/pk.h"
#include "mbedtls/oid.h"
#include "mbedtls/error.h"
#include <string.h>
/* Translations for symmetric crypto. */
@ -120,49 +121,6 @@ static inline psa_key_usage_t mbedtls_psa_translate_cipher_operation(
}
}
/* Translations for hashing. */
/* Note: this function should not be used from inside the library, use
* mbedtls_hash_info_psa_from_md() from the internal hash_info.h instead.
* It is kept only for compatibility in case applications were using it. */
static inline psa_algorithm_t mbedtls_psa_translate_md(mbedtls_md_type_t md_alg)
{
switch (md_alg) {
#if defined(MBEDTLS_MD5_C) || defined(PSA_WANT_ALG_MD5)
case MBEDTLS_MD_MD5:
return PSA_ALG_MD5;
#endif
#if defined(MBEDTLS_SHA1_C) || defined(PSA_WANT_ALG_SHA_1)
case MBEDTLS_MD_SHA1:
return PSA_ALG_SHA_1;
#endif
#if defined(MBEDTLS_SHA224_C) || defined(PSA_WANT_ALG_SHA_224)
case MBEDTLS_MD_SHA224:
return PSA_ALG_SHA_224;
#endif
#if defined(MBEDTLS_SHA256_C) || defined(PSA_WANT_ALG_SHA_256)
case MBEDTLS_MD_SHA256:
return PSA_ALG_SHA_256;
#endif
#if defined(MBEDTLS_SHA384_C) || defined(PSA_WANT_ALG_SHA_384)
case MBEDTLS_MD_SHA384:
return PSA_ALG_SHA_384;
#endif
#if defined(MBEDTLS_SHA512_C) || defined(PSA_WANT_ALG_SHA_512)
case MBEDTLS_MD_SHA512:
return PSA_ALG_SHA_512;
#endif
#if defined(MBEDTLS_RIPEMD160_C) || defined(PSA_WANT_ALG_RIPEMD160)
case MBEDTLS_MD_RIPEMD160:
return PSA_ALG_RIPEMD160;
#endif
case MBEDTLS_MD_NONE:
return 0;
default:
return 0;
}
}
/* Translations for ECC. */
static inline int mbedtls_psa_get_ecc_oid_from_id(
@ -248,6 +206,22 @@ static inline int mbedtls_psa_get_ecc_oid_from_id(
#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
}
break;
case PSA_ECC_FAMILY_MONTGOMERY:
switch (bits) {
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
case 255:
*oid = MBEDTLS_OID_X25519;
*oid_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_X25519);
return 0;
#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
case 448:
*oid = MBEDTLS_OID_X448;
*oid_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_X448);
return 0;
#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */
}
break;
}
(void) oid;
(void) oid_len;
@ -260,6 +234,9 @@ static inline int mbedtls_psa_get_ecc_oid_from_id(
#define MBEDTLS_PSA_MAX_EC_KEY_PAIR_LENGTH \
PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
#define MBEDTLS_PSA_MAX_FFDH_PUBKEY_LENGTH \
PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS)
/* Expose whatever RNG the PSA subsystem uses to applications using the
* mbedtls_xxx API. The declarations and definitions here need to be
* consistent with the implementation in library/psa_crypto_random_impl.h.
@ -345,11 +322,15 @@ extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state;
#endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
typedef struct {
psa_status_t psa_status;
/* Error codes used by PSA crypto are in -255..-128, fitting in 16 bits. */
int16_t psa_status;
/* Error codes used by Mbed TLS are in one of the ranges
* -127..-1 (low-level) or -32767..-4096 (high-level with a low-level
* code optionally added), fitting in 16 bits. */
int16_t mbedtls_error;
} mbedtls_error_pair_t;
#if !defined(MBEDTLS_MD_C) || !defined(MBEDTLS_MD5_C) || defined(MBEDTLS_USE_PSA_CRYPTO)
#if defined(MBEDTLS_MD_LIGHT)
extern const mbedtls_error_pair_t psa_to_md_errors[4];
#endif
@ -362,7 +343,7 @@ extern const mbedtls_error_pair_t psa_to_ssl_errors[7];
#endif
#if defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
defined(MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY)
extern const mbedtls_error_pair_t psa_to_pk_rsa_errors[8];
#endif

184
include/mbedtls/sha3.h Normal file
View File

@ -0,0 +1,184 @@
/**
* \file sha3.h
*
* \brief This file contains SHA-3 definitions and functions.
*
* The Secure Hash Algorithms cryptographic
* hash functions are defined in <em>FIPS 202: SHA-3 Standard:
* Permutation-Based Hash and Extendable-Output Functions </em>.
*/
/*
* 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_SHA3_H
#define MBEDTLS_SHA3_H
#include "mbedtls/private_access.h"
#include "mbedtls/build_info.h"
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** SHA-3 input data was malformed. */
#define MBEDTLS_ERR_SHA3_BAD_INPUT_DATA -0x0076
/**
* SHA-3 family id.
*
* It identifies the family (SHA3-256, SHA3-512, etc.)
*/
typedef enum {
MBEDTLS_SHA3_NONE = 0, /*!< Operation not defined. */
MBEDTLS_SHA3_224, /*!< SHA3-224 */
MBEDTLS_SHA3_256, /*!< SHA3-256 */
MBEDTLS_SHA3_384, /*!< SHA3-384 */
MBEDTLS_SHA3_512, /*!< SHA3-512 */
} mbedtls_sha3_id;
/**
* \brief The SHA-3 context structure.
*
* The structure is used SHA-3 checksum calculations.
*/
typedef struct {
uint64_t MBEDTLS_PRIVATE(state[25]);
uint32_t MBEDTLS_PRIVATE(index);
uint16_t MBEDTLS_PRIVATE(olen);
uint16_t MBEDTLS_PRIVATE(max_block_size);
}
mbedtls_sha3_context;
/**
* \brief This function initializes a SHA-3 context.
*
* \param ctx The SHA-3 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha3_init(mbedtls_sha3_context *ctx);
/**
* \brief This function clears a SHA-3 context.
*
* \param ctx The SHA-3 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-3 context.
*/
void mbedtls_sha3_free(mbedtls_sha3_context *ctx);
/**
* \brief This function clones the state of a SHA-3 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void mbedtls_sha3_clone(mbedtls_sha3_context *dst,
const mbedtls_sha3_context *src);
/**
* \brief This function starts a SHA-3 checksum
* calculation.
*
* \param ctx The context to use. This must be initialized.
* \param id The id of the SHA-3 family.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha3_starts(mbedtls_sha3_context *ctx, mbedtls_sha3_id id);
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-3 checksum calculation.
*
* \param ctx The SHA-3 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha3_update(mbedtls_sha3_context *ctx,
const uint8_t *input,
size_t ilen);
/**
* \brief This function finishes the SHA-3 operation, and writes
* the result to the output buffer.
*
* \param ctx The SHA-3 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-3 checksum result.
* This must be a writable buffer of length \c olen bytes.
* \param olen Defines the length of output buffer (in bytes). For SHA-3 224, SHA-3 256,
* SHA-3 384 and SHA-3 512 \c olen must equal to 28, 32, 48 and 64,
* respectively.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha3_finish(mbedtls_sha3_context *ctx,
uint8_t *output, size_t olen);
/**
* \brief This function calculates the SHA-3
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-3 result is calculated as
* output = SHA-3(id, input buffer, d).
*
* \param id The id of the SHA-3 family.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-3 checksum result.
* This must be a writable buffer of length \c olen bytes.
* \param olen Defines the length of output buffer (in bytes). For SHA-3 224, SHA-3 256,
* SHA-3 384 and SHA-3 512 \c olen must equal to 28, 32, 48 and 64,
* respectively.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha3(mbedtls_sha3_id id, const uint8_t *input,
size_t ilen,
uint8_t *output,
size_t olen);
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine for the algorithms implemented
* by this module: SHA3-224, SHA3-256, SHA3-384, SHA3-512.
*
* \return 0 if successful, or 1 if the test failed.
*/
int mbedtls_sha3_self_test(int verbose);
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha3.h */

View File

@ -243,6 +243,17 @@ typedef mbedtls_asn1_named_data mbedtls_x509_name;
*/
typedef mbedtls_asn1_sequence mbedtls_x509_sequence;
/*
* Container for the fields of the Authority Key Identifier object
*/
typedef struct mbedtls_x509_authority {
mbedtls_x509_buf keyIdentifier;
mbedtls_x509_sequence authorityCertIssuer;
mbedtls_x509_buf authorityCertSerialNumber;
mbedtls_x509_buf raw;
}
mbedtls_x509_authority;
/** Container for date and time (precision in seconds). */
typedef struct mbedtls_x509_time {
int year, mon, day; /**< Date. */
@ -293,7 +304,7 @@ mbedtls_x509_san_other_name;
typedef struct mbedtls_x509_subject_alternative_name {
int type; /**< The SAN type, value of MBEDTLS_X509_SAN_XXX. */
union {
mbedtls_x509_san_other_name other_name; /**< The otherName supported type. */
mbedtls_x509_san_other_name other_name;
mbedtls_x509_name directory_name;
mbedtls_x509_buf unstructured_name; /**< The buffer for the unstructured types. rfc822Name, dnsName and uniformResourceIdentifier are currently supported. */
}
@ -301,6 +312,12 @@ typedef struct mbedtls_x509_subject_alternative_name {
}
mbedtls_x509_subject_alternative_name;
typedef struct mbedtls_x509_san_list {
mbedtls_x509_subject_alternative_name node;
struct mbedtls_x509_san_list *next;
}
mbedtls_x509_san_list;
/** \} name Structures for parsing X.509 certificates, CRLs and CSRs */
/**
@ -349,6 +366,31 @@ static inline mbedtls_x509_name *mbedtls_x509_dn_get_next(
*/
int mbedtls_x509_serial_gets(char *buf, size_t size, const mbedtls_x509_buf *serial);
/**
* \brief Compare pair of mbedtls_x509_time.
*
* \param t1 mbedtls_x509_time to compare
* \param t2 mbedtls_x509_time to compare
*
* \return < 0 if t1 is before t2
* 0 if t1 equals t2
* > 0 if t1 is after t2
*/
int mbedtls_x509_time_cmp(const mbedtls_x509_time *t1, const mbedtls_x509_time *t2);
#if defined(MBEDTLS_HAVE_TIME_DATE)
/**
* \brief Fill mbedtls_x509_time with provided mbedtls_time_t.
*
* \param tt mbedtls_time_t to convert
* \param now mbedtls_x509_time to fill with converted mbedtls_time_t
*
* \return \c 0 on success
* \return A non-zero return value on failure.
*/
int mbedtls_x509_time_gmtime(mbedtls_time_t tt, mbedtls_x509_time *now);
#endif /* MBEDTLS_HAVE_TIME_DATE */
/**
* \brief Check a given mbedtls_x509_time against the system time
* and tell if it's in the past.
@ -390,7 +432,8 @@ int mbedtls_x509_time_is_future(const mbedtls_x509_time *from);
* of the subject alternative name encoded in \p san_raw.
*
* \note Supported GeneralName types, as defined in RFC 5280:
* "rfc822Name", "dnsName", "uniformResourceIdentifier" and "hardware_module_name"
* "rfc822Name", "dnsName", "directoryName",
* "uniformResourceIdentifier" and "hardware_module_name"
* of type "otherName", as defined in RFC 4108.
*
* \note This function should be called on a single raw data of
@ -470,6 +513,9 @@ int mbedtls_x509_get_key_usage(unsigned char **p,
int mbedtls_x509_get_subject_alt_name(unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name);
int mbedtls_x509_get_subject_alt_name_ext(unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name);
int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size,
const mbedtls_x509_sequence
*subject_alt_name,
@ -479,6 +525,23 @@ int mbedtls_x509_info_cert_type(char **buf, size_t *size,
int mbedtls_x509_info_key_usage(char **buf, size_t *size,
unsigned int key_usage);
/**
* \brief This function parses a CN string as an IP address.
*
* \param cn The CN string to parse. CN string MUST be null-terminated.
* \param dst The target buffer to populate with the binary IP address.
* The buffer MUST be 16 bytes to save IPv6, and should be
* 4-byte aligned if the result will be used as struct in_addr.
* e.g. uint32_t dst[4]
*
* \note \p cn is parsed as an IPv6 address if string contains ':',
* else \p cn is parsed as an IPv4 address.
*
* \return Length of binary IP address; num bytes written to target.
* \return \c 0 on failure to parse CN string as an IP address.
*/
size_t mbedtls_x509_crt_parse_cn_inet_pton(const char *cn, void *dst);
#define MBEDTLS_X509_SAFE_SNPRINTF \
do { \
if (ret < 0 || (size_t) ret >= n) \

View File

@ -75,7 +75,9 @@ typedef struct mbedtls_x509_crt {
mbedtls_x509_buf issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */
mbedtls_x509_buf subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */
mbedtls_x509_buf v3_ext; /**< Optional X.509 v3 extensions. */
mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension (currently only dNSName, uniformResourceIdentifier, DirectoryName and OtherName are listed). */
mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension. These can be later parsed by mbedtls_x509_parse_subject_alt_name. */
mbedtls_x509_buf subject_key_id; /**< Optional X.509 v3 extension subject key identifier. */
mbedtls_x509_authority authority_key_id; /**< Optional X.509 v3 extension authority key identifier. */
mbedtls_x509_sequence certificate_policies; /**< Optional list of certificate policies (Only anyPolicy is printed and enforced, however the rest of the policies are still listed). */
@ -239,6 +241,21 @@ typedef struct mbedtls_x509write_cert {
}
mbedtls_x509write_cert;
/**
* \brief Set Subject Alternative Name
*
* \param ctx Certificate context to use
* \param san_list List of SAN values
*
* \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
*
* \note "dnsName", "uniformResourceIdentifier", "IP address",
* "otherName", and "DirectoryName", as defined in RFC 5280,
* are supported.
*/
int mbedtls_x509write_crt_set_subject_alternative_name(mbedtls_x509write_cert *ctx,
const mbedtls_x509_san_list *san_list);
/**
* Item in a verification chain: cert and flags for it
*/
@ -559,6 +576,7 @@ int mbedtls_x509_crt_parse_file(mbedtls_x509_crt *chain, const char *path);
int mbedtls_x509_crt_parse_path(mbedtls_x509_crt *chain, const char *path);
#endif /* MBEDTLS_FS_IO */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Returns an informational string about the
@ -638,8 +656,12 @@ int mbedtls_x509_crt_verify_info(char *buf, size_t size, const char *prefix,
* \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. DNS names and IP addresses are supported. This
* may be \c NULL if the CN need not be verified.
* Subject name. DNS names and IP addresses are fully
* supported, while the URI subtype is partially supported:
* only exact matching, without any normalization procedures
* described in 7.4 of RFC5280, will result in a positive
* URI verification.
* 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.

View File

@ -60,7 +60,7 @@ typedef struct mbedtls_x509_csr {
unsigned int key_usage; /**< Optional key usage extension value: See the values in x509.h */
unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension (currently only dNSName and OtherName are listed). */
mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension. These can be later parsed by mbedtls_x509_parse_subject_alt_name. */
int MBEDTLS_PRIVATE(ext_types); /**< Bit string containing detected and parsed extensions */
@ -83,12 +83,6 @@ typedef struct mbedtls_x509write_csr {
}
mbedtls_x509write_csr;
typedef struct mbedtls_x509_san_list {
mbedtls_x509_subject_alternative_name node;
struct mbedtls_x509_san_list *next;
}
mbedtls_x509_san_list;
#if defined(MBEDTLS_X509_CSR_PARSE_C)
/**
* \brief Load a Certificate Signing Request (CSR) in DER format

View File

@ -105,5 +105,26 @@ typedef struct psa_tls12_prf_key_derivation_s {
} psa_tls12_prf_key_derivation_t;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
typedef enum {
PSA_PBKDF2_STATE_INIT, /* no input provided */
PSA_PBKDF2_STATE_INPUT_COST_SET, /* input cost has been set */
PSA_PBKDF2_STATE_SALT_SET, /* salt has been set */
PSA_PBKDF2_STATE_PASSWORD_SET, /* password has been set */
PSA_PBKDF2_STATE_OUTPUT /* output has been started */
} psa_pbkdf2_key_derivation_state_t;
typedef struct {
psa_pbkdf2_key_derivation_state_t MBEDTLS_PRIVATE(state);
uint64_t MBEDTLS_PRIVATE(input_cost);
uint8_t *MBEDTLS_PRIVATE(salt);
size_t MBEDTLS_PRIVATE(salt_length);
uint8_t MBEDTLS_PRIVATE(password)[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
size_t MBEDTLS_PRIVATE(password_length);
uint8_t MBEDTLS_PRIVATE(output_block)[PSA_HASH_MAX_SIZE];
uint8_t MBEDTLS_PRIVATE(bytes_used);
uint32_t MBEDTLS_PRIVATE(block_number);
} psa_pbkdf2_key_derivation_t;
#endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
#endif /* PSA_CRYPTO_BUILTIN_KEY_DERIVATION_H */

View File

@ -5,7 +5,7 @@
*
* 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.
* These names may be removed in a future version of Mbed TLS.
*
* \note This file may not be included directly. Applications must
* include psa/crypto.h.

View File

@ -65,6 +65,7 @@
#define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1
#define PSA_WANT_ALG_ECB_NO_PADDING 1
#define PSA_WANT_ALG_ECDH 1
#define PSA_WANT_ALG_FFDH 1
#define PSA_WANT_ALG_ECDSA 1
#define PSA_WANT_ALG_JPAKE 1
#define PSA_WANT_ALG_GCM 1
@ -74,9 +75,7 @@
#define PSA_WANT_ALG_HMAC 1
#define PSA_WANT_ALG_MD5 1
#define PSA_WANT_ALG_OFB 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_PBKDF2_HMAC 1
#define PSA_WANT_ALG_PBKDF2_HMAC 1
#define PSA_WANT_ALG_RIPEMD160 1
#define PSA_WANT_ALG_RSA_OAEP 1
#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
@ -92,8 +91,7 @@
#define PSA_WANT_ALG_TLS12_PSK_TO_MS 1
#define PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
/* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_XTS 1
#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
@ -124,10 +122,36 @@
#define PSA_WANT_KEY_TYPE_CAMELLIA 1
#define PSA_WANT_KEY_TYPE_CHACHA20 1
#define PSA_WANT_KEY_TYPE_DES 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1
//#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1 /* Deprecated */
#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_RAW_DATA 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1
//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1 /* Deprecated */
#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
/*
* The following symbols extend and deprecate the legacy
* PSA_WANT_KEY_TYPE_xxx_KEY_PAIR ones. They include the usage of that key in
* the name's suffix. "_USE" is the most generic and it can be used to describe
* a generic suport, whereas other ones add more features on top of that and
* they are more specific.
*/
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE 1 /* Not supported */
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
//#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE 1 /* Not supported */
#endif /* PSA_CRYPTO_CONFIG_H */

View File

@ -55,6 +55,9 @@ typedef union {
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
psa_tls12_ecjpake_to_pms_t MBEDTLS_PRIVATE(tls12_ecjpake_to_pms);
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
psa_pbkdf2_key_derivation_t MBEDTLS_PRIVATE(pbkdf2);
#endif
} psa_driver_key_derivation_context_t;
#endif /* PSA_CRYPTO_DRIVER_CONTEXTS_KEY_DERIVATION_H */

View File

@ -106,7 +106,7 @@ static inline psa_algorithm_t psa_get_key_enrollment_algorithm(
* indicates the slot number that contains it.
* \retval #PSA_ERROR_NOT_PERMITTED
* The caller is not permitted to query the slot number.
* Mbed Crypto currently does not return this error.
* Mbed TLS currently does not return this error.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The key is not located in a secure element.
*/
@ -219,7 +219,7 @@ void mbedtls_psa_crypto_free(void);
* resource consumption related to the PSA keystore.
*
* \note The content of this structure is not part of the stable API and ABI
* of Mbed Crypto and may change arbitrarily from version to version.
* of Mbed TLS and may change arbitrarily from version to version.
*/
typedef struct mbedtls_psa_stats_s {
/** Number of slots containing key material for a volatile key. */
@ -248,7 +248,7 @@ typedef struct mbedtls_psa_stats_s {
/** \brief Get statistics about
* resource consumption related to the PSA keystore.
*
* \note When Mbed Crypto is built as part of a service, with isolation
* \note When Mbed TLS is built as part of a service, with isolation
* between the application and the keystore, the service may or
* may not expose this function.
*/
@ -572,8 +572,7 @@ psa_status_t psa_get_key_domain_parameters(
/** \defgroup psa_tls_helpers TLS helper functions
* @{
*/
#if defined(MBEDTLS_ECP_LIGHT)
#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
#include <mbedtls/ecp.h>
/** Convert an ECC curve identifier from the Mbed TLS encoding to PSA.
@ -589,54 +588,8 @@ psa_status_t psa_get_key_domain_parameters(
* (`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;
}
}
psa_ecc_family_t mbedtls_ecc_group_to_psa(mbedtls_ecp_group_id grpid,
size_t *bits);
/** Convert an ECC curve identifier from the PSA encoding to Mbed TLS.
*
@ -660,7 +613,7 @@ static inline psa_ecc_family_t mbedtls_ecc_group_to_psa(mbedtls_ecp_group_id grp
mbedtls_ecp_group_id mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,
size_t bits,
int bits_is_sloppy);
#endif /* MBEDTLS_ECP_LIGHT */
#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
/**@}*/
@ -956,7 +909,7 @@ psa_status_t mbedtls_psa_platform_get_builtin_key(
* the official PSA Crypto API yet.
*
* \note The content of this section is not part of the stable API and ABI
* of Mbed Crypto and may change arbitrarily from version to version.
* of Mbed TLS and may change arbitrarily from version to version.
* Same holds for the corresponding macros #PSA_ALG_CATEGORY_PAKE and
* #PSA_ALG_JPAKE.
* @{
@ -2031,34 +1984,6 @@ struct psa_crypto_driver_pake_inputs_s {
psa_pake_cipher_suite_t MBEDTLS_PRIVATE(cipher_suite);
};
typedef enum psa_jpake_step {
PSA_PAKE_STEP_INVALID = 0,
PSA_PAKE_STEP_X1_X2 = 1,
PSA_PAKE_STEP_X2S = 2,
PSA_PAKE_STEP_DERIVE = 3,
} psa_jpake_step_t;
typedef enum psa_jpake_state {
PSA_PAKE_STATE_INVALID = 0,
PSA_PAKE_STATE_SETUP = 1,
PSA_PAKE_STATE_READY = 2,
PSA_PAKE_OUTPUT_X1_X2 = 3,
PSA_PAKE_OUTPUT_X2S = 4,
PSA_PAKE_INPUT_X1_X2 = 5,
PSA_PAKE_INPUT_X4S = 6,
} psa_jpake_state_t;
typedef enum psa_jpake_sequence {
PSA_PAKE_SEQ_INVALID = 0,
PSA_PAKE_X1_STEP_KEY_SHARE = 1, /* also X2S & X4S KEY_SHARE */
PSA_PAKE_X1_STEP_ZK_PUBLIC = 2, /* also X2S & X4S ZK_PUBLIC */
PSA_PAKE_X1_STEP_ZK_PROOF = 3, /* also X2S & X4S ZK_PROOF */
PSA_PAKE_X2_STEP_KEY_SHARE = 4,
PSA_PAKE_X2_STEP_ZK_PUBLIC = 5,
PSA_PAKE_X2_STEP_ZK_PROOF = 6,
PSA_PAKE_SEQ_END = 7,
} psa_jpake_sequence_t;
typedef enum psa_crypto_driver_pake_step {
PSA_JPAKE_STEP_INVALID = 0, /* Invalid step */
PSA_JPAKE_X1_STEP_KEY_SHARE = 1, /* Round 1: input/output key share (for ephemeral private key X1).*/
@ -2075,14 +2000,35 @@ typedef enum psa_crypto_driver_pake_step {
PSA_JPAKE_X4S_STEP_ZK_PROOF = 12 /* Round 2: input Schnorr NIZKP proof for the X4S key (from peer) */
} psa_crypto_driver_pake_step_t;
typedef enum psa_jpake_round {
PSA_JPAKE_FIRST = 0,
PSA_JPAKE_SECOND = 1,
PSA_JPAKE_FINISHED = 2
} psa_jpake_round_t;
typedef enum psa_jpake_io_mode {
PSA_JPAKE_INPUT = 0,
PSA_JPAKE_OUTPUT = 1
} psa_jpake_io_mode_t;
struct psa_jpake_computation_stage_s {
psa_jpake_state_t MBEDTLS_PRIVATE(state);
psa_jpake_sequence_t MBEDTLS_PRIVATE(sequence);
psa_jpake_step_t MBEDTLS_PRIVATE(input_step);
psa_jpake_step_t MBEDTLS_PRIVATE(output_step);
/* The J-PAKE round we are currently on */
psa_jpake_round_t MBEDTLS_PRIVATE(round);
/* The 'mode' we are currently in (inputting or outputting) */
psa_jpake_io_mode_t MBEDTLS_PRIVATE(io_mode);
/* The number of completed inputs so far this round */
uint8_t MBEDTLS_PRIVATE(inputs);
/* The number of completed outputs so far this round */
uint8_t MBEDTLS_PRIVATE(outputs);
/* The next expected step (KEY_SHARE, ZK_PUBLIC or ZK_PROOF) */
psa_pake_step_t MBEDTLS_PRIVATE(step);
};
#define PSA_JPAKE_EXPECTED_INPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
((round) == PSA_JPAKE_FIRST ? 2 : 1))
#define PSA_JPAKE_EXPECTED_OUTPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
((round) == PSA_JPAKE_FIRST ? 2 : 1))
struct psa_pake_operation_s {
/** Unique ID indicating which driver got assigned to do the
* operation. Since driver contexts are driver-specific, swapping

100
include/psa/crypto_legacy.h Normal file
View File

@ -0,0 +1,100 @@
/**
* \file psa/crypto_legacy.h
*
* \brief Add temporary suppport for deprecated symbols before they are
* removed from the library.
*
* PSA_WANT_KEY_TYPE_xxx_KEY_PAIR_LEGACY and
* MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR_LEGACY symbols are deprecated.
* New symols add a suffix to that base name in order to clearly state what is
* the expected use for the key (use, import, export, generate, derive).
* Here we define some backward compatibility support for uses stil using
* the legacy symbols.
*/
/*
* 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_PSA_CRYPTO_LEGACY_H
#define MBEDTLS_PSA_CRYPTO_LEGACY_H
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) //no-check-names
#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
#endif
#endif
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) //no-check-names
#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
#endif
#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
#endif
#endif
#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) //no-check-names
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE
#endif
#endif
#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) //no-check-names
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT
#endif
#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE
#endif
#endif
#endif /* MBEDTLS_PSA_CRYPTO_LEGACY_H */

View File

@ -83,7 +83,7 @@ static inline int mbedtls_key_owner_id_equal(mbedtls_key_owner_id_t id1,
*/
#if defined(MBEDTLS_PSA_CRYPTO_SPM)
#define PSA_CRYPTO_SECURE 1
#include "crypto_spe.h"
#include "../tests/include/spe/crypto_spe.h"
#endif // MBEDTLS_PSA_CRYPTO_SPM
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)

View File

@ -138,7 +138,7 @@ typedef psa_status_t (*psa_drv_se_init_t)(psa_drv_se_context_t *drv_context,
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
/* Mbed TLS with secure element support enabled defines this type in
* crypto_types.h because it is also visible to applications through an
* implementation-specific extension.
* For the PSA Cryptography specification, this type is only visible
@ -837,7 +837,7 @@ typedef enum {
* and #PSA_ERROR_DOES_NOT_EXIST if the driver can determine that there
* is no key with the specified slot number.
*
* This is an Mbed Crypto extension.
* This is an Mbed TLS extension.
*/
PSA_KEY_CREATION_REGISTER,
#endif

View File

@ -51,6 +51,8 @@
#define PSA_BITS_TO_BYTES(bits) (((bits) + 7) / 8)
#define PSA_BYTES_TO_BITS(bytes) ((bytes) * 8)
#define PSA_MAX_OF_THREE(a, b, c) ((a) <= (b) ? (b) <= (c) ? \
(c) : (b) : (a) <= (c) ? (c) : (a))
#define PSA_ROUND_UP_TO_MULTIPLE(block_size, length) \
(((length) + (block_size) - 1) / (block_size) * (block_size))
@ -126,12 +128,23 @@
/* Note: for HMAC-SHA-3, the block size is 144 bytes for HMAC-SHA3-226,
* 136 bytes for HMAC-SHA3-256, 104 bytes for SHA3-384, 72 bytes for
* HMAC-SHA3-512. */
#if defined(PSA_WANT_ALG_SHA_512) || defined(PSA_WANT_ALG_SHA_384)
/* Note: PSA_HASH_MAX_SIZE should be kept in sync with MBEDTLS_MD_MAX_SIZE,
* see the note on MBEDTLS_MD_MAX_SIZE for details. */
#if defined(PSA_WANT_ALG_SHA_512)
#define PSA_HASH_MAX_SIZE 64
#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128
#else
#elif defined(PSA_WANT_ALG_SHA_384)
#define PSA_HASH_MAX_SIZE 48
#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128
#elif defined(PSA_WANT_ALG_SHA_256)
#define PSA_HASH_MAX_SIZE 32
#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64
#elif defined(PSA_WANT_ALG_SHA_224)
#define PSA_HASH_MAX_SIZE 28
#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64
#else /* SHA-1 or smaller */
#define PSA_HASH_MAX_SIZE 20
#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64
#endif
/** \def PSA_MAC_MAX_SIZE
@ -195,6 +208,12 @@
* 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 DH key on this implementation, in bits.
*
* Note that an implementation may set different size limits for different
* operations, and does not need to accept all key sizes up to the limit. */
#define PSA_VENDOR_FFDH_MAX_KEY_BITS 8192
/* The maximum size of an ECC key on this implementation, in bits.
* This is a vendor-specific macro. */
#if defined(PSA_WANT_ECC_SECP_R1_521)
@ -253,6 +272,10 @@
* curve. */
#define PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE 32
/* The maximum number of iterations for PBKDF2 on this implementation, in bits.
* This is a vendor-specific macro. This can be configured if necessary */
#define PSA_VENDOR_PBKDF2_MAX_ITERATIONS 0xffffffff
/** The maximum size of a block cipher. */
#define PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE 16
@ -804,6 +827,18 @@
#define PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(key_bits) \
(PSA_BITS_TO_BYTES(key_bits))
/* Maximum size of the export encoding of an DH key pair.
*
* An DH key pair is represented by the secret value.
*/
#define PSA_KEY_EXPORT_FFDH_KEY_PAIR_MAX_SIZE(key_bits) \
(PSA_BITS_TO_BYTES(key_bits))
/* Maximum size of the export encoding of an DH public key.
*/
#define PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(key_bits) \
(PSA_BITS_TO_BYTES(key_bits))
/** Sufficient output buffer size for psa_export_key() or
* psa_export_public_key().
*
@ -845,6 +880,7 @@
*/
#define PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, key_bits) \
(PSA_KEY_TYPE_IS_UNSTRUCTURED(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
PSA_KEY_TYPE_IS_DH(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
(key_type) == PSA_KEY_TYPE_RSA_KEY_PAIR ? PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(key_bits) : \
(key_type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \
(key_type) == PSA_KEY_TYPE_DSA_KEY_PAIR ? PSA_KEY_EXPORT_DSA_KEY_PAIR_MAX_SIZE(key_bits) : \
@ -901,6 +937,7 @@
#define PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, key_bits) \
(PSA_KEY_TYPE_IS_RSA(key_type) ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \
PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \
PSA_KEY_TYPE_IS_DH(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
0)
/** Sufficient buffer size for exporting any asymmetric key pair.
@ -911,11 +948,10 @@
*
* See also #PSA_EXPORT_KEY_OUTPUT_SIZE(\p key_type, \p key_bits).
*/
#define PSA_EXPORT_KEY_PAIR_MAX_SIZE \
(PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \
PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) ? \
PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) : \
PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS))
#define PSA_EXPORT_KEY_PAIR_MAX_SIZE \
PSA_MAX_OF_THREE(PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS), \
PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS), \
PSA_KEY_EXPORT_FFDH_KEY_PAIR_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS))
/** Sufficient buffer size for exporting any asymmetric public key.
*
@ -926,11 +962,11 @@
*
* See also #PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(\p key_type, \p key_bits).
*/
#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \
(PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \
PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) ? \
PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) : \
PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS))
#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \
PSA_MAX_OF_THREE(PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS), \
PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS), \
PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS))
/** Sufficient output buffer size for psa_raw_key_agreement().
*
@ -955,11 +991,9 @@
* If the parameters are not valid,
* the return value is unspecified.
*/
/* FFDH is not yet supported in PSA. */
#define PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(key_type, key_bits) \
(PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) ? \
PSA_BITS_TO_BYTES(key_bits) : \
0)
((PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) || \
PSA_KEY_TYPE_IS_DH_KEY_PAIR(key_type)) ? PSA_BITS_TO_BYTES(key_bits) : 0)
/** Maximum size of the output from psa_raw_key_agreement().
*
@ -968,8 +1002,11 @@
*
* See also #PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(\p key_type, \p key_bits).
*/
#define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE \
(PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS))
#define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE \
(PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS) > \
PSA_BITS_TO_BYTES(PSA_VENDOR_FFDH_MAX_KEY_BITS) ? \
PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS) : \
PSA_BITS_TO_BYTES(PSA_VENDOR_FFDH_MAX_KEY_BITS))
/** The default IV size for a cipher algorithm, in bytes.
*

View File

@ -35,8 +35,8 @@
* GCC and Clang initialize the whole structure to 0 (at the time of writing),
* but MSVC and CompCert don't.
*
* In Mbed Crypto, multipart operation structures live independently from
* the key. This allows Mbed Crypto to free the key objects when destroying
* In Mbed TLS, multipart operation structures live independently from
* the key. This allows Mbed TLS to free the key objects when destroying
* a key slot. If a multipart operation needs to remember the key after
* the setup function returns, the operation structure needs to contain a
* copy of the key.

View File

@ -297,7 +297,7 @@ typedef uint32_t psa_key_id_t;
typedef psa_key_id_t mbedtls_svc_key_id_t;
#else /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
/* Implementation-specific: The Mbed Cryptography library can be built as
/* Implementation-specific: The Mbed TLS library can be built as
* part of a multi-client service that exposes the PSA Cryptography API in each
* client and encodes the client identity in the key identifier argument of
* functions such as psa_open_key().
@ -439,7 +439,7 @@ typedef struct psa_key_attributes_s psa_key_attributes_t;
#ifndef __DOXYGEN_ONLY__
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Mbed Crypto defines this type in crypto_types.h because it is also
/* Mbed TLS defines this type in crypto_types.h because it is also
* visible to applications through an implementation-specific extension.
* For the PSA Cryptography specification, this type is only visible
* via crypto_se_driver.h. */

View File

@ -2102,7 +2102,8 @@
*/
#define PSA_ALG_IS_PBKDF2_HMAC(alg) \
(((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_PBKDF2_HMAC_BASE)
#define PSA_ALG_PBKDF2_HMAC_GET_HASH(pbkdf2_alg) \
(PSA_ALG_CATEGORY_HASH | ((pbkdf2_alg) & PSA_ALG_HASH_MASK))
/** The PBKDF2-AES-CMAC-PRF-128 password hashing / key stretching algorithm.
*
* PBKDF2 is defined by PKCS#5, republished as RFC 8018 (section 5.2).

1
library/.gitignore vendored
View File

@ -1,4 +1,3 @@
*.o
libmbed*
*.sln
*.vcxproj

View File

@ -42,7 +42,6 @@ set(src_crypto
entropy_poll.c
error.c
gcm.c
hash_info.c
hkdf.c
hmac_drbg.c
lmots.c
@ -69,6 +68,7 @@ set(src_crypto
psa_crypto_client.c
psa_crypto_driver_wrappers.c
psa_crypto_ecp.c
psa_crypto_ffdh.c
psa_crypto_hash.c
psa_crypto_mac.c
psa_crypto_pake.c
@ -84,6 +84,7 @@ set(src_crypto
sha1.c
sha256.c
sha512.c
sha3.c
threading.c
timing.c
version.c

View File

@ -107,7 +107,6 @@ OBJS_CRYPTO= \
entropy_poll.o \
error.o \
gcm.o \
hash_info.o \
hkdf.o \
hmac_drbg.o \
lmots.o \
@ -134,6 +133,7 @@ OBJS_CRYPTO= \
psa_crypto_client.o \
psa_crypto_driver_wrappers.o \
psa_crypto_ecp.o \
psa_crypto_ffdh.o \
psa_crypto_hash.o \
psa_crypto_mac.o \
psa_crypto_pake.o \
@ -149,6 +149,7 @@ OBJS_CRYPTO= \
sha1.o \
sha256.o \
sha512.o \
sha3.o \
threading.o \
timing.o \
version.o \

File diff suppressed because it is too large Load Diff

View File

@ -72,7 +72,7 @@
# define MBEDTLS_POP_TARGET_PRAGMA
# elif defined(__GNUC__)
# pragma GCC push_options
# pragma GCC target ("arch=armv8-a+crypto")
# pragma GCC target ("+crypto")
# define MBEDTLS_POP_TARGET_PRAGMA
# elif defined(_MSC_VER)
# error "Required feature(__ARM_FEATURE_AES) is not enabled."
@ -101,59 +101,105 @@ int mbedtls_aesce_has_support(void)
#endif
}
/* Single round of AESCE encryption */
#define AESCE_ENCRYPT_ROUND \
block = vaeseq_u8(block, vld1q_u8(keys)); \
block = vaesmcq_u8(block); \
keys += 16
/* Two rounds of AESCE encryption */
#define AESCE_ENCRYPT_ROUND_X2 AESCE_ENCRYPT_ROUND; AESCE_ENCRYPT_ROUND
MBEDTLS_OPTIMIZE_FOR_PERFORMANCE
static uint8x16_t aesce_encrypt_block(uint8x16_t block,
unsigned char *keys,
int rounds)
{
for (int i = 0; i < rounds - 1; i++) {
/* AES AddRoundKey, SubBytes, ShiftRows (in this order).
* AddRoundKey adds the round key for the previous round. */
block = vaeseq_u8(block, vld1q_u8(keys + i * 16));
/* AES mix columns */
block = vaesmcq_u8(block);
/* 10, 12 or 14 rounds. Unroll loop. */
if (rounds == 10) {
goto rounds_10;
}
if (rounds == 12) {
goto rounds_12;
}
AESCE_ENCRYPT_ROUND_X2;
rounds_12:
AESCE_ENCRYPT_ROUND_X2;
rounds_10:
AESCE_ENCRYPT_ROUND_X2;
AESCE_ENCRYPT_ROUND_X2;
AESCE_ENCRYPT_ROUND_X2;
AESCE_ENCRYPT_ROUND_X2;
AESCE_ENCRYPT_ROUND;
/* AES AddRoundKey for the previous round.
* SubBytes, ShiftRows for the final round. */
block = vaeseq_u8(block, vld1q_u8(keys + (rounds -1) * 16));
block = vaeseq_u8(block, vld1q_u8(keys));
keys += 16;
/* Final round: no MixColumns */
/* Final AddRoundKey */
block = veorq_u8(block, vld1q_u8(keys + rounds * 16));
block = veorq_u8(block, vld1q_u8(keys));
return block;
}
/* Single round of AESCE decryption
*
* AES AddRoundKey, SubBytes, ShiftRows
*
* block = vaesdq_u8(block, vld1q_u8(keys));
*
* AES inverse MixColumns for the next round.
*
* This means that we switch the order of the inverse AddRoundKey and
* inverse MixColumns operations. We have to do this as AddRoundKey is
* done in an atomic instruction together with the inverses of SubBytes
* and ShiftRows.
*
* It works because MixColumns is a linear operation over GF(2^8) and
* AddRoundKey is an exclusive or, which is equivalent to addition over
* GF(2^8). (The inverse of MixColumns needs to be applied to the
* affected round keys separately which has been done when the
* decryption round keys were calculated.)
*
* block = vaesimcq_u8(block);
*/
#define AESCE_DECRYPT_ROUND \
block = vaesdq_u8(block, vld1q_u8(keys)); \
block = vaesimcq_u8(block); \
keys += 16
/* Two rounds of AESCE decryption */
#define AESCE_DECRYPT_ROUND_X2 AESCE_DECRYPT_ROUND; AESCE_DECRYPT_ROUND
static uint8x16_t aesce_decrypt_block(uint8x16_t block,
unsigned char *keys,
int rounds)
{
for (int i = 0; i < rounds - 1; i++) {
/* AES AddRoundKey, SubBytes, ShiftRows */
block = vaesdq_u8(block, vld1q_u8(keys + i * 16));
/* AES inverse MixColumns for the next round.
*
* This means that we switch the order of the inverse AddRoundKey and
* inverse MixColumns operations. We have to do this as AddRoundKey is
* done in an atomic instruction together with the inverses of SubBytes
* and ShiftRows.
*
* It works because MixColumns is a linear operation over GF(2^8) and
* AddRoundKey is an exclusive or, which is equivalent to addition over
* GF(2^8). (The inverse of MixColumns needs to be applied to the
* affected round keys separately which has been done when the
* decryption round keys were calculated.) */
block = vaesimcq_u8(block);
/* 10, 12 or 14 rounds. Unroll loop. */
if (rounds == 10) {
goto rounds_10;
}
if (rounds == 12) {
goto rounds_12;
}
AESCE_DECRYPT_ROUND_X2;
rounds_12:
AESCE_DECRYPT_ROUND_X2;
rounds_10:
AESCE_DECRYPT_ROUND_X2;
AESCE_DECRYPT_ROUND_X2;
AESCE_DECRYPT_ROUND_X2;
AESCE_DECRYPT_ROUND_X2;
AESCE_DECRYPT_ROUND;
/* The inverses of AES AddRoundKey, SubBytes, ShiftRows finishing up the
* last full round. */
block = vaesdq_u8(block, vld1q_u8(keys + (rounds - 1) * 16));
block = vaesdq_u8(block, vld1q_u8(keys));
keys += 16;
/* Inverse AddRoundKey for inverting the initial round key addition. */
block = veorq_u8(block, vld1q_u8(keys + rounds * 16));
block = veorq_u8(block, vld1q_u8(keys));
return block;
}
@ -251,6 +297,7 @@ static void aesce_setkey_enc(unsigned char *rk,
/* Do not write overflow words.*/
continue;
}
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
switch (key_bit_length) {
case 128:
break;
@ -265,6 +312,7 @@ static void aesce_setkey_enc(unsigned char *rk,
rko[7] = rko[6] ^ rki[7];
break;
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
}
}

View File

@ -52,6 +52,9 @@ int mbedtls_aesce_has_support(void);
/**
* \brief Internal AES-ECB block encryption and decryption
*
* \warning This assumes that the context specifies either 10, 12 or 14
* rounds and will behave incorrectly if this is not the case.
*
* \param ctx AES context
* \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
* \param input 16-byte input block

View File

@ -273,6 +273,7 @@ static void aesni_setkey_enc_128(unsigned char *rk_bytes,
/*
* Key expansion, 192-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_set_rk_192(__m128i *state0, __m128i *state1, __m128i xword,
unsigned char *rk)
{
@ -327,10 +328,12 @@ static void aesni_setkey_enc_192(unsigned char *rk,
aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x40), rk + 24 * 7);
aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x80), rk + 24 * 8);
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/*
* Key expansion, 256-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_set_rk_256(__m128i state0, __m128i state1, __m128i xword,
__m128i *rk0, __m128i *rk1)
{
@ -387,6 +390,7 @@ static void aesni_setkey_enc_256(unsigned char *rk_bytes,
aesni_set_rk_256(rk[10], rk[11], _mm_aeskeygenassist_si128(rk[11], 0x20), &rk[12], &rk[13]);
aesni_set_rk_256(rk[12], rk[13], _mm_aeskeygenassist_si128(rk[13], 0x40), &rk[14], &rk[15]);
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#else /* MBEDTLS_AESNI_HAVE_CODE == 1 */
@ -656,6 +660,7 @@ static void aesni_setkey_enc_128(unsigned char *rk,
/*
* Key expansion, 192-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_setkey_enc_192(unsigned char *rk,
const unsigned char *key)
{
@ -709,10 +714,12 @@ static void aesni_setkey_enc_192(unsigned char *rk,
: "r" (rk), "r" (key)
: "memory", "cc", "0");
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/*
* Key expansion, 256-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_setkey_enc_256(unsigned char *rk,
const unsigned char *key)
{
@ -775,6 +782,7 @@ static void aesni_setkey_enc_256(unsigned char *rk,
: "r" (rk), "r" (key)
: "memory", "cc", "0");
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_AESNI_HAVE_CODE */
@ -787,8 +795,10 @@ int mbedtls_aesni_setkey_enc(unsigned char *rk,
{
switch (bits) {
case 128: aesni_setkey_enc_128(rk, key); break;
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
case 192: aesni_setkey_enc_192(rk, key); break;
case 256: aesni_setkey_enc_256(rk, key); break;
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
}

View File

@ -59,16 +59,16 @@
#define MBEDTLS_AESNI_HAVE_INTRINSICS
#endif
/* Choose the implementation of AESNI, if one is available. */
#undef MBEDTLS_AESNI_HAVE_CODE
/* To minimize disruption when releasing the intrinsics-based implementation,
* favor the assembly-based implementation if it's available. We intend to
* revise this in a later release of Mbed TLS 3.x. In the long run, we will
* likely remove the assembly implementation. */
#if defined(MBEDTLS_HAVE_X86_64)
#define MBEDTLS_AESNI_HAVE_CODE 1 // via assembly
#elif defined(MBEDTLS_AESNI_HAVE_INTRINSICS)
/* Choose the implementation of AESNI, if one is available.
*
* Favor the intrinsics-based implementation if it's available, for better
* maintainability.
* Performance is about the same (see #7380).
* In the long run, we will likely remove the assembly implementation. */
#if defined(MBEDTLS_AESNI_HAVE_INTRINSICS)
#define MBEDTLS_AESNI_HAVE_CODE 2 // via intrinsics
#elif defined(MBEDTLS_HAVE_X86_64)
#define MBEDTLS_AESNI_HAVE_CODE 1 // via assembly
#endif
#if defined(MBEDTLS_AESNI_HAVE_CODE)

View File

@ -194,14 +194,23 @@ int mbedtls_asn1_write_oid(unsigned char **p, const unsigned char *start,
int mbedtls_asn1_write_algorithm_identifier(unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len)
{
return mbedtls_asn1_write_algorithm_identifier_ext(p, start, oid, oid_len, par_len, 1);
}
int mbedtls_asn1_write_algorithm_identifier_ext(unsigned char **p, const unsigned char *start,
const char *oid, size_t oid_len,
size_t par_len, int has_par)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
if (par_len == 0) {
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_null(p, start));
} else {
len += par_len;
if (has_par) {
if (par_len == 0) {
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_null(p, start));
} else {
len += par_len;
}
}
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_oid(p, start, oid, oid_len));

View File

@ -17,6 +17,8 @@
* limitations under the License.
*/
#include <limits.h>
#include "common.h"
#if defined(MBEDTLS_BASE64_C)
@ -31,8 +33,6 @@
#include "mbedtls/platform.h"
#endif /* MBEDTLS_SELF_TEST */
#define BASE64_SIZE_T_MAX ((size_t) -1) /* SIZE_T_MAX is not standard */
/*
* Encode a buffer into base64 format
*/
@ -50,8 +50,8 @@ int mbedtls_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
n = slen / 3 + (slen % 3 != 0);
if (n > (BASE64_SIZE_T_MAX - 1) / 4) {
*olen = BASE64_SIZE_T_MAX;
if (n > (SIZE_MAX - 1) / 4) {
*olen = SIZE_MAX;
return MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL;
}

View File

@ -54,8 +54,6 @@
#define MPI_VALIDATE(cond) \
MBEDTLS_INTERNAL_VALIDATE(cond)
#define MPI_SIZE_T_MAX ((size_t) -1) /* SIZE_T_MAX is not standard */
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_mpi_zeroize(mbedtls_mpi_uint *v, size_t n)
{
@ -416,7 +414,7 @@ int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s)
slen = strlen(s);
if (radix == 16) {
if (slen > MPI_SIZE_T_MAX >> 2) {
if (slen > SIZE_MAX >> 2) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
@ -750,13 +748,9 @@ int mbedtls_mpi_write_binary(const mbedtls_mpi *X,
int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i, v0, t1;
mbedtls_mpi_uint r0 = 0, r1;
size_t i;
MPI_VALIDATE_RET(X != NULL);
v0 = count / (biL);
t1 = count & (biL - 1);
i = mbedtls_mpi_bitlen(X) + count;
if (X->n * biL < i) {
@ -765,31 +759,7 @@ int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count)
ret = 0;
/*
* shift by count / limb_size
*/
if (v0 > 0) {
for (i = X->n; i > v0; i--) {
X->p[i - 1] = X->p[i - v0 - 1];
}
for (; i > 0; i--) {
X->p[i - 1] = 0;
}
}
/*
* shift by count % limb_size
*/
if (t1 > 0) {
for (i = v0; i < X->n; i++) {
r1 = X->p[i] >> (biL - t1);
X->p[i] <<= t1;
X->p[i] |= r0;
r0 = r1;
}
}
mbedtls_mpi_core_shift_l(X->p, X->n, count);
cleanup:
return ret;

View File

@ -366,6 +366,41 @@ void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,
}
}
void mbedtls_mpi_core_shift_l(mbedtls_mpi_uint *X, size_t limbs,
size_t count)
{
size_t i, v0, v1;
mbedtls_mpi_uint r0 = 0, r1;
v0 = count / (biL);
v1 = count & (biL - 1);
/*
* shift by count / limb_size
*/
if (v0 > 0) {
for (i = limbs; i > v0; i--) {
X[i - 1] = X[i - v0 - 1];
}
for (; i > 0; i--) {
X[i - 1] = 0;
}
}
/*
* shift by count % limb_size
*/
if (v1 > 0) {
for (i = v0; i < limbs; i++) {
r1 = X[i] >> (biL - v1);
X[i] <<= v1;
X[i] |= r0;
r0 = r1;
}
}
}
mbedtls_mpi_uint mbedtls_mpi_core_add(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,

View File

@ -281,7 +281,7 @@ int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *A,
unsigned char *output,
size_t output_length);
/** \brief Shift an MPI right in place by a number of bits.
/** \brief Shift an MPI in-place right by a number of bits.
*
* Shifting by more bits than there are bit positions
* in \p X is valid and results in setting \p X to 0.
@ -296,6 +296,21 @@ int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *A,
void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,
size_t count);
/**
* \brief Shift an MPI in-place left by a number of bits.
*
* Shifting by more bits than there are bit positions
* in \p X will produce an unspecified result.
*
* This function's execution time depends on the value
* of \p count (and of course \p limbs).
* \param[in,out] X The number to shift.
* \param limbs The number of limbs of \p X. This must be at least 1.
* \param count The number of bits to shift by.
*/
void mbedtls_mpi_core_shift_l(mbedtls_mpi_uint *X, size_t limbs,
size_t count);
/**
* \brief Add two fixed-size large unsigned integers, returning the carry.
*

View File

@ -88,7 +88,7 @@ void mbedtls_mpi_mod_modulus_free(mbedtls_mpi_mod_modulus *N)
N->rep.mont.mm = 0;
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
mbedtls_free(N->rep.ored);
N->rep.ored.modp = NULL;
break;
case MBEDTLS_MPI_MOD_REP_INVALID:
break;
@ -136,33 +136,25 @@ cleanup:
return ret;
}
int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep)
static inline void standard_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep)
{
int ret = 0;
N->p = p;
N->limbs = p_limbs;
N->bits = mbedtls_mpi_core_bitlen(p, p_limbs);
N->int_rep = int_rep;
}
switch (int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
N->int_rep = int_rep;
N->rep.mont.mm = mbedtls_mpi_core_montmul_init(N->p);
ret = set_mont_const_square(&N->rep.mont.rr, N->p, N->limbs);
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
N->int_rep = int_rep;
N->rep.ored = NULL;
break;
default:
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
goto exit;
}
exit:
int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs)
{
int ret = 0;
standard_modulus_setup(N, p, p_limbs, MBEDTLS_MPI_MOD_REP_MONTGOMERY);
N->rep.mont.mm = mbedtls_mpi_core_montmul_init(N->p);
ret = set_mont_const_square(&N->rep.mont.rr, N->p, N->limbs);
if (ret != 0) {
mbedtls_mpi_mod_modulus_free(N);
@ -171,6 +163,16 @@ exit:
return ret;
}
int mbedtls_mpi_mod_optred_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_modp_fn modp)
{
standard_modulus_setup(N, p, p_limbs, MBEDTLS_MPI_MOD_REP_OPT_RED);
N->rep.ored.modp = modp;
return 0;
}
int mbedtls_mpi_mod_mul(mbedtls_mpi_mod_residue *X,
const mbedtls_mpi_mod_residue *A,
const mbedtls_mpi_mod_residue *B,
@ -235,8 +237,7 @@ static int mbedtls_mpi_mod_inv_non_mont(mbedtls_mpi_mod_residue *X,
mbedtls_mpi_mod_modulus Nmont;
mbedtls_mpi_mod_modulus_init(&Nmont);
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_modulus_setup(&Nmont, N->p, N->limbs,
MBEDTLS_MPI_MOD_REP_MONTGOMERY));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_modulus_setup(&Nmont, N->p, N->limbs));
/* We'll use X->p to hold the Montgomery form of the input A->p */
mbedtls_mpi_core_to_mont_rep(X->p, A->p, Nmont.p, Nmont.limbs,

View File

@ -98,10 +98,11 @@ typedef enum {
/* Skip 1 as it is slightly easier to accidentally pass to functions. */
/** Montgomery representation. */
MBEDTLS_MPI_MOD_REP_MONTGOMERY = 2,
/** TODO: document this.
*
* Residues are in canonical representation.
*/
/* Optimised reduction available. This indicates a coordinate modulus (P)
* and one or more of the following have been configured:
* - A nist curve (MBEDTLS_ECP_DP_SECPXXXR1_ENABLED) & MBEDTLS_ECP_NIST_OPTIM.
* - A Kobliz Curve.
* - A Fast Reduction Curve CURVE25519 or CURVE448. */
MBEDTLS_MPI_MOD_REP_OPT_RED,
} mbedtls_mpi_mod_rep_selector;
@ -123,7 +124,11 @@ typedef struct {
mbedtls_mpi_uint mm; /* Montgomery const for -N^{-1} mod 2^{ciL} */
} mbedtls_mpi_mont_struct;
typedef void *mbedtls_mpi_opt_red_struct;
typedef int (*mbedtls_mpi_modp_fn)(mbedtls_mpi_uint *X, size_t X_limbs);
typedef struct {
mbedtls_mpi_modp_fn modp; /* The optimised reduction function pointer */
} mbedtls_mpi_opt_red_struct;
typedef struct {
const mbedtls_mpi_uint *p;
@ -197,16 +202,29 @@ void mbedtls_mpi_mod_modulus_init(mbedtls_mpi_mod_modulus *N);
* not be modified in any way until after
* mbedtls_mpi_mod_modulus_free() is called.
* \param p_limbs The number of limbs of \p p.
* \param int_rep The internal representation to be used for residues
* associated with \p N (see #mbedtls_mpi_mod_rep_selector).
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p int_rep is invalid.
*/
int mbedtls_mpi_mod_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_mod_rep_selector int_rep);
size_t p_limbs);
/** Setup an optimised-reduction compatible modulus structure.
*
* \param[out] N The address of the modulus structure to populate.
* \param[in] p The address of the limb array storing the value of \p N.
* The memory pointed to by \p p will be used by \p N and must
* not be modified in any way until after
* mbedtls_mpi_mod_modulus_free() is called.
* \param p_limbs The number of limbs of \p p.
* \param modp A pointer to the optimised reduction function to use. \p p.
*
* \return \c 0 if successful.
*/
int mbedtls_mpi_mod_optred_modulus_setup(mbedtls_mpi_mod_modulus *N,
const mbedtls_mpi_uint *p,
size_t p_limbs,
mbedtls_mpi_modp_fn modp);
/** Free elements of a modulus structure.
*

View File

@ -114,8 +114,6 @@ void mbedtls_mpi_mod_raw_sub(mbedtls_mpi_uint *X,
(void) mbedtls_mpi_core_add_if(X, N->p, N->limbs, (unsigned) c);
}
#if defined(MBEDTLS_TEST_HOOKS)
MBEDTLS_STATIC_TESTABLE
void mbedtls_mpi_mod_raw_fix_quasi_reduction(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N)
@ -125,7 +123,6 @@ void mbedtls_mpi_mod_raw_fix_quasi_reduction(mbedtls_mpi_uint *X,
(void) mbedtls_mpi_core_add_if(X, N->p, N->limbs, (unsigned) c);
}
#endif /* MBEDTLS_TEST_HOOKS */
void mbedtls_mpi_mod_raw_mul(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
@ -133,8 +130,31 @@ void mbedtls_mpi_mod_raw_mul(mbedtls_mpi_uint *X,
const mbedtls_mpi_mod_modulus *N,
mbedtls_mpi_uint *T)
{
mbedtls_mpi_core_montmul(X, A, B, N->limbs, N->p, N->limbs,
N->rep.mont.mm, T);
/* Standard (A * B) multiplication stored into pre-allocated T
* buffer of fixed limb size of (2N + 1).
*
* The space may not not fully filled by when
* MBEDTLS_MPI_MOD_REP_OPT_RED is used. */
const size_t T_limbs = BITS_TO_LIMBS(N->bits) * 2;
switch (N->int_rep) {
case MBEDTLS_MPI_MOD_REP_MONTGOMERY:
mbedtls_mpi_core_montmul(X, A, B, N->limbs, N->p, N->limbs,
N->rep.mont.mm, T);
break;
case MBEDTLS_MPI_MOD_REP_OPT_RED:
mbedtls_mpi_core_mul(T, A, N->limbs, B, N->limbs);
/* Optimised Reduction */
(*N->rep.ored.modp)(T, T_limbs);
/* Convert back to canonical representation */
mbedtls_mpi_mod_raw_fix_quasi_reduction(T, N);
memcpy(X, T, N->limbs * sizeof(mbedtls_mpi_uint));
break;
default:
break;
}
}
size_t mbedtls_mpi_mod_raw_inv_prime_working_limbs(size_t AN_limbs)

View File

@ -248,27 +248,39 @@
#endif /* AMD64 */
#if defined(__aarch64__)
// The following assembly code assumes that a pointer will fit in a 64-bit register
// (including ILP32 __aarch64__ ABIs such as on watchOS, hence the 2^32 - 1)
#if defined(__aarch64__) && (UINTPTR_MAX == 0xfffffffful || UINTPTR_MAX == 0xfffffffffffffffful)
/*
* There are some issues around different compilers requiring different constraint
* syntax for updating pointers from assembly code (see notes for
* MBEDTLS_ASM_AARCH64_PTR_CONSTRAINT in common.h), especially on aarch64_32 (aka ILP32).
*
* For this reason we cast the pointers to/from uintptr_t here.
*/
#define MULADDC_X1_INIT \
asm(
do { uintptr_t muladdc_d = (uintptr_t) d, muladdc_s = (uintptr_t) s; asm(
#define MULADDC_X1_CORE \
"ldr x4, [%2], #8 \n\t" \
"ldr x5, [%1] \n\t" \
"ldr x4, [%x2], #8 \n\t" \
"ldr x5, [%x1] \n\t" \
"mul x6, x4, %4 \n\t" \
"umulh x7, x4, %4 \n\t" \
"adds x5, x5, x6 \n\t" \
"adc x7, x7, xzr \n\t" \
"adds x5, x5, %0 \n\t" \
"adc %0, x7, xzr \n\t" \
"str x5, [%1], #8 \n\t"
"str x5, [%x1], #8 \n\t"
#define MULADDC_X1_STOP \
: "+r" (c), "+r" (d), "+r" (s), "+m" (*(uint64_t (*)[16]) d) \
: "+r" (c), \
"+r" (muladdc_d), \
"+r" (muladdc_s), \
"+m" (*(uint64_t (*)[16]) d) \
: "r" (b), "m" (*(const uint64_t (*)[16]) s) \
: "x4", "x5", "x6", "x7", "cc" \
);
); d = (mbedtls_mpi_uint *)muladdc_d; s = (mbedtls_mpi_uint *)muladdc_s; } while (0);
#endif /* Aarch64 */
@ -658,6 +670,16 @@
#endif /* TriCore */
#if defined(__arm__)
#if defined(__thumb__) && !defined(__thumb2__)
#if defined(MBEDTLS_COMPILER_IS_GCC)
/*
* Thumb 1 ISA. This code path has only been tested successfully on gcc;
* it does not compile on clang or armclang.
*/
#if !defined(__OPTIMIZE__) && defined(__GNUC__)
/*
* Note, gcc -O0 by default uses r7 for the frame pointer, so it complains about
* our use of r7 below, unless -fomit-frame-pointer is passed.
@ -666,32 +688,39 @@
* x !=0, which we can detect using __OPTIMIZE__ (which is also defined by
* clang and armcc5 under the same conditions).
*
* So, only use the optimized assembly below for optimized build, which avoids
* the build error and is pretty reasonable anyway.
* If gcc needs to use r7, we use r1 as a scratch register and have a few extra
* instructions to preserve/restore it; otherwise, we can use r7 and avoid
* the preserve/restore overhead.
*/
#if defined(__GNUC__) && !defined(__OPTIMIZE__)
#define MULADDC_CANNOT_USE_R7
#endif
#if defined(__arm__) && !defined(MULADDC_CANNOT_USE_R7)
#if defined(__thumb__) && !defined(__thumb2__)
#define MULADDC_SCRATCH "RS .req r1 \n\t"
#define MULADDC_PRESERVE_SCRATCH "mov r10, r1 \n\t"
#define MULADDC_RESTORE_SCRATCH "mov r1, r10 \n\t"
#define MULADDC_SCRATCH_CLOBBER "r10"
#else /* !defined(__OPTIMIZE__) && defined(__GNUC__) */
#define MULADDC_SCRATCH "RS .req r7 \n\t"
#define MULADDC_PRESERVE_SCRATCH ""
#define MULADDC_RESTORE_SCRATCH ""
#define MULADDC_SCRATCH_CLOBBER "r7"
#endif /* !defined(__OPTIMIZE__) && defined(__GNUC__) */
#define MULADDC_X1_INIT \
asm( \
MULADDC_SCRATCH \
"ldr r0, %3 \n\t" \
"ldr r1, %4 \n\t" \
"ldr r2, %5 \n\t" \
"ldr r3, %6 \n\t" \
"lsr r7, r3, #16 \n\t" \
"mov r9, r7 \n\t" \
"lsl r7, r3, #16 \n\t" \
"lsr r7, r7, #16 \n\t" \
"mov r8, r7 \n\t"
"lsr r4, r3, #16 \n\t" \
"mov r9, r4 \n\t" \
"lsl r4, r3, #16 \n\t" \
"lsr r4, r4, #16 \n\t" \
"mov r8, r4 \n\t" \
#define MULADDC_X1_CORE \
MULADDC_PRESERVE_SCRATCH \
"ldmia r0!, {r6} \n\t" \
"lsr r7, r6, #16 \n\t" \
"lsr RS, r6, #16 \n\t" \
"lsl r6, r6, #16 \n\t" \
"lsr r6, r6, #16 \n\t" \
"mov r4, r8 \n\t" \
@ -699,12 +728,12 @@
"mov r3, r9 \n\t" \
"mul r6, r3 \n\t" \
"mov r5, r9 \n\t" \
"mul r5, r7 \n\t" \
"mul r5, RS \n\t" \
"mov r3, r8 \n\t" \
"mul r7, r3 \n\t" \
"mul RS, r3 \n\t" \
"lsr r3, r6, #16 \n\t" \
"add r5, r5, r3 \n\t" \
"lsr r3, r7, #16 \n\t" \
"lsr r3, RS, #16 \n\t" \
"add r5, r5, r3 \n\t" \
"add r4, r4, r2 \n\t" \
"mov r2, #0 \n\t" \
@ -712,9 +741,10 @@
"lsl r3, r6, #16 \n\t" \
"add r4, r4, r3 \n\t" \
"adc r5, r2 \n\t" \
"lsl r3, r7, #16 \n\t" \
"lsl r3, RS, #16 \n\t" \
"add r4, r4, r3 \n\t" \
"adc r5, r2 \n\t" \
MULADDC_RESTORE_SCRATCH \
"ldr r3, [r1] \n\t" \
"add r4, r4, r3 \n\t" \
"adc r2, r5 \n\t" \
@ -727,11 +757,15 @@
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r0", "r1", "r2", "r3", "r4", "r5", \
"r6", "r7", "r8", "r9", "cc" \
"r6", MULADDC_SCRATCH_CLOBBER, "r8", "r9", "cc" \
);
#endif /* !defined(__ARMCC_VERSION) && !defined(__clang__) */
#elif (__ARM_ARCH >= 6) && \
defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1)
/* Armv6-M (or later) with DSP Instruction Set Extensions.
* Requires support for either Thumb 2 or Arm ISA.
*/
#define MULADDC_X1_INIT \
{ \
@ -796,7 +830,7 @@
); \
}
#else
#else /* Thumb 2 or Arm ISA, without DSP extensions */
#define MULADDC_X1_INIT \
asm( \
@ -810,9 +844,9 @@
"mov r5, #0 \n\t" \
"ldr r6, [r1] \n\t" \
"umlal r2, r5, r3, r4 \n\t" \
"adds r7, r6, r2 \n\t" \
"adds r4, r6, r2 \n\t" \
"adc r2, r5, #0 \n\t" \
"str r7, [r1], #4 \n\t"
"str r4, [r1], #4 \n\t"
#define MULADDC_X1_STOP \
"str r2, %0 \n\t" \
@ -821,12 +855,12 @@
: "=m" (c), "=m" (d), "=m" (s) \
: "m" (s), "m" (d), "m" (c), "m" (b) \
: "r0", "r1", "r2", "r3", "r4", "r5", \
"r6", "r7", "cc" \
"r6", "cc" \
);
#endif /* Thumb */
#endif /* ISA codepath selection */
#endif /* ARMv3 */
#endif /* defined(__arm__) */
#if defined(__alpha__)

View File

@ -70,7 +70,7 @@ int mbedtls_ccm_setkey(mbedtls_ccm_context *ctx,
return MBEDTLS_ERR_CCM_BAD_INPUT;
}
if (cipher_info->block_size != 16) {
if (mbedtls_cipher_info_get_block_size(cipher_info) != 16) {
return MBEDTLS_ERR_CCM_BAD_INPUT;
}

View File

@ -42,13 +42,13 @@
#endif
#if defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA) && \
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY))
#error "PSA_WANT_ALG_DETERMINISTIC_ECDSA defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_ECDSA) && \
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
!(defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY))
#error "PSA_WANT_ALG_ECDSA defined, but not all prerequisites"
#endif
@ -60,32 +60,84 @@
#endif
#if defined(PSA_WANT_ALG_RSA_PKCS1V15_CRYPT) && \
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
!(defined(MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PKCS1V15_CRYPT defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) && \
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
!(defined(MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PKCS1V15_SIGN defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_OAEP) && \
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
!(defined(MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_OAEP defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_ALG_RSA_PSS) && \
!(defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) || \
!(defined(MBEDTLS_PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_LEGACY) || \
defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY))
#error "PSA_WANT_ALG_RSA_PSS defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) && \
#if (defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT) || \
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) || \
defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)) && \
!defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
#error "PSA_WANT_KEY_TYPE_ECC_KEY_PAIR defined, but not all prerequisites"
#error "PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_xxx defined, but not all prerequisites"
#endif
#if (defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)) && \
!defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY)
#error "PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_xxx defined, but not all prerequisites"
#endif
#if (defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \
defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)) && \
!defined(PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY)
#error "PSA_WANT_KEY_TYPE_DH_KEY_PAIR_xxx defined, but not all prerequisites"
#endif
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
#if defined(MBEDTLS_DEPRECATED_REMOVED)
#error "PSA_WANT_KEY_TYPE_ECC_KEY_PAIR is deprecated and will be removed in a \
future version of Mbed TLS. Please switch to new PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_xxx \
symbols, where xxx can be: USE, IMPORT, EXPORT, GENERATE, DERIVE"
#elif defined(MBEDTLS_DEPRECATED_WARNING)
#warning "PSA_WANT_KEY_TYPE_ECC_KEY_PAIR is deprecated and will be removed in a \
future version of Mbed TLS. Please switch to new PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_xxx \
symbols, where xxx can be: USE, IMPORT, EXPORT, GENERATE, DERIVE"
#endif /* MBEDTLS_DEPRECATED_WARNING */
#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
#if defined(MBEDTLS_DEPRECATED_REMOVED)
#error "PSA_WANT_KEY_TYPE_RSA_KEY_PAIR is deprecated and will be removed in a \
future version of Mbed TLS. Please switch to new PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_xxx \
symbols, where xxx can be: USE, IMPORT, EXPORT, GENERATE, DERIVE"
#elif defined(MBEDTLS_DEPRECATED_WARNING)
#warning "PSA_WANT_KEY_TYPE_RSA_KEY_PAIR is deprecated and will be removed in a \
future version of Mbed TLS. Please switch to new PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_xxx \
symbols, where xxx can be: USE, IMPORT, EXPORT, GENERATE, DERIVE"
#endif /* MBEDTLS_DEPRECATED_WARNING */
#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR */
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE)
#error "PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE defined, but feature is not supported"
#endif
#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE)
#error "PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE defined, but feature is not supported"
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && defined(MBEDTLS_USE_PSA_CRYPTO) && \

View File

@ -67,6 +67,12 @@
static int supported_init = 0;
static inline const mbedtls_cipher_base_t *mbedtls_cipher_get_base(
const mbedtls_cipher_info_t *info)
{
return mbedtls_cipher_base_lookup_table[info->base_idx];
}
const int *mbedtls_cipher_list(void)
{
const mbedtls_cipher_definition_t *def;
@ -128,8 +134,8 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values(
const mbedtls_cipher_definition_t *def;
for (def = mbedtls_cipher_definitions; def->info != NULL; def++) {
if (def->info->base->cipher == cipher_id &&
def->info->key_bitlen == (unsigned) key_bitlen &&
if (mbedtls_cipher_get_base(def->info)->cipher == cipher_id &&
mbedtls_cipher_info_get_key_bitlen(def->info) == (unsigned) key_bitlen &&
def->info->mode == mode) {
return def->info;
}
@ -178,7 +184,7 @@ void mbedtls_cipher_free(mbedtls_cipher_context_t *ctx)
#endif
if (ctx->cipher_ctx) {
ctx->cipher_info->base->ctx_free_func(ctx->cipher_ctx);
mbedtls_cipher_get_base(ctx->cipher_info)->ctx_free_func(ctx->cipher_ctx);
}
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_cipher_context_t));
@ -193,7 +199,7 @@ int mbedtls_cipher_setup(mbedtls_cipher_context_t *ctx,
memset(ctx, 0, sizeof(mbedtls_cipher_context_t));
if (NULL == (ctx->cipher_ctx = cipher_info->base->ctx_alloc_func())) {
if (NULL == (ctx->cipher_ctx = mbedtls_cipher_get_base(cipher_info)->ctx_alloc_func())) {
return MBEDTLS_ERR_CIPHER_ALLOC_FAILED;
}
@ -228,11 +234,11 @@ int mbedtls_cipher_setup_psa(mbedtls_cipher_context_t *ctx,
/* Check that the underlying cipher mode and cipher type are
* supported by the underlying PSA Crypto implementation. */
alg = mbedtls_psa_translate_cipher_mode(cipher_info->mode, taglen);
alg = mbedtls_psa_translate_cipher_mode(((mbedtls_cipher_mode_t) cipher_info->mode), taglen);
if (alg == 0) {
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
if (mbedtls_psa_translate_cipher_type(cipher_info->type) == 0) {
if (mbedtls_psa_translate_cipher_type(((mbedtls_cipher_type_t) cipher_info->type)) == 0) {
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
@ -285,7 +291,7 @@ int mbedtls_cipher_setkey(mbedtls_cipher_context_t *ctx,
}
key_type = mbedtls_psa_translate_cipher_type(
ctx->cipher_info->type);
((mbedtls_cipher_type_t) ctx->cipher_info->type));
if (key_type == 0) {
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
@ -323,7 +329,7 @@ int mbedtls_cipher_setkey(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO */
if ((ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN) == 0 &&
(int) ctx->cipher_info->key_bitlen != key_bitlen) {
(int) mbedtls_cipher_info_get_key_bitlen(ctx->cipher_info) != key_bitlen) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
@ -334,16 +340,16 @@ int mbedtls_cipher_setkey(mbedtls_cipher_context_t *ctx,
* For OFB, CFB and CTR mode always use the encryption key schedule
*/
if (MBEDTLS_ENCRYPT == operation ||
MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_CTR == ctx->cipher_info->mode) {
return ctx->cipher_info->base->setkey_enc_func(ctx->cipher_ctx, key,
ctx->key_bitlen);
MBEDTLS_MODE_CFB == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_OFB == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_CTR == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
return mbedtls_cipher_get_base(ctx->cipher_info)->setkey_enc_func(ctx->cipher_ctx, key,
ctx->key_bitlen);
}
if (MBEDTLS_DECRYPT == operation) {
return ctx->cipher_info->base->setkey_dec_func(ctx->cipher_ctx, key,
ctx->key_bitlen);
return mbedtls_cipher_get_base(ctx->cipher_info)->setkey_dec_func(ctx->cipher_ctx, key,
ctx->key_bitlen);
}
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
@ -375,7 +381,7 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
if ((ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_IV_LEN) != 0) {
actual_iv_size = iv_len;
} else {
actual_iv_size = ctx->cipher_info->iv_size;
actual_iv_size = mbedtls_cipher_info_get_iv_size(ctx->cipher_info);
/* avoid reading past the end of input buffer */
if (actual_iv_size > iv_len) {
@ -384,7 +390,7 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
}
#if defined(MBEDTLS_CHACHA20_C)
if (ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20) {
if (((mbedtls_cipher_type_t) ctx->cipher_info->type) == MBEDTLS_CIPHER_CHACHA20) {
/* Even though the actual_iv_size is overwritten with a correct value
* of 12 from the cipher info, return an error to indicate that
* the input iv_len is wrong. */
@ -399,7 +405,7 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
}
}
#if defined(MBEDTLS_CHACHAPOLY_C)
if (ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 &&
if (((mbedtls_cipher_type_t) ctx->cipher_info->type) == MBEDTLS_CIPHER_CHACHA20_POLY1305 &&
iv_len != 12) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
@ -407,7 +413,7 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
#endif
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
return mbedtls_gcm_starts((mbedtls_gcm_context *) ctx->cipher_ctx,
ctx->operation,
iv, iv_len);
@ -415,7 +421,7 @@ int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
#endif
#if defined(MBEDTLS_CCM_C)
if (MBEDTLS_MODE_CCM_STAR_NO_TAG == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_CCM_STAR_NO_TAG == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
int set_lengths_result;
int ccm_star_mode;
@ -485,14 +491,14 @@ int mbedtls_cipher_update_ad(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
return mbedtls_gcm_update_ad((mbedtls_gcm_context *) ctx->cipher_ctx,
ad, ad_len);
}
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type) {
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) {
int result;
mbedtls_chachapoly_mode_t mode;
@ -541,15 +547,16 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;
}
if (ctx->cipher_info->mode == MBEDTLS_MODE_ECB) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_ECB) {
if (ilen != block_size) {
return MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED;
}
*olen = ilen;
if (0 != (ret = ctx->cipher_info->base->ecb_func(ctx->cipher_ctx,
ctx->operation, input, output))) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->ecb_func(ctx->cipher_ctx,
ctx->operation, input,
output))) {
return ret;
}
@ -557,7 +564,7 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
}
#if defined(MBEDTLS_GCM_C)
if (ctx->cipher_info->mode == MBEDTLS_MODE_GCM) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_GCM) {
return mbedtls_gcm_update((mbedtls_gcm_context *) ctx->cipher_ctx,
input, ilen,
output, ilen, olen);
@ -565,7 +572,7 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif
#if defined(MBEDTLS_CCM_C)
if (ctx->cipher_info->mode == MBEDTLS_MODE_CCM_STAR_NO_TAG) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_CCM_STAR_NO_TAG) {
return mbedtls_ccm_update((mbedtls_ccm_context *) ctx->cipher_ctx,
input, ilen,
output, ilen, olen);
@ -573,7 +580,7 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if (ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305) {
if (((mbedtls_cipher_type_t) ctx->cipher_info->type) == MBEDTLS_CIPHER_CHACHA20_POLY1305) {
*olen = ilen;
return mbedtls_chachapoly_update((mbedtls_chachapoly_context *) ctx->cipher_ctx,
ilen, input, output);
@ -586,7 +593,7 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
if (ctx->cipher_info->mode == MBEDTLS_MODE_CBC) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_CBC) {
size_t copy_len = 0;
/*
@ -614,9 +621,12 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
memcpy(&(ctx->unprocessed_data[ctx->unprocessed_len]), input,
copy_len);
if (0 != (ret = ctx->cipher_info->base->cbc_func(ctx->cipher_ctx,
ctx->operation, block_size, ctx->iv,
ctx->unprocessed_data, output))) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->cbc_func(ctx->cipher_ctx,
ctx->operation,
block_size, ctx->iv,
ctx->
unprocessed_data,
output))) {
return ret;
}
@ -654,9 +664,11 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
* Process remaining full blocks
*/
if (ilen) {
if (0 != (ret = ctx->cipher_info->base->cbc_func(ctx->cipher_ctx,
ctx->operation, ilen, ctx->iv, input,
output))) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->cbc_func(ctx->cipher_ctx,
ctx->operation,
ilen, ctx->iv,
input,
output))) {
return ret;
}
@ -668,11 +680,12 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
if (ctx->cipher_info->mode == MBEDTLS_MODE_CFB) {
if (0 != (ret = ctx->cipher_info->base->cfb_func(ctx->cipher_ctx,
ctx->operation, ilen,
&ctx->unprocessed_len, ctx->iv,
input, output))) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_CFB) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->cfb_func(ctx->cipher_ctx,
ctx->operation, ilen,
&ctx->unprocessed_len,
ctx->iv,
input, output))) {
return ret;
}
@ -683,10 +696,12 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
if (ctx->cipher_info->mode == MBEDTLS_MODE_OFB) {
if (0 != (ret = ctx->cipher_info->base->ofb_func(ctx->cipher_ctx,
ilen, &ctx->unprocessed_len, ctx->iv,
input, output))) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_OFB) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->ofb_func(ctx->cipher_ctx,
ilen,
&ctx->unprocessed_len,
ctx->iv,
input, output))) {
return ret;
}
@ -697,10 +712,13 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
if (ctx->cipher_info->mode == MBEDTLS_MODE_CTR) {
if (0 != (ret = ctx->cipher_info->base->ctr_func(ctx->cipher_ctx,
ilen, &ctx->unprocessed_len, ctx->iv,
ctx->unprocessed_data, input, output))) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_CTR) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->ctr_func(ctx->cipher_ctx,
ilen,
&ctx->unprocessed_len,
ctx->iv,
ctx->unprocessed_data,
input, output))) {
return ret;
}
@ -711,14 +729,18 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
if (ctx->cipher_info->mode == MBEDTLS_MODE_XTS) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_XTS) {
if (ctx->unprocessed_len > 0) {
/* We can only process an entire data unit at a time. */
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
ret = ctx->cipher_info->base->xts_func(ctx->cipher_ctx,
ctx->operation, ilen, ctx->iv, input, output);
ret = mbedtls_cipher_get_base(ctx->cipher_info)->xts_func(ctx->cipher_ctx,
ctx->operation,
ilen,
ctx->iv,
input,
output);
if (ret != 0) {
return ret;
}
@ -730,9 +752,10 @@ int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx, const unsigned char *in
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
if (ctx->cipher_info->mode == MBEDTLS_MODE_STREAM) {
if (0 != (ret = ctx->cipher_info->base->stream_func(ctx->cipher_ctx,
ilen, input, output))) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) == MBEDTLS_MODE_STREAM) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->stream_func(ctx->cipher_ctx,
ilen, input,
output))) {
return ret;
}
@ -944,22 +967,22 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
*olen = 0;
if (MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||
MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||
MBEDTLS_MODE_CCM_STAR_NO_TAG == ctx->cipher_info->mode ||
MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||
MBEDTLS_MODE_STREAM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_CFB == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_OFB == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_CTR == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_CCM_STAR_NO_TAG == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_XTS == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_STREAM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
return 0;
}
if ((MBEDTLS_CIPHER_CHACHA20 == ctx->cipher_info->type) ||
(MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type)) {
if ((MBEDTLS_CIPHER_CHACHA20 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) ||
(MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type))) {
return 0;
}
if (MBEDTLS_MODE_ECB == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_ECB == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
if (ctx->unprocessed_len != 0) {
return MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED;
}
@ -968,7 +991,7 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
if (MBEDTLS_MODE_CBC == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_CBC == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
int ret = 0;
if (MBEDTLS_ENCRYPT == ctx->operation) {
@ -996,11 +1019,13 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
}
/* cipher block */
if (0 != (ret = ctx->cipher_info->base->cbc_func(ctx->cipher_ctx,
ctx->operation,
mbedtls_cipher_get_block_size(ctx),
ctx->iv,
ctx->unprocessed_data, output))) {
if (0 != (ret = mbedtls_cipher_get_base(ctx->cipher_info)->cbc_func(ctx->cipher_ctx,
ctx->operation,
mbedtls_cipher_get_block_size(
ctx),
ctx->iv,
ctx->unprocessed_data,
output))) {
return ret;
}
@ -1025,7 +1050,8 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
int mbedtls_cipher_set_padding_mode(mbedtls_cipher_context_t *ctx,
mbedtls_cipher_padding_t mode)
{
if (NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode) {
if (NULL == ctx->cipher_info ||
MBEDTLS_MODE_CBC != ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
@ -1102,7 +1128,7 @@ int mbedtls_cipher_write_tag(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
size_t output_length;
/* The code here doesn't yet support alternative implementations
* that can delay up to a block of output. */
@ -1113,7 +1139,7 @@ int mbedtls_cipher_write_tag(mbedtls_cipher_context_t *ctx,
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type) {
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) {
/* Don't allow truncated MAC for Poly1305 */
if (tag_len != 16U) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
@ -1154,7 +1180,7 @@ int mbedtls_cipher_check_tag(mbedtls_cipher_context_t *ctx,
ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
size_t output_length;
/* The code here doesn't yet support alternative implementations
* that can delay up to a block of output. */
@ -1179,7 +1205,7 @@ int mbedtls_cipher_check_tag(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type) {
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) {
/* Don't allow truncated MAC for Poly1305 */
if (tag_len != sizeof(check_tag)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
@ -1250,7 +1276,7 @@ int mbedtls_cipher_crypt(mbedtls_cipher_context_t *ctx,
return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
}
if (ctx->cipher_info->mode != MBEDTLS_MODE_ECB) {
if (((mbedtls_cipher_mode_t) ctx->cipher_info->mode) != MBEDTLS_MODE_ECB) {
status = psa_cipher_set_iv(&cipher_op, iv, iv_len);
if (status != PSA_SUCCESS) {
return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
@ -1345,7 +1371,7 @@ static int mbedtls_cipher_aead_encrypt(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
*olen = ilen;
return mbedtls_gcm_crypt_and_tag(ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT,
ilen, iv, iv_len, ad, ad_len,
@ -1353,7 +1379,7 @@ static int mbedtls_cipher_aead_encrypt(mbedtls_cipher_context_t *ctx,
}
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
if (MBEDTLS_MODE_CCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_CCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
*olen = ilen;
return mbedtls_ccm_encrypt_and_tag(ctx->cipher_ctx, ilen,
iv, iv_len, ad, ad_len, input, output,
@ -1361,9 +1387,9 @@ static int mbedtls_cipher_aead_encrypt(mbedtls_cipher_context_t *ctx,
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type) {
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) {
/* ChachaPoly has fixed length nonce and MAC (tag) */
if ((iv_len != ctx->cipher_info->iv_size) ||
if ((iv_len != mbedtls_cipher_info_get_iv_size(ctx->cipher_info)) ||
(tag_len != 16U)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
@ -1423,7 +1449,7 @@ static int mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#if defined(MBEDTLS_GCM_C)
if (MBEDTLS_MODE_GCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_GCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
*olen = ilen;
@ -1439,7 +1465,7 @@ static int mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t *ctx,
}
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
if (MBEDTLS_MODE_CCM == ctx->cipher_info->mode) {
if (MBEDTLS_MODE_CCM == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) {
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
*olen = ilen;
@ -1455,11 +1481,11 @@ static int mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t *ctx,
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type) {
if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ((mbedtls_cipher_type_t) ctx->cipher_info->type)) {
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* ChachaPoly has fixed length nonce and MAC (tag) */
if ((iv_len != ctx->cipher_info->iv_size) ||
if ((iv_len != mbedtls_cipher_info_get_iv_size(ctx->cipher_info)) ||
(tag_len != 16U)) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
@ -1496,10 +1522,11 @@ int mbedtls_cipher_auth_encrypt_ext(mbedtls_cipher_context_t *ctx,
#if defined(MBEDTLS_USE_PSA_CRYPTO)
ctx->psa_enabled == 0 &&
#endif
(MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
MBEDTLS_MODE_KWP == ctx->cipher_info->mode)) {
mbedtls_nist_kw_mode_t mode = (MBEDTLS_MODE_KW == ctx->cipher_info->mode) ?
MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
(MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_KWP == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode))) {
mbedtls_nist_kw_mode_t mode =
(MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) ?
MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
/* There is no iv, tag or ad associated with KW and KWP,
* so these length should be 0 as documented. */
@ -1546,10 +1573,11 @@ int mbedtls_cipher_auth_decrypt_ext(mbedtls_cipher_context_t *ctx,
#if defined(MBEDTLS_USE_PSA_CRYPTO)
ctx->psa_enabled == 0 &&
#endif
(MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
MBEDTLS_MODE_KWP == ctx->cipher_info->mode)) {
mbedtls_nist_kw_mode_t mode = (MBEDTLS_MODE_KW == ctx->cipher_info->mode) ?
MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
(MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode) ||
MBEDTLS_MODE_KWP == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode))) {
mbedtls_nist_kw_mode_t mode =
(MBEDTLS_MODE_KW == ((mbedtls_cipher_mode_t) ctx->cipher_info->mode)) ?
MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
/* There is no iv, tag or ad associated with KW and KWP,
* so these length should be 0 as documented. */

File diff suppressed because it is too large Load Diff

View File

@ -135,6 +135,8 @@ extern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[];
extern int mbedtls_cipher_supported[];
extern const mbedtls_cipher_base_t *mbedtls_cipher_base_lookup_table[];
#ifdef __cplusplus
}
#endif

View File

@ -119,7 +119,7 @@ static int cmac_generate_subkeys(mbedtls_cipher_context_t *ctx,
mbedtls_platform_zeroize(L, sizeof(L));
block_size = ctx->cipher_info->block_size;
block_size = mbedtls_cipher_info_get_block_size(ctx->cipher_info);
/* Calculate Ek(0) */
if ((ret = mbedtls_cipher_update(ctx, L, block_size, L, &olen)) != 0) {
@ -186,7 +186,7 @@ int mbedtls_cipher_cmac_starts(mbedtls_cipher_context_t *ctx,
return retval;
}
type = ctx->cipher_info->type;
type = mbedtls_cipher_info_get_type(ctx->cipher_info);
switch (type) {
case MBEDTLS_CIPHER_AES_128_ECB:
@ -226,7 +226,7 @@ int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,
}
cmac_ctx = ctx->cmac_ctx;
block_size = ctx->cipher_info->block_size;
block_size = mbedtls_cipher_info_get_block_size(ctx->cipher_info);
state = ctx->cmac_ctx->state;
/* Is there data still to process from the last call, that's greater in
@ -237,7 +237,7 @@ int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,
input,
block_size - cmac_ctx->unprocessed_len);
mbedtls_xor(state, cmac_ctx->unprocessed_block, state, block_size);
mbedtls_xor_no_simd(state, cmac_ctx->unprocessed_block, state, block_size);
if ((ret = mbedtls_cipher_update(ctx, state, block_size, state,
&olen)) != 0) {
@ -255,7 +255,7 @@ int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,
/* Iterate across the input data in block sized chunks, excluding any
* final partial or complete block */
for (j = 1; j < n; j++) {
mbedtls_xor(state, input, state, block_size);
mbedtls_xor_no_simd(state, input, state, block_size);
if ((ret = mbedtls_cipher_update(ctx, state, block_size, state,
&olen)) != 0) {
@ -295,7 +295,7 @@ int mbedtls_cipher_cmac_finish(mbedtls_cipher_context_t *ctx,
}
cmac_ctx = ctx->cmac_ctx;
block_size = ctx->cipher_info->block_size;
block_size = mbedtls_cipher_info_get_block_size(ctx->cipher_info);
state = cmac_ctx->state;
mbedtls_platform_zeroize(K1, sizeof(K1));
@ -521,6 +521,7 @@ static const unsigned char aes_128_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTL
};
/* CMAC-AES192 Test Data */
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const unsigned char aes_192_key[24] = {
0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52,
0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
@ -561,8 +562,10 @@ static const unsigned char aes_192_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTL
0x4d, 0x77, 0x58, 0x96, 0x59, 0xf3, 0x9a, 0x11
}
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/* CMAC-AES256 Test Data */
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const unsigned char aes_256_key[32] = {
0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe,
0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
@ -604,6 +607,7 @@ static const unsigned char aes_256_expected_result[NB_CMAC_TESTS_PER_KEY][MBEDTL
0x69, 0x6a, 0x2c, 0x05, 0x6c, 0x31, 0x54, 0x10
}
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_DES_C)
@ -951,6 +955,7 @@ int mbedtls_cmac_self_test(int verbose)
}
/* AES-192 */
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
if ((ret = cmac_test_subkeys(verbose,
"AES 192",
aes_192_key,
@ -974,8 +979,10 @@ int mbedtls_cmac_self_test(int verbose)
NB_CMAC_TESTS_PER_KEY)) != 0) {
return ret;
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/* AES-256 */
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
if ((ret = cmac_test_subkeys(verbose,
"AES 256",
aes_256_key,
@ -999,6 +1006,7 @@ int mbedtls_cmac_self_test(int verbose)
NB_CMAC_TESTS_PER_KEY)) != 0) {
return ret;
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_DES_C)

Some files were not shown because too many files have changed in this diff Show More