Merge pull request #1261 from mpg/merge-3.6

[3.6] merge public into -restricted
This commit is contained in:
Manuel Pégourié-Gonnard 2024-08-08 12:25:04 +02:00 committed by GitHub
commit 1e6ed524c2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
947 changed files with 11338 additions and 36351 deletions

6
.gitignore vendored
View File

@ -2,6 +2,9 @@
seedfile
# MBEDTLS_PSA_INJECT_ENTROPY seed file created by the test framework
00000000ffffff52.psa_its
# Log files created by all.sh to reduce the logs in case a component runs
# successfully
quiet-make.*
# CMake build artifacts:
CMakeCache.txt
@ -67,3 +70,6 @@ massif-*
compile_commands.json
# clangd index files
/.cache/clangd/index/
# VScode folder to store local debug files and configurations
.vscode

1
3rdparty/p256-m/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
Makefile

View File

@ -22,6 +22,10 @@ cmake_minimum_required(VERSION 3.5.1)
include(CMakePackageConfigHelpers)
# Include convenience functions for printing properties and variables, like
# cmake_print_properties(), cmake_print_variables().
include(CMakePrintHelpers)
# https://cmake.org/cmake/help/latest/policy/CMP0011.html
# Setting this policy is required in CMake >= 3.18.0, otherwise a warning is generated. The OLD
# policy setting is deprecated, and will be removed in future versions.
@ -73,10 +77,16 @@ endif()
option(DISABLE_PACKAGE_CONFIG_AND_INSTALL "Disable package configuration, target export and installation" ${MBEDTLS_AS_SUBPROJECT})
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "GNU" CMAKE_COMPILER_IS_GNU "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "IAR" CMAKE_COMPILER_IS_IAR "${CMAKE_C_COMPILER_ID}")
string(REGEX MATCH "MSVC" CMAKE_COMPILER_IS_MSVC "${CMAKE_C_COMPILER_ID}")
if (CMAKE_C_SIMULATE_ID)
set(COMPILER_ID ${CMAKE_C_SIMULATE_ID})
else()
set(COMPILER_ID ${CMAKE_C_COMPILER_ID})
endif(CMAKE_C_SIMULATE_ID)
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${COMPILER_ID}")
string(REGEX MATCH "GNU" CMAKE_COMPILER_IS_GNU "${COMPILER_ID}")
string(REGEX MATCH "IAR" CMAKE_COMPILER_IS_IAR "${COMPILER_ID}")
string(REGEX MATCH "MSVC" CMAKE_COMPILER_IS_MSVC "${COMPILER_ID}")
# the test suites currently have compile errors with MSVC
if(CMAKE_COMPILER_IS_MSVC)
@ -184,8 +194,6 @@ function(get_name_without_last_ext dest_var full_name)
set(${dest_var} ${no_ext_name} PARENT_SCOPE)
endfunction(get_name_without_last_ext)
string(REGEX MATCH "Clang" CMAKE_COMPILER_IS_CLANG "${CMAKE_C_COMPILER_ID}")
include(CheckCCompilerFlag)
set(CMAKE_C_EXTENSIONS OFF)
@ -273,6 +281,15 @@ if(MBEDTLS_FATAL_WARNINGS)
endif(CMAKE_COMPILER_IS_IAR)
endif(MBEDTLS_FATAL_WARNINGS)
if(CMAKE_BUILD_TYPE STREQUAL "Check" AND TEST_CPP)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
if(CMAKE_COMPILER_IS_CLANG OR CMAKE_COMPILER_IS_GNU)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic")
endif()
endif()
if(CMAKE_BUILD_TYPE STREQUAL "Coverage")
if(CMAKE_COMPILER_IS_GNU OR CMAKE_COMPILER_IS_CLANG)
set(CMAKE_SHARED_LINKER_FLAGS "--coverage")
@ -315,6 +332,37 @@ if(ENABLE_TESTING OR ENABLE_PROGRAMS)
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/drivers/*.c)
add_library(mbedtls_test OBJECT ${MBEDTLS_TEST_FILES})
if(GEN_FILES)
add_custom_command(
OUTPUT
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_keys.h
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}/tests
COMMAND
"${MBEDTLS_PYTHON_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/framework/scripts/generate_test_keys.py"
"--output"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_keys.h"
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/framework/scripts/generate_test_keys.py
)
add_custom_target(test_keys_header DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_keys.h)
add_custom_command(
OUTPUT
${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_certs.h
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}/tests
COMMAND
"${MBEDTLS_PYTHON_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/framework/scripts/generate_test_cert_macros.py"
"--output"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_certs.h"
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/framework/scripts/generate_test_cert_macros.py
)
add_custom_target(test_certs_header DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/src/test_certs.h)
add_dependencies(mbedtls_test test_keys_header test_certs_header)
endif()
target_include_directories(mbedtls_test
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include

View File

@ -144,6 +144,7 @@ Security
* Fix a stack buffer overread (less than 256 bytes) when parsing a TLS 1.3
ClientHello in a TLS 1.3 server supporting some PSK key exchange mode. A
malicious client could cause information disclosure or a denial of service.
Fixes CVE-2024-30166.
* Passing buffers that are stored in untrusted memory as arguments
to PSA functions is now secure by default.
The PSA core now protects against modification of inputs or exposure

5
ChangeLog.d/9126.txt Normal file
View File

@ -0,0 +1,5 @@
Default behavior changes
* In a PSA-client-only build (i.e. MBEDTLS_PSA_CRYPTO_CLIENT &&
!MBEDTLS_PSA_CRYPTO_C), do not automatically enable local crypto when the
corresponding PSA mechanism is enabled, since the server provides the
crypto. Fixes #9126.

View File

@ -0,0 +1,9 @@
Changes
* Warn if mbedtls/check_config.h is included manually, as this can
lead to spurious errors. Error if a *adjust*.h header is included
manually, as this can lead to silently inconsistent configurations,
potentially resulting in buffer overflows.
When migrating from Mbed TLS 2.x, if you had a custom config.h that
included check_config.h, remove this inclusion from the Mbed TLS 3.x
configuration file (renamed to mbedtls_config.h). This change was made
in Mbed TLS 3.0, but was not announced in a changelog entry at the time.

View File

@ -0,0 +1,4 @@
Bugfix
* Fix rare concurrent access bug where attempting to operate on a
non-existent key while concurrently creating a new key could potentially
corrupt the key store.

View File

@ -0,0 +1,4 @@
Bugfix
* Fix the build when MBEDTLS_PSA_CRYPTO_CONFIG is enabled and the built-in
CMAC is enabled, but no built-in unauthenticated cipher is enabled.
Fixes #9209.

View File

@ -0,0 +1,5 @@
Bugfix
* Fix issue of redefinition warning messages for _GNU_SOURCE in
entropy_poll.c and sha_256.c. There was a build warning during
building for linux platform.
Resolves #9026

View File

@ -0,0 +1,5 @@
Bugfix
* Fix error handling when creating a key in a dynamic secure element
(feature enabled by MBEDTLS_PSA_CRYPTO_SE_C). In a low memory condition,
the creation could return PSA_SUCCESS but using or destroying the key
would not work. Fixes #8537.

View File

@ -0,0 +1,3 @@
Bugfix
* Fix redefinition warnings when SECP192R1 and/or SECP192K1 are disabled.
Fixes #9029.

View File

@ -0,0 +1,3 @@
Bugfix
* Fix undefined behaviour (incrementing a NULL pointer by zero length) when
passing in zero length additional data to multipart AEAD.

View File

@ -0,0 +1,2 @@
Bugfix
* Fix a compilation warning in pk.c when PSA is enabled and RSA is disabled.

View File

@ -0,0 +1,3 @@
Bugfix
* Fix psa_cipher_decrypt() with CCM* rejecting messages less than 3 bytes
long. Credit to Cryptofuzz. Fixes #9314.

View File

@ -0,0 +1,14 @@
API changes
* The experimental functions psa_generate_key_ext() and
psa_key_derivation_output_key_ext() are no longer declared when compiling
in C++. This resolves a build failure under C++ compilers that do not
support flexible array members (a C99 feature not adopted by C++).
Fixes #9020.
New deprecations
* The experimental functions psa_generate_key_ext() and
psa_key_derivation_output_key_ext() are deprecated in favor of
psa_generate_key_custom() and psa_key_derivation_output_key_custom().
They have almost exactly the same interface, but the variable-length
data is passed in a separate parameter instead of a flexible array
member.

View File

@ -65,13 +65,11 @@
#define MBEDTLS_PSA_ITS_FILE_C
#define MBEDTLS_RIPEMD160_C
#define MBEDTLS_SHA1_C
/* The library does not currently support enabling SHA-224 without SHA-256.
* A future version of the library will have this option disabled
* by default. */
#define MBEDTLS_SHA224_C
#define MBEDTLS_SHA256_C
#define MBEDTLS_SHA384_C
#define MBEDTLS_SHA512_C
#define MBEDTLS_SHA3_C
//#define MBEDTLS_THREADING_C
#define MBEDTLS_TIMING_C
#define MBEDTLS_VERSION_C

View File

@ -2,7 +2,7 @@
* \file configs/crypto-config-ccm-aes-sha256.h
*
* \brief PSA crypto configuration with only symmetric cryptography: CCM-AES,
* SHA-256, HMAC and key derivation
* SHA-256 and key derivation (uses HMAC).
*/
/*
* Copyright The Mbed TLS Contributors
@ -13,12 +13,10 @@
#define PSA_CRYPTO_CONFIG_H
#define PSA_WANT_ALG_CCM 1
#define PSA_WANT_ALG_HMAC 1
#define PSA_WANT_ALG_SHA_256 1
#define PSA_WANT_ALG_TLS12_PRF 1
#define PSA_WANT_ALG_TLS12_PSK_TO_MS 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_RAW_DATA 1

View File

@ -86,7 +86,7 @@ Summary of files to modify when adding a new algorithm or key type:
* [ ] `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)
* [ ] `framework/scripts/mbedtls_framework/crypto_knowledge.py`, `framework/scripts/mbedtls_framework/asymmetric_key_data.py` — [Unit tests](#unit-tests)
* [ ] `ChangeLog.d/*.txt` — changelog entry
Summary of files to modify when adding new API functions:
@ -153,7 +153,7 @@ The size of operation structures needs to be known at compile time, since caller
### 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`:
A number of unit tests are automatically generated by `framework/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.
@ -161,8 +161,8 @@ A number of unit tests are automatically generated by `tests/scripts/generate_ps
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.
* `framework/scripts/mbedtls_framework/crypto_knowledge.py` contains knowledge about the compatibility of key types, key sizes and algorithms.
* `framework/scripts/mbedtls_framework/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):

View File

@ -0,0 +1,212 @@
PSA key store design
====================
## Introduction
This document describes the architecture of the key storage in memory in the Mbed TLS and TF-PSA-Crypto implementation of the PSA Cryptography API.
In the PSA Cryptography API, cryptographic operations access key materials via a key identifier (key ID for short). Applications must first create a key object, which allocates storage in memory for the key material and metadata. This storage is under the control of the library and may be located in a different memory space such as a trusted execution environment or a secure element.
The storage of persistent keys is out of scope of this document. See the [Mbed Crypto storage specification](mbed-crypto-storage-specification.md).
## Key slot management interface
### Key store and key slots
The **key store** consists of a collection of **key slots**. Each key slot contains the metadata for one key, as well as the key material or a reference to the key material.
A key slot has the type `psa_key_slot_t`. The key store is a global object which is private inside `psa_crypto_slot_management.c`.
### Key slot entry points
The following operations allocate a key slot by calling `psa_reserve_free_key_slot()`:
* **Creating** a key object, through means such as import, random generation, deterministic derivation, copy, or registration of an existing key that is stored in protected hardware (secure element, hardware unique key (HUK)).
* **Loading** a persistent key from storage, or loading a built-in key. This is done through `psa_get_and_lock_key_slot()`, which calls `psa_reserve_free_key_slot()` and loads the key if applicable.
The following operations free a key slot by calling `psa_wipe_key_slot()` and, if applicable, `psa_free_key_slot()`:
* **Destroying** a key.
* **Purging** a persistent key from memory, either explicitly at the application's request or to free memory.
Deinitializing the PSA Crypto subsystem with `mbedtls_psa_crypto_free()` destroys all volatile keys and purges all persistent keys.
The library accesses key slots in the following scenarios:
* while the key is being created or loaded;
* while the key is being destroyed or purged;
* while the key metadata or key material is being accessed.
### Key slot states
The state of a key slot is indicated by its `state` field of type `psa_key_slot_state_t`, which can be:
* `PSA_SLOT_EMPTY`: a slot that occupies memory but does not currently contain a key.
* `PSA_SLOT_FILLING`: a slot that is being filled to create or load a key.
* `PSA_SLOT_FULL`: a slot containing a key.
* `PSA_SLOT_PENDING_DELETION`: a slot whose key is being destroy or purged.
These states are mostly useful for concurrency. See [Concurrency](#concurrency) below and [key slot states in the PSA thread safety specification](psa-thread-safety/psa-thread-safety.md#key-slot-states).
#### Concurrency
In a multithreaded environment, since Mbed TLS 3.6.0, each key slot is protected by a reader-writer lock. (In earlier versions, the key store was not thread-safe.) The lock is controlled by a single global mutex `mbedtls_threading_psa_globaldata_mutex`. The concurrency state of the slot is indicated by the state and the `registered_readers` field:
* `EMPTY` or `FULL` state, `registered_readers == 0`: the slot is not in use by any thread.
* `FULL` state, `registered_readers != 0`: the slot is being read.
* `FILLING` or `PENDING_DELETION` state: the slot is being written.
For more information, see [PSA thread safety](psa-thread-safety/psa-thread-safety.md).
Note that a slot must not be moved in memory while it is being read or written.
## Key slot management implementations
### Key store implementation variants
There are three variants of the key store implementation, responding to different needs.
* Hybrid key store ([static key slots](#static-key-store) with dynamic key data): the key store is a statically allocated array of slots, of size `MBEDTLS_PSA_KEY_SLOT_COUNT`. Key material is allocated on the heap. This is the historical implementation. It remains the default in the Mbed TLS 3.6 long-time support (LTS) branch when using a handwritten `mbedtls_config.h`, as is common on resource-constrained platforms, because the alternatives have tradeoffs (key size limit and larger RAM usage at rest for the static key store, larger code size and more risk due to code complexity for the dynamic key store).
* Fully [static key store](#static-key-store) (since Mbed TLS 3.6.1): the key store is a statically allocated array of slots, of size `MBEDTLS_PSA_KEY_SLOT_COUNT`. Each key slot contains the key representation directly, and the key representation must be no more than `MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZE` bytes. This is intended for very constrained devices that do not have a heap.
* [Dynamic key store](#dynamic-key-store) (since Mbed TLS 3.6.1): the key store is dynamically allocated as multiple slices on the heap, with a size that adjusts to the application's usage. Key material is allocated on the heap. Compared to the hybrid key store, the code size and RAM consumption are larger. This is intended for higher-end devices where applications are not expected to have a highly predicatable resource usage. This is the default implementation when using the default `mbedtls_config.h` file, as is common on platforms such as Linux, starting with Mbed TLS 3.6.1.
#### Future improvement: merging the key store variants
In the future, we may reduce the number of key store variants to just two, perhaps even one.
We introduced the variants other than the hybrid key store in a patch release of a long-time support version. As a consequence, we wanted to minimize making changes to the default build (when not using the supplied `mbedtls_config.h`, as explained above), to minimize the risk of bugs and the increase in code size. These considerations will not apply in future major or minor releases, so the default key store can change later.
The static key store could become a runtime decision, where only keys larger than some threshold require the use of heap memory. The reasons not to do this in Mbed TLS 3.6.x are that this increases complexity somewhat (slightly more code size, and more risk), and this changes the RAM usage profile somewhat.
A major constraint on the design of the dynamic key store is the need to preserve slot pointers while a slot may be accessed by another thread (see [“Concurrency”](#concurrency)). With the concurrency primitives available in Mbed TLS 3.x, it is very hard to move a key slot in memory, because there could be an indefinite wait until some other thread has finished accessing the slot. This pushed towards the slice-based organisation described below, where each slice is allocated for the long term. In particular, slices cannot be compacted (compacting would be moving slots out of a sparsely-used slice to free it). Better concurrency primitives (e.g. condition variables or semaphores), together with a `realloc()` primitive, could allow freeing unused memory more aggressively, which could make the dynamic key store not detrimental in RAM usage compared to the historical hybrid key store.
#### Slice abstraction
Some parts of the key slot management code use **key slices** as an abstraction. A key slice is an array of key slots. Key slices are identified by an index which is a small non-negative integer.
* With a [static key store](#static-key-store), there is a single, statically allocated slice, with the index 0.
* With a [dynamic key store](#dynamic-key-store), there is statically allocated array of pointers to key slices. The index of a slice is the index in that array. The slices are allocated on the heap as needed.
#### Key identifiers and slot location
When creating a volatile key, the slice containing the slot and index of the slot in its slice determine the key identifier. When accessing a volatile key, the slice and the slot index in the slice are calculated from the key identifier. The encoding of the slot location in the volatile key identifier is different for a [static](#volatile-key-identifiers-in-the-static-key-store) or [dynamic](#volatile-key-identifiers-in-the-dynamic-key-store) key store.
### Static key store
The static key store is the historical implementation. The key store is a statically allocated array of slots, of size `MBEDTLS_PSA_KEY_SLOT_COUNT`. This value is an upper bound for the total number of volatile keys plus loaded keys.
Since Mbed TLS 3.6.1, there are two variants for the static key store: a hybrid variant (default), and a fully-static variant enabled by the configuration option `MBEDTLS_PSA_STATIC_KEY_SLOTS`. The two variants have the same key store management: the only difference is in how the memory for key data is managed. With fully static key slots, the key data is directly inside the slot, and limited to `MBEDTLS_PSA_KEY_SLOT_BUFFER_SIZE` bytes. With the hybrid key store, the slot contains a pointer to the key data, which is allocated on the heap.
#### Volatile key identifiers in the static key store
For easy lookup, a volatile key whose index is `id` is stored at the index `id - PSA_KEY_ID_VOLATILE_MIN`.
#### Key creation with a static key store
To create a key, `psa_reserve_free_key_slot()` searches the key slot array until it finds one that is empty. If there are none, the code looks for a persistent key that can be purged (see [“Persistent key cache”](#persistent-key-cache)), and purges it. If no slot is free and no slot contains a purgeable key, the key creation fails.
#### Freeing a key slot with a static key store
With a static key store, `psa_wipe_key_slot()` destroys or purges a key by freeing any associated resources, then setting the key slot to the empty state. The slot is then ready for reuse.
### Dynamic key store
The dynamic key store allows a large number of keys, at the expense of more complex memory management.
#### Dynamic key slot performance characteristics
Key management and key access have $O(1)$ amortized performance, and mostly $O(1)$ performance for actions involving keys. More precisely:
* Access to an existing volatile key takes $O(1)$ time.
* Access to a persistent key (including creation and destruction) takes time that is linear in `MBEDTLS_PSA_KEY_SLOT_COUNT`.
* Allocating a key takes amortized $O(1)$ time. Usually the time is $O(s)$ where $s$ is the number of slices (which is a hard-coded value less than $30$), but when creating $k$ volatile keys, at most $\log(k)$ creations will involve calls to `calloc()`, totalling $O(k)$ memory.
* Destroying a volatile key takes $O(1)$ time as of Mbed TLS 3.6.1. Later improvements to memory consumption are likely to involve calls to `free()` which may total $O(k)$ memory where $k$ is the maximum number of volatile keys.
#### Key slices in the dynamic key store
The key slot is organized in slices, which are dynamically arrays of key slot. The number of slices is determined at compile time. The key store contains a static array of pointers to slices.
Volatile keys and loaded keys (persistent or built-in) are stored in separate slices.
Key slices number 0 to `KEY_SLOT_VOLATILE_SLICE_COUNT - 1` contain only volatile keys.
One key slice contains only loaded keys: that key slice is thus the cache slice. See [“Persistent key cache”](persistent-key-cache) for how the cache is managed.
#### Volatile key identifiers in the dynamic key store
A volatile key identifier encodes the slice index and the slot index at separate bit positions. That is, `key_id = BASE | slice_index | slot_index` where the bits set in `BASE`, `slice_index` and `slot_index` do not overlap.
#### From key slot to key slice
Some parts of the slot management code need to determine which key slice contains a key slot when given a pointer to the key slot. In principle, the key slice is uniquely determined from the key identifier which is located in the slot:
* for a volatile key identifier, the [slice index is encoded in the key identifier](#volatile-key-identifiers-in-the-dynamic-key-store);
* for a persistent key identifier or built-in key identifier, [the slot is in the sole cache slice](#key-slices-in-the-dynamic-key-store).
Nonetheless, we store the slice index as a field in the slot, for two reasons:
* It is more robust in case the slice assignment becomes more complex in the future or is somehow buggy.
* It allows the slot to slice correspondence to work even if the key identifier field has not been filled yet or has been wiped. The implementation in Mbed TLS 3.6.1 requires this because `psa_wipe_key_slot()` wipes the slot, then calls `psa_free_key_slot()`, which needs to determine the slice. Keeping the slice index as a separate field allows us to better separate the concerns of key liveness and slot liveness. A redesign of the internal interfaces could improve this, but would be too disruptive in the 3.6 LTS branch.
#### Length of the volatile key slices
The volatile key slices have exponentially increasing length: each slice is twice as long as the previous one. Thus if the length of slice 0 is `B` and there are `N` slices, then there are `B * (2^N - 1)` slots.
As of Mbed TLS 3.6.1, the maximum number of volatile key slots is less than the theoretical maximum of 2^30 - 2^16 (0x10000000..0x7ffeffff, the largest range of key identifiers reserved for the PSA Crypto implementation that does not overlap the range for built-in keys). The reason is that we limit the slot index to 2^25-1 so that the [encoding of volatile key identifiers](#volatile-key-identifiers-in-the-dynamic-key-store) has 25 bits for the slot index.
When `MBEDTLS_TEST_HOOKS` is enabled, the length of key slices can be overridden. We use this in tests that need to fill the key store.
#### Free list
Each volatile key slice has a **free list**. This is a linked list of all the slots in the slice that are free. The global data contains a static array of free list heads, i.e. the index of a free slot in the slice. Each free slot contains the index of the next free slot in that slice's free list. The end of the list is indicated by an index that is larger than the length of the slice. If the list is empty, the head contains an index that is larger than the length.
As a small optimization, a free slot does not actually contain the index of the next slot, but the index of the next free slot on the list _relative to the next slot in the array_. For example, 0 indicates that the next free slot is the slot immediately after the current slot. This fact is the reason for the encoding: a slice freshly obtained from `calloc` has all of its slots in the free list in order. The value 1 indicates that there is one element between this slot and the next free slot. The next element of the free list can come before the current slot: -2 indicates that it's the slot immediately before, -3 is two slots before, and so on (-1 is impossible). In general, the absolute index of the next slot after slot `i` in the free list is `i + 1 slice[i].next_free_relative_to_next`.
#### Dynamic key slot allocation
To create a volatile key, `psa_reserve_free_key_slot()` searches the free lists of each allocated slice until it finds a slice that is not full. If all allocated slices are full, the code allocates a new slice at the lowest possible slice index. If all possible slices are already allocated and full, the key creation fails.
The newly allocated slot is removed from the slice's free list.
We only allocate a slice of size `B * 2^k` if there are already `B * (2^k - 1)` occupied slots. Thus the memory overhead is at most `B` slots plus the number of occupied slots, i.e. the memory consumption for slots is at most twice the required memory plus a small constant overhead.
#### Dynamic key slot deallocation
When destroying a volatile key, `psa_wipe_key_slot()` calls `psa_free_key_slot()`. This function adds the newly freed slot to the head of the free list.
##### Future improvement: slice deallocation
As of Mbed TLS 3.6.1, `psa_free_key_slot()` does not deallocate slices. Thus the memory consumption for slots never decreases (except when the PSA crypto subsystem is deinitialized). Freeing key slices intelligently would be a desirable improvement.
We should not free a key slice as soon as it becomes empty, because that would cause large allocations and deallocations if there are slices full of long-lived keys, and then one slice keeps being allocate and deallocated for the occasional short-lived keys. Rather, there should be some hysteresis, e.g. only deallocate a slice if there are at least T free slots in the previous slice. [#9435](https://github.com/Mbed-TLS/mbedtls/issues/9435)
Note that currently, the slice array contains one sequence of allocated slices followed by one sequence of unallocated slices. Mixing allocated and unallocated slices may make some parts of the code a little more complex, and should be tested thoroughly.
### Persistent key cache
Persistent keys and built-in keys need to be loaded into the in-memory key store each time they are accessed:
* while creating them;
* to access their metadata;
* to start performing an operation with the key;
* when destroying the key.
To avoid frequent storage access, we cache persistent keys in memory. This cache also applies to built-in keys.
With the [static key store](#static-key-store), a non-empty slot can contain either a volatile key or a cache entry for a persistent or built-in key. With the [dynamic key store](#dynamic-key-store), volatile keys and cached keys are placed in separate [slices](#key-slices-in-the-dynamic-key-store).
The persistent key cache is a fixed-size array of `MBEDTLS_PSA_KEY_SLOT_COUNT` slots. In the static key store, this array is shared with volatile keys. In the dynamic key store, the cache is a separate array that does not contain volatile keys.
#### Accessing a persistent key
`psa_get_and_lock_key_slot()` automatically loads persistent and built-in keys if the specified key identifier is in the corresponding range. To that effect, it traverses the key cache to see if a key with the given identifier is already loaded. If not, it loads the key. This cache walk takes time that is proportional to the cache size.
#### Cache eviction
A key slot must be allocated in the cache slice:
* to create a volatile key (static key store only);
* to create a persistent key;
* to load a persistent or built-in key.
If the cache slice is full, the code will try to evict an entry. Only slots that do not have readers can be evicted (see [“Concurrency”](#concurrency)). In the static key store, slots containing volatile keys cannot be evicted.
As of Mbed TLS 3.6.1, there is no tracking of a key's usage frequency or age. The slot eviction code picks the first evictable slot it finds in its traversal order. We have not reasoned about or experimented with different strategies.

View File

@ -663,7 +663,7 @@ psa_status_t mem_poison_psa_aead_update(psa_aead_operation_t *operation,
There now exists a more generic mechanism for making exactly this kind of transformation - the PSA test wrappers, which exist in the files `tests/include/test/psa_test_wrappers.h` and `tests/src/psa_test_wrappers.c`. These are wrappers around all PSA functions that allow testing code to be inserted at the start and end of a PSA function call.
The test wrappers are generated by a script, although they are not automatically generated as part of the build process. Instead, they are checked into source control and must be manually updated when functions change by running `tests/scripts/generate_psa_wrappers.py`.
The test wrappers are generated by a script, although they are not automatically generated as part of the build process. Instead, they are checked into source control and must be manually updated when functions change by running `framework/scripts/generate_psa_wrappers.py`.
Poisoning code is added to these test wrappers where relevant in order to pre-poison and post-unpoison the parameters to the functions.

View File

@ -277,6 +277,11 @@ The same holds for the associated algorithm:
`[PSA_WANT|MBEDTLS_PSA_ACCEL]_ALG_FFDH` allow builds accelerating FFDH and
removing builtin support (i.e. `MBEDTLS_DHM_C`).
Note that the PSA API only supports FFDH with RFC 7919 groups, whereas the
Mbed TLS legacy API supports custom groups. As a consequence, the TLS layer
of Mbed TLS only supports DHE cipher suites if built-in FFDH
(`MBEDTLS_DHM_C`) is present, even when `MBEDTLS_USE_PSA_CRYPTO` is enabled.
RSA
---

View File

@ -779,7 +779,7 @@ A finite-field Diffie-Hellman key can be used for key agreement with the algorit
The easiest way to create a key pair object is by randomly generating it with [`psa_generate_key`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__random/#group__random_1ga1985eae417dfbccedf50d5fff54ea8c5). Compared with the low-level functions from the legacy API (`mbedtls_rsa_gen_key`, `mbedtls_ecp_gen_privkey`, `mbedtls_ecp_gen_keypair`, `mbedtls_ecp_gen_keypair_base`, `mbedtls_ecdsa_genkey`), this directly creates an object that can be used with high-level APIs, but removes some of the flexibility. Note that if you want to export the generated private key, you must pass the flag [`PSA_KEY_USAGE_EXPORT`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__policy/#group__policy_1ga7dddccdd1303176e87a4d20c87b589ed) to [`psa_set_key_usage_flags`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__attributes/#group__attributes_1ga42a65b3c4522ce9b67ea5ea7720e17de); exporting the public key with [`psa_export_public_key`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__import__export/#group__import__export_1gaf22ae73312217aaede2ea02cdebb6062) is always permitted.
For RSA keys, `psa_generate_key` uses 65537 as the public exponent. You can use [`psa_generate_key_ext`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__random/#group__random_1ga6776360ae8046a4456a5f990f997da58) to select a different public exponent. As of Mbed TLS 3.6.0, selecting a different public exponent is only supported with the built-in RSA implementation, not with PSA drivers.
For RSA keys, `psa_generate_key` uses 65537 as the public exponent. You can use [`psa_generate_key_custom`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__random/#ga0415617443afe42a712027bbb8ad89f0) to select a different public exponent. As of Mbed TLS 3.6.1, selecting a different public exponent is only supported with the built-in RSA implementation, not with PSA drivers.
To create a key object from existing material, use [`psa_import_key`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__import__export/#group__import__export_1ga0336ea76bf30587ab204a8296462327b). This function has the same basic goal as the PK parse functions (`mbedtls_pk_parse_key`, `mbedtls_pk_parse_public_key`, `mbedtls_pk_parse_subpubkey`), but only supports a single format that just contains the number(s) that make up the key, with very little metadata. The table below summarizes the PSA import/export format for key pairs and public keys; see the documentation of [`psa_export_key`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__import__export/#group__import__export_1ga668e35be8d2852ad3feeef74ac6f75bf) and [`psa_export_public_key`](https://mbed-tls.readthedocs.io/projects/api/en/development/api/group/group__import__export/#group__import__export_1gaf22ae73312217aaede2ea02cdebb6062) for more details.

View File

@ -1,63 +1,66 @@
#
# This file is autogenerated by pip-compile with Python 3.9
# This file is autogenerated by pip-compile with Python 3.8
# by the following command:
#
# pip-compile requirements.in
#
alabaster==0.7.13
# via sphinx
babel==2.12.1
babel==2.15.0
# via sphinx
breathe==4.35.0
# via -r requirements.in
certifi==2022.12.7
certifi==2024.7.4
# via requests
charset-normalizer==3.1.0
charset-normalizer==3.3.2
# via requests
click==8.1.3
click==8.1.7
# via readthedocs-cli
docutils==0.17.1
docutils==0.20.1
# via
# breathe
# sphinx
# sphinx-rtd-theme
idna==3.4
idna==3.7
# via requests
imagesize==1.4.1
# via sphinx
importlib-metadata==6.0.0
importlib-metadata==8.0.0
# via sphinx
jinja2==3.1.2
jinja2==3.1.4
# via sphinx
markdown-it-py==2.2.0
markdown-it-py==3.0.0
# via rich
markupsafe==2.1.2
markupsafe==2.1.5
# via jinja2
mdurl==0.1.2
# via markdown-it-py
packaging==23.0
packaging==24.1
# via sphinx
pygments==2.14.0
pygments==2.18.0
# via
# rich
# sphinx
pyyaml==6.0
pytz==2024.1
# via babel
pyyaml==6.0.1
# via readthedocs-cli
readthedocs-cli==4
# via -r requirements.in
requests==2.28.2
requests==2.32.3
# via
# readthedocs-cli
# sphinx
rich==13.3.5
rich==13.7.1
# via readthedocs-cli
snowballstemmer==2.2.0
# via sphinx
sphinx==4.5.0
sphinx==7.1.2
# via
# breathe
# sphinx-rtd-theme
sphinx-rtd-theme==1.2.0
# sphinxcontrib-jquery
sphinx-rtd-theme==2.0.0
# via -r requirements.in
sphinxcontrib-applehelp==1.0.4
# via sphinx
@ -65,7 +68,7 @@ sphinxcontrib-devhelp==1.0.2
# via sphinx
sphinxcontrib-htmlhelp==2.0.1
# via sphinx
sphinxcontrib-jquery==2.0.0
sphinxcontrib-jquery==4.1
# via sphinx-rtd-theme
sphinxcontrib-jsmath==1.0.1
# via sphinx
@ -73,10 +76,9 @@ sphinxcontrib-qthelp==1.0.3
# via sphinx
sphinxcontrib-serializinghtml==1.1.5
# via sphinx
urllib3==1.26.15
typing-extensions==4.12.2
# via rich
urllib3==2.2.2
# via requests
zipp==3.15.0
zipp==3.19.2
# via importlib-metadata
# The following packages are considered to be unsafe in a requirements file:
# setuptools

@ -1 +1 @@
Subproject commit 750634d3a51eb9d61b59fd5d801546927c946588
Subproject commit 331565b041f794df2da76394b3b0039abce30355

View File

@ -101,6 +101,13 @@
#define inline __inline
#endif
#if defined(MBEDTLS_CONFIG_FILES_READ)
#error "Something went wrong: MBEDTLS_CONFIG_FILES_READ defined before reading the config files!"
#endif
#if defined(MBEDTLS_CONFIG_IS_FINALIZED)
#error "Something went wrong: MBEDTLS_CONFIG_IS_FINALIZED defined before reading the config files!"
#endif
/* X.509, TLS and non-PSA crypto configuration */
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/mbedtls_config.h"
@ -135,6 +142,12 @@
#endif
#endif /* defined(MBEDTLS_PSA_CRYPTO_CONFIG) */
/* Indicate that all configuration files have been read.
* It is now time to adjust the configuration (follow through on dependencies,
* make PSA and legacy crypto consistent, etc.).
*/
#define MBEDTLS_CONFIG_FILES_READ
/* 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.
@ -169,8 +182,13 @@
#include "mbedtls/config_adjust_ssl.h"
/* Make sure all configuration symbols are set before including check_config.h,
* even the ones that are calculated programmatically. */
/* Indicate that all configuration symbols are set,
* even the ones that are calculated programmatically.
* It is now safe to query the configuration (to check it, to size buffers,
* etc.).
*/
#define MBEDTLS_CONFIG_IS_FINALIZED
#include "mbedtls/check_config.h"
#endif /* MBEDTLS_BUILD_INFO_H */

View File

@ -2,6 +2,13 @@
* \file check_config.h
*
* \brief Consistency checks for configuration options
*
* This is an internal header. Do not include it directly.
*
* This header is included automatically by all public Mbed TLS headers
* (via mbedtls/build_info.h). Do not include it directly in a configuration
* file such as mbedtls/mbedtls_config.h or #MBEDTLS_USER_CONFIG_FILE!
* It would run at the wrong time due to missing derived symbols.
*/
/*
* Copyright The Mbed TLS Contributors
@ -12,6 +19,13 @@
#define MBEDTLS_CHECK_CONFIG_H
/* *INDENT-OFF* */
#if !defined(MBEDTLS_CONFIG_IS_FINALIZED)
#warning "Do not include mbedtls/check_config.h manually! " \
"This may cause spurious errors. " \
"It is included automatically at the right point since Mbed TLS 3.0."
#endif /* !MBEDTLS_CONFIG_IS_FINALIZED */
/*
* We assume CHAR_BIT is 8 in many places. In practice, this is true on our
* target platforms, so not an issue, but let's just be extra sure.

View File

@ -2,7 +2,9 @@
* \file mbedtls/config_adjust_legacy_crypto.h
* \brief Adjust legacy configuration configuration
*
* Automatically enable certain dependencies. Generally, MBEDLTS_xxx
* This is an internal header. Do not include it directly.
*
* Automatically enable certain dependencies. Generally, MBEDTLS_xxx
* configurations need to be explicitly enabled by the user: enabling
* MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
* compilation error. However, we do automatically enable certain options
@ -22,6 +24,14 @@
#ifndef MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H
#define MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/* Ideally, we'd set those as defaults in mbedtls_config.h, but
* putting an #ifdef _WIN32 in mbedtls_config.h would confuse config.py.
*
@ -48,7 +58,8 @@
defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG))
defined(MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC))
#define MBEDTLS_CIPHER_C
#endif
@ -422,7 +433,7 @@
#define MBEDTLS_PSA_UTIL_HAVE_ECDSA
#endif
/* Some internal helpers to determine which keys are availble. */
/* Some internal helpers to determine which keys are available. */
#if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_AES_C)) || \
(defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_AES))
#define MBEDTLS_SSL_HAVE_AES
@ -436,7 +447,7 @@
#define MBEDTLS_SSL_HAVE_CAMELLIA
#endif
/* Some internal helpers to determine which operation modes are availble. */
/* Some internal helpers to determine which operation modes are available. */
#if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_CIPHER_MODE_CBC)) || \
(defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_CBC_NO_PADDING))
#define MBEDTLS_SSL_HAVE_CBC

View File

@ -2,6 +2,8 @@
* \file mbedtls/config_adjust_legacy_from_psa.h
* \brief Adjust PSA configuration: activate legacy implementations
*
* This is an internal header. Do not include it directly.
*
* When MBEDTLS_PSA_CRYPTO_CONFIG is enabled, activate legacy implementations
* of cryptographic mechanisms as needed to fulfill the needs of the PSA
* configuration. Generally speaking, we activate a legacy mechanism if
@ -16,6 +18,14 @@
#ifndef MBEDTLS_CONFIG_ADJUST_LEGACY_FROM_PSA_H
#define MBEDTLS_CONFIG_ADJUST_LEGACY_FROM_PSA_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/* Define appropriate ACCEL macros for the p256-m driver.
* In the future, those should be generated from the drivers JSON description.
*/
@ -498,7 +508,6 @@
* The PSA implementation has its own implementation of HKDF, separate from
* hkdf.c. No need to enable MBEDTLS_HKDF_C here.
*/
#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
#define MBEDTLS_PSA_BUILTIN_ALG_HKDF 1
#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF */
#endif /* PSA_WANT_ALG_HKDF */
@ -509,7 +518,6 @@
* The PSA implementation has its own implementation of HKDF, separate from
* hkdf.c. No need to enable MBEDTLS_HKDF_C here.
*/
#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT 1
#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF_EXTRACT */
#endif /* PSA_WANT_ALG_HKDF_EXTRACT */
@ -520,7 +528,6 @@
* The PSA implementation has its own implementation of HKDF, separate from
* hkdf.c. No need to enable MBEDTLS_HKDF_C here.
*/
#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND 1
#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF_EXPAND */
#endif /* PSA_WANT_ALG_HKDF_EXPAND */
@ -630,9 +637,6 @@
#if !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_HMAC)
#define MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC 1
#define PSA_HAVE_SOFT_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 */

View File

@ -2,6 +2,8 @@
* \file mbedtls/config_adjust_psa_from_legacy.h
* \brief Adjust PSA configuration: construct PSA configuration from legacy
*
* This is an internal header. Do not include it directly.
*
* When MBEDTLS_PSA_CRYPTO_CONFIG is disabled, we automatically enable
* cryptographic mechanisms through the PSA interface when the corresponding
* legacy mechanism is enabled. In many cases, this just enables the PSA
@ -18,6 +20,14 @@
#ifndef MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H
#define MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/*
* Ensure PSA_WANT_* defines are setup properly if MBEDTLS_PSA_CRYPTO_CONFIG
* is not defined

View File

@ -2,6 +2,8 @@
* \file mbedtls/config_adjust_psa_superset_legacy.h
* \brief Adjust PSA configuration: automatic enablement from legacy
*
* This is an internal header. Do not include it directly.
*
* To simplify some edge cases, we automatically enable certain cryptographic
* mechanisms in the PSA API if they are enabled in the legacy API. The general
* idea is that if legacy module M uses mechanism A internally, and A has
@ -17,6 +19,14 @@
#ifndef MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H
#define MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/****************************************************************/
/* Hashes that are built in are also enabled in PSA.
* This simplifies dependency declarations especially

View File

@ -2,7 +2,9 @@
* \file mbedtls/config_adjust_ssl.h
* \brief Adjust TLS configuration
*
* Automatically enable certain dependencies. Generally, MBEDLTS_xxx
* This is an internal header. Do not include it directly.
*
* Automatically enable certain dependencies. Generally, MBEDTLS_xxx
* configurations need to be explicitly enabled by the user: enabling
* MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
* compilation error. However, we do automatically enable certain options
@ -22,6 +24,14 @@
#ifndef MBEDTLS_CONFIG_ADJUST_SSL_H
#define MBEDTLS_CONFIG_ADJUST_SSL_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/* The following blocks make it easier to disable all of TLS,
* or of TLS 1.2 or 1.3 or DTLS, without having to manually disable all
* key exchanges, options and extensions related to them. */

View File

@ -2,7 +2,9 @@
* \file mbedtls/config_adjust_x509.h
* \brief Adjust X.509 configuration
*
* Automatically enable certain dependencies. Generally, MBEDLTS_xxx
* This is an internal header. Do not include it directly.
*
* Automatically enable certain dependencies. Generally, MBEDTLS_xxx
* configurations need to be explicitly enabled by the user: enabling
* MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
* compilation error. However, we do automatically enable certain options
@ -22,4 +24,12 @@
#ifndef MBEDTLS_CONFIG_ADJUST_X509_H
#define MBEDTLS_CONFIG_ADJUST_X509_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
#endif /* MBEDTLS_CONFIG_ADJUST_X509_H */

View File

@ -22,6 +22,8 @@
#include "psa/crypto_adjust_config_synonyms.h"
#include "psa/crypto_adjust_config_dependencies.h"
#include "mbedtls/config_adjust_psa_superset_legacy.h"
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
@ -32,7 +34,11 @@
* before we deduce what built-ins are required. */
#include "psa/crypto_adjust_config_key_pair_types.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
/* If we are implementing PSA crypto ourselves, then we want to enable the
* required built-ins. Otherwise, PSA features will be provided by the server. */
#include "mbedtls/config_adjust_legacy_from_psa.h"
#endif
#else /* MBEDTLS_PSA_CRYPTO_CONFIG */

View File

@ -325,7 +325,7 @@ int mbedtls_ecdh_read_params(mbedtls_ecdh_context *ctx,
* \brief This function sets up an ECDH context from an EC key.
*
* It is used by clients and servers in place of the
* ServerKeyEchange for static ECDH, and imports ECDH
* ServerKeyExchange for static ECDH, and imports ECDH
* parameters from the EC key information of a certificate.
*
* \see ecp.h

View File

@ -216,7 +216,7 @@ mbedtls_ecp_point;
* range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer
* which is congruent mod \p P to the given MPI, and is close enough to \p pbits
* in size, so that it may be efficiently brought in the 0..P-1 range by a few
* additions or subtractions. Therefore, it is only an approximative modular
* additions or subtractions. Therefore, it is only an approximate modular
* reduction. It must return 0 on success and non-zero on failure.
*
* \note Alternative implementations of the ECP module must obey the

View File

@ -1118,7 +1118,7 @@
* MBEDTLS_ECP_DP_SECP256R1_ENABLED
*
* \warning If SHA-256 is provided only by a PSA driver, you must call
* psa_crypto_init() before the first hanshake (even if
* psa_crypto_init() before the first handshake (even if
* MBEDTLS_USE_PSA_CRYPTO is disabled).
*
* This enables the following ciphersuites (if other requisites are
@ -2625,7 +2625,7 @@
* The CTR_DRBG generator uses AES-256 by default.
* To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above.
*
* AES support can either be achived through builtin (MBEDTLS_AES_C) or PSA.
* AES support can either be achieved through builtin (MBEDTLS_AES_C) or PSA.
* Builtin is the default option when MBEDTLS_AES_C is defined otherwise PSA
* is used.
*

View File

@ -2364,7 +2364,7 @@ int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
*/
int mbedtls_ssl_get_own_cid(mbedtls_ssl_context *ssl,
int *enabled,
unsigned char own_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
unsigned char own_cid[MBEDTLS_SSL_CID_IN_LEN_MAX],
size_t *own_cid_len);
/**

View File

@ -119,8 +119,8 @@ static psa_key_attributes_t psa_key_attributes_init(void);
* value in the structure.
* The persistent key will be written to storage when the attribute
* structure is passed to a key creation function such as
* psa_import_key(), psa_generate_key(), psa_generate_key_ext(),
* psa_key_derivation_output_key(), psa_key_derivation_output_key_ext()
* psa_import_key(), psa_generate_key(), psa_generate_key_custom(),
* psa_key_derivation_output_key(), psa_key_derivation_output_key_custom()
* or psa_copy_key().
*
* This function may be declared as `static` (i.e. without external
@ -164,8 +164,8 @@ static void mbedtls_set_key_owner_id(psa_key_attributes_t *attributes,
* value in the structure.
* The persistent key will be written to storage when the attribute
* structure is passed to a key creation function such as
* psa_import_key(), psa_generate_key(), psa_generate_key_ext(),
* psa_key_derivation_output_key(), psa_key_derivation_output_key_ext()
* psa_import_key(), psa_generate_key(), psa_generate_key_custom(),
* psa_key_derivation_output_key(), psa_key_derivation_output_key_custom()
* or psa_copy_key().
*
* This function may be declared as `static` (i.e. without external
@ -871,7 +871,7 @@ psa_status_t psa_hash_compute(psa_algorithm_t alg,
* such that #PSA_ALG_IS_HASH(\p alg) is true).
* \param[in] input Buffer containing the message to hash.
* \param input_length Size of the \p input buffer in bytes.
* \param[out] hash Buffer containing the expected hash value.
* \param[in] hash Buffer containing the expected hash value.
* \param hash_length Size of the \p hash buffer in bytes.
*
* \retval #PSA_SUCCESS
@ -1224,7 +1224,7 @@ psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
* such that #PSA_ALG_IS_MAC(\p alg) is true).
* \param[in] input Buffer containing the input message.
* \param input_length Size of the \p input buffer in bytes.
* \param[out] mac Buffer containing the expected MAC value.
* \param[in] mac Buffer containing the expected MAC value.
* \param mac_length Size of the \p mac buffer in bytes.
*
* \retval #PSA_SUCCESS
@ -2910,7 +2910,7 @@ psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
* \p key.
* \param[in] input The message whose signature is to be verified.
* \param[in] input_length Size of the \p input buffer in bytes.
* \param[out] signature Buffer containing the signature to verify.
* \param[in] signature Buffer containing the signature to verify.
* \param[in] signature_length Size of the \p signature buffer in bytes.
*
* \retval #PSA_SUCCESS \emptydescription
@ -3234,7 +3234,7 @@ static psa_key_derivation_operation_t psa_key_derivation_operation_init(void);
* of or after providing inputs. For some algorithms, this step is mandatory
* because the output depends on the maximum capacity.
* -# To derive a key, call psa_key_derivation_output_key() or
* psa_key_derivation_output_key_ext().
* psa_key_derivation_output_key_custom().
* To derive a byte string for a different purpose, call
* psa_key_derivation_output_bytes().
* Successive calls to these functions use successive output bytes
@ -3457,7 +3457,7 @@ psa_status_t psa_key_derivation_input_integer(
* \note Once all inputs steps are completed, the operations will allow:
* - psa_key_derivation_output_bytes() if each input was either a direct input
* or a key with #PSA_KEY_USAGE_DERIVE set;
* - psa_key_derivation_output_key() or psa_key_derivation_output_key_ext()
* - psa_key_derivation_output_key() or psa_key_derivation_output_key_custom()
* if the input for step
* #PSA_KEY_DERIVATION_INPUT_SECRET or #PSA_KEY_DERIVATION_INPUT_PASSWORD
* was from a key slot with #PSA_KEY_USAGE_DERIVE and each other input was
@ -3707,9 +3707,9 @@ psa_status_t psa_key_derivation_output_bytes(
* on the derived key based on the attributes and strength of the secret key.
*
* \note This function is equivalent to calling
* psa_key_derivation_output_key_ext()
* with the production parameters #PSA_KEY_PRODUCTION_PARAMETERS_INIT
* and `params_data_length == 0` (i.e. `params->data` is empty).
* psa_key_derivation_output_key_custom()
* with the custom production parameters #PSA_CUSTOM_KEY_PARAMETERS_INIT
* and `custom_data_length == 0` (i.e. `custom_data` is empty).
*
* \param[in] attributes The attributes for the new key.
* If the key type to be created is
@ -3781,6 +3781,85 @@ psa_status_t psa_key_derivation_output_key(
* the policy must be the same as in the current
* operation.
* \param[in,out] operation The key derivation operation object to read from.
* \param[in] custom Customization parameters for the key generation.
* When this is #PSA_CUSTOM_KEY_PARAMETERS_INIT
* with \p custom_data_length = 0,
* this function is equivalent to
* psa_key_derivation_output_key().
* \param[in] custom_data Variable-length data associated with \c custom.
* \param custom_data_length
* Length of `custom_data` in bytes.
* \param[out] key On success, an identifier for the newly created
* key. For persistent keys, this is the key
* identifier defined in \p attributes.
* \c 0 on failure.
*
* \retval #PSA_SUCCESS
* Success.
* If the key is persistent, the key material and the key's metadata
* have been saved to persistent storage.
* \retval #PSA_ERROR_ALREADY_EXISTS
* This is an attempt to create a persistent key, and there is
* already a persistent key with the given identifier.
* \retval #PSA_ERROR_INSUFFICIENT_DATA
* There was not enough data to create the desired key.
* Note that in this case, no output is written to the output buffer.
* The operation's capacity is set to 0, thus subsequent calls to
* this function will not succeed, even with a smaller output buffer.
* \retval #PSA_ERROR_NOT_SUPPORTED
* The key type or key size is not supported, either by the
* implementation in general or in this particular location.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The provided key attributes are not valid for the operation.
* \retval #PSA_ERROR_NOT_PERMITTED
* The #PSA_KEY_DERIVATION_INPUT_SECRET or
* #PSA_KEY_DERIVATION_INPUT_PASSWORD input was not provided through a
* key; or one of the inputs was a key whose policy didn't allow
* #PSA_KEY_USAGE_DERIVE.
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
* \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
* \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
* \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
* \retval #PSA_ERROR_DATA_INVALID \emptydescription
* \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
* \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
* \retval #PSA_ERROR_BAD_STATE
* The operation state is not valid (it must be active and completed
* all required input steps), or the library has not been previously
* initialized by psa_crypto_init().
* It is implementation-dependent whether a failure to initialize
* results in this error code.
*/
psa_status_t psa_key_derivation_output_key_custom(
const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
mbedtls_svc_key_id_t *key);
#ifndef __cplusplus
/* Omitted when compiling in C++, because one of the parameters is a
* pointer to a struct with a flexible array member, and that is not
* standard C++.
* https://github.com/Mbed-TLS/mbedtls/issues/9020
*/
/** Derive a key from an ongoing key derivation operation with custom
* production parameters.
*
* \note
* This is a deprecated variant of psa_key_derivation_output_key_custom().
* It is equivalent except that the associated variable-length data
* is passed in `params->data` instead of a separate parameter.
* This function will be removed in a future version of Mbed TLS.
*
* \param[in] attributes The attributes for the new key.
* If the key type to be created is
* #PSA_KEY_TYPE_PASSWORD_HASH then the algorithm in
* the policy must be the same as in the current
* operation.
* \param[in,out] operation The key derivation operation object to read from.
* \param[in] params Customization parameters for the key derivation.
* When this is #PSA_KEY_PRODUCTION_PARAMETERS_INIT
* with \p params_data_length = 0,
@ -3840,6 +3919,7 @@ psa_status_t psa_key_derivation_output_key_ext(
const psa_key_production_parameters_t *params,
size_t params_data_length,
mbedtls_svc_key_id_t *key);
#endif /* !__cplusplus */
/** Compare output data from a key derivation operation to an expected value.
*
@ -3865,8 +3945,8 @@ psa_status_t psa_key_derivation_output_key_ext(
* psa_key_derivation_abort().
*
* \param[in,out] operation The key derivation operation object to read from.
* \param[in] expected_output Buffer containing the expected derivation output.
* \param output_length Length of the expected output; this is also the
* \param[in] expected Buffer containing the expected derivation output.
* \param expected_length Length of the expected output; this is also the
* number of bytes that will be read.
*
* \retval #PSA_SUCCESS \emptydescription
@ -3896,8 +3976,8 @@ psa_status_t psa_key_derivation_output_key_ext(
*/
psa_status_t psa_key_derivation_verify_bytes(
psa_key_derivation_operation_t *operation,
const uint8_t *expected_output,
size_t output_length);
const uint8_t *expected,
size_t expected_length);
/** Compare output data from a key derivation operation to an expected value
* stored in a key object.
@ -3927,7 +4007,7 @@ psa_status_t psa_key_derivation_verify_bytes(
* operation. The value of this key was likely
* computed by a previous call to
* psa_key_derivation_output_key() or
* psa_key_derivation_output_key_ext().
* psa_key_derivation_output_key_custom().
*
* \retval #PSA_SUCCESS \emptydescription
* \retval #PSA_ERROR_INVALID_SIGNATURE
@ -4095,9 +4175,9 @@ psa_status_t psa_generate_random(uint8_t *output,
* between 2^{n-1} and 2^n where n is the bit size specified in the
* attributes.
*
* \note This function is equivalent to calling psa_generate_key_ext()
* with the production parameters #PSA_KEY_PRODUCTION_PARAMETERS_INIT
* and `params_data_length == 0` (i.e. `params->data` is empty).
* \note This function is equivalent to calling psa_generate_key_custom()
* with the custom production parameters #PSA_CUSTOM_KEY_PARAMETERS_INIT
* and `custom_data_length == 0` (i.e. `custom_data` is empty).
*
* \param[in] attributes The attributes for the new key.
* \param[out] key On success, an identifier for the newly created
@ -4137,7 +4217,7 @@ psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
* See the description of psa_generate_key() for the operation of this
* function with the default production parameters. In addition, this function
* supports the following production customizations, described in more detail
* in the documentation of ::psa_key_production_parameters_t:
* in the documentation of ::psa_custom_key_parameters_t:
*
* - RSA keys: generation with a custom public exponent.
*
@ -4145,6 +4225,64 @@ psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
* versions of Mbed TLS.
*
* \param[in] attributes The attributes for the new key.
* \param[in] custom Customization parameters for the key generation.
* When this is #PSA_CUSTOM_KEY_PARAMETERS_INIT
* with \p custom_data_length = 0,
* this function is equivalent to
* psa_generate_key().
* \param[in] custom_data Variable-length data associated with \c custom.
* \param custom_data_length
* Length of `custom_data` in bytes.
* \param[out] key On success, an identifier for the newly created
* key. For persistent keys, this is the key
* identifier defined in \p attributes.
* \c 0 on failure.
*
* \retval #PSA_SUCCESS
* Success.
* If the key is persistent, the key material and the key's metadata
* have been saved to persistent storage.
* \retval #PSA_ERROR_ALREADY_EXISTS
* This is an attempt to create a persistent key, and there is
* already a persistent key with the given identifier.
* \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
* \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
* \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
* \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
* \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
* \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
* \retval #PSA_ERROR_DATA_INVALID \emptydescription
* \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
* \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
* \retval #PSA_ERROR_BAD_STATE
* The library has not been previously initialized by psa_crypto_init().
* It is implementation-dependent whether a failure to initialize
* results in this error code.
*/
psa_status_t psa_generate_key_custom(const psa_key_attributes_t *attributes,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
mbedtls_svc_key_id_t *key);
#ifndef __cplusplus
/* Omitted when compiling in C++, because one of the parameters is a
* pointer to a struct with a flexible array member, and that is not
* standard C++.
* https://github.com/Mbed-TLS/mbedtls/issues/9020
*/
/**
* \brief Generate a key or key pair using custom production parameters.
*
* \note
* This is a deprecated variant of psa_key_derivation_output_key_custom().
* It is equivalent except that the associated variable-length data
* is passed in `params->data` instead of a separate parameter.
* This function will be removed in a future version of Mbed TLS.
*
* \param[in] attributes The attributes for the new key.
* \param[in] params Customization parameters for the key generation.
* When this is #PSA_KEY_PRODUCTION_PARAMETERS_INIT
* with \p params_data_length = 0,
@ -4184,6 +4322,7 @@ psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params,
size_t params_data_length,
mbedtls_svc_key_id_t *key);
#endif /* !__cplusplus */
/**@}*/

View File

@ -2,6 +2,8 @@
* \file psa/crypto_adjust_auto_enabled.h
* \brief Adjust PSA configuration: enable always-on features
*
* This is an internal header. Do not include it directly.
*
* Always enable certain features which require a negligible amount of code
* to implement, to avoid some edge cases in the configuration combinatorics.
*/
@ -13,6 +15,14 @@
#ifndef PSA_CRYPTO_ADJUST_AUTO_ENABLED_H
#define PSA_CRYPTO_ADJUST_AUTO_ENABLED_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
#define PSA_WANT_KEY_TYPE_DERIVE 1
#define PSA_WANT_KEY_TYPE_PASSWORD 1
#define PSA_WANT_KEY_TYPE_PASSWORD_HASH 1

View File

@ -0,0 +1,51 @@
/**
* \file psa/crypto_adjust_config_dependencies.h
* \brief Adjust PSA configuration by resolving some dependencies.
*
* This is an internal header. Do not include it directly.
*
* See docs/proposed/psa-conditional-inclusion-c.md.
* If the Mbed TLS implementation of a cryptographic mechanism A depends on a
* cryptographic mechanism B then if the cryptographic mechanism A is enabled
* and not accelerated enable B. Note that if A is enabled and accelerated, it
* is not necessary to enable B for A support.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H
#define PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
#if (defined(PSA_WANT_ALG_TLS12_PRF) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PRF)) || \
(defined(PSA_WANT_ALG_TLS12_PSK_TO_MS) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PSK_TO_MS)) || \
(defined(PSA_WANT_ALG_HKDF) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_HKDF)) || \
(defined(PSA_WANT_ALG_HKDF_EXTRACT) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXTRACT)) || \
(defined(PSA_WANT_ALG_HKDF_EXPAND) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXPAND)) || \
(defined(PSA_WANT_ALG_PBKDF2_HMAC) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_HMAC))
#define PSA_WANT_ALG_HMAC 1
#define PSA_WANT_KEY_TYPE_HMAC 1
#endif
#if (defined(PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128) && \
!defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_AES_CMAC_PRF_128))
#define PSA_WANT_KEY_TYPE_AES 1
#define PSA_WANT_ALG_CMAC 1
#endif
#endif /* PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H */

View File

@ -2,6 +2,8 @@
* \file psa/crypto_adjust_config_key_pair_types.h
* \brief Adjust PSA configuration for key pair types.
*
* This is an internal header. Do not include it directly.
*
* See docs/proposed/psa-conditional-inclusion-c.md.
* - Support non-basic operations in a keypair type implicitly enables basic
* support for that keypair type.
@ -19,6 +21,14 @@
#ifndef PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H
#define PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/*****************************************************************
* ANYTHING -> BASIC
****************************************************************/

View File

@ -2,6 +2,8 @@
* \file psa/crypto_adjust_config_synonyms.h
* \brief Adjust PSA configuration: enable quasi-synonyms
*
* This is an internal header. Do not include it directly.
*
* When two features require almost the same code, we automatically enable
* both when either one is requested, to reduce the combinatorics of
* possible configurations.
@ -14,6 +16,14 @@
#ifndef PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H
#define PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H
#if !defined(MBEDTLS_CONFIG_FILES_READ)
#error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \
"up to and including runtime errors such as buffer overflows. " \
"If you're trying to fix a complaint from check_config.h, just remove " \
"it from your configuration file: since Mbed TLS 3.0, it is included " \
"automatically at the right point."
#endif /* */
/****************************************************************/
/* De facto synonyms */
/****************************************************************/

View File

@ -223,9 +223,34 @@ static inline struct psa_key_derivation_s psa_key_derivation_operation_init(
return v;
}
struct psa_key_production_parameters_s {
struct psa_custom_key_parameters_s {
/* Future versions may add other fields in this structure. */
uint32_t flags;
};
/** The default production parameters for key generation or key derivation.
*
* Calling psa_generate_key_custom() or psa_key_derivation_output_key_custom()
* with `custom=PSA_CUSTOM_KEY_PARAMETERS_INIT` and `custom_data_length=0` is
* equivalent to calling psa_generate_key() or psa_key_derivation_output_key()
* respectively.
*/
#define PSA_CUSTOM_KEY_PARAMETERS_INIT { 0 }
#ifndef __cplusplus
/* Omitted when compiling in C++, because one of the parameters is a
* pointer to a struct with a flexible array member, and that is not
* standard C++.
* https://github.com/Mbed-TLS/mbedtls/issues/9020
*/
/* This is a deprecated variant of `struct psa_custom_key_parameters_s`.
* It has exactly the same layout, plus an extra field which is a flexible
* array member. Thus a `const struct psa_key_production_parameters_s *`
* can be passed to any function that reads a
* `const struct psa_custom_key_parameters_s *`.
*/
struct psa_key_production_parameters_s {
uint32_t flags;
uint8_t data[];
};
@ -238,6 +263,7 @@ struct psa_key_production_parameters_s {
* respectively.
*/
#define PSA_KEY_PRODUCTION_PARAMETERS_INIT { 0 }
#endif /* !__cplusplus */
struct psa_key_policy_s {
psa_key_usage_t MBEDTLS_PRIVATE(usage);

View File

@ -455,6 +455,30 @@ typedef uint64_t psa_key_slot_number_t;
*/
typedef uint16_t psa_key_derivation_step_t;
/** \brief Custom parameters for key generation or key derivation.
*
* This is a structure type with at least the following field:
*
* - \c flags: an unsigned integer type. 0 for the default production parameters.
*
* Functions that take such a structure as input also take an associated
* input buffer \c custom_data of length \c custom_data_length.
*
* The interpretation of this structure and the associated \c custom_data
* parameter depend on the type of the created key.
*
* - #PSA_KEY_TYPE_RSA_KEY_PAIR:
* - \c flags: must be 0.
* - \c custom_data: the public exponent, in little-endian order.
* This must be an odd integer and must not be 1.
* Implementations must support 65537, should support 3 and may
* support other values.
* When not using a driver, Mbed TLS supports values up to \c INT_MAX.
* If this is empty, the default value 65537 is used.
* - Other key types: reserved for future use. \c flags must be 0.
*/
typedef struct psa_custom_key_parameters_s psa_custom_key_parameters_t;
/** \brief Custom parameters for key generation or key derivation.
*
* This is a structure type with at least the following fields:

View File

@ -51,6 +51,10 @@ static int mbedtls_cipher_error_from_psa(psa_status_t status)
void mbedtls_block_cipher_free(mbedtls_block_cipher_context_t *ctx)
{
if (ctx == NULL) {
return;
}
#if defined(MBEDTLS_BLOCK_CIPHER_SOME_PSA)
if (ctx->engine == MBEDTLS_BLOCK_CIPHER_ENGINE_PSA) {
psa_destroy_key(ctx->psa_key_id);

View File

@ -849,6 +849,9 @@ static int get_pkcs_padding(unsigned char *input, size_t input_len,
}
padding_len = input[input_len - 1];
if (padding_len == 0 || padding_len > input_len) {
return MBEDTLS_ERR_CIPHER_INVALID_PADDING;
}
*data_len = input_len - padding_len;
mbedtls_ct_condition_t bad = mbedtls_ct_uint_gt(padding_len, input_len);

View File

@ -61,6 +61,10 @@ void mbedtls_entropy_init(mbedtls_entropy_context *ctx)
void mbedtls_entropy_free(mbedtls_entropy_context *ctx)
{
if (ctx == NULL) {
return;
}
/* If the context was already free, don't call free() again.
* This is important for mutexes which don't allow double-free. */
if (ctx->accumulator_started == -1) {

View File

@ -5,10 +5,12 @@
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#if defined(__linux__) || defined(__midipix__) && !defined(_GNU_SOURCE)
#if defined(__linux__) || defined(__midipix__)
/* Ensure that syscall() is available even when compiling with -std=c99 */
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#endif
#include "common.h"

View File

@ -387,6 +387,10 @@ void mbedtls_lmots_public_init(mbedtls_lmots_public_t *ctx)
void mbedtls_lmots_public_free(mbedtls_lmots_public_t *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize(ctx, sizeof(*ctx));
}
@ -556,6 +560,10 @@ void mbedtls_lmots_private_init(mbedtls_lmots_private_t *ctx)
void mbedtls_lmots_private_free(mbedtls_lmots_private_t *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize(ctx,
sizeof(*ctx));
}

View File

@ -229,6 +229,10 @@ void mbedtls_lms_public_init(mbedtls_lms_public_t *ctx)
void mbedtls_lms_public_free(mbedtls_lms_public_t *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_platform_zeroize(ctx, sizeof(*ctx));
}
@ -528,6 +532,10 @@ void mbedtls_lms_private_init(mbedtls_lms_private_t *ctx)
void mbedtls_lms_private_free(mbedtls_lms_private_t *ctx)
{
if (ctx == NULL) {
return;
}
unsigned int idx;
if (ctx->have_private_key) {

View File

@ -41,7 +41,7 @@
#include "mbedtls/sha512.h"
#include "mbedtls/sha3.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
#include <psa/crypto.h>
#include "md_psa.h"
#include "psa_util_internal.h"
@ -761,13 +761,13 @@ mbedtls_md_type_t mbedtls_md_get_type(const mbedtls_md_info_t *md_info)
return md_info->type;
}
#if defined(MBEDTLS_PSA_CRYPTO_C)
#if defined(MBEDTLS_PSA_CRYPTO_CLIENT)
int mbedtls_md_error_from_psa(psa_status_t status)
{
return PSA_TO_MBEDTLS_ERR_LIST(status, psa_to_md_errors,
psa_generic_status_to_mbedtls);
}
#endif /* MBEDTLS_PSA_CRYPTO_C */
#endif /* MBEDTLS_PSA_CRYPTO_CLIENT */
/************************************************************************

View File

@ -683,7 +683,7 @@ void mbedtls_net_close(mbedtls_net_context *ctx)
*/
void mbedtls_net_free(mbedtls_net_context *ctx)
{
if (ctx->fd == -1) {
if (ctx == NULL || ctx->fd == -1) {
return;
}

View File

@ -102,6 +102,10 @@ int mbedtls_nist_kw_setkey(mbedtls_nist_kw_context *ctx,
*/
void mbedtls_nist_kw_free(mbedtls_nist_kw_context *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_cipher_free(&ctx->cipher_ctx);
mbedtls_platform_zeroize(ctx, sizeof(mbedtls_nist_kw_context));
}

View File

@ -481,6 +481,10 @@ int mbedtls_pem_read_buffer(mbedtls_pem_context *ctx, const char *header, const
void mbedtls_pem_free(mbedtls_pem_context *ctx)
{
if (ctx == NULL) {
return;
}
if (ctx->buf != NULL) {
mbedtls_zeroize_and_free(ctx->buf, ctx->buflen);
}

View File

@ -868,7 +868,6 @@ static int copy_from_psa(mbedtls_svc_key_id_t key_id,
psa_status_t status;
psa_key_attributes_t key_attr = PSA_KEY_ATTRIBUTES_INIT;
psa_key_type_t key_type;
psa_algorithm_t alg_type;
size_t key_bits;
/* Use a buffer size large enough to contain either a key pair or public key. */
unsigned char exp_key[PSA_EXPORT_KEY_PAIR_OR_PUBLIC_MAX_SIZE];
@ -899,7 +898,6 @@ static int copy_from_psa(mbedtls_svc_key_id_t key_id,
key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(key_type);
}
key_bits = psa_get_key_bits(&key_attr);
alg_type = psa_get_key_algorithm(&key_attr);
#if defined(MBEDTLS_RSA_C)
if ((key_type == PSA_KEY_TYPE_RSA_KEY_PAIR) ||
@ -919,6 +917,7 @@ static int copy_from_psa(mbedtls_svc_key_id_t key_id,
goto exit;
}
psa_algorithm_t alg_type = psa_get_key_algorithm(&key_attr);
mbedtls_md_type_t md_type = MBEDTLS_MD_NONE;
if (PSA_ALG_GET_HASH(alg_type) != PSA_ALG_ANY_HASH) {
md_type = mbedtls_md_type_from_psa_alg(alg_type);
@ -968,6 +967,7 @@ static int copy_from_psa(mbedtls_svc_key_id_t key_id,
} else
#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
{
(void) key_bits;
return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
}

View File

@ -149,7 +149,7 @@ void mbedtls_zeroize_and_free(void *buf, size_t len)
#include <time.h>
#if !defined(_WIN32) && (defined(unix) || \
defined(__unix) || defined(__unix__) || (defined(__APPLE__) && \
defined(__MACH__)) || defined__midipix__)
defined(__MACH__)) || defined(__midipix__))
#include <unistd.h>
#endif /* !_WIN32 && (unix || __unix || __unix__ ||
* (__APPLE__ && __MACH__) || __midipix__) */

View File

@ -1835,6 +1835,9 @@ static psa_status_t psa_start_key_creation(
status = psa_copy_key_material_into_slot(
slot, (uint8_t *) (&slot_number), sizeof(slot_number));
if (status != PSA_SUCCESS) {
return status;
}
}
if (*p_drv == NULL && method == PSA_KEY_CREATION_REGISTER) {
@ -4628,11 +4631,7 @@ psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
goto exit;
}
if (alg == PSA_ALG_CCM_STAR_NO_TAG &&
input_length < PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type)) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
} else if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
@ -5194,6 +5193,12 @@ psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
goto exit;
}
/* No input to add (zero length), nothing to do. */
if (input_length == 0) {
status = PSA_SUCCESS;
goto exit;
}
if (operation->lengths_set) {
if (operation->ad_remaining < input_length) {
status = PSA_ERROR_INVALID_ARGUMENT;
@ -6407,27 +6412,28 @@ exit:
return status;
}
static const psa_key_production_parameters_t default_production_parameters =
PSA_KEY_PRODUCTION_PARAMETERS_INIT;
static const psa_custom_key_parameters_t default_custom_production =
PSA_CUSTOM_KEY_PARAMETERS_INIT;
int psa_key_production_parameters_are_default(
const psa_key_production_parameters_t *params,
size_t params_data_length)
int psa_custom_key_parameters_are_default(
const psa_custom_key_parameters_t *custom,
size_t custom_data_length)
{
if (params->flags != 0) {
if (custom->flags != 0) {
return 0;
}
if (params_data_length != 0) {
if (custom_data_length != 0) {
return 0;
}
return 1;
}
psa_status_t psa_key_derivation_output_key_ext(
psa_status_t psa_key_derivation_output_key_custom(
const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
const psa_key_production_parameters_t *params,
size_t params_data_length,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
mbedtls_svc_key_id_t *key)
{
psa_status_t status;
@ -6442,7 +6448,8 @@ psa_status_t psa_key_derivation_output_key_ext(
return PSA_ERROR_INVALID_ARGUMENT;
}
if (!psa_key_production_parameters_are_default(params, params_data_length)) {
(void) custom_data; /* We only accept 0-length data */
if (!psa_custom_key_parameters_are_default(custom, custom_data_length)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
@ -6477,14 +6484,29 @@ psa_status_t psa_key_derivation_output_key_ext(
return status;
}
psa_status_t psa_key_derivation_output_key_ext(
const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
const psa_key_production_parameters_t *params,
size_t params_data_length,
mbedtls_svc_key_id_t *key)
{
return psa_key_derivation_output_key_custom(
attributes, operation,
(const psa_custom_key_parameters_t *) params,
params->data, params_data_length,
key);
}
psa_status_t psa_key_derivation_output_key(
const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
mbedtls_svc_key_id_t *key)
{
return psa_key_derivation_output_key_ext(attributes, operation,
&default_production_parameters, 0,
key);
return psa_key_derivation_output_key_custom(attributes, operation,
&default_custom_production,
NULL, 0,
key);
}
@ -7858,15 +7880,18 @@ static psa_status_t psa_validate_key_type_and_size_for_key_generation(
psa_status_t psa_generate_key_internal(
const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params, size_t params_data_length,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_type_t type = attributes->type;
/* Only used for RSA */
(void) params;
(void) params_data_length;
(void) custom;
(void) custom_data;
(void) custom_data_length;
if (key_type_is_raw_bytes(type)) {
status = psa_generate_random_internal(key_buffer, key_buffer_size);
@ -7884,7 +7909,7 @@ psa_status_t psa_generate_key_internal(
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
return mbedtls_psa_rsa_generate_key(attributes,
params, params_data_length,
custom_data, custom_data_length,
key_buffer,
key_buffer_size,
key_buffer_length);
@ -7916,10 +7941,11 @@ psa_status_t psa_generate_key_internal(
return PSA_SUCCESS;
}
psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params,
size_t params_data_length,
mbedtls_svc_key_id_t *key)
psa_status_t psa_generate_key_custom(const psa_key_attributes_t *attributes,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
mbedtls_svc_key_id_t *key)
{
psa_status_t status;
psa_key_slot_t *slot = NULL;
@ -7941,12 +7967,12 @@ psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
if (params->flags != 0) {
if (custom->flags != 0) {
return PSA_ERROR_INVALID_ARGUMENT;
}
} else
#endif
if (!psa_key_production_parameters_are_default(params, params_data_length)) {
if (!psa_custom_key_parameters_are_default(custom, custom_data_length)) {
return PSA_ERROR_INVALID_ARGUMENT;
}
@ -7987,7 +8013,8 @@ psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
}
status = psa_driver_wrapper_generate_key(attributes,
params, params_data_length,
custom,
custom_data, custom_data_length,
slot->key.data, slot->key.bytes,
&slot->key.bytes);
if (status != PSA_SUCCESS) {
@ -8005,12 +8032,25 @@ exit:
return status;
}
psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params,
size_t params_data_length,
mbedtls_svc_key_id_t *key)
{
return psa_generate_key_custom(
attributes,
(const psa_custom_key_parameters_t *) params,
params->data, params_data_length,
key);
}
psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
mbedtls_svc_key_id_t *key)
{
return psa_generate_key_ext(attributes,
&default_production_parameters, 0,
key);
return psa_generate_key_custom(attributes,
&default_custom_production,
NULL, 0,
key);
}
/****************************************************************/

View File

@ -263,7 +263,7 @@ const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
{
mbedtls_cipher_mode_t mode;
psa_status_t status;
mbedtls_cipher_id_t cipher_id_tmp;
mbedtls_cipher_id_t cipher_id_tmp = MBEDTLS_CIPHER_ID_NONE;
status = mbedtls_cipher_values_from_psa(alg, key_type, &key_bits, &mode, &cipher_id_tmp);
if (status != PSA_SUCCESS) {

View File

@ -343,17 +343,18 @@ psa_status_t psa_export_public_key_internal(
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length);
/** Whether a key production parameters structure is the default.
/** Whether a key custom production parameters structure is the default.
*
* Calls to a key generation driver with non-default production parameters
* Calls to a key generation driver with non-default custom production parameters
* require a driver supporting custom production parameters.
*
* \param[in] params The key production parameters to check.
* \param params_data_length Size of `params->data` in bytes.
* \param[in] custom The key custom production parameters to check.
* \param custom_data_length Size of the associated variable-length data
* in bytes.
*/
int psa_key_production_parameters_are_default(
const psa_key_production_parameters_t *params,
size_t params_data_length);
int psa_custom_key_parameters_are_default(
const psa_custom_key_parameters_t *custom,
size_t custom_data_length);
/**
* \brief Generate a key.
@ -362,9 +363,9 @@ int psa_key_production_parameters_are_default(
* entry point.
*
* \param[in] attributes The attributes for the key to generate.
* \param[in] params The production parameters from
* psa_generate_key_ext().
* \param params_data_length The size of `params->data` in bytes.
* \param[in] custom Custom parameters for the key generation.
* \param[in] custom_data Variable-length data associated with \c custom.
* \param custom_data_length Length of `custom_data` in bytes.
* \param[out] key_buffer Buffer where the key data is to be written.
* \param[in] key_buffer_size Size of \p key_buffer in bytes.
* \param[out] key_buffer_length On success, the number of bytes written in
@ -379,8 +380,9 @@ int psa_key_production_parameters_are_default(
* The size of \p key_buffer is too small.
*/
psa_status_t psa_generate_key_internal(const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params,
size_t params_data_length,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data,
size_t custom_data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length);

View File

@ -241,7 +241,7 @@ static psa_status_t psa_rsa_read_exponent(const uint8_t *e_bytes,
psa_status_t mbedtls_psa_rsa_generate_key(
const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params, size_t params_data_length,
const uint8_t *custom_data, size_t custom_data_length,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
{
psa_status_t status;
@ -249,8 +249,8 @@ psa_status_t mbedtls_psa_rsa_generate_key(
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int exponent = 65537;
if (params_data_length != 0) {
status = psa_rsa_read_exponent(params->data, params_data_length,
if (custom_data_length != 0) {
status = psa_rsa_read_exponent(custom_data, custom_data_length,
&exponent);
if (status != PSA_SUCCESS) {
return status;

View File

@ -105,17 +105,11 @@ psa_status_t mbedtls_psa_rsa_export_public_key(
/**
* \brief Generate an RSA key.
*
* \note The signature of the function is that of a PSA driver generate_key
* entry point.
*
* \param[in] attributes The attributes for the RSA key to generate.
* \param[in] params Production parameters for the key
* generation. This function only uses
* `params->data`,
* which contains the public exponent.
* \param[in] custom_data The public exponent to use.
* This can be a null pointer if
* \c params_data_length is 0.
* \param params_data_length Length of `params->data` in bytes.
* \param custom_data_length Length of \p custom_data in bytes.
* This can be 0, in which case the
* public exponent will be 65537.
* \param[out] key_buffer Buffer where the key data is to be written.
@ -132,7 +126,7 @@ psa_status_t mbedtls_psa_rsa_export_public_key(
*/
psa_status_t mbedtls_psa_rsa_generate_key(
const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params, size_t params_data_length,
const uint8_t *custom_data, size_t custom_data_length,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length);
/** Sign an already-calculated hash with an RSA private key.

View File

@ -424,6 +424,8 @@ psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
if (status != PSA_SUCCESS) {
psa_wipe_key_slot(*p_slot);
/* If the key does not exist, we need to return
* PSA_ERROR_INVALID_HANDLE. */
if (status == PSA_ERROR_DOES_NOT_EXIST) {
status = PSA_ERROR_INVALID_HANDLE;
}
@ -440,6 +442,9 @@ psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
status = PSA_ERROR_INVALID_HANDLE;
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
if (status != PSA_SUCCESS) {
*p_slot = NULL;
}
#if defined(MBEDTLS_THREADING_C)
PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
&mbedtls_threading_key_slot_mutex));

View File

@ -58,6 +58,9 @@ static inline int psa_key_id_is_volatile(psa_key_id_t key_id)
* It is the responsibility of the caller to call psa_unregister_read(slot)
* when they have finished reading the contents of the slot.
*
* On failure, `*p_slot` is set to NULL. This ensures that it is always valid
* to call psa_unregister_read on the returned slot.
*
* \param key Key identifier to query.
* \param[out] p_slot On success, `*p_slot` contains a pointer to the
* key slot containing the description of the key

View File

@ -44,7 +44,9 @@
#endif /* defined(__clang__) && (__clang_major__ >= 4) */
/* Ensure that SIG_SETMASK is defined when -std=c99 is used. */
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include "common.h"

View File

@ -84,6 +84,10 @@ void mbedtls_ssl_cookie_set_timeout(mbedtls_ssl_cookie_ctx *ctx, unsigned long d
void mbedtls_ssl_cookie_free(mbedtls_ssl_cookie_ctx *ctx)
{
if (ctx == NULL) {
return;
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
psa_destroy_key(ctx->psa_hmac_key);
#else

View File

@ -534,6 +534,10 @@ cleanup:
*/
void mbedtls_ssl_ticket_free(mbedtls_ssl_ticket_context *ctx)
{
if (ctx == NULL) {
return;
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
psa_destroy_key(ctx->keys[0].key);
psa_destroy_key(ctx->keys[1].key);

View File

@ -132,7 +132,7 @@ int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
int mbedtls_ssl_get_own_cid(mbedtls_ssl_context *ssl,
int *enabled,
unsigned char own_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
unsigned char own_cid[MBEDTLS_SSL_CID_IN_LEN_MAX],
size_t *own_cid_len)
{
*enabled = MBEDTLS_SSL_CID_DISABLED;
@ -2243,6 +2243,7 @@ static void ssl_remove_psk(mbedtls_ssl_context *ssl)
mbedtls_zeroize_and_free(ssl->handshake->psk,
ssl->handshake->psk_len);
ssl->handshake->psk_len = 0;
ssl->handshake->psk = NULL;
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
}
@ -6039,6 +6040,10 @@ int mbedtls_ssl_config_defaults(mbedtls_ssl_config *conf,
*/
void mbedtls_ssl_config_free(mbedtls_ssl_config *conf)
{
if (conf == NULL) {
return;
}
#if defined(MBEDTLS_DHM_C)
mbedtls_mpi_free(&conf->dhm_P);
mbedtls_mpi_free(&conf->dhm_G);

View File

@ -2631,13 +2631,8 @@ static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
ssl->handshake->xxdh_psa_type = psa_get_key_type(&key_attributes);
ssl->handshake->xxdh_psa_bits = psa_get_key_bits(&key_attributes);
if (pk_type == MBEDTLS_PK_OPAQUE) {
/* Opaque key is created by the user (externally from Mbed TLS)
* so we assume it already has the right algorithm and flags
* set. Just copy its ID as reference. */
ssl->handshake->xxdh_psa_privkey = pk->priv_id;
ssl->handshake->xxdh_psa_privkey_is_external = 1;
} else {
#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
if (pk_type != MBEDTLS_PK_OPAQUE) {
/* PK_ECKEY[_DH] and PK_ECDSA instead as parsed from the PK
* module and only have ECDSA capabilities. Since we need
* them for ECDH later, we export and then re-import them with
@ -2665,10 +2660,20 @@ static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
/* Set this key as owned by the TLS library: it will be its duty
* to clear it exit. */
ssl->handshake->xxdh_psa_privkey_is_external = 0;
}
ret = 0;
break;
}
#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
/* Opaque key is created by the user (externally from Mbed TLS)
* so we assume it already has the right algorithm and flags
* set. Just copy its ID as reference. */
ssl->handshake->xxdh_psa_privkey = pk->priv_id;
ssl->handshake->xxdh_psa_privkey_is_external = 1;
ret = 0;
break;
#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
case MBEDTLS_PK_ECKEY:
case MBEDTLS_PK_ECKEY_DH:

View File

@ -1484,9 +1484,11 @@ int mbedtls_ssl_tls13_check_early_data_len(mbedtls_ssl_context *ssl,
ssl->total_early_data_size)) {
MBEDTLS_SSL_DEBUG_MSG(
2, ("EarlyData: Too much early data received, %u + %" MBEDTLS_PRINTF_SIZET " > %u",
ssl->total_early_data_size, early_data_len,
ssl->session_negotiate->max_early_data_size));
2, ("EarlyData: Too much early data received, "
"%lu + %" MBEDTLS_PRINTF_SIZET " > %lu",
(unsigned long) ssl->total_early_data_size,
early_data_len,
(unsigned long) ssl->session_negotiate->max_early_data_size));
MBEDTLS_SSL_PEND_FATAL_ALERT(
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,

View File

@ -92,8 +92,9 @@ static void ssl_tls13_select_ciphersuite(
return;
}
MBEDTLS_SSL_DEBUG_MSG(2, ("No matched ciphersuite, psk_ciphersuite_id=%x, psk_hash_alg=%x",
(unsigned) psk_ciphersuite_id, psk_hash_alg));
MBEDTLS_SSL_DEBUG_MSG(2, ("No matched ciphersuite, psk_ciphersuite_id=%x, psk_hash_alg=%lx",
(unsigned) psk_ciphersuite_id,
(unsigned long) psk_hash_alg));
}
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)

View File

@ -46,6 +46,10 @@ void mbedtls_x509write_crt_init(mbedtls_x509write_cert *ctx)
void mbedtls_x509write_crt_free(mbedtls_x509write_cert *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_asn1_free_named_data_list(&ctx->subject);
mbedtls_asn1_free_named_data_list(&ctx->issuer);
mbedtls_asn1_free_named_data_list(&ctx->extensions);

View File

@ -43,6 +43,10 @@ void mbedtls_x509write_csr_init(mbedtls_x509write_csr *ctx)
void mbedtls_x509write_csr_free(mbedtls_x509write_csr *ctx)
{
if (ctx == NULL) {
return;
}
mbedtls_asn1_free_named_data_list(&ctx->subject);
mbedtls_asn1_free_named_data_list(&ctx->extensions);

2
pkgconfig/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
Makefile
*.pc

View File

@ -9,9 +9,7 @@ ifdef FUZZINGENGINE
LOCAL_LDFLAGS += -lFuzzingEngine
endif
# A test application is built for each suites/test_suite_*.data file.
# Application name is same as .data file's base name and can be
# constructed by stripping path 'suites/' and extension .data.
# A test application is built for each fuzz_*.c file.
APPS = $(basename $(wildcard fuzz_*.c))
# Construct executable name by adding OS specific suffix $(EXEXT).

View File

@ -70,7 +70,7 @@ const char psk_id[] = "Client_identity";
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
/* This is tests/data_files/test-ca2.crt, a CA using EC secp384r1 */
/* This is framework/data_files/test-ca2.crt, a CA using EC secp384r1 */
const unsigned char ca_cert[] = {
0x30, 0x82, 0x02, 0x52, 0x30, 0x82, 0x01, 0xd7, 0xa0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x09, 0x00, 0xc1, 0x43, 0xe2, 0x7e, 0x62, 0x43, 0xcc, 0xe8,

View File

@ -727,7 +727,11 @@ usage:
mbedtls_printf(" > Write MAIL FROM to server:");
fflush(stdout);
len = sprintf((char *) buf, "MAIL FROM:<%s>\r\n", opt.mail_from);
len = mbedtls_snprintf((char *) buf, sizeof(buf), "MAIL FROM:<%s>\r\n", opt.mail_from);
if (len < 0 || (size_t) len >= sizeof(buf)) {
mbedtls_printf(" failed\n ! mbedtls_snprintf encountered error or truncated output\n\n");
goto exit;
}
ret = write_ssl_and_get_response(&ssl, buf, len);
if (ret < 200 || ret > 299) {
mbedtls_printf(" failed\n ! server responded with %d\n\n", ret);
@ -739,7 +743,11 @@ usage:
mbedtls_printf(" > Write RCPT TO to server:");
fflush(stdout);
len = sprintf((char *) buf, "RCPT TO:<%s>\r\n", opt.mail_to);
len = mbedtls_snprintf((char *) buf, sizeof(buf), "RCPT TO:<%s>\r\n", opt.mail_to);
if (len < 0 || (size_t) len >= sizeof(buf)) {
mbedtls_printf(" failed\n ! mbedtls_snprintf encountered error or truncated output\n\n");
goto exit;
}
ret = write_ssl_and_get_response(&ssl, buf, len);
if (ret < 200 || ret > 299) {
mbedtls_printf(" failed\n ! server responded with %d\n\n", ret);
@ -763,11 +771,16 @@ usage:
mbedtls_printf(" > Write content to server:");
fflush(stdout);
len = sprintf((char *) buf, "From: %s\r\nSubject: Mbed TLS Test mail\r\n\r\n"
"This is a simple test mail from the "
"Mbed TLS mail client example.\r\n"
"\r\n"
"Enjoy!", opt.mail_from);
len = mbedtls_snprintf((char *) buf, sizeof(buf),
"From: %s\r\nSubject: Mbed TLS Test mail\r\n\r\n"
"This is a simple test mail from the "
"Mbed TLS mail client example.\r\n"
"\r\n"
"Enjoy!", opt.mail_from);
if (len < 0 || (size_t) len >= sizeof(buf)) {
mbedtls_printf(" failed\n ! mbedtls_snprintf encountered error or truncated output\n\n");
goto exit;
}
ret = write_ssl_data(&ssl, buf, len);
len = sprintf((char *) buf, "\r\n.\r\n");

View File

@ -1,3 +1,4 @@
build
Makefile
cmake_package
mbedtls

View File

@ -1,3 +1,4 @@
build
Makefile
cmake_package_install
mbedtls

View File

@ -381,7 +381,7 @@ typedef struct {
void (*entry_point)(const char *name);
} metatest_t;
/* The list of availble meta-tests. Remember to register new functions here!
/* The list of available meta-tests. Remember to register new functions here!
*
* Note that we always compile all the functions, so that `metatest --list`
* will always list all the available meta-tests.

View File

@ -101,7 +101,8 @@ from types import SimpleNamespace
import xml.etree.ElementTree as ET
from mbedtls_dev import build_tree
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
class AbiChecker:
@ -325,8 +326,14 @@ class AbiChecker:
@staticmethod
def _list_generated_test_data_files(git_worktree_path):
"""List the generated test data files."""
generate_psa_tests = 'framework/scripts/generate_psa_tests.py'
if not os.path.isfile(git_worktree_path + '/' + generate_psa_tests):
# The checked-out revision is from before generate_psa_tests.py
# was moved to the framework submodule. Use the old location.
generate_psa_tests = 'tests/scripts/generate_psa_tests.py'
output = subprocess.check_output(
['tests/scripts/generate_psa_tests.py', '--list'],
[generate_psa_tests, '--list'],
cwd=git_worktree_path,
).decode('ascii')
return [line for line in output.split('\n') if line]
@ -352,8 +359,14 @@ class AbiChecker:
if 'storage_format' in filename:
storage_data_files.add(filename)
to_be_generated.add(filename)
generate_psa_tests = 'framework/scripts/generate_psa_tests.py'
if not os.path.isfile(git_worktree_path + '/' + generate_psa_tests):
# The checked-out revision is from before generate_psa_tests.py
# was moved to the framework submodule. Use the old location.
generate_psa_tests = 'tests/scripts/generate_psa_tests.py'
subprocess.check_call(
['tests/scripts/generate_psa_tests.py'] + sorted(to_be_generated),
[generate_psa_tests] + sorted(to_be_generated),
cwd=git_worktree_path,
)
for test_file in sorted(storage_data_files):

View File

@ -19,6 +19,6 @@ mypy >= 0.780
# to run audit-validity-dates.py on Python >=3.6.
cryptography # >= 35.0.0
# For building `tests/data_files/server9-bad-saltlen.crt` and check python
# For building `framework/data_files/server9-bad-saltlen.crt` and check python
# files.
asn1crypto

View File

@ -21,9 +21,10 @@ import sys
import typing
from enum import Enum
from mbedtls_dev import build_tree
from mbedtls_dev import logging_util
from mbedtls_dev import typing_util
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
from mbedtls_framework import logging_util
from mbedtls_framework import typing_util
class SupportedArch(Enum):
"""Supported architecture for code size measurement."""

View File

@ -75,16 +75,55 @@ def get_src_files(since: Optional[str]) -> List[str]:
output = subprocess.check_output(["git", "ls-files"] + file_patterns,
universal_newlines=True)
src_files = output.split()
# When this script is called from a git hook, some environment variables
# are set by default which force all git commands to use the main repository
# (i.e. prevent us from performing commands on the framework repo).
# Create an environment without these variables for running commands on the
# framework repo.
framework_env = os.environ.copy()
# Get a list of environment vars that git sets
git_env_vars = subprocess.check_output(["git", "rev-parse", "--local-env-vars"],
universal_newlines=True)
# Remove the vars from the environment
for var in git_env_vars.split():
framework_env.pop(var, None)
output = subprocess.check_output(["git", "-C", "framework", "ls-files"]
+ file_patterns,
universal_newlines=True,
env=framework_env)
framework_src_files = output.split()
if since:
# get all files changed in commits since the starting point
cmd = ["git", "log", since + "..HEAD", "--name-only", "--pretty=", "--"] + src_files
# get all files changed in commits since the starting point in ...
# ... the main repository
cmd = ["git", "log", since + "..HEAD", "--ignore-submodules",
"--name-only", "--pretty=", "--"] + src_files
output = subprocess.check_output(cmd, universal_newlines=True)
committed_changed_files = output.split()
# and also get all files with uncommitted changes
# ... the framework submodule
cmd = ["git", "-C", "framework", "log", since + "..HEAD",
"--name-only", "--pretty=", "--"] + framework_src_files
output = subprocess.check_output(cmd, universal_newlines=True,
env=framework_env)
committed_changed_files += ["framework/" + s for s in output.split()]
# and also get all files with uncommitted changes in ...
# ... the main repository
cmd = ["git", "diff", "--name-only", "--"] + src_files
output = subprocess.check_output(cmd, universal_newlines=True)
uncommitted_changed_files = output.split()
src_files = list(set(committed_changed_files + uncommitted_changed_files))
# ... the framework submodule
cmd = ["git", "-C", "framework", "diff", "--name-only", "--"] + \
framework_src_files
output = subprocess.check_output(cmd, universal_newlines=True,
env=framework_env)
uncommitted_changed_files += ["framework/" + s for s in output.split()]
src_files = committed_changed_files + uncommitted_changed_files
else:
src_files += ["framework/" + s for s in framework_src_files]
generated_files = list_generated_files()
# Don't correct style for third-party files (and, for simplicity,

View File

@ -18,7 +18,7 @@ include $(MBEDTLS_PATH)/framework/exported.make
CFLAGS ?= -O2
WARNING_CFLAGS ?= -Wall -Wextra -Wformat=2 -Wno-format-nonliteral
WARNING_CXXFLAGS ?= -Wall -Wextra -Wformat=2 -Wno-format-nonliteral
WARNING_CXXFLAGS ?= -Wall -Wextra -Wformat=2 -Wno-format-nonliteral -std=c++11 -pedantic
LDFLAGS ?=
LOCAL_CFLAGS = $(WARNING_CFLAGS) -I$(MBEDTLS_TEST_PATH)/include -I$(MBEDTLS_PATH)/include -D_FILE_OFFSET_BITS=64

View File

@ -396,6 +396,7 @@ class ConfigFile(Config):
self.default_path)
super().__init__()
self.filename = filename
self.inclusion_guard = None
self.current_section = 'header'
with open(filename, 'r', encoding='utf-8') as file:
self.templates = [self._parse_line(line) for line in file]
@ -413,9 +414,11 @@ class ConfigFile(Config):
r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
r'(?P<separator>\s*)' +
r'(?P<value>.*)')
_ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
_section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
r'(?P<section>.*)[ */]*')
_config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
_ifndef_line_regexp,
_section_line_regexp]))
def _parse_line(self, line):
"""Parse a line in mbedtls_config.h and return the corresponding template."""
@ -426,10 +429,16 @@ class ConfigFile(Config):
elif m.group('section'):
self.current_section = m.group('section')
return line
elif m.group('inclusion_guard') and self.inclusion_guard is None:
self.inclusion_guard = m.group('inclusion_guard')
return line
else:
active = not m.group('commented_out')
name = m.group('name')
value = m.group('value')
if name == self.inclusion_guard and value == '':
# The file double-inclusion guard is not an option.
return line
template = (name,
m.group('indentation'),
m.group('define') + name +

View File

@ -731,7 +731,8 @@ static inline psa_status_t psa_driver_wrapper_get_key_buffer_size_from_key_data(
static inline psa_status_t psa_driver_wrapper_generate_key(
const psa_key_attributes_t *attributes,
const psa_key_production_parameters_t *params, size_t params_data_length,
const psa_custom_key_parameters_t *custom,
const uint8_t *custom_data, size_t custom_data_length,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
@ -740,7 +741,7 @@ static inline psa_status_t psa_driver_wrapper_generate_key(
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
int is_default_production =
psa_key_production_parameters_are_default(params, params_data_length);
psa_custom_key_parameters_are_default(custom, custom_data_length);
if( location != PSA_KEY_LOCATION_LOCAL_STORAGE && !is_default_production )
{
/* We don't support passing custom production parameters
@ -811,7 +812,7 @@ static inline psa_status_t psa_driver_wrapper_generate_key(
/* Software fallback */
status = psa_generate_key_internal(
attributes, params, params_data_length,
attributes, custom, custom_data, custom_data_length,
key_buffer, key_buffer_size, key_buffer_length );
break;

View File

@ -0,0 +1,17 @@
"""Add our Python library directory to the module search path.
Usage:
import framework_scripts_path # pylint: disable=unused-import
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir,
'framework', 'scripts'))

View File

@ -17,7 +17,9 @@ from traceback import format_tb
import argparse
import jsonschema
import jinja2
from mbedtls_dev import build_tree
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
JSONSchema = NewType('JSONSchema', object)
# The Driver is an Object, but practically it's indexable and can called a dictionary to

View File

@ -17,8 +17,9 @@ file is written:
import os
import sys
from mbedtls_dev import build_tree
from mbedtls_dev import macro_collector
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
from mbedtls_framework import macro_collector
OUTPUT_TEMPLATE = '''\
/* Automatically generated by generate_psa_constant.py. DO NOT EDIT. */

View File

@ -14,7 +14,9 @@ import re
import os
import textwrap
import argparse
from mbedtls_dev import build_tree
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
def remove_c_comments(string):
@ -328,7 +330,7 @@ class NamedGroupDefinition:
{translation_table}
}};
return "UNKOWN";
return "UNKNOWN";
}}''')
body = body.format(translation_table='\n'.join(translation_table))
return body

View File

@ -30,9 +30,15 @@ EOF
set -eu
# Repository detection
in_mbedtls_build_dir () {
test -d library
# Project detection
PROJECT_NAME_FILE='./scripts/project_name.txt'
if read -r PROJECT_NAME < "$PROJECT_NAME_FILE"; then :; else
echo "$PROJECT_NAME_FILE does not exist... Exiting..." >&2
exit 1
fi
in_mbedtls_repo () {
test "$PROJECT_NAME" = "Mbed TLS"
}
# Collect stats and build a HTML report.
@ -68,7 +74,7 @@ if [ $# -gt 0 ] && [ "$1" = "--help" ]; then
exit
fi
if in_mbedtls_build_dir; then
if in_mbedtls_repo; then
library_dir='library'
title='Mbed TLS'
else

View File

@ -10,6 +10,9 @@ perl scripts\generate_features.pl || exit /b 1
python scripts\generate_ssl_debug_helpers.py || exit /b 1
perl scripts\generate_visualc_files.pl || exit /b 1
python scripts\generate_psa_constants.py || exit /b 1
python tests\scripts\generate_bignum_tests.py || exit /b 1
python tests\scripts\generate_ecp_tests.py || exit /b 1
python tests\scripts\generate_psa_tests.py || exit /b 1
python framework\scripts\generate_bignum_tests.py || exit /b 1
python framework\scripts\generate_config_tests.py || exit /b 1
python framework\scripts\generate_ecp_tests.py || exit /b 1
python framework\scripts\generate_psa_tests.py || exit /b 1
python framework\scripts\generate_test_keys.py --output tests\src\test_keys.h || exit /b 1
python framework\scripts\generate_test_cert_macros.py --output tests\src\test_certs.h || exit /b 1

View File

@ -1,3 +0,0 @@
# This file needs to exist to make mbedtls_dev a package.
# Among other things, this allows modules in this directory to make
# relative imports.

View File

@ -1,157 +0,0 @@
"""Sample key material for asymmetric key types.
Meant for use in crypto_knowledge.py.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
import binascii
import re
from typing import Dict
STR_TRANS_REMOVE_BLANKS = str.maketrans('', '', ' \t\n\r')
def unhexlify(text: str) -> bytes:
return binascii.unhexlify(text.translate(STR_TRANS_REMOVE_BLANKS))
def construct_asymmetric_key_data(src) -> Dict[str, Dict[int, bytes]]:
"""Split key pairs into separate table entries and convert hex to bytes.
Input format: src[abbreviated_type][size] = (private_key_hex, public_key_hex)
Output format: dst['PSA_KEY_TYPE_xxx'][size] = key_bytes
"""
dst = {} #type: Dict[str, Dict[int, bytes]]
for typ in src:
private = 'PSA_KEY_TYPE_' + re.sub(r'(\(|\Z)', r'_KEY_PAIR\1', typ, 1)
public = 'PSA_KEY_TYPE_' + re.sub(r'(\(|\Z)', r'_PUBLIC_KEY\1', typ, 1)
dst[private] = {}
dst[public] = {}
for size in src[typ]:
dst[private][size] = unhexlify(src[typ][size][0])
dst[public][size] = unhexlify(src[typ][size][1])
return dst
## These are valid keys that don't try to exercise any edge cases. They're
## either test vectors from some specification, or randomly generated. All
## pairs consist of a private key and its public key.
#pylint: disable=line-too-long
ASYMMETRIC_KEY_DATA = construct_asymmetric_key_data({
'ECC(PSA_ECC_FAMILY_SECP_K1)': {
192: ("297ac1722ccac7589ecb240dc719842538ca974beb79f228",
"0426b7bb38da649ac2138fc050c6548b32553dab68afebc36105d325b75538c12323cb0764789ecb992671beb2b6bef2f5"),
225: ("0024122bf020fa113f6c0ac978dfbd41f749257a9468febdbe0dc9f7e8",
"042cc7335f4b76042bed44ef45959a62aa215f7a5ff0c8111b8c44ed654ee71c1918326ad485b2d599fe2a6eab096ee26d977334d2bac6d61d"),
256: ("7fa06fa02d0e911b9a47fdc17d2d962ca01e2f31d60c6212d0ed7e3bba23a7b9",
"045c39154579efd667adc73a81015a797d2c8682cdfbd3c3553c4a185d481cdc50e42a0e1cbc3ca29a32a645e927f54beaed14c9dbbf8279d725f5495ca924b24d"),
},
'ECC(PSA_ECC_FAMILY_SECP_R1)': {
192: ("d83b57a59c51358d9c8bbb898aff507f44dd14cf16917190",
"04e35fcbee11cec3154f80a1a61df7d7612de4f2fd70c5608d0ee3a4a1a5719471adb33966dd9b035fdb774feeba94b04c"),
224: ("872f203b3ad35b7f2ecc803c3a0e1e0b1ed61cc1afe71b189cd4c995",
"046f00eadaa949fee3e9e1c7fa1247eecec86a0dce46418b9bd3117b981d4bd0ae7a990de912f9d060d6cb531a42d22e394ac29e81804bf160"),
256: ("49c9a8c18c4b885638c431cf1df1c994131609b580d4fd43a0cab17db2f13eee",
"047772656f814b399279d5e1f1781fac6f099a3c5ca1b0e35351834b08b65e0b572590cdaf8f769361bcf34acfc11e5e074e8426bdde04be6e653945449617de45"),
384: ("3f5d8d9be280b5696cc5cc9f94cf8af7e6b61dd6592b2ab2b3a4c607450417ec327dcdcaed7c10053d719a0574f0a76a",
"04d9c662b50ba29ca47990450e043aeaf4f0c69b15676d112f622a71c93059af999691c5680d2b44d111579db12f4a413a2ed5c45fcfb67b5b63e00b91ebe59d09a6b1ac2c0c4282aa12317ed5914f999bc488bb132e8342cc36f2ca5e3379c747"),
521: ("01b1b6ad07bb79e7320da59860ea28e055284f6058f279de666e06d435d2af7bda28d99fa47b7dd0963e16b0073078ee8b8a38d966a582f46d19ff95df3ad9685aae",
"04001de142d54f69eb038ee4b7af9d3ca07736fd9cf719eb354d69879ee7f3c136fb0fbf9f08f86be5fa128ec1a051d3e6c643e85ada8ffacf3663c260bd2c844b6f5600cee8e48a9e65d09cadd89f235dee05f3b8a646be715f1f67d5b434e0ff23a1fc07ef7740193e40eeff6f3bcdfd765aa9155033524fe4f205f5444e292c4c2f6ac1"),
},
'ECC(PSA_ECC_FAMILY_SECP_R2)': {
160: ("00bf539a1cdda0d7f71a50a3f98aec0a2e8e4ced1e",
"049570d541398665adb5cfa16f5af73b3196926bbd4b876bdb80f8eab20d0f540c22f4de9c140f6d7b"),
},
'ECC(PSA_ECC_FAMILY_SECT_K1)': {
163: ("03ebc8fcded2d6ab72ec0f75bdb4fd080481273e71",
"0406f88f90b4b65950f06ce433afdb097e320f433dc2062b8a65db8fafd3c110f46bc45663fbf021ee7eb9"),
233: ("41f08485ce587b06061c087e76e247c359de2ba9927ee013b2f1ed9ca8",
"0401e9d7189189f773bd8f71be2c10774ba18842434dfa9312595ea545104400f45a9d5675647513ba75b079fe66a29daac2ec86a6a5d4e75c5f290c1f"),
239: ("1a8069ce2c2c8bdd7087f2a6ab49588797e6294e979495602ab9650b9c61",
"04068d76b9f4508762c2379db9ee8b87ad8d86d9535132ffba3b5680440cfa28eb133d4232faf1c9aba96af11aefe634a551440800d5f8185105d3072d"),
283: ("006d627885dd48b9ec6facb5b3865377d755b75a5d51440e45211c1f600e15eff8a881a0",
"0405f48374debceaadb46ba385fd92048fcc5b9af1a1c90408bf94a68b9378df1cbfdfb6fb026a96bea06d8f181bf10c020adbcc88b6ecff96bdc564a9649c247cede601c4be63afc3"),
409: ("3ff5e74d932fa77db139b7c948c81e4069c72c24845574064beea8976b70267f1c6f9a503e3892ea1dcbb71fcea423faa370a8",
"04012c587f69f68b308ba6dcb238797f4e22290ca939ae806604e2b5ab4d9caef5a74a98fd87c4f88d292dd39d92e556e16c6ecc3c019a105826eef507cd9a04119f54d5d850b3720b3792d5d03410e9105610f7e4b420166ed45604a7a1f229d80975ba6be2060e8b"),
571: ("005008c97b4a161c0db1bac6452c72846d57337aa92d8ecb4a66eb01d2f29555ffb61a5317225dcc8ca6917d91789e227efc0bfe9eeda7ee21998cd11c3c9885056b0e55b4f75d51",
"04050172a7fd7adf98e4e2ed2742faa5cd12731a15fb0dbbdf75b1c3cc771a4369af6f2fa00e802735650881735759ea9c79961ded18e0daa0ac59afb1d513b5bbda9962e435f454fc020b4afe1445c2302ada07d295ec2580f8849b2dfa7f956b09b4cbe4c88d3b1c217049f75d3900d36df0fa12689256b58dd2ef784ebbeb0564600cf47a841485f8cf897a68accd5a"),
},
'ECC(PSA_ECC_FAMILY_SECT_R1)': {
163: ("009b05dc82d46d64a04a22e6e5ca70ca1231e68c50",
"0400465eeb9e7258b11e33c02266bfe834b20bcb118700772796ee4704ec67651bd447e3011959a79a04cb"),
233: ("00e5e42834e3c78758088b905deea975f28dc20ef6173e481f96e88afe7f",
"0400cd68c8af4430c92ec7a7048becfdf00a6bae8d1b4c37286f2d336f2a0e017eca3748f4ad6d435c85867aa014eea1bd6d9d005bbd8319cab629001d"),
283: ("004cecad915f6f3c9bbbd92d1eb101eda23f16c7dad60a57c87c7e1fd2b29b22f6d666ad",
"04052f9ff887254c2d1440ba9e30f13e2185ba53c373b2c410dae21cf8c167f796c08134f601cbc4c570bffbc2433082cf4d9eb5ba173ecb8caec15d66a02673f60807b2daa729b765"),
409: ("00c22422d265721a3ae2b3b2baeb77bee50416e19877af97b5fc1c700a0a88916ecb9050135883accb5e64edc77a3703f4f67a64",
"0401aa25466b1d291846db365957b25431591e50d9c109fe2106e93bb369775896925b15a7bfec397406ab4fe6f6b1a13bf8fdcb9300fa5500a813228676b0a6c572ed96b0f4aec7e87832e7e20f17ca98ecdfd36f59c82bddb8665f1f357a73900e827885ec9e1f22"),
571: ("026ac1cdf92a13a1b8d282da9725847908745138f5c6706b52d164e3675fcfbf86fc3e6ab2de732193267db029dd35a0599a94a118f480231cfc6ccca2ebfc1d8f54176e0f5656a1",
"040708f3403ee9948114855c17572152a08f8054d486defef5f29cbffcfb7cfd9280746a1ac5f751a6ad902ec1e0525120e9be56f03437af196fbe60ee7856e3542ab2cf87880632d80290e39b1a2bd03c6bbf6225511c567bd2ff41d2325dc58346f2b60b1feee4dc8b2af2296c2dc52b153e0556b5d24152b07f690c3fa24e4d1d19efbdeb1037833a733654d2366c74"),
},
'ECC(PSA_ECC_FAMILY_SECT_R2)': {
163: ("0210b482a458b4822d0cb21daa96819a67c8062d34",
"0403692601144c32a6cfa369ae20ae5d43c1c764678c037bafe80c6fd2e42b7ced96171d9c5367fd3dca6f"),
},
'ECC(PSA_ECC_FAMILY_BRAINPOOL_P_R1)': {
160: ("69502c4fdaf48d4fa617bdd24498b0406d0eeaac",
"04d4b9186816358e2f9c59cf70748cb70641b22fbab65473db4b4e22a361ed7e3de7e8a8ddc4130c5c"),
192: ("1688a2c5fbf4a3c851d76a98c3ec88f445a97996283db59f",
"043fdd168c179ff5363dd71dcd58de9617caad791ae0c37328be9ca0bfc79cebabf6a95d1c52df5b5f3c8b1a2441cf6c88"),
224: ("a69835dafeb5da5ab89c59860dddebcfd80b529a99f59b880882923c",
"045fbea378fc8583b3837e3f21a457c31eaf20a54e18eb11d104b3adc47f9d1c97eb9ea4ac21740d70d88514b98bf0bc31addac1d19c4ab3cc"),
256: ("2161d6f2db76526fa62c16f356a80f01f32f776784b36aa99799a8b7662080ff",
"04768c8cae4abca6306db0ed81b0c4a6215c378066ec6d616c146e13f1c7df809b96ab6911c27d8a02339f0926840e55236d3d1efbe2669d090e4c4c660fada91d"),
320: ("61b8daa7a6e5aa9fccf1ef504220b2e5a5b8c6dc7475d16d3172d7db0b2778414e4f6e8fa2032ead",
"049caed8fb4742956cc2ad12a9a1c995e21759ef26a07bc2054136d3d2f28bb331a70e26c4c687275ab1f434be7871e115d2350c0c5f61d4d06d2bcdb67f5cb63fdb794e5947c87dc6849a58694e37e6cd"),
384: ("3dd92e750d90d7d39fc1885cd8ad12ea9441f22b9334b4d965202adb1448ce24c5808a85dd9afc229af0a3124f755bcb",
"04719f9d093a627e0d350385c661cebf00c61923566fe9006a3107af1d871bc6bb68985fd722ea32be316f8e783b7cd1957785f66cfc0cb195dd5c99a8e7abaa848553a584dfd2b48e76d445fe00dd8be59096d877d4696d23b4bc8db14724e66a"),
512: ("372c9778f69f726cbca3f4a268f16b4d617d10280d79a6a029cd51879fe1012934dfe5395455337df6906dc7d6d2eea4dbb2065c0228f73b3ed716480e7d71d2",
"0438b7ec92b61c5c6c7fbc28a4ec759d48fcd4e2e374defd5c4968a54dbef7510e517886fbfc38ea39aa529359d70a7156c35d3cbac7ce776bdb251dd64bce71234424ee7049eed072f0dbc4d79996e175d557e263763ae97095c081e73e7db2e38adc3d4c9a0487b1ede876dc1fca61c902e9a1d8722b8612928f18a24845591a"),
},
'ECC(PSA_ECC_FAMILY_MONTGOMERY)': {
255: ("70076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c6a",
"8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"),
448: ("e4e49f52686f9ee3b638528f721f1596196ffd0a1cddb64c3f216f06541805cfeb1a286dc78018095cdfec050e8007b5f4908962ba20d6c1",
"c0d3a5a2b416a573dc9909f92f134ac01323ab8f8e36804e578588ba2d09fe7c3e737f771ca112825b548a0ffded6d6a2fd09a3e77dec30e"),
},
'ECC(PSA_ECC_FAMILY_TWISTED_EDWARDS)': {
255: ("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"),
448: ("6c82a562cb808d10d632be89c8513ebf6c929f34ddfa8c9f63c9960ef6e348a3528c8a3fcc2f044e39a3fc5b94492f8f032e7549a20098f95b",
"5fd7449b59b461fd2ce787ec616ad46a1da1342485a70e1f8a0ea75d80e96778edf124769b46c7061bd6783df1e50f6cd1fa1abeafe8256180"),
},
'RSA': {
1024: ("""
3082025e
020100
02818100af057d396ee84fb75fdbb5c2b13c7fe5a654aa8aa2470b541ee1feb0b12d25c79711531249e1129628042dbbb6c120d1443524ef4c0e6e1d8956eeb2077af12349ddeee54483bc06c2c61948cd02b202e796aebd94d3a7cbf859c2c1819c324cb82b9cd34ede263a2abffe4733f077869e8660f7d6834da53d690ef7985f6bc3
0203010001
02818100874bf0ffc2f2a71d14671ddd0171c954d7fdbf50281e4f6d99ea0e1ebcf82faa58e7b595ffb293d1abe17f110b37c48cc0f36c37e84d876621d327f64bbe08457d3ec4098ba2fa0a319fba411c2841ed7be83196a8cdf9daa5d00694bc335fc4c32217fe0488bce9cb7202e59468b1ead119000477db2ca797fac19eda3f58c1
024100e2ab760841bb9d30a81d222de1eb7381d82214407f1b975cbbfe4e1a9467fd98adbd78f607836ca5be1928b9d160d97fd45c12d6b52e2c9871a174c66b488113
024100c5ab27602159ae7d6f20c3c2ee851e46dc112e689e28d5fcbbf990a99ef8a90b8bb44fd36467e7fc1789ceb663abda338652c3c73f111774902e840565927091
024100b6cdbd354f7df579a63b48b3643e353b84898777b48b15f94e0bfc0567a6ae5911d57ad6409cf7647bf96264e9bd87eb95e263b7110b9a1f9f94acced0fafa4d
024071195eec37e8d257decfc672b07ae639f10cbb9b0c739d0c809968d644a94e3fd6ed9287077a14583f379058f76a8aecd43c62dc8c0f41766650d725275ac4a1
024100bb32d133edc2e048d463388b7be9cb4be29f4b6250be603e70e3647501c97ddde20a4e71be95fd5e71784e25aca4baf25be5738aae59bbfe1c997781447a2b24
""", """
308189
02818100af057d396ee84fb75fdbb5c2b13c7fe5a654aa8aa2470b541ee1feb0b12d25c79711531249e1129628042dbbb6c120d1443524ef4c0e6e1d8956eeb2077af12349ddeee54483bc06c2c61948cd02b202e796aebd94d3a7cbf859c2c1819c324cb82b9cd34ede263a2abffe4733f077869e8660f7d6834da53d690ef7985f6bc3
0203010001
"""),
1536: ("""
3082037b
020100
0281c100c870feb6ca6b1d2bd9f2dd99e20f1fe2d7e5192de662229dbe162bd1ba66336a7182903ca0b72796cd441c83d24bcdc3e9a2f5e4399c8a043f1c3ddf04754a66d4cfe7b3671a37dd31a9b4c13bfe06ee90f9d94ddaa06de67a52ac863e68f756736ceb014405a6160579640f831dddccc34ad0b05070e3f9954a58d1815813e1b83bcadba814789c87f1ef2ba5d738b793ec456a67360eea1b5faf1c7cc7bf24f3b2a9d0f8958b1096e0f0c335f8888d0c63a51c3c0337214fa3f5efdf6dcc35
0203010001
0281c06d2d670047973a87752a9d5bc14f3dae00acb01f593aa0e24cf4a49f932931de4bbfb332e2d38083da80bc0b6d538edba479f7f77d0deffb4a28e6e67ff6273585bb4cd862535c946605ab0809d65f0e38f76e4ec2c3d9b8cd6e14bcf667943892cd4b34cc6420a439abbf3d7d35ef73976dd6f9cbde35a51fa5213f0107f83e3425835d16d3c9146fc9e36ce75a09bb66cdff21dd5a776899f1cb07e282cca27be46510e9c799f0d8db275a6be085d9f3f803218ee3384265bfb1a3640e8ca1
026100e6848c31d466fffefc547e3a3b0d3785de6f78b0dd12610843512e495611a0675509b1650b27415009838dd8e68eec6e7530553b637d602424643b33e8bc5b762e1799bc79d56b13251d36d4f201da2182416ce13574e88278ff04467ad602d9
026100de994fdf181f02be2bf9e5f5e4e517a94993b827d1eaf609033e3a6a6f2396ae7c44e9eb594cf1044cb3ad32ea258f0c82963b27bb650ed200cde82cb993374be34be5b1c7ead5446a2b82a4486e8c1810a0b01551609fb0841d474bada802bd
026076ddae751b73a959d0bfb8ff49e7fcd378e9be30652ecefe35c82cb8003bc29cc60ae3809909baf20c95db9516fe680865417111d8b193dbcf30281f1249de57c858bf1ba32f5bb1599800e8398a9ef25c7a642c95261da6f9c17670e97265b1
0260732482b837d5f2a9443e23c1aa0106d83e82f6c3424673b5fdc3769c0f992d1c5c93991c7038e882fcda04414df4d7a5f4f698ead87851ce37344b60b72d7b70f9c60cae8566e7a257f8e1bef0e89df6e4c2f9d24d21d9f8889e4c7eccf91751
026009050d94493da8f00a4ddbe9c800afe3d44b43f78a48941a79b2814a1f0b81a18a8b2347642a03b27998f5a18de9abc9ae0e54ab8294feac66dc87e854cce6f7278ac2710cb5878b592ffeb1f4f0a1853e4e8d1d0561b6efcc831a296cf7eeaf
""", """
3081c9
0281c100c870feb6ca6b1d2bd9f2dd99e20f1fe2d7e5192de662229dbe162bd1ba66336a7182903ca0b72796cd441c83d24bcdc3e9a2f5e4399c8a043f1c3ddf04754a66d4cfe7b3671a37dd31a9b4c13bfe06ee90f9d94ddaa06de67a52ac863e68f756736ceb014405a6160579640f831dddccc34ad0b05070e3f9954a58d1815813e1b83bcadba814789c87f1ef2ba5d738b793ec456a67360eea1b5faf1c7cc7bf24f3b2a9d0f8958b1096e0f0c335f8888d0c63a51c3c0337214fa3f5efdf6dcc35
0203010001
"""),
},
})

View File

@ -1,406 +0,0 @@
"""Common features for bignum in test generation framework."""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
from abc import abstractmethod
import enum
from typing import Iterator, List, Tuple, TypeVar, Any
from copy import deepcopy
from itertools import chain
from math import ceil
from . import test_case
from . import test_data_generation
from .bignum_data import INPUTS_DEFAULT, MODULI_DEFAULT
T = TypeVar('T') #pylint: disable=invalid-name
def invmod(a: int, n: int) -> int:
"""Return inverse of a to modulo n.
Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
to long_invmod() in CPython.
"""
b, c = 1, 0
while n:
q, r = divmod(a, n)
a, b, c, n = n, c, b - q*c, r
# at this point a is the gcd of the original inputs
if a == 1:
return b
raise ValueError("Not invertible")
def invmod_positive(a: int, n: int) -> int:
"""Return a non-negative inverse of a to modulo n."""
inv = invmod(a, n)
return inv if inv >= 0 else inv + n
def hex_to_int(val: str) -> int:
"""Implement the syntax accepted by mbedtls_test_read_mpi().
This is a superset of what is accepted by mbedtls_test_read_mpi_core().
"""
if val in ['', '-']:
return 0
return int(val, 16)
def quote_str(val: str) -> str:
return "\"{}\"".format(val)
def bound_mpi(val: int, bits_in_limb: int) -> int:
"""First number exceeding number of limbs needed for given input value."""
return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
"""First number exceeding maximum of given number of limbs."""
bits = bits_in_limb * limbs
return 1 << bits
def limbs_mpi(val: int, bits_in_limb: int) -> int:
"""Return the number of limbs required to store value."""
bit_length = max(val.bit_length(), 1)
return (bit_length + bits_in_limb - 1) // bits_in_limb
def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
"""Return all pair combinations from input values."""
return [(x, y) for x in values for y in values]
def bits_to_limbs(bits: int, bits_in_limb: int) -> int:
""" Return the appropriate ammount of limbs needed to store
a number contained in input bits"""
return ceil(bits / bits_in_limb)
def hex_digits_for_limb(limbs: int, bits_in_limb: int) -> int:
""" Return the hex digits need for a number of limbs. """
return 2 * ((limbs * bits_in_limb) // 8)
def hex_digits_max_int(val: str, bits_in_limb: int) -> int:
""" Return the first number exceeding maximum the limb space
required to store the input hex-string value. This method
weights on the input str_len rather than numerical value
and works with zero-padded inputs"""
n = ((1 << (len(val) * 4)) - 1)
l = limbs_mpi(n, bits_in_limb)
return bound_mpi_limbs(l, bits_in_limb)
def zfill_match(reference: str, target: str) -> str:
""" Zero pad target hex-string to match the limb size of
the reference input """
lt = len(target)
lr = len(reference)
target_len = lr if lt < lr else lt
return "{:x}".format(int(target, 16)).zfill(target_len)
class OperationCommon(test_data_generation.BaseTest):
"""Common features for bignum binary operations.
This adds functionality common in binary operation tests.
Attributes:
symbol: Symbol to use for the operation in case description.
input_values: List of values to use as test case inputs. These are
combined to produce pairs of values.
input_cases: List of tuples containing pairs of test case inputs. This
can be used to implement specific pairs of inputs.
unique_combinations_only: Boolean to select if test case combinations
must be unique. If True, only A,B or B,A would be included as a test
case. If False, both A,B and B,A would be included.
input_style: Controls the way how test data is passed to the functions
in the generated test cases. "variable" passes them as they are
defined in the python source. "arch_split" pads the values with
zeroes depending on the architecture/limb size. If this is set,
test cases are generated for all architectures.
arity: the number of operands for the operation. Currently supported
values are 1 and 2.
"""
symbol = ""
input_values = INPUTS_DEFAULT # type: List[str]
input_cases = [] # type: List[Any]
dependencies = [] # type: List[Any]
unique_combinations_only = False
input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
input_style = "variable" # type: str
limb_sizes = [32, 64] # type: List[int]
arities = [1, 2]
arity = 2
suffix = False # for arity = 1, symbol can be prefix (default) or suffix
def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
self.val_a = val_a
self.val_b = val_b
# Setting the int versions here as opposed to making them @properties
# provides earlier/more robust input validation.
self.int_a = hex_to_int(val_a)
self.int_b = hex_to_int(val_b)
self.dependencies = deepcopy(self.dependencies)
if bits_in_limb not in self.limb_sizes:
raise ValueError("Invalid number of bits in limb!")
if self.input_style == "arch_split":
self.dependencies.append("MBEDTLS_HAVE_INT{:d}".format(bits_in_limb))
self.bits_in_limb = bits_in_limb
@property
def boundary(self) -> int:
if self.arity == 1:
return self.int_a
elif self.arity == 2:
return max(self.int_a, self.int_b)
raise ValueError("Unsupported number of operands!")
@property
def limb_boundary(self) -> int:
return bound_mpi(self.boundary, self.bits_in_limb)
@property
def limbs(self) -> int:
return limbs_mpi(self.boundary, self.bits_in_limb)
@property
def hex_digits(self) -> int:
return hex_digits_for_limb(self.limbs, self.bits_in_limb)
def format_arg(self, val: str) -> str:
if self.input_style not in self.input_styles:
raise ValueError("Unknown input style!")
if self.input_style == "variable":
return val
else:
return val.zfill(self.hex_digits)
def format_result(self, res: int) -> str:
res_str = '{:x}'.format(res)
return quote_str(self.format_arg(res_str))
@property
def arg_a(self) -> str:
return self.format_arg(self.val_a)
@property
def arg_b(self) -> str:
if self.arity == 1:
raise AttributeError("Operation is unary and doesn't have arg_b!")
return self.format_arg(self.val_b)
def arguments(self) -> List[str]:
args = [quote_str(self.arg_a)]
if self.arity == 2:
args.append(quote_str(self.arg_b))
return args + self.result()
def description(self) -> str:
"""Generate a description for the test case.
If not set, case_description uses the form A `symbol` B, where symbol
is used to represent the operation. Descriptions of each value are
generated to provide some context to the test case.
"""
if not self.case_description:
if self.arity == 1:
format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}"
self.case_description = format_string.format(
self.symbol, self.int_a
)
elif self.arity == 2:
self.case_description = "{:x} {} {:x}".format(
self.int_a, self.symbol, self.int_b
)
return super().description()
@property
def is_valid(self) -> bool:
return True
@abstractmethod
def result(self) -> List[str]:
"""Get the result of the operation.
This could be calculated during initialization and stored as `_result`
and then returned, or calculated when the method is called.
"""
raise NotImplementedError
@classmethod
def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
"""Generator to yield pairs of inputs.
Combinations are first generated from all input values, and then
specific cases provided.
"""
if cls.arity == 1:
yield from ((a, "0") for a in cls.input_values)
elif cls.arity == 2:
if cls.unique_combinations_only:
yield from combination_pairs(cls.input_values)
else:
yield from (
(a, b)
for a in cls.input_values
for b in cls.input_values
)
else:
raise ValueError("Unsupported number of operands!")
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
if cls.input_style not in cls.input_styles:
raise ValueError("Unknown input style!")
if cls.arity not in cls.arities:
raise ValueError("Unsupported number of operands!")
if cls.input_style == "arch_split":
test_objects = (cls(a, b, bits_in_limb=bil)
for a, b in cls.get_value_pairs()
for bil in cls.limb_sizes)
special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
for args in cls.input_cases
for bil in cls.limb_sizes)
else:
test_objects = (cls(a, b)
for a, b in cls.get_value_pairs())
special_cases = (cls(*args) for args in cls.input_cases)
yield from (valid_test_object.create_test_case()
for valid_test_object in filter(
lambda test_object: test_object.is_valid,
chain(test_objects, special_cases)
)
)
class ModulusRepresentation(enum.Enum):
"""Representation selector of a modulus."""
# Numerical values aligned with the type mbedtls_mpi_mod_rep_selector
INVALID = 0
MONTGOMERY = 2
OPT_RED = 3
def symbol(self) -> str:
"""The C symbol for this representation selector."""
return 'MBEDTLS_MPI_MOD_REP_' + self.name
@classmethod
def supported_representations(cls) -> List['ModulusRepresentation']:
"""Return all representations that are supported in positive test cases."""
return [cls.MONTGOMERY, cls.OPT_RED]
class ModOperationCommon(OperationCommon):
#pylint: disable=abstract-method
"""Target for bignum mod_raw test case generation."""
moduli = MODULI_DEFAULT # type: List[str]
montgomery_form_a = False
disallow_zero_a = False
def __init__(self, val_n: str, val_a: str, val_b: str = "0",
bits_in_limb: int = 64) -> None:
super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
self.val_n = val_n
# Setting the int versions here as opposed to making them @properties
# provides earlier/more robust input validation.
self.int_n = hex_to_int(val_n)
def to_montgomery(self, val: int) -> int:
return (val * self.r) % self.int_n
def from_montgomery(self, val: int) -> int:
return (val * self.r_inv) % self.int_n
def convert_from_canonical(self, canonical: int,
rep: ModulusRepresentation) -> int:
"""Convert values from canonical representation to the given representation."""
if rep is ModulusRepresentation.MONTGOMERY:
return self.to_montgomery(canonical)
elif rep is ModulusRepresentation.OPT_RED:
return canonical
else:
raise ValueError('Modulus representation not supported: {}'
.format(rep.name))
@property
def boundary(self) -> int:
return self.int_n
@property
def arg_a(self) -> str:
if self.montgomery_form_a:
value_a = self.to_montgomery(self.int_a)
else:
value_a = self.int_a
return self.format_arg('{:x}'.format(value_a))
@property
def arg_n(self) -> str:
return self.format_arg(self.val_n)
def format_arg(self, val: str) -> str:
return super().format_arg(val).zfill(self.hex_digits)
def arguments(self) -> List[str]:
return [quote_str(self.arg_n)] + super().arguments()
@property
def r(self) -> int: # pylint: disable=invalid-name
l = limbs_mpi(self.int_n, self.bits_in_limb)
return bound_mpi_limbs(l, self.bits_in_limb)
@property
def r_inv(self) -> int:
return invmod(self.r, self.int_n)
@property
def r2(self) -> int: # pylint: disable=invalid-name
return pow(self.r, 2)
@property
def is_valid(self) -> bool:
if self.int_a >= self.int_n:
return False
if self.disallow_zero_a and self.int_a == 0:
return False
if self.arity == 2 and self.int_b >= self.int_n:
return False
return True
def description(self) -> str:
"""Generate a description for the test case.
It uses the form A `symbol` B mod N, where symbol is used to represent
the operation.
"""
if not self.case_description:
return super().description() + " mod {:x}".format(self.int_n)
return super().description()
@classmethod
def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
if cls.arity == 1:
yield from ((n, a, "0") for a, n in cls.input_cases)
elif cls.arity == 2:
yield from ((n, a, b) for a, b, n in cls.input_cases)
else:
raise ValueError("Unsupported number of operands!")
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
if cls.input_style not in cls.input_styles:
raise ValueError("Unknown input style!")
if cls.arity not in cls.arities:
raise ValueError("Unsupported number of operands!")
if cls.input_style == "arch_split":
test_objects = (cls(n, a, b, bits_in_limb=bil)
for n in cls.moduli
for a, b in cls.get_value_pairs()
for bil in cls.limb_sizes)
special_cases = (cls(*args, bits_in_limb=bil)
for args in cls.input_cases_args()
for bil in cls.limb_sizes)
else:
test_objects = (cls(n, a, b)
for n in cls.moduli
for a, b in cls.get_value_pairs())
special_cases = (cls(*args) for args in cls.input_cases_args())
yield from (valid_test_object.create_test_case()
for valid_test_object in filter(
lambda test_object: test_object.is_valid,
chain(test_objects, special_cases)
))

View File

@ -1,896 +0,0 @@
"""Framework classes for generation of bignum core test cases."""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
import random
from typing import Dict, Iterator, List, Tuple
from . import test_case
from . import test_data_generation
from . import bignum_common
from .bignum_data import ADD_SUB_DATA
class BignumCoreTarget(test_data_generation.BaseTarget):
#pylint: disable=abstract-method, too-few-public-methods
"""Target for bignum core test case generation."""
target_basename = 'test_suite_bignum_core.generated'
class BignumCoreShiftR(BignumCoreTarget, test_data_generation.BaseTest):
"""Test cases for mbedtls_bignum_core_shift_r()."""
count = 0
test_function = "mpi_core_shift_r"
test_name = "Core shift right"
DATA = [
('00', '0', [0, 1, 8]),
('01', '1', [0, 1, 2, 8, 64]),
('dee5ca1a7ef10a75', '64-bit',
list(range(11)) + [31, 32, 33, 63, 64, 65, 71, 72]),
('002e7ab0070ad57001', '[leading 0 limb]',
[0, 1, 8, 63, 64]),
('a1055eb0bb1efa1150ff', '80-bit',
[0, 1, 8, 63, 64, 65, 72, 79, 80, 81, 88, 128, 129, 136]),
('020100000000000000001011121314151617', '138-bit',
[0, 1, 8, 9, 16, 72, 73, 136, 137, 138, 144]),
]
def __init__(self, input_hex: str, descr: str, count: int) -> None:
self.input_hex = input_hex
self.number_description = descr
self.shift_count = count
self.result = bignum_common.hex_to_int(input_hex) >> count
def arguments(self) -> List[str]:
return ['"{}"'.format(self.input_hex),
str(self.shift_count),
'"{:0{}x}"'.format(self.result, len(self.input_hex))]
def description(self) -> str:
return 'Core shift {} >> {}'.format(self.number_description,
self.shift_count)
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
for input_hex, descr, counts in cls.DATA:
for count in counts:
yield cls(input_hex, descr, count).create_test_case()
class BignumCoreShiftL(BignumCoreTarget, bignum_common.ModOperationCommon):
"""Test cases for mbedtls_bignum_core_shift_l()."""
BIT_SHIFT_VALUES = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'1f', '20', '21', '3f', '40', '41', '47', '48', '4f',
'50', '51', '58', '80', '81', '88']
DATA = ["0", "1", "40", "dee5ca1a7ef10a75", "a1055eb0bb1efa1150ff",
"002e7ab0070ad57001", "020100000000000000001011121314151617",
"1946e2958a85d8863ae21f4904fcc49478412534ed53eaf321f63f2a222"
"7a3c63acbf50b6305595f90cfa8327f6db80d986fe96080bcbb5df1bdbe"
"9b74fb8dedf2bddb3f8215b54dffd66409323bcc473e45a8fe9d08e77a51"
"1698b5dad0416305db7fcf"]
arity = 1
test_function = "mpi_core_shift_l"
test_name = "Core shift(L)"
input_style = "arch_split"
symbol = "<<"
input_values = BIT_SHIFT_VALUES
moduli = DATA
@property
def val_n_max_limbs(self) -> int:
""" Return the limb count required to store the maximum number that can
fit in a the number of digits used by val_n """
m = bignum_common.hex_digits_max_int(self.val_n, self.bits_in_limb) - 1
return bignum_common.limbs_mpi(m, self.bits_in_limb)
def arguments(self) -> List[str]:
return [bignum_common.quote_str(self.val_n),
str(self.int_a)
] + self.result()
def description(self) -> str:
""" Format the output as:
#{count} {hex input} ({input bits} {limbs capacity}) << {bit shift} """
bits = "({} bits in {} limbs)".format(self.int_n.bit_length(), self.val_n_max_limbs)
return "{} #{} {} {} {} {}".format(self.test_name,
self.count,
self.val_n,
bits,
self.symbol,
self.int_a)
def format_result(self, res: int) -> str:
# Override to match zero-pading for leading digits between the output and input.
res_str = bignum_common.zfill_match(self.val_n, "{:x}".format(res))
return bignum_common.quote_str(res_str)
def result(self) -> List[str]:
result = (self.int_n << self.int_a)
# Calculate if there is space for shifting to the left(leading zero limbs)
mx = bignum_common.hex_digits_max_int(self.val_n, self.bits_in_limb)
# If there are empty limbs ahead, adjust the bitmask accordingly
result = result & (mx - 1)
return [self.format_result(result)]
@property
def is_valid(self) -> bool:
return True
class BignumCoreCTLookup(BignumCoreTarget, test_data_generation.BaseTest):
"""Test cases for mbedtls_mpi_core_ct_uint_table_lookup()."""
test_function = "mpi_core_ct_uint_table_lookup"
test_name = "Constant time MPI table lookup"
bitsizes = [
(32, "One limb"),
(192, "Smallest curve sized"),
(512, "Largest curve sized"),
(2048, "Small FF/RSA sized"),
(4096, "Large FF/RSA sized"),
]
window_sizes = [0, 1, 2, 3, 4, 5, 6]
def __init__(self,
bitsize: int, descr: str, window_size: int) -> None:
self.bitsize = bitsize
self.bitsize_description = descr
self.window_size = window_size
def arguments(self) -> List[str]:
return [str(self.bitsize), str(self.window_size)]
def description(self) -> str:
return '{} - {} MPI with {} bit window'.format(
BignumCoreCTLookup.test_name,
self.bitsize_description,
self.window_size
)
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
for bitsize, bitsize_description in cls.bitsizes:
for window_size in cls.window_sizes:
yield (cls(bitsize, bitsize_description, window_size)
.create_test_case())
class BignumCoreAddAndAddIf(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for bignum core add and add-if."""
count = 0
symbol = "+"
test_function = "mpi_core_add_and_add_if"
test_name = "mpi_core_add_and_add_if"
input_style = "arch_split"
input_values = ADD_SUB_DATA
unique_combinations_only = True
def result(self) -> List[str]:
result = self.int_a + self.int_b
carry, result = divmod(result, self.limb_boundary)
return [
self.format_result(result),
str(carry)
]
class BignumCoreSub(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for bignum core sub."""
count = 0
input_style = "arch_split"
symbol = "-"
test_function = "mpi_core_sub"
test_name = "mbedtls_mpi_core_sub"
input_values = ADD_SUB_DATA
def result(self) -> List[str]:
if self.int_a >= self.int_b:
result = self.int_a - self.int_b
carry = 0
else:
result = self.limb_boundary + self.int_a - self.int_b
carry = 1
return [
self.format_result(result),
str(carry)
]
class BignumCoreMLA(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for fixed-size multiply accumulate."""
count = 0
test_function = "mpi_core_mla"
test_name = "mbedtls_mpi_core_mla"
input_values = [
"0", "1", "fffe", "ffffffff", "100000000", "20000000000000",
"ffffffffffffffff", "10000000000000000", "1234567890abcdef0",
"fffffffffffffffffefefefefefefefe",
"100000000000000000000000000000000",
"1234567890abcdef01234567890abcdef0",
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"1234567890abcdef01234567890abcdef01234567890abcdef01234567890abcdef0",
(
"4df72d07b4b71c8dacb6cffa954f8d88254b6277099308baf003fab73227f"
"34029643b5a263f66e0d3c3fa297ef71755efd53b8fb6cb812c6bbf7bcf17"
"9298bd9947c4c8b14324140a2c0f5fad7958a69050a987a6096e9f055fb38"
"edf0c5889eca4a0cfa99b45fbdeee4c696b328ddceae4723945901ec02507"
"6b12b"
)
] # type: List[str]
input_scalars = [
"0", "3", "fe", "ff", "ffff", "10000", "ffffffff", "100000000",
"7f7f7f7f7f7f7f7f", "8000000000000000", "fffffffffffffffe"
] # type: List[str]
def __init__(self, val_a: str, val_b: str, val_s: str) -> None:
super().__init__(val_a, val_b)
self.arg_scalar = val_s
self.int_scalar = bignum_common.hex_to_int(val_s)
if bignum_common.limbs_mpi(self.int_scalar, 32) > 1:
self.dependencies = ["MBEDTLS_HAVE_INT64"]
def arguments(self) -> List[str]:
return [
bignum_common.quote_str(self.arg_a),
bignum_common.quote_str(self.arg_b),
bignum_common.quote_str(self.arg_scalar)
] + self.result()
def description(self) -> str:
"""Override and add the additional scalar."""
if not self.case_description:
self.case_description = "0x{} + 0x{} * 0x{}".format(
self.arg_a, self.arg_b, self.arg_scalar
)
return super().description()
def result(self) -> List[str]:
result = self.int_a + (self.int_b * self.int_scalar)
bound_val = max(self.int_a, self.int_b)
bound_4 = bignum_common.bound_mpi(bound_val, 32)
bound_8 = bignum_common.bound_mpi(bound_val, 64)
carry_4, remainder_4 = divmod(result, bound_4)
carry_8, remainder_8 = divmod(result, bound_8)
return [
"\"{:x}\"".format(remainder_4),
"\"{:x}\"".format(carry_4),
"\"{:x}\"".format(remainder_8),
"\"{:x}\"".format(carry_8)
]
@classmethod
def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
"""Generator to yield pairs of inputs.
Combinations are first generated from all input values, and then
specific cases provided.
"""
yield from super().get_value_pairs()
yield from cls.input_cases
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
"""Override for additional scalar input."""
for a_value, b_value in cls.get_value_pairs():
for s_value in cls.input_scalars:
cur_op = cls(a_value, b_value, s_value)
yield cur_op.create_test_case()
class BignumCoreMul(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for bignum core multiplication."""
count = 0
input_style = "arch_split"
symbol = "*"
test_function = "mpi_core_mul"
test_name = "mbedtls_mpi_core_mul"
arity = 2
unique_combinations_only = True
def format_arg(self, val: str) -> str:
return val
def format_result(self, res: int) -> str:
res_str = '{:x}'.format(res)
a_limbs = bignum_common.limbs_mpi(self.int_a, self.bits_in_limb)
b_limbs = bignum_common.limbs_mpi(self.int_b, self.bits_in_limb)
hex_digits = bignum_common.hex_digits_for_limb(a_limbs + b_limbs, self.bits_in_limb)
return bignum_common.quote_str(self.format_arg(res_str).zfill(hex_digits))
def result(self) -> List[str]:
result = self.int_a * self.int_b
return [self.format_result(result)]
class BignumCoreMontmul(BignumCoreTarget, test_data_generation.BaseTest):
"""Test cases for Montgomery multiplication."""
count = 0
test_function = "mpi_core_montmul"
test_name = "mbedtls_mpi_core_montmul"
start_2_mpi4 = False
start_2_mpi8 = False
replay_test_cases = [
(2, 1, 1, 1, "19", "1", "1D"), (2, 1, 1, 1, "7", "1", "9"),
(2, 1, 1, 1, "4", "1", "9"),
(
12, 1, 6, 1, (
"3C246D0E059A93A266288A7718419EC741661B474C58C032C5EDAF92709402"
"B07CC8C7CE0B781C641A1EA8DB2F4343"
), "1", (
"66A198186C18C10B2F5ED9B522752A9830B69916E535C8F047518A889A43A5"
"94B6BED27A168D31D4A52F88925AA8F5"
)
), (
8, 1, 4, 1,
"1E442976B0E63D64FCCE74B999E470CA9888165CB75BFA1F340E918CE03C6211",
"1", "B3A119602EE213CDE28581ECD892E0F592A338655DCE4CA88054B3D124D0E561"
), (
22, 1, 11, 1, (
"7CF5AC97304E0B63C65413F57249F59994B0FED1D2A8D3D83ED5FA38560FFB"
"82392870D6D08F87D711917FD7537E13B7E125BE407E74157776839B0AC9DB"
"23CBDFC696104353E4D2780B2B4968F8D8542306BCA7A2366E"
), "1", (
"284139EA19C139EBE09A8111926AAA39A2C2BE12ED487A809D3CB5BC558547"
"25B4CDCB5734C58F90B2F60D99CC1950CDBC8D651793E93C9C6F0EAD752500"
"A32C56C62082912B66132B2A6AA42ADA923E1AD22CEB7BA0123"
)
)
] # type: List[Tuple[int, int, int, int, str, str, str]]
random_test_cases = [
("2", "2", "3", ""), ("1", "2", "3", ""), ("2", "1", "3", ""),
("6", "5", "7", ""), ("3", "4", "7", ""), ("1", "6", "7", ""), ("5", "6", "7", ""),
("3", "4", "B", ""), ("7", "4", "B", ""), ("9", "7", "B", ""), ("2", "a", "B", ""),
("25", "16", "29", "(0x29 is prime)"), ("8", "28", "29", ""),
("18", "21", "29", ""), ("15", "f", "29", ""),
("e2", "ea", "FF", ""), ("43", "72", "FF", ""),
("d8", "70", "FF", ""), ("3c", "7c", "FF", ""),
("99", "b9", "101", "(0x101 is prime)"), ("65", "b2", "101", ""),
("81", "32", "101", ""), ("51", "dd", "101", ""),
("d5", "143", "38B", "(0x38B is prime)"), ("3d", "387", "38B", ""),
("160", "2e5", "38B", ""), ("10f", "137", "38B", ""),
("7dac", "25a", "8003", "(0x8003 is prime)"), ("6f1c", "3286", "8003", ""),
("59ed", "2f3f", "8003", ""), ("6893", "736d", "8003", ""),
("d199", "2832", "10001", "(0x10001 is prime)"), ("c3b2", "3e5b", "10001", ""),
("abe4", "214e", "10001", ""), ("4360", "a05d", "10001", ""),
("3f5a1", "165b2", "7F7F7", ""), ("3bd29", "37863", "7F7F7", ""),
("60c47", "64819", "7F7F7", ""), ("16584", "12c49", "7F7F7", ""),
("1ff03f", "610347", "800009", "(0x800009 is prime)"), ("340fd5", "19812e", "800009", ""),
("3fe2e8", "4d0dc7", "800009", ""), ("40356", "e6392", "800009", ""),
("dd8a1d", "266c0e", "100002B", "(0x100002B is prime)"),
("3fa1cb", "847fd6", "100002B", ""), ("5f439d", "5c3196", "100002B", ""),
("18d645", "f72dc6", "100002B", ""),
("20051ad", "37def6e", "37EEE9D", "(0x37EEE9D is prime)"),
("2ec140b", "3580dbf", "37EEE9D", ""), ("1d91b46", "190d4fc", "37EEE9D", ""),
("34e488d", "1224d24", "37EEE9D", ""),
("2a4fe2cb", "263466a9", "8000000B", "(0x8000000B is prime)"),
("5643fe94", "29a1aefa", "8000000B", ""), ("29633513", "7b007ac4", "8000000B", ""),
("2439cef5", "5c9d5a47", "8000000B", ""),
("4de3cfaa", "50dea178", "8CD626B9", "(0x8CD626B9 is prime)"),
("b8b8563", "10dbbbac", "8CD626B9", ""), ("4e8a6151", "5574ec19", "8CD626B9", ""),
("69224878", "309cfc23", "8CD626B9", ""),
("fb6f7fb6", "afb05423", "10000000F", "(0x10000000F is prime)"),
("8391a243", "26034dcd", "10000000F", ""), ("d26b98c", "14b2d6aa", "10000000F", ""),
("6b9f1371", "a21daf1d", "10000000F", ""),
(
"9f49435ad", "c8264ade8", "174876E7E9",
"0x174876E7E9 is prime (dec) 99999999977"
),
("c402da434", "1fb427acf", "174876E7E9", ""),
("f6ebc2bb1", "1096d39f2a", "174876E7E9", ""),
("153b7f7b6b", "878fda8ff", "174876E7E9", ""),
("2c1adbb8d6", "4384d2d3c6", "8000000017", "(0x8000000017 is prime)"),
("2e4f9cf5fb", "794f3443d9", "8000000017", ""),
("149e495582", "3802b8f7b7", "8000000017", ""),
("7b9d49df82", "69c68a442a", "8000000017", ""),
("683a134600", "6dd80ea9f6", "864CB9076D", "(0x864CB9076D is prime)"),
("13a870ff0d", "59b099694a", "864CB9076D", ""),
("37d06b0e63", "4d2147e46f", "864CB9076D", ""),
("661714f8f4", "22e55df507", "864CB9076D", ""),
("2f0a96363", "52693307b4", "F7F7F7F7F7", ""),
("3c85078e64", "f2275ecb6d", "F7F7F7F7F7", ""),
("352dae68d1", "707775b4c6", "F7F7F7F7F7", ""),
("37ae0f3e0b", "912113040f", "F7F7F7F7F7", ""),
("6dada15e31", "f58ed9eff7", "1000000000F", "(0x1000000000F is prime)"),
("69627a7c89", "cfb5ebd13d", "1000000000F", ""),
("a5e1ad239b", "afc030c731", "1000000000F", ""),
("f1cc45f4c5", "c64ad607c8", "1000000000F", ""),
("2ebad87d2e31", "4c72d90bca78", "800000000005", "(0x800000000005 is prime)"),
("a30b3cc50d", "29ac4fe59490", "800000000005", ""),
("33674e9647b4", "5ec7ee7e72d3", "800000000005", ""),
("3d956f474f61", "74070040257d", "800000000005", ""),
("48348e3717d6", "43fcb4399571", "800795D9BA47", "(0x800795D9BA47 is prime)"),
("5234c03cc99b", "2f3cccb87803", "800795D9BA47", ""),
("3ed13db194ab", "44b8f4ba7030", "800795D9BA47", ""),
("1c11e843bfdb", "95bd1b47b08", "800795D9BA47", ""),
("a81d11cb81fd", "1e5753a3f33d", "1000000000015", "(0x1000000000015 is prime)"),
("688c4db99232", "36fc0cf7ed", "1000000000015", ""),
("f0720cc07e07", "fc76140ed903", "1000000000015", ""),
("2ec61f8d17d1", "d270c85e36d2", "1000000000015", ""),
(
"6a24cd3ab63820", "ed4aad55e5e348", "100000000000051",
"(0x100000000000051 is prime)"
),
("e680c160d3b248", "31e0d8840ed510", "100000000000051", ""),
("a80637e9aebc38", "bb81decc4e1738", "100000000000051", ""),
("9afa5a59e9d630", "be9e65a6d42938", "100000000000051", ""),
("ab5e104eeb71c000", "2cffbd639e9fea00", "ABCDEF0123456789", ""),
("197b867547f68a00", "44b796cf94654800", "ABCDEF0123456789", ""),
("329f9483a04f2c00", "9892f76961d0f000", "ABCDEF0123456789", ""),
("4a2e12dfb4545000", "1aa3e89a69794500", "ABCDEF0123456789", ""),
(
"8b9acdf013d140f000", "12e4ceaefabdf2b2f00", "25A55A46E5DA99C71C7",
"0x25A55A46E5DA99C71C7 is the 3rd repunit prime(dec) 11111111111111111111111"
),
("1b8d960ea277e3f5500", "14418aa980e37dd000", "25A55A46E5DA99C71C7", ""),
("7314524977e8075980", "8172fa45618ccd0d80", "25A55A46E5DA99C71C7", ""),
("ca14f031769be63580", "147a2f3cf2964ca9400", "25A55A46E5DA99C71C7", ""),
(
"18532ba119d5cd0cf39735c0000", "25f9838e31634844924733000000",
"314DC643FB763F2B8C0E2DE00879",
"0x314DC643FB763F2B8C0E2DE00879 is (dec)99999999977^3"
),
(
"a56e2d2517519e3970e70c40000", "ec27428d4bb380458588fa80000",
"314DC643FB763F2B8C0E2DE00879", ""
),
(
"1cb5e8257710e8653fff33a00000", "15fdd42fe440fd3a1d121380000",
"314DC643FB763F2B8C0E2DE00879", ""
),
(
"e50d07a65fc6f93e538ce040000", "1f4b059ca609f3ce597f61240000",
"314DC643FB763F2B8C0E2DE00879", ""
),
(
"1ea3ade786a095d978d387f30df9f20000000",
"127c448575f04af5a367a7be06c7da0000000",
"47BF19662275FA2F6845C74942ED1D852E521",
"0x47BF19662275FA2F6845C74942ED1D852E521 is (dec) 99999999977^4"
),
(
"16e15b0ca82764e72e38357b1f10a20000000",
"43e2355d8514bbe22b0838fdc3983a0000000",
"47BF19662275FA2F6845C74942ED1D852E521", ""
),
(
"be39332529d93f25c3d116c004c620000000",
"5cccec42370a0a2c89c6772da801a0000000",
"47BF19662275FA2F6845C74942ED1D852E521", ""
),
(
"ecaa468d90de0eeda474d39b3e1fc0000000",
"1e714554018de6dc0fe576bfd3b5660000000",
"47BF19662275FA2F6845C74942ED1D852E521", ""
),
(
"32298816711c5dce46f9ba06e775c4bedfc770e6700000000000000",
"8ee751fd5fb24f0b4a653cb3a0c8b7d9e724574d168000000000000",
"97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931",
(
"0x97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931"
" is (dec) 99999999977^6"
)
),
(
"29213b9df3cfd15f4b428645b67b677c29d1378d810000000000000",
"6cbb732c65e10a28872394dfdd1936d5171c3c3aac0000000000000",
"97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931", ""
),
(
"6f18db06ad4abc52c0c50643dd13098abccd4a232f0000000000000",
"7e6bf41f2a86098ad51f98dfc10490ba3e8081bc830000000000000",
"97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931", ""
),
(
"62d3286cd706ad9d73caff63f1722775d7e8c731208000000000000",
"530f7ba02ae2b04c2fe3e3d27ec095925631a6c2528000000000000",
"97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931", ""
),
(
"a6c6503e3c031fdbf6009a89ed60582b7233c5a85de28b16000000000000000",
"75c8ed18270b583f16d442a467d32bf95c5e491e9b8523798000000000000000",
"DD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499",
(
"0xDD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499"
" is (dec) 99999999977^7"
)
),
(
"bf84d1f85cf6b51e04d2c8f4ffd03532d852053cf99b387d4000000000000000",
"397ba5a743c349f4f28bc583ecd5f06e0a25f9c6d98f09134000000000000000",
"DD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499", ""
),
(
"6db11c3a4152ed1a2aa6fa34b0903ec82ea1b88908dcb482000000000000000",
"ac8ac576a74ad6ca48f201bf89f77350ce86e821358d85920000000000000000",
"DD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499", ""
),
(
"3001d96d7fe8b733f33687646fc3017e3ac417eb32e0ec708000000000000000",
"925ddbdac4174e8321a48a32f79640e8cf7ec6f46ea235a80000000000000000",
"DD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499", ""
),
(
"1029048755f2e60dd98c8de6d9989226b6bb4f0db8e46bd1939de560000000000000000000",
"51bb7270b2e25cec0301a03e8275213bb6c2f6e6ec93d4d46d36ca0000000000000000000",
"141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146380E41",
(
"0x141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146"
"380E41 is 99999999977^8"
)
),
(
"1c5337ff982b3ad6611257dbff5bbd7a9920ba2d4f5838a0cc681ce000000000000000000",
"520c5d049ca4702031ba728591b665c4d4ccd3b2b86864d4c160fd2000000000000000000",
"141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146380E41",
""
),
(
"57074dfa00e42f6555bae624b7f0209f218adf57f73ed34ab0ff90c000000000000000000",
"41eb14b6c07bfd3d1fe4f4a610c17cc44fcfcda695db040e011065000000000000000000",
"141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146380E41",
""
),
(
"d8ed7feed2fe855e6997ad6397f776158573d425031bf085a615784000000000000000000",
"6f121dcd18c578ab5e229881006007bb6d319b179f11015fe958b9c000000000000000000",
"141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146380E41",
""
),
(
(
"2a462b156180ea5fe550d3758c764e06fae54e626b5f503265a09df76edbdfbf"
"a1e6000000000000000000000000"
), (
"1136f41d1879fd4fb9e49e0943a46b6704d77c068ee237c3121f9071cfd3e6a0"
"0315800000000000000000000000"
), (
"2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E2833EC90"
"2713E40F51E3B3C214EDFABC451"
), (
"0x2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E2833EC"
"902713E40F51E3B3C214EDFABC451 is (dec) 99999999977^10"
)
),
(
(
"c1ac3800dfb3c6954dea391d206200cf3c47f795bf4a5603b4cb88ae7e574de47"
"40800000000000000000000000"
), (
"c0d16eda0549ede42fa0deb4635f7b7ce061fadea02ee4d85cba4c4f709603419"
"3c800000000000000000000000"
), (
"2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E2833EC90"
"2713E40F51E3B3C214EDFABC451"
), ""
),
(
(
"19e45bb7633094d272588ad2e43bcb3ee341991c6731b6fa9d47c4018d7ce7bba"
"5ee800000000000000000000000"
), (
"1e4f83166ae59f6b9cc8fd3e7677ed8bfc01bb99c98bd3eb084246b64c1e18c33"
"65b800000000000000000000000"
), (
"2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E2833EC90"
"2713E40F51E3B3C214EDFABC451"
), ""
),
(
(
"1aa93395fad5f9b7f20b8f9028a054c0bb7c11bb8520e6a95e5a34f06cb70bcdd"
"01a800000000000000000000000"
), (
"54b45afa5d4310192f8d224634242dd7dcfb342318df3d9bd37b4c614788ba13b"
"8b000000000000000000000000"
), (
"2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E2833EC90"
"2713E40F51E3B3C214EDFABC451"
), ""
),
(
(
"544f2628a28cfb5ce0a1b7180ee66b49716f1d9476c466c57f0c4b23089917843"
"06d48f78686115ee19e25400000000000000000000000000000000"
), (
"677eb31ef8d66c120fa872a60cd47f6e10cbfdf94f90501bd7883cba03d185be0"
"a0148d1625745e9c4c827300000000000000000000000000000000"
), (
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA1"
"1DABD6E6144BEF37C6800000000000000000000000000000000051"
), (
"0x8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBF"
"A11DABD6E6144BEF37C6800000000000000000000000000000000051 is prime,"
" (dec) 10^143 + 3^4"
)
),
(
(
"76bb3470985174915e9993522aec989666908f9e8cf5cb9f037bf4aee33d8865c"
"b6464174795d07e30015b80000000000000000000000000000000"
), (
"6aaaf60d5784dcef612d133613b179a317532ecca0eed40b8ad0c01e6d4a6d8c7"
"9a52af190abd51739009a900000000000000000000000000000000"
), (
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA1"
"1DABD6E6144BEF37C6800000000000000000000000000000000051"
), ""
),
(
(
"6cfdd6e60912e441d2d1fc88f421b533f0103a5322ccd3f4db84861643ad63fd6"
"3d1d8cfbc1d498162786ba00000000000000000000000000000000"
), (
"1177246ec5e93814816465e7f8f248b350d954439d35b2b5d75d917218e7fd5fb"
"4c2f6d0667f9467fdcf33400000000000000000000000000000000"
), (
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA1"
"1DABD6E6144BEF37C6800000000000000000000000000000000051"
), ""
),
(
(
"7a09a0b0f8bbf8057116fb0277a9bdf3a91b5eaa8830d448081510d8973888be5"
"a9f0ad04facb69aa3715f00000000000000000000000000000000"
), (
"764dec6c05a1c0d87b649efa5fd94c91ea28bffb4725d4ab4b33f1a3e8e3b314d"
"799020e244a835a145ec9800000000000000000000000000000000"
), (
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA1"
"1DABD6E6144BEF37C6800000000000000000000000000000000051"
), ""
)
] # type: List[Tuple[str, str, str, str]]
def __init__(
self, val_a: str, val_b: str, val_n: str, case_description: str = ""
):
self.case_description = case_description
self.arg_a = val_a
self.int_a = bignum_common.hex_to_int(val_a)
self.arg_b = val_b
self.int_b = bignum_common.hex_to_int(val_b)
self.arg_n = val_n
self.int_n = bignum_common.hex_to_int(val_n)
limbs_a4 = bignum_common.limbs_mpi(self.int_a, 32)
limbs_a8 = bignum_common.limbs_mpi(self.int_a, 64)
self.limbs_b4 = bignum_common.limbs_mpi(self.int_b, 32)
self.limbs_b8 = bignum_common.limbs_mpi(self.int_b, 64)
self.limbs_an4 = bignum_common.limbs_mpi(self.int_n, 32)
self.limbs_an8 = bignum_common.limbs_mpi(self.int_n, 64)
if limbs_a4 > self.limbs_an4 or limbs_a8 > self.limbs_an8:
raise Exception("Limbs of input A ({}) exceeds N ({})".format(
self.arg_a, self.arg_n
))
def arguments(self) -> List[str]:
return [
str(self.limbs_an4), str(self.limbs_b4),
str(self.limbs_an8), str(self.limbs_b8),
bignum_common.quote_str(self.arg_a),
bignum_common.quote_str(self.arg_b),
bignum_common.quote_str(self.arg_n)
] + self.result()
def description(self) -> str:
if self.case_description != "replay":
if not self.start_2_mpi4 and self.limbs_an4 > 1:
tmp = "(start of 2-MPI 4-byte bignums) "
self.__class__.start_2_mpi4 = True
elif not self.start_2_mpi8 and self.limbs_an8 > 1:
tmp = "(start of 2-MPI 8-byte bignums) "
self.__class__.start_2_mpi8 = True
else:
tmp = "(gen) "
self.case_description = tmp + self.case_description
return super().description()
def result(self) -> List[str]:
"""Get the result of the operation."""
r4 = bignum_common.bound_mpi_limbs(self.limbs_an4, 32)
i4 = bignum_common.invmod(r4, self.int_n)
x4 = self.int_a * self.int_b * i4
x4 = x4 % self.int_n
r8 = bignum_common.bound_mpi_limbs(self.limbs_an8, 64)
i8 = bignum_common.invmod(r8, self.int_n)
x8 = self.int_a * self.int_b * i8
x8 = x8 % self.int_n
return [
"\"{:x}\"".format(x4),
"\"{:x}\"".format(x8)
]
def set_limbs(
self, limbs_an4: int, limbs_b4: int, limbs_an8: int, limbs_b8: int
) -> None:
"""Set number of limbs for each input.
Replaces default values set during initialization.
"""
self.limbs_an4 = limbs_an4
self.limbs_b4 = limbs_b4
self.limbs_an8 = limbs_an8
self.limbs_b8 = limbs_b8
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
"""Generate replay and randomly generated test cases."""
# Test cases which replay captured invocations during unit test runs.
for limbs_an4, limbs_b4, limbs_an8, limbs_b8, a, b, n in cls.replay_test_cases:
cur_op = cls(a, b, n, case_description="replay")
cur_op.set_limbs(limbs_an4, limbs_b4, limbs_an8, limbs_b8)
yield cur_op.create_test_case()
# Random test cases can be generated using mpi_modmul_case_generate()
# Uses a mixture of primes and odd numbers as N, with four randomly
# generated cases for each N.
for a, b, n, description in cls.random_test_cases:
cur_op = cls(a, b, n, case_description=description)
yield cur_op.create_test_case()
def mpi_modmul_case_generate() -> None:
"""Generate valid inputs for montmul tests using moduli.
For each modulus, generates random values for A and B and simple descriptions
for the test case.
"""
moduli = [
("3", ""), ("7", ""), ("B", ""), ("29", ""), ("FF", ""),
("101", ""), ("38B", ""), ("8003", ""), ("10001", ""),
("7F7F7", ""), ("800009", ""), ("100002B", ""), ("37EEE9D", ""),
("8000000B", ""), ("8CD626B9", ""), ("10000000F", ""),
("174876E7E9", "is prime (dec) 99999999977"),
("8000000017", ""), ("864CB9076D", ""), ("F7F7F7F7F7", ""),
("1000000000F", ""), ("800000000005", ""), ("800795D9BA47", ""),
("1000000000015", ""), ("100000000000051", ""), ("ABCDEF0123456789", ""),
(
"25A55A46E5DA99C71C7",
"is the 3rd repunit prime (dec) 11111111111111111111111"
),
("314DC643FB763F2B8C0E2DE00879", "is (dec)99999999977^3"),
("47BF19662275FA2F6845C74942ED1D852E521", "is (dec) 99999999977^4"),
(
"97EDD86E4B5C4592C6D32064AC55C888A7245F07CA3CC455E07C931",
"is (dec) 99999999977^6"
),
(
"DD15FE80B731872AC104DB37832F7E75A244AA2631BC87885B861E8F20375499",
"is (dec) 99999999977^7"
),
(
"141B8EBD9009F84C241879A1F680FACCED355DA36C498F73E96E880CF78EA5F96146380E41",
"is (dec) 99999999977^8"
),
(
(
"2A94608DE88B6D5E9F8920F5ABB06B24CC35AE1FBACC87D075C621C3E283"
"3EC902713E40F51E3B3C214EDFABC451"
),
"is (dec) 99999999977^10"
),
(
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA11"
"DABD6E6144BEF37C6800000000000000000000000000000000051",
"is prime, (dec) 10^143 + 3^4"
)
] # type: List[Tuple[str, str]]
primes = [
"3", "7", "B", "29", "101", "38B", "8003", "10001", "800009",
"100002B", "37EEE9D", "8000000B", "8CD626B9",
# From here they require > 1 4-byte MPI
"10000000F", "174876E7E9", "8000000017", "864CB9076D", "1000000000F",
"800000000005", "800795D9BA47", "1000000000015", "100000000000051",
# From here they require > 1 8-byte MPI
"25A55A46E5DA99C71C7", # this is 11111111111111111111111 decimal
# 10^143 + 3^4: (which is prime)
# 100000000000000000000000000000000000000000000000000000000000000000000000000000
# 000000000000000000000000000000000000000000000000000000000000000081
(
"8335616AED761F1F7F44E6BD49E807B82E3BF2BF11BFA6AF813C808DBF33DBFA11"
"DABD6E6144BEF37C6800000000000000000000000000000000051"
)
] # type: List[str]
generated_inputs = []
for mod, description in moduli:
n = bignum_common.hex_to_int(mod)
mod_read = "{:x}".format(n)
case_count = 3 if n < 5 else 4
cases = {} # type: Dict[int, int]
i = 0
while i < case_count:
a = random.randint(1, n)
b = random.randint(1, n)
if cases.get(a) == b:
continue
cases[a] = b
if description:
out_description = "0x{} {}".format(mod_read, description)
elif i == 0 and len(mod) > 1 and mod in primes:
out_description = "(0x{} is prime)"
else:
out_description = ""
generated_inputs.append(
("{:x}".format(a), "{:x}".format(b), mod, out_description)
)
i += 1
print(generated_inputs)
class BignumCoreExpMod(BignumCoreTarget, bignum_common.ModOperationCommon):
"""Test cases for bignum core exponentiation."""
symbol = "^"
test_function = "mpi_core_exp_mod"
test_name = "Core modular exponentiation (Mongtomery form only)"
input_style = "fixed"
montgomery_form_a = True
def result(self) -> List[str]:
# Result has to be given in Montgomery form too
result = pow(self.int_a, self.int_b, self.int_n)
mont_result = self.to_montgomery(result)
return [self.format_result(mont_result)]
@property
def is_valid(self) -> bool:
# The base needs to be canonical, but the exponent can be larger than
# the modulus (see for example exponent blinding)
return bool(self.int_a < self.int_n)
class BignumCoreSubInt(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for bignum core sub int."""
count = 0
symbol = "-"
test_function = "mpi_core_sub_int"
test_name = "mpi_core_sub_int"
input_style = "arch_split"
@property
def is_valid(self) -> bool:
# This is "sub int", so b is only one limb
if bignum_common.limbs_mpi(self.int_b, self.bits_in_limb) > 1:
return False
return True
# Overriding because we don't want leading zeros on b
@property
def arg_b(self) -> str:
return self.val_b
def result(self) -> List[str]:
result = self.int_a - self.int_b
borrow, result = divmod(result, self.limb_boundary)
# Borrow will be -1 if non-zero, but we want it to be 1 in the test data
return [
self.format_result(result),
str(-borrow)
]
class BignumCoreZeroCheckCT(BignumCoreTarget, bignum_common.OperationCommon):
"""Test cases for bignum core zero check (constant flow)."""
count = 0
symbol = "== 0"
test_function = "mpi_core_check_zero_ct"
test_name = "mpi_core_check_zero_ct"
input_style = "variable"
arity = 1
suffix = True
def result(self) -> List[str]:
result = 1 if self.int_a == 0 else 0
return [str(result)]

View File

@ -1,159 +0,0 @@
"""Base values and datasets for bignum generated tests and helper functions that
produced them."""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
import random
# Functions calling these were used to produce test data and are here only for
# reproducibility, they are not used by the test generation framework/classes
try:
from Cryptodome.Util.number import isPrime, getPrime #type: ignore #pylint: disable=import-error
except ImportError:
pass
# Generated by bignum_common.gen_safe_prime(192,1)
SAFE_PRIME_192_BIT_SEED_1 = "d1c127a667786703830500038ebaef20e5a3e2dc378fb75b"
# First number generated by random.getrandbits(192) - seed(2,2), not a prime
RANDOM_192_BIT_SEED_2_NO1 = "177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"
# Second number generated by random.getrandbits(192) - seed(2,2), not a prime
RANDOM_192_BIT_SEED_2_NO2 = "cf1822ffbc6887782b491044d5e341245c6e433715ba2bdd"
# Third number generated by random.getrandbits(192) - seed(2,2), not a prime
RANDOM_192_BIT_SEED_2_NO3 = "3653f8dd9b1f282e4067c3584ee207f8da94e3e8ab73738f"
# Fourth number generated by random.getrandbits(192) - seed(2,2), not a prime
RANDOM_192_BIT_SEED_2_NO4 = "ffed9235288bc781ae66267594c9c9500925e4749b575bd1"
# Ninth number generated by random.getrandbits(192) - seed(2,2), not a prime
RANDOM_192_BIT_SEED_2_NO9 = "2a1be9cd8697bbd0e2520e33e44c50556c71c4a66148a86f"
# Generated by bignum_common.gen_safe_prime(1024,3)
SAFE_PRIME_1024_BIT_SEED_3 = ("c93ba7ec74d96f411ba008bdb78e63ff11bb5df46a51e16b"
"2c9d156f8e4e18abf5e052cb01f47d0d1925a77f60991577"
"e128fb6f52f34a27950a594baadd3d8057abeb222cf3cca9"
"62db16abf79f2ada5bd29ab2f51244bf295eff9f6aaba130"
"2efc449b128be75eeaca04bc3c1a155d11d14e8be32a2c82"
"87b3996cf6ad5223")
# First number generated by random.getrandbits(1024) - seed(4,2), not a prime
RANDOM_1024_BIT_SEED_4_NO1 = ("6905269ed6f0b09f165c8ce36e2f24b43000de01b2ed40ed"
"3addccb2c33be0ac79d679346d4ac7a5c3902b38963dc6e8"
"534f45738d048ec0f1099c6c3e1b258fd724452ccea71ff4"
"a14876aeaff1a098ca5996666ceab360512bd13110722311"
"710cf5327ac435a7a97c643656412a9b8a1abcd1a6916c74"
"da4f9fc3c6da5d7")
# Second number generated by random.getrandbits(1024) - seed(4,2), not a prime
RANDOM_1024_BIT_SEED_4_NO2 = ("f1cfd99216df648647adec26793d0e453f5082492d83a823"
"3fb62d2c81862fc9634f806fabf4a07c566002249b191bf4"
"d8441b5616332aca5f552773e14b0190d93936e1daca3c06"
"f5ff0c03bb5d7385de08caa1a08179104a25e4664f5253a0"
"2a3187853184ff27459142deccea264542a00403ce80c4b0"
"a4042bb3d4341aad")
# Third number generated by random.getrandbits(1024) - seed(4,2), not a prime
RANDOM_1024_BIT_SEED_4_NO3 = ("14c15c910b11ad28cc21ce88d0060cc54278c2614e1bcb38"
"3bb4a570294c4ea3738d243a6e58d5ca49c7b59b995253fd"
"6c79a3de69f85e3131f3b9238224b122c3e4a892d9196ada"
"4fcfa583e1df8af9b474c7e89286a1754abcb06ae8abb93f"
"01d89a024cdce7a6d7288ff68c320f89f1347e0cdd905ecf"
"d160c5d0ef412ed6")
# Fourth number generated by random.getrandbits(1024) - seed(4,2), not a prime
RANDOM_1024_BIT_SEED_4_NO4 = ("32decd6b8efbc170a26a25c852175b7a96b98b5fbf37a2be"
"6f98bca35b17b9662f0733c846bbe9e870ef55b1a1f65507"
"a2909cb633e238b4e9dd38b869ace91311021c9e32111ac1"
"ac7cc4a4ff4dab102522d53857c49391b36cc9aa78a330a1"
"a5e333cb88dcf94384d4cd1f47ca7883ff5a52f1a05885ac"
"7671863c0bdbc23a")
# Fifth number generated by random.getrandbits(1024) - seed(4,2), not a prime
RANDOM_1024_BIT_SEED_4_NO5 = ("53be4721f5b9e1f5acdac615bc20f6264922b9ccf469aef8"
"f6e7d078e55b85dd1525f363b281b8885b69dc230af5ac87"
"0692b534758240df4a7a03052d733dcdef40af2e54c0ce68"
"1f44ebd13cc75f3edcb285f89d8cf4d4950b16ffc3e1ac3b"
"4708d9893a973000b54a23020fc5b043d6e4a51519d9c9cc"
"52d32377e78131c1")
# Adding 192 bit and 1024 bit numbers because these are the shortest required
# for ECC and RSA respectively.
INPUTS_DEFAULT = [
"0", "1", # corner cases
"2", "3", # small primes
"4", # non-prime even
"38", # small random
SAFE_PRIME_192_BIT_SEED_1, # prime
RANDOM_192_BIT_SEED_2_NO1, # not a prime
RANDOM_192_BIT_SEED_2_NO2, # not a prime
SAFE_PRIME_1024_BIT_SEED_3, # prime
RANDOM_1024_BIT_SEED_4_NO1, # not a prime
RANDOM_1024_BIT_SEED_4_NO3, # not a prime
RANDOM_1024_BIT_SEED_4_NO2, # largest (not a prime)
]
ADD_SUB_DATA = [
"0", "1", "3", "f", "fe", "ff", "100", "ff00",
"fffe", "ffff", "10000", # 2^16 - 1, 2^16, 2^16 + 1
"fffffffe", "ffffffff", "100000000", # 2^32 - 1, 2^32, 2^32 + 1
"1f7f7f7f7f7f7f",
"8000000000000000", "fefefefefefefefe",
"fffffffffffffffe", "ffffffffffffffff", "10000000000000000", # 2^64 - 1, 2^64, 2^64 + 1
"1234567890abcdef0",
"fffffffffffffffffffffffe",
"ffffffffffffffffffffffff",
"1000000000000000000000000",
"fffffffffffffffffefefefefefefefe",
"fffffffffffffffffffffffffffffffe",
"ffffffffffffffffffffffffffffffff",
"100000000000000000000000000000000",
"1234567890abcdef01234567890abcdef0",
"fffffffffffffffffffffffffffffffffffffffffffffffffefefefefefefefe",
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe",
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"10000000000000000000000000000000000000000000000000000000000000000",
"1234567890abcdef01234567890abcdef01234567890abcdef01234567890abcdef0",
]
# Only odd moduli are present as in the new bignum code only odd moduli are
# supported for now.
MODULI_DEFAULT = [
"53", # safe prime
"45", # non-prime
SAFE_PRIME_192_BIT_SEED_1, # safe prime
RANDOM_192_BIT_SEED_2_NO4, # not a prime
SAFE_PRIME_1024_BIT_SEED_3, # safe prime
RANDOM_1024_BIT_SEED_4_NO5, # not a prime
]
# Some functions, e.g. mbedtls_mpi_mod_raw_inv_prime(), only support prime moduli.
ONLY_PRIME_MODULI = [
"53", # safe prime
"8ac72304057392b5", # 9999999997777777333 (longer, not safe, prime)
# The next prime has a different R in Montgomery form depending on
# whether 32- or 64-bit MPIs are used.
"152d02c7e14af67fe0bf", # 99999999999999999991999
SAFE_PRIME_192_BIT_SEED_1, # safe prime
SAFE_PRIME_1024_BIT_SEED_3, # safe prime
]
def __gen_safe_prime(bits, seed):
'''
Generate a safe prime.
This function is intended for generating constants offline and shouldn't be
used in test generation classes.
Requires pycryptodomex for getPrime and isPrime and python 3.9 or later for
randbytes.
'''
rng = random.Random()
# We want reproducibility across python versions
rng.seed(seed, version=2)
while True:
prime = 2*getPrime(bits-1, rng.randbytes)+1 #pylint: disable=no-member
if isPrime(prime, 1e-30):
return prime

View File

@ -1,102 +0,0 @@
"""Framework classes for generation of bignum mod test cases."""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
from typing import Dict, List
from . import test_data_generation
from . import bignum_common
from .bignum_data import ONLY_PRIME_MODULI
class BignumModTarget(test_data_generation.BaseTarget):
#pylint: disable=abstract-method, too-few-public-methods
"""Target for bignum mod test case generation."""
target_basename = 'test_suite_bignum_mod.generated'
class BignumModMul(bignum_common.ModOperationCommon,
BignumModTarget):
# pylint:disable=duplicate-code
"""Test cases for bignum mpi_mod_mul()."""
symbol = "*"
test_function = "mpi_mod_mul"
test_name = "mbedtls_mpi_mod_mul"
input_style = "arch_split"
arity = 2
def arguments(self) -> List[str]:
return [self.format_result(self.to_montgomery(self.int_a)),
self.format_result(self.to_montgomery(self.int_b)),
bignum_common.quote_str(self.arg_n)
] + self.result()
def result(self) -> List[str]:
result = (self.int_a * self.int_b) % self.int_n
return [self.format_result(self.to_montgomery(result))]
class BignumModSub(bignum_common.ModOperationCommon, BignumModTarget):
"""Test cases for bignum mpi_mod_sub()."""
symbol = "-"
test_function = "mpi_mod_sub"
test_name = "mbedtls_mpi_mod_sub"
input_style = "fixed"
arity = 2
def result(self) -> List[str]:
result = (self.int_a - self.int_b) % self.int_n
# To make negative tests easier, append 0 for success to the
# generated cases
return [self.format_result(result), "0"]
class BignumModInvNonMont(bignum_common.ModOperationCommon, BignumModTarget):
"""Test cases for bignum mpi_mod_inv() - not in Montgomery form."""
moduli = ONLY_PRIME_MODULI # for now only prime moduli supported
symbol = "^ -1"
test_function = "mpi_mod_inv_non_mont"
test_name = "mbedtls_mpi_mod_inv non-Mont. form"
input_style = "fixed"
arity = 1
suffix = True
disallow_zero_a = True
def result(self) -> List[str]:
result = bignum_common.invmod_positive(self.int_a, self.int_n)
# To make negative tests easier, append 0 for success to the
# generated cases
return [self.format_result(result), "0"]
class BignumModInvMont(bignum_common.ModOperationCommon, BignumModTarget):
"""Test cases for bignum mpi_mod_inv() - Montgomery form."""
moduli = ONLY_PRIME_MODULI # for now only prime moduli supported
symbol = "^ -1"
test_function = "mpi_mod_inv_mont"
test_name = "mbedtls_mpi_mod_inv Mont. form"
input_style = "arch_split" # Mont. form requires arch_split
arity = 1
suffix = True
disallow_zero_a = True
montgomery_form_a = True
def result(self) -> List[str]:
result = bignum_common.invmod_positive(self.int_a, self.int_n)
mont_result = self.to_montgomery(result)
# To make negative tests easier, append 0 for success to the
# generated cases
return [self.format_result(mont_result), "0"]
class BignumModAdd(bignum_common.ModOperationCommon, BignumModTarget):
"""Test cases for bignum mpi_mod_add()."""
count = 0
symbol = "+"
test_function = "mpi_mod_add"
test_name = "mbedtls_mpi_mod_add"
input_style = "fixed"
def result(self) -> List[str]:
result = (self.int_a + self.int_b) % self.int_n
# To make negative tests easier, append "0" for success to the
# generated cases
return [self.format_result(result), "0"]

View File

@ -1,242 +0,0 @@
"""Framework classes for generation of bignum mod_raw test cases."""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
from typing import Iterator, List
from . import test_case
from . import test_data_generation
from . import bignum_common
from .bignum_data import ONLY_PRIME_MODULI
class BignumModRawTarget(test_data_generation.BaseTarget):
#pylint: disable=abstract-method, too-few-public-methods
"""Target for bignum mod_raw test case generation."""
target_basename = 'test_suite_bignum_mod_raw.generated'
class BignumModRawSub(bignum_common.ModOperationCommon,
BignumModRawTarget):
"""Test cases for bignum mpi_mod_raw_sub()."""
symbol = "-"
test_function = "mpi_mod_raw_sub"
test_name = "mbedtls_mpi_mod_raw_sub"
input_style = "fixed"
arity = 2
def arguments(self) -> List[str]:
return [bignum_common.quote_str(n) for n in [self.arg_a,
self.arg_b,
self.arg_n]
] + self.result()
def result(self) -> List[str]:
result = (self.int_a - self.int_b) % self.int_n
return [self.format_result(result)]
class BignumModRawFixQuasiReduction(bignum_common.ModOperationCommon,
BignumModRawTarget):
"""Test cases for ecp quasi_reduction()."""
symbol = "-"
test_function = "mpi_mod_raw_fix_quasi_reduction"
test_name = "fix_quasi_reduction"
input_style = "fixed"
arity = 1
# Extend the default values with n < x < 2n
input_values = bignum_common.ModOperationCommon.input_values + [
"73",
# First number generated by random.getrandbits(1024) - seed(3,2)
"ea7b5bf55eb561a4216363698b529b4a97b750923ceb3ffd",
# First number generated by random.getrandbits(1024) - seed(1,2)
("cd447e35b8b6d8fe442e3d437204e52db2221a58008a05a6c4647159c324c985"
"9b810e766ec9d28663ca828dd5f4b3b2e4b06ce60741c7a87ce42c8218072e8c"
"35bf992dc9e9c616612e7696a6cecc1b78e510617311d8a3c2ce6f447ed4d57b"
"1e2feb89414c343c1027c4d1c386bbc4cd613e30d8f16adf91b7584a2265b1f5")
] # type: List[str]
def result(self) -> List[str]:
result = self.int_a % self.int_n
return [self.format_result(result)]
@property
def is_valid(self) -> bool:
return bool(self.int_a < 2 * self.int_n)
class BignumModRawMul(bignum_common.ModOperationCommon,
BignumModRawTarget):
"""Test cases for bignum mpi_mod_raw_mul()."""
symbol = "*"
test_function = "mpi_mod_raw_mul"
test_name = "mbedtls_mpi_mod_raw_mul"
input_style = "arch_split"
arity = 2
def arguments(self) -> List[str]:
return [self.format_result(self.to_montgomery(self.int_a)),
self.format_result(self.to_montgomery(self.int_b)),
bignum_common.quote_str(self.arg_n)
] + self.result()
def result(self) -> List[str]:
result = (self.int_a * self.int_b) % self.int_n
return [self.format_result(self.to_montgomery(result))]
class BignumModRawInvPrime(bignum_common.ModOperationCommon,
BignumModRawTarget):
"""Test cases for bignum mpi_mod_raw_inv_prime()."""
moduli = ONLY_PRIME_MODULI
symbol = "^ -1"
test_function = "mpi_mod_raw_inv_prime"
test_name = "mbedtls_mpi_mod_raw_inv_prime (Montgomery form only)"
input_style = "arch_split"
arity = 1
suffix = True
montgomery_form_a = True
disallow_zero_a = True
def result(self) -> List[str]:
result = bignum_common.invmod_positive(self.int_a, self.int_n)
mont_result = self.to_montgomery(result)
return [self.format_result(mont_result)]
class BignumModRawAdd(bignum_common.ModOperationCommon,
BignumModRawTarget):
"""Test cases for bignum mpi_mod_raw_add()."""
symbol = "+"
test_function = "mpi_mod_raw_add"
test_name = "mbedtls_mpi_mod_raw_add"
input_style = "fixed"
arity = 2
def result(self) -> List[str]:
result = (self.int_a + self.int_b) % self.int_n
return [self.format_result(result)]
class BignumModRawConvertRep(bignum_common.ModOperationCommon,
BignumModRawTarget):
# This is an abstract class, it's ok to have unimplemented methods.
#pylint: disable=abstract-method
"""Test cases for representation conversion."""
symbol = ""
input_style = "arch_split"
arity = 1
rep = bignum_common.ModulusRepresentation.INVALID
def set_representation(self, r: bignum_common.ModulusRepresentation) -> None:
self.rep = r
def arguments(self) -> List[str]:
return ([bignum_common.quote_str(self.arg_n), self.rep.symbol(),
bignum_common.quote_str(self.arg_a)] +
self.result())
def description(self) -> str:
base = super().description()
mod_with_rep = 'mod({})'.format(self.rep.name)
return base.replace('mod', mod_with_rep, 1)
@classmethod
def test_cases_for_values(cls, rep: bignum_common.ModulusRepresentation,
n: str, a: str) -> Iterator[test_case.TestCase]:
"""Emit test cases for the given values (if any).
This may emit no test cases if a isn't valid for the modulus n,
or multiple test cases if rep requires different data depending
on the limb size.
"""
for bil in cls.limb_sizes:
test_object = cls(n, a, bits_in_limb=bil)
test_object.set_representation(rep)
# The class is set to having separate test cases for each limb
# size, because the Montgomery representation requires it.
# But other representations don't require it. So for other
# representations, emit a single test case with no dependency
# on the limb size.
if rep is not bignum_common.ModulusRepresentation.MONTGOMERY:
test_object.dependencies = \
[dep for dep in test_object.dependencies
if not dep.startswith('MBEDTLS_HAVE_INT')]
if test_object.is_valid:
yield test_object.create_test_case()
if rep is not bignum_common.ModulusRepresentation.MONTGOMERY:
# A single test case (emitted, or skipped due to invalidity)
# is enough, since this test case doesn't depend on the
# limb size.
break
# The parent class doesn't support non-bignum parameters. So we override
# test generation, in order to have the representation as a parameter.
@classmethod
def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
for rep in bignum_common.ModulusRepresentation.supported_representations():
for n in cls.moduli:
for a in cls.input_values:
yield from cls.test_cases_for_values(rep, n, a)
class BignumModRawCanonicalToModulusRep(BignumModRawConvertRep):
"""Test cases for mpi_mod_raw_canonical_to_modulus_rep."""
test_function = "mpi_mod_raw_canonical_to_modulus_rep"
test_name = "Rep canon->mod"
def result(self) -> List[str]:
return [self.format_result(self.convert_from_canonical(self.int_a, self.rep))]
class BignumModRawModulusToCanonicalRep(BignumModRawConvertRep):
"""Test cases for mpi_mod_raw_modulus_to_canonical_rep."""
test_function = "mpi_mod_raw_modulus_to_canonical_rep"
test_name = "Rep mod->canon"
@property
def arg_a(self) -> str:
return self.format_arg("{:x}".format(self.convert_from_canonical(self.int_a, self.rep)))
def result(self) -> List[str]:
return [self.format_result(self.int_a)]
class BignumModRawConvertToMont(bignum_common.ModOperationCommon,
BignumModRawTarget):
""" Test cases for mpi_mod_raw_to_mont_rep(). """
test_function = "mpi_mod_raw_to_mont_rep"
test_name = "Convert into Mont: "
symbol = "R *"
input_style = "arch_split"
arity = 1
def result(self) -> List[str]:
result = self.to_montgomery(self.int_a)
return [self.format_result(result)]
class BignumModRawConvertFromMont(bignum_common.ModOperationCommon,
BignumModRawTarget):
""" Test cases for mpi_mod_raw_from_mont_rep(). """
test_function = "mpi_mod_raw_from_mont_rep"
test_name = "Convert from Mont: "
symbol = "1/R *"
input_style = "arch_split"
arity = 1
def result(self) -> List[str]:
result = self.from_montgomery(self.int_a)
return [self.format_result(result)]
class BignumModRawModNegate(bignum_common.ModOperationCommon,
BignumModRawTarget):
""" Test cases for mpi_mod_raw_neg(). """
test_function = "mpi_mod_raw_neg"
test_name = "Modular negation: "
symbol = "-"
input_style = "arch_split"
arity = 1
def result(self) -> List[str]:
result = (self.int_n - self.int_a) % self.int_n
return [self.format_result(result)]

View File

@ -1,120 +0,0 @@
"""Mbed TLS build tree information and manipulation.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
import os
import inspect
from typing import Optional
def looks_like_tf_psa_crypto_root(path: str) -> bool:
"""Whether the given directory looks like the root of the PSA Crypto source tree."""
return all(os.path.isdir(os.path.join(path, subdir))
for subdir in ['include', 'core', 'drivers', 'programs', 'tests'])
def looks_like_mbedtls_root(path: str) -> bool:
"""Whether the given directory looks like the root of the Mbed TLS source tree."""
return all(os.path.isdir(os.path.join(path, subdir))
for subdir in ['include', 'library', 'programs', 'tests'])
def looks_like_root(path: str) -> bool:
return looks_like_tf_psa_crypto_root(path) or looks_like_mbedtls_root(path)
def crypto_core_directory(root: Optional[str] = None, relative: Optional[bool] = False) -> str:
"""
Return the path of the directory containing the PSA crypto core
for either TF-PSA-Crypto or Mbed TLS.
Returns either the full path or relative path depending on the
"relative" boolean argument.
"""
if root is None:
root = guess_project_root()
if looks_like_tf_psa_crypto_root(root):
if relative:
return "core"
return os.path.join(root, "core")
elif looks_like_mbedtls_root(root):
if relative:
return "library"
return os.path.join(root, "library")
else:
raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
def crypto_library_filename(root: Optional[str] = None) -> str:
"""Return the crypto library filename for either TF-PSA-Crypto or Mbed TLS."""
if root is None:
root = guess_project_root()
if looks_like_tf_psa_crypto_root(root):
return "tfpsacrypto"
elif looks_like_mbedtls_root(root):
return "mbedcrypto"
else:
raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
def check_repo_path():
"""Check that the current working directory is the project root, and throw
an exception if not.
"""
if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
raise Exception("This script must be run from Mbed TLS root")
def chdir_to_root() -> None:
"""Detect the root of the Mbed TLS source tree and change to it.
The current directory must be up to two levels deep inside an Mbed TLS
source tree.
"""
for d in [os.path.curdir,
os.path.pardir,
os.path.join(os.path.pardir, os.path.pardir)]:
if looks_like_root(d):
os.chdir(d)
return
raise Exception('Mbed TLS source tree not found')
def guess_project_root():
"""Guess project source code directory.
Return the first possible project root directory.
"""
dirs = set({})
for frame in inspect.stack():
path = os.path.dirname(frame.filename)
for d in ['.', os.path.pardir] \
+ [os.path.join(*([os.path.pardir]*i)) for i in range(2, 10)]:
d = os.path.abspath(os.path.join(path, d))
if d in dirs:
continue
dirs.add(d)
if looks_like_root(d):
return d
raise Exception('Neither Mbed TLS nor TF-PSA-Crypto source tree found')
def guess_mbedtls_root(root: Optional[str] = None) -> str:
"""Guess Mbed TLS source code directory.
Return the first possible Mbed TLS root directory.
Raise an exception if we are not in Mbed TLS.
"""
if root is None:
root = guess_project_root()
if looks_like_mbedtls_root(root):
return root
else:
raise Exception('Mbed TLS source tree not found')
def guess_tf_psa_crypto_root(root: Optional[str] = None) -> str:
"""Guess TF-PSA-Crypto source code directory.
Return the first possible TF-PSA-Crypto root directory.
Raise an exception if we are not in TF-PSA-Crypto.
"""
if root is None:
root = guess_project_root()
if looks_like_tf_psa_crypto_root(root):
return root
else:
raise Exception('TF-PSA-Crypto source tree not found')

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