Merge pull request #6753 from mpg/restartable-docfix-2.28
[Backport 2.28] Document ECP_RESTARTABLE
diff --git a/.uncrustify.cfg b/.uncrustify.cfg
new file mode 100644
index 0000000..ac9173e
--- /dev/null
+++ b/.uncrustify.cfg
@@ -0,0 +1,254 @@
+# Configuration options for Uncrustify specifying the Mbed TLS code style.
+#
+# Note: The code style represented by this file has not yet been introduced
+# to Mbed TLS.
+#
+# Copyright The Mbed TLS Contributors
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+# Line length options
+
+# Wrap lines at 100 characters
+code_width = 100
+
+# Allow splitting long for statements between the condition statements
+ls_for_split_full = true
+
+# Allow splitting function calls between arguments
+ls_func_split_full = true
+
+input_tab_size = 4
+
+# Spaces-only indentation
+indent_with_tabs = 0
+
+indent_columns = 4
+
+# Indent 'case' 1 level from 'switch'
+indent_switch_case = indent_columns
+
+# Line-up strings broken by '\'
+indent_align_string = true
+
+# Braces on the same line (Egyptian-style braces)
+nl_enum_brace = remove
+nl_union_brace = remove
+nl_struct_brace = remove
+nl_do_brace = remove
+nl_if_brace = remove
+nl_for_brace = remove
+nl_else_brace = remove
+nl_while_brace = remove
+nl_switch_brace = remove
+
+# Braces on same line as keywords that follow them - 'else' and the 'while' in 'do {} while ()';
+nl_brace_else = remove
+nl_brace_while = remove
+# Space before else on the same line
+sp_brace_else = add
+# If else is on the same line as '{', force exactly 1 space between them
+sp_else_brace = force
+
+# Functions are the exception and have braces on the next line
+nl_fcall_brace = add
+nl_fdef_brace = add
+
+# Force exactly one space between ')' and '{' in statements
+sp_sparen_brace = force
+
+# At least 1 space around assignment
+sp_assign = add
+
+# Remove spaces around the preprocessor '##' token-concatenate
+sp_pp_concat = ignore
+
+# At least 1 space around '||' and '&&'
+sp_bool = add
+
+# But no space after the '!' operator
+sp_not = remove
+
+# No space after the bitwise-not '~' operator
+sp_inv = remove
+
+# No space after the addressof '&' operator
+sp_addr = remove
+
+# No space around the member '.' and '->' operators
+sp_member = remove
+
+# No space after the dereference '*' operator
+sp_deref = remove
+
+# No space after a unary negation '-'
+sp_sign = remove
+
+# No space between the '++'/'--' operator and its operand
+sp_incdec = remove
+
+# At least 1 space around comparison operators
+sp_compare = add
+
+# Remove spaces inside all kinds of parentheses:
+
+# Remove spaces inside parentheses
+sp_inside_paren = remove
+
+# No spaces inside statement parentheses
+sp_inside_sparen = remove
+
+# No spaces inside cast parentheses '( char )x' -> '(char)x'
+sp_inside_paren_cast = remove
+
+# No spaces inside function parentheses
+sp_inside_fparen = remove
+# (The case where the function has no parameters/arguments)
+sp_inside_fparens = remove
+
+# No spaces inside the first parentheses in a function type
+sp_inside_tparen = remove
+
+# (Uncrustify >= 0.74.0) No spaces inside parens in for statements
+sp_inside_for = remove
+
+# Remove spaces between nested parentheses '( (' -> '(('
+sp_paren_paren = remove
+# (Uncrustify >= 0.74.0)
+sp_sparen_paren = remove
+
+# Remove spaces between ')' and adjacent '('
+sp_cparen_oparen = remove
+
+# (Uncrustify >= 0.73.0) space between 'do' and '{'
+sp_do_brace_open = force
+
+# (Uncrustify >= 0.73.0) space between '}' and 'while'
+sp_brace_close_while = force
+
+# At least 1 space before a '*' pointer star
+sp_before_ptr_star = add
+
+# Remove spaces between pointer stars
+sp_between_ptr_star = remove
+
+# No space after a pointer star
+sp_after_ptr_star = remove
+
+# But allow a space in the case of e.g. char * const x;
+sp_after_ptr_star_qualifier = ignore
+
+# Remove space after star in a function return type
+sp_after_ptr_star_func = remove
+
+# At least 1 space after a type in variable definition etc
+sp_after_type = add
+
+# Force exactly 1 space between a statement keyword (e.g. 'if') and an opening parenthesis
+sp_before_sparen = force
+
+# Remove a space before a ';'
+sp_before_semi = remove
+# (Uncrustify >= 0.73.0) Remove space before a semi in a non-empty for
+sp_before_semi_for = remove
+# (Uncrustify >= 0.73.0) Remove space in empty first statement of a for
+sp_before_semi_for_empty = remove
+# (Uncrustify >= 0.74.0) Remove space in empty middle statement of a for
+sp_between_semi_for_empty = remove
+
+# Add a space after a ';' (unless a comment follows)
+sp_after_semi = add
+# (Uncrustify >= 0.73.0) Add a space after a semi in non-empty for statements
+sp_after_semi_for = add
+# (Uncrustify >= 0.73.0) No space after final semi in empty for statements
+sp_after_semi_for_empty = remove
+
+# Remove spaces on the inside of square brackets '[]'
+sp_inside_square = remove
+
+# Must have at least 1 space after a comma
+sp_after_comma = add
+
+# Must not have a space before a comma
+sp_before_comma = remove
+
+# No space before the ':' in a case statement
+sp_before_case_colon = remove
+
+# No space after a cast - '(char) x' -> '(char)x'
+sp_after_cast = remove
+
+# No space between 'sizeof' and '('
+sp_sizeof_paren = remove
+
+# At least 1 space inside '{ }'
+sp_inside_braces = add
+
+# At least 1 space inside '{ }' in an enum
+sp_inside_braces_enum = add
+
+# At least 1 space inside '{ }' in a struct
+sp_inside_braces_struct = add
+
+# At least 1 space between a function return type and the function name
+sp_type_func = add
+
+# No space between a function name and its arguments/parameters
+sp_func_proto_paren = remove
+sp_func_def_paren = remove
+sp_func_call_paren = remove
+
+# No space between '__attribute__' and '('
+sp_attribute_paren = remove
+
+# No space between 'defined' and '(' in preprocessor conditions
+sp_defined_paren = remove
+
+# At least 1 space between a macro's name and its definition
+sp_macro = add
+sp_macro_func = add
+
+# Force exactly 1 space between a '}' and the name of a typedef if on the same line
+sp_brace_typedef = force
+
+# At least 1 space before a '\' line continuation
+sp_before_nl_cont = add
+
+# At least 1 space around '?' and ':' in ternary statements
+sp_cond_colon = add
+sp_cond_question = add
+
+# Space between #else/#endif and comment afterwards
+sp_endif_cmt = add
+
+# Remove newlines at the start of a file
+nl_start_of_file = remove
+
+# At least 1 newline at the end of a file
+nl_end_of_file = add
+nl_end_of_file_min = 1
+
+# Add braces in single-line statements
+mod_full_brace_do = add
+mod_full_brace_for = add
+mod_full_brace_if = add
+mod_full_brace_while = add
+
+# Remove parentheses from return statements
+mod_paren_on_return = remove
+
+# Disable removal of leading spaces in a multi-line comment if the first and
+# last lines are the same length
+cmt_multi_check_last = false
diff --git a/BRANCHES.md b/BRANCHES.md
index 7fb706d..d4fa506 100644
--- a/BRANCHES.md
+++ b/BRANCHES.md
@@ -70,6 +70,7 @@
- [master](https://github.com/Mbed-TLS/mbedtls/tree/master)
- [`development`](https://github.com/Mbed-TLS/mbedtls/)
- [`mbedtls-2.28`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-2.28)
- maintained until at least the end of 2024.
+ maintained until at least the end of 2024, see
+ <https://github.com/Mbed-TLS/mbedtls/releases/tag/v2.28.2>.
Users are urged to always use the latest version of a maintained branch.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e18f607..ddeb115 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -137,35 +137,32 @@
# Create a symbolic link from ${base_name} in the binary directory
# to the corresponding path in the source directory.
+# Note: Copies the file(s) on Windows.
function(link_to_source base_name)
- # Get OS dependent path to use in `execute_process`
- if (CMAKE_HOST_WIN32)
- #mklink is an internal command of cmd.exe it can only work with \
- string(REPLACE "/" "\\" link "${CMAKE_CURRENT_BINARY_DIR}/${base_name}")
- string(REPLACE "/" "\\" target "${CMAKE_CURRENT_SOURCE_DIR}/${base_name}")
- else()
- set(link "${CMAKE_CURRENT_BINARY_DIR}/${base_name}")
- set(target "${CMAKE_CURRENT_SOURCE_DIR}/${base_name}")
- endif()
+ set(link "${CMAKE_CURRENT_BINARY_DIR}/${base_name}")
+ set(target "${CMAKE_CURRENT_SOURCE_DIR}/${base_name}")
if (NOT EXISTS ${link})
if (CMAKE_HOST_UNIX)
- set(command ln -s ${target} ${link})
+ execute_process(COMMAND ln -s ${target} ${link}
+ RESULT_VARIABLE result
+ ERROR_VARIABLE output)
+
+ if (NOT ${result} EQUAL 0)
+ message(FATAL_ERROR "Could not create symbolic link for: ${target} --> ${output}")
+ endif()
else()
if (IS_DIRECTORY ${target})
- set(command cmd.exe /c mklink /j ${link} ${target})
+ file(GLOB_RECURSE files FOLLOW_SYMLINKS RELATIVE ${target} "${target}/*")
+ foreach(file IN LISTS files)
+ if(NOT IS_DIRECTORY "${target}/${file}")
+ configure_file("${target}/${file}" "${link}/${file}" COPYONLY)
+ endif()
+ endforeach(file)
else()
- set(command cmd.exe /c mklink /h ${link} ${target})
+ configure_file(${target} ${link} COPYONLY)
endif()
endif()
-
- execute_process(COMMAND ${command}
- RESULT_VARIABLE result
- ERROR_VARIABLE output)
-
- if (NOT ${result} EQUAL 0)
- message(FATAL_ERROR "Could not create symbolic link for: ${target} --> ${output}")
- endif()
endif()
endfunction(link_to_source)
@@ -314,22 +311,15 @@
# additional convenience targets for Unix only
if(UNIX)
- ADD_CUSTOM_TARGET(covtest
- COMMAND make test
- COMMAND programs/test/selftest
- COMMAND tests/compat.sh
- COMMAND tests/ssl-opt.sh
- )
-
+ # For coverage testing:
+ # 1. Build with:
+ # cmake -D CMAKE_BUILD_TYPE=Coverage /path/to/source && make
+ # 2. Run the relevant tests for the part of the code you're interested in.
+ # For the reference coverage measurement, see
+ # tests/scripts/basic-build-test.sh
+ # 3. Run scripts/lcov.sh to generate an HTML report.
ADD_CUSTOM_TARGET(lcov
- COMMAND rm -rf Coverage
- COMMAND lcov --capture --initial --directory library/CMakeFiles/mbedtls.dir -o files.info
- COMMAND lcov --capture --directory library/CMakeFiles/mbedtls.dir -o tests.info
- COMMAND lcov --add-tracefile files.info --add-tracefile tests.info -o all.info
- COMMAND lcov --remove all.info -o final.info '*.h'
- COMMAND gendesc tests/Descriptions.txt -o descriptions
- COMMAND genhtml --title "mbed TLS" --description-file descriptions --keep-descriptions --legend --no-branch-coverage -o Coverage final.info
- COMMAND rm -f files.info tests.info all.info final.info descriptions
+ COMMAND scripts/lcov.sh
)
ADD_CUSTOM_TARGET(memcheck
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d19fe57..fc79e49 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -32,13 +32,9 @@
The project aims to minimise the impact on users upgrading to newer versions of the library and it should not be necessary for a user to make any changes to their own code to work with a newer version of the library. Unless the user has made an active decision to use newer features, a newer generation of the library or a change has been necessary due to a security issue or other significant software defect, no modifications to their own code should be necessary. To achieve this, API compatibility is maintained between different versions of Mbed TLS on the main development branch and in LTS (Long Term Support) branches, as described in [BRANCHES.md](BRANCHES.md).
-To minimise such disruption to users, where a change to the interface is required, all changes to the ABI or API, even on the main development branch where new features are added, need to be justifiable by either being a significant enhancement, new feature or bug fix which is best resolved by an interface change. If there is an API change, the contribution, if accepted, will be merged only when there will be a major release.
+To minimise such disruption to users, where a change to the interface is required, all changes to the ABI or API, even on the main development branch where new features are added, need to be justifiable by either being a significant enhancement, new feature or bug fix which is best resolved by an interface change. If there is an API change, the contribution, if accepted, will be merged only when there is a major release.
-Where changes to an existing interface are necessary, functions in the public interface which need to be changed, are marked as 'deprecated'. This is done with the preprocessor symbols `MBEDTLS_DEPRECATED_WARNING` and `MBEDTLS_DEPRECATED_REMOVED`. Then, a new function with a new name but similar if not identical behaviour to the original function containing the necessary changes should be created alongside the existing deprecated function.
-
-When a build is made with the deprecation preprocessor symbols defined, a compiler warning will be generated to warn a user that the function will be removed at some point in the future, notifying users that they should change from the older deprecated function to the newer function at their own convenience.
-
-Therefore, no changes are permitted to the definition of functions in the public interface which will change the API. Instead the interface can only be changed by its extension. As described above, if a function needs to be changed, a new function needs to be created alongside it, with a new name, and whatever change is necessary, such as a new parameter or the addition of a return value.
+No changes are permitted to the definition of functions in the public interface which will change the API. Instead the interface can only be changed by its extension. Where changes to an existing interface are necessary, functions in the public interface which need to be changed are marked as 'deprecated'. If there is a strong reason to replace an existing function with one that has a slightly different interface (different prototype, or different documented behavior), create a new function with a new name with the desired interface. Keep the old function, but mark it as deprecated.
Periodically, the library will remove deprecated functions from the library which will be a breaking change in the API, but such changes will be made only in a planned, structured way that gives sufficient notice to users of the library.
diff --git a/ChangeLog b/ChangeLog
index 54217fe..3673f5d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,74 @@
Mbed TLS ChangeLog (Sorted per branch, date)
+= Mbed TLS 2.28.2 branch released 2022-12-14
+
+Security
+ * Fix potential heap buffer overread and overwrite in DTLS if
+ MBEDTLS_SSL_DTLS_CONNECTION_ID is enabled and
+ MBEDTLS_SSL_CID_IN_LEN_MAX > 2 * MBEDTLS_SSL_CID_OUT_LEN_MAX.
+ * An adversary with access to precise enough information about memory
+ accesses (typically, an untrusted operating system attacking a secure
+ enclave) could recover an RSA private key after observing the victim
+ performing a single private-key operation if the window size used for the
+ exponentiation was 3 or smaller. Found and reported by Zili KOU,
+ Wenjian HE, Sharad Sinha, and Wei ZHANG. See "Cache Side-channel Attacks
+ and Defenses of the Sliding Window Algorithm in TEEs" - Design, Automation
+ and Test in Europe 2023.
+
+Bugfix
+ * Fix a long-standing build failure when building x86 PIC code with old
+ gcc (4.x). The code will be slower, but will compile. We do however
+ recommend upgrading to a more recent compiler instead. Fixes #1910.
+ * Fix support for little-endian Microblaze when MBEDTLS_HAVE_ASM is defined.
+ Contributed by Kazuyuki Kimura to fix #2020.
+ * Use double quotes to include private header file psa_crypto_cipher.h.
+ Fixes 'file not found with <angled> include' error
+ when building with Xcode.
+ * Fix handling of broken symlinks when loading certificates using
+ mbedtls_x509_crt_parse_path(). Instead of returning an error as soon as a
+ broken link is encountered, skip the broken link and continue parsing
+ other certificate files. Contributed by Eduardo Silva in #2602.
+ * Fix a compilation error when using CMake with an IAR toolchain.
+ Fixes #5964.
+ * Fix bugs and missing dependencies when building and testing
+ configurations with only one encryption type enabled in TLS 1.2.
+ * Provide the missing definition of mbedtls_setbuf() in some configurations
+ with MBEDTLS_PLATFORM_C disabled. Fixes #6118, #6196.
+ * Fix compilation errors when trying to build with
+ PSA drivers for AEAD (GCM, CCM, Chacha20-Poly1305).
+ * Fix memory leak in ssl_parse_certificate_request() caused by
+ mbedtls_x509_get_name() not freeing allocated objects in case of error.
+ Change mbedtls_x509_get_name() to clean up allocated objects on error.
+ * Fix checks on PK in check_config.h for builds with PSA and RSA. This does
+ not change which builds actually work, only moving a link-time error to
+ an early check.
+ * Fix ECDSA verification, where it was not always validating the
+ public key. This bug meant that it was possible to verify a
+ signature with an invalid public key, in some cases. Reported by
+ Guido Vranken using Cryptofuzz in #4420.
+ * Fix a possible null pointer dereference if a memory allocation fails
+ in TLS PRF code. Reported by Michael Madsen in #6516.
+ * Fix a bug in which mbedtls_x509_crt_info() would produce non-printable
+ bytes when parsing certificates containing a binary RFC 4108
+ HardwareModuleName as a Subject Alternative Name extension. Hardware
+ serial numbers are now rendered in hex format. Fixes #6262.
+ * Fix bug in error reporting in dh_genprime.c where upon failure,
+ the error code returned by mbedtls_mpi_write_file() is overwritten
+ and therefore not printed.
+ * In the bignum module, operations of the form (-A) - (+A) or (-A) - (-A)
+ with A > 0 created an unintended representation of the value 0 which was
+ not processed correctly by some bignum operations. Fix this. This had no
+ consequence on cryptography code, but might affect applications that call
+ bignum directly and use negative numbers.
+ * Fix undefined behavior (typically harmless in practice) of
+ mbedtls_mpi_add_mpi(), mbedtls_mpi_add_abs() and mbedtls_mpi_add_int()
+ when both operands are 0 and the left operand is represented with 0 limbs.
+ * Fix undefined behavior (typically harmless in practice) when some bignum
+ functions receive the most negative value of mbedtls_mpi_sint. Credit
+ to OSS-Fuzz. Fixes #6597.
+ * Fix undefined behavior (typically harmless in practice) in PSA ECB
+ encryption and decryption.
+
= Mbed TLS 2.28.1 branch released 2022-07-11
Default behavior changes
diff --git a/ChangeLog.d/bn_mul-fix-x86-pic-compilation-for-gcc-4.txt b/ChangeLog.d/bn_mul-fix-x86-pic-compilation-for-gcc-4.txt
deleted file mode 100644
index 1d59c22..0000000
--- a/ChangeLog.d/bn_mul-fix-x86-pic-compilation-for-gcc-4.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix a long-standing build failure when building x86 PIC code with old
- gcc (4.x). The code will be slower, but will compile. We do however
- recommend upgrading to a more recent compiler instead. Fixes #1910.
diff --git a/ChangeLog.d/ecdsa-verify-fixes.txt b/ChangeLog.d/ecdsa-verify-fixes.txt
deleted file mode 100644
index b41b046..0000000
--- a/ChangeLog.d/ecdsa-verify-fixes.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Bugfix
- * Fix ECDSA verification, where it was not always validating the
- public key. This bug meant that it was possible to verify a
- signature with an invalid public key, in some cases. Reported by
- Guido Vranken using Cryptofuzz in #4420.
diff --git a/ChangeLog.d/fix_aead_psa_driver_build.txt b/ChangeLog.d/fix_aead_psa_driver_build.txt
deleted file mode 100644
index a6d11d3..0000000
--- a/ChangeLog.d/fix_aead_psa_driver_build.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix compilation errors when trying to build with
- PSA drivers for AEAD (GCM, CCM, Chacha20-Poly1305).
diff --git a/ChangeLog.d/fix_build_tls1_2_with_single_encryption_type.txt b/ChangeLog.d/fix_build_tls1_2_with_single_encryption_type.txt
deleted file mode 100644
index c7d2691..0000000
--- a/ChangeLog.d/fix_build_tls1_2_with_single_encryption_type.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix bugs and missing dependencies when building and testing
- configurations with only one encryption type enabled in TLS 1.2.
diff --git a/ChangeLog.d/fix_cmake_using_iar_toolchain.txt b/ChangeLog.d/fix_cmake_using_iar_toolchain.txt
deleted file mode 100644
index 9ec6e0d..0000000
--- a/ChangeLog.d/fix_cmake_using_iar_toolchain.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix a compilation error when using CMake with an IAR toolchain.
- Fixes #5964.
diff --git a/ChangeLog.d/fix_dh_genprime_error_reporting.txt b/ChangeLog.d/fix_dh_genprime_error_reporting.txt
deleted file mode 100644
index 1c98947..0000000
--- a/ChangeLog.d/fix_dh_genprime_error_reporting.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix bug in error reporting in dh_genprime.c where upon failure,
- the error code returned by mbedtls_mpi_write_file() is overwritten
- and therefore not printed.
diff --git a/ChangeLog.d/fix_hard_link_across_drives b/ChangeLog.d/fix_hard_link_across_drives
new file mode 100644
index 0000000..0c55c30
--- /dev/null
+++ b/ChangeLog.d/fix_hard_link_across_drives
@@ -0,0 +1,3 @@
+Bugfix
+ * Fix a build issue on Windows where the source and build directory could not be on
+ different drives (#5751).
diff --git a/ChangeLog.d/fix_psa_crypto_cipher_h_include.txt b/ChangeLog.d/fix_psa_crypto_cipher_h_include.txt
deleted file mode 100644
index bf2e65d..0000000
--- a/ChangeLog.d/fix_psa_crypto_cipher_h_include.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Use double quotes to include private header file psa_crypto_cipher.h.
- Fixes 'file not found with <angled> include' error
- when building with Xcode.
diff --git a/ChangeLog.d/fix_x509_get_name_mem_leak.txt b/ChangeLog.d/fix_x509_get_name_mem_leak.txt
deleted file mode 100644
index 358d1af..0000000
--- a/ChangeLog.d/fix_x509_get_name_mem_leak.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix memory leak in ssl_parse_certificate_request() caused by
- mbedtls_x509_get_name() not freeing allocated objects in case of error.
- Change mbedtls_x509_get_name() to clean up allocated objects on error.
diff --git a/ChangeLog.d/fix_x509_info_hwmodulename.txt b/ChangeLog.d/fix_x509_info_hwmodulename.txt
deleted file mode 100644
index 8b227ce..0000000
--- a/ChangeLog.d/fix_x509_info_hwmodulename.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Bugfix
- * Fix a bug in which mbedtls_x509_crt_info() would produce non-printable
- bytes when parsing certificates containing a binary RFC 4108
- HardwareModuleName as a Subject Alternative Name extension. Hardware
- serial numbers are now rendered in hex format. Fixes #6262.
diff --git a/ChangeLog.d/fix_zeroization.txt b/ChangeLog.d/fix_zeroization.txt
deleted file mode 100644
index 8b00dcc..0000000
--- a/ChangeLog.d/fix_zeroization.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix a possible null pointer dereference if a memory allocation fails
- in TLS PRF code. Reported by Michael Madsen in #6516.
diff --git a/ChangeLog.d/mpi-add-0-ub.txt b/ChangeLog.d/mpi-add-0-ub.txt
deleted file mode 100644
index 9f131a4..0000000
--- a/ChangeLog.d/mpi-add-0-ub.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix undefined behavior (typically harmless in practice) of
- mbedtls_mpi_add_mpi(), mbedtls_mpi_add_abs() and mbedtls_mpi_add_int()
- when both operands are 0 and the left operand is represented with 0 limbs.
diff --git a/ChangeLog.d/mpi-most-negative-sint.txt b/ChangeLog.d/mpi-most-negative-sint.txt
deleted file mode 100644
index 5e775c4..0000000
--- a/ChangeLog.d/mpi-most-negative-sint.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix undefined behavior (typically harmless in practice) when some bignum
- functions receive the most negative value of mbedtls_mpi_sint. Credit
- to OSS-Fuzz. Fixes #6597.
diff --git a/ChangeLog.d/muladdc_microblaze.txt b/ChangeLog.d/muladdc_microblaze.txt
deleted file mode 100644
index 70fdff0..0000000
--- a/ChangeLog.d/muladdc_microblaze.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix support for little-endian Microblaze when MBEDTLS_HAVE_ASM is defined.
- Contributed by Kazuyuki Kimura to fix #2020.
diff --git a/ChangeLog.d/negative-zero-from-add.txt b/ChangeLog.d/negative-zero-from-add.txt
deleted file mode 100644
index 107d858..0000000
--- a/ChangeLog.d/negative-zero-from-add.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Bugfix
- * In the bignum module, operations of the form (-A) - (+A) or (-A) - (-A)
- with A > 0 created an unintended representation of the value 0 which was
- not processed correctly by some bignum operations. Fix this. This had no
- consequence on cryptography code, but might affect applications that call
- bignum directly and use negative numbers.
diff --git a/ChangeLog.d/platform-setbuf.txt b/ChangeLog.d/platform-setbuf.txt
deleted file mode 100644
index 844f70c..0000000
--- a/ChangeLog.d/platform-setbuf.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Provide the missing definition of mbedtls_setbuf() in some configurations
- with MBEDTLS_PLATFORM_C disabled. Fixes #6118, #6196.
diff --git a/ChangeLog.d/psa-ecb-ub.txt b/ChangeLog.d/psa-ecb-ub.txt
deleted file mode 100644
index 9d725ac..0000000
--- a/ChangeLog.d/psa-ecb-ub.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
- * Fix undefined behavior (typically harmless in practice) in PSA ECB
- encryption and decryption.
diff --git a/ChangeLog.d/psa_rsa_needs_pk.txt b/ChangeLog.d/psa_rsa_needs_pk.txt
deleted file mode 100644
index eb817f3..0000000
--- a/ChangeLog.d/psa_rsa_needs_pk.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
- * Fix checks on PK in check_config.h for builds with PSA and RSA. This does
- not change which builds actually work, only moving a link-time error to
- an early check.
diff --git a/ChangeLog.d/x509-broken-symlink-handling.txt b/ChangeLog.d/x509-broken-symlink-handling.txt
deleted file mode 100644
index 52288dc..0000000
--- a/ChangeLog.d/x509-broken-symlink-handling.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Bugfix
- * Fix handling of broken symlinks when loading certificates using
- mbedtls_x509_crt_parse_path(). Instead of returning an error as soon as a
- broken link is encountered, skip the broken link and continue parsing
- other certificate files. Contributed by Eduardo Silva in #2602.
diff --git a/Makefile b/Makefile
index 6a8b230..1efe89d 100644
--- a/Makefile
+++ b/Makefile
@@ -3,7 +3,7 @@
.SILENT:
-.PHONY: all no_test programs lib tests install uninstall clean test check covtest lcov apidoc apidoc_clean
+.PHONY: all no_test programs lib tests install uninstall clean test check lcov apidoc apidoc_clean
all: programs tests
$(MAKE) post_build
@@ -100,23 +100,15 @@
test: check
ifndef WINDOWS
-# note: for coverage testing, build with:
-# make CFLAGS='--coverage -g3 -O0'
-covtest:
- $(MAKE) check
- programs/test/selftest
- tests/compat.sh
- tests/ssl-opt.sh
-
+# For coverage testing:
+# 1. Build with:
+# make CFLAGS='--coverage -g3 -O0' LDFLAGS='--coverage'
+# 2. Run the relevant tests for the part of the code you're interested in.
+# For the reference coverage measurement, see
+# tests/scripts/basic-build-test.sh
+# 3. Run scripts/lcov.sh to generate an HTML report.
lcov:
- rm -rf Coverage
- lcov --capture --initial --directory library -o files.info
- lcov --rc lcov_branch_coverage=1 --capture --directory library -o tests.info
- lcov --rc lcov_branch_coverage=1 --add-tracefile files.info --add-tracefile tests.info -o all.info
- lcov --rc lcov_branch_coverage=1 --remove all.info -o final.info '*.h'
- gendesc tests/Descriptions.txt -o descriptions
- genhtml --title "mbed TLS" --description-file descriptions --keep-descriptions --legend --branch-coverage -o Coverage final.info
- rm -f files.info tests.info all.info final.info descriptions
+ scripts/lcov.sh
apidoc:
mkdir -p apidoc
diff --git a/doxygen/input/doc_mainpage.h b/doxygen/input/doc_mainpage.h
index e454a19..54b2f7a 100644
--- a/doxygen/input/doc_mainpage.h
+++ b/doxygen/input/doc_mainpage.h
@@ -22,7 +22,7 @@
*/
/**
- * @mainpage mbed TLS v2.28.1 source code documentation
+ * @mainpage mbed TLS v2.28.2 source code documentation
*
* This documentation describes the internal structure of mbed TLS. It was
* automatically generated from specially formatted comment blocks in
diff --git a/doxygen/mbedtls.doxyfile b/doxygen/mbedtls.doxyfile
index f180081..7c4f31c 100644
--- a/doxygen/mbedtls.doxyfile
+++ b/doxygen/mbedtls.doxyfile
@@ -1,4 +1,4 @@
-PROJECT_NAME = "mbed TLS v2.28.1"
+PROJECT_NAME = "mbed TLS v2.28.2"
OUTPUT_DIRECTORY = ../apidoc/
FULL_PATH_NAMES = NO
OPTIMIZE_OUTPUT_FOR_C = YES
diff --git a/include/mbedtls/check_config.h b/include/mbedtls/check_config.h
index 25df257..2ab9982 100644
--- a/include/mbedtls/check_config.h
+++ b/include/mbedtls/check_config.h
@@ -28,6 +28,7 @@
#ifndef MBEDTLS_CHECK_CONFIG_H
#define MBEDTLS_CHECK_CONFIG_H
+/* *INDENT-OFF* */
/*
* 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.
@@ -960,4 +961,5 @@
*/
typedef int mbedtls_iso_c_forbids_empty_translation_units;
+/* *INDENT-ON* */
#endif /* MBEDTLS_CHECK_CONFIG_H */
diff --git a/include/mbedtls/cipher.h b/include/mbedtls/cipher.h
index 6d83da8..ce100d3 100644
--- a/include/mbedtls/cipher.h
+++ b/include/mbedtls/cipher.h
@@ -917,13 +917,13 @@
* parameter-verification failure.
* \return A cipher-specific error code on failure.
*/
-int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
- const unsigned char *iv, size_t iv_len,
- const unsigned char *ad, size_t ad_len,
- const unsigned char *input, size_t ilen,
- unsigned char *output, size_t *olen,
- unsigned char *tag, size_t tag_len )
- MBEDTLS_DEPRECATED;
+int MBEDTLS_DEPRECATED mbedtls_cipher_auth_encrypt(
+ mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t *olen,
+ unsigned char *tag, size_t tag_len );
/**
* \brief The generic authenticated decryption (AEAD) function.
@@ -976,13 +976,13 @@
* \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic.
* \return A cipher-specific error code on failure.
*/
-int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
- const unsigned char *iv, size_t iv_len,
- const unsigned char *ad, size_t ad_len,
- const unsigned char *input, size_t ilen,
- unsigned char *output, size_t *olen,
- const unsigned char *tag, size_t tag_len )
- MBEDTLS_DEPRECATED;
+int MBEDTLS_DEPRECATED mbedtls_cipher_auth_decrypt(
+ mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t *olen,
+ const unsigned char *tag, size_t tag_len );
#undef MBEDTLS_DEPRECATED
#endif /* MBEDTLS_DEPRECATED_REMOVED */
#endif /* MBEDTLS_CIPHER_MODE_AEAD */
diff --git a/include/mbedtls/ssl_internal.h b/include/mbedtls/ssl_internal.h
index 46ade67..77ad755 100644
--- a/include/mbedtls/ssl_internal.h
+++ b/include/mbedtls/ssl_internal.h
@@ -782,7 +782,7 @@
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
uint8_t in_cid_len;
uint8_t out_cid_len;
- unsigned char in_cid [ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
+ unsigned char in_cid [ MBEDTLS_SSL_CID_IN_LEN_MAX ];
unsigned char out_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ];
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
diff --git a/include/mbedtls/version.h b/include/mbedtls/version.h
index 44adcbf..b3b441d 100644
--- a/include/mbedtls/version.h
+++ b/include/mbedtls/version.h
@@ -38,16 +38,16 @@
*/
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 28
-#define MBEDTLS_VERSION_PATCH 1
+#define MBEDTLS_VERSION_PATCH 2
/**
* The single version number has the following structure:
* MMNNPP00
* Major version | Minor version | Patch version
*/
-#define MBEDTLS_VERSION_NUMBER 0x021C0100
-#define MBEDTLS_VERSION_STRING "2.28.1"
-#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.28.1"
+#define MBEDTLS_VERSION_NUMBER 0x021C0200
+#define MBEDTLS_VERSION_STRING "2.28.2"
+#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.28.2"
#if defined(MBEDTLS_VERSION_C)
diff --git a/include/psa/crypto.h b/include/psa/crypto.h
index faa3b9e..b75947c 100644
--- a/include/psa/crypto.h
+++ b/include/psa/crypto.h
@@ -2861,7 +2861,7 @@
*
* \note To perform a multi-part hash-and-sign signature algorithm, first use
* a multi-part hash operation and then pass the resulting hash to
- * psa_sign_hash(). PSA_ALG_GET_HASH(\p alg) can be used to determine the
+ * psa_sign_hash(). PSA_ALG_SIGN_GET_HASH(\p alg) can be used to determine the
* hash algorithm to use.
*
* \param[in] key Identifier of the key to use for the operation.
@@ -2927,7 +2927,7 @@
* \note To perform a multi-part hash-and-sign signature verification
* algorithm, first use a multi-part hash operation to hash the message
* and then pass the resulting hash to psa_verify_hash().
- * PSA_ALG_GET_HASH(\p alg) can be used to determine the hash algorithm
+ * PSA_ALG_SIGN_GET_HASH(\p alg) can be used to determine the hash algorithm
* to use.
*
* \param[in] key Identifier of the key to use for the operation.
diff --git a/include/psa/crypto_values.h b/include/psa/crypto_values.h
index a4b4927..4df4fe4 100644
--- a/include/psa/crypto_values.h
+++ b/include/psa/crypto_values.h
@@ -1690,7 +1690,7 @@
#define PSA_ALG_HKDF_BASE ((psa_algorithm_t)0x08000100)
/** Macro to build an HKDF algorithm.
*
- * For example, `PSA_ALG_HKDF(PSA_ALG_SHA256)` is HKDF using HMAC-SHA-256.
+ * For example, `PSA_ALG_HKDF(PSA_ALG_SHA_256)` is HKDF using HMAC-SHA-256.
*
* This key derivation algorithm uses the following inputs:
* - #PSA_KEY_DERIVATION_INPUT_SALT is the salt used in the "extract" step.
@@ -1743,7 +1743,7 @@
* concatenation of ServerHello.Random + ClientHello.Random,
* and the label is "key expansion".
*
- * For example, `PSA_ALG_TLS12_PRF(PSA_ALG_SHA256)` represents the
+ * For example, `PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256)` represents the
* TLS 1.2 PRF using HMAC-SHA-256.
*
* \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
@@ -1789,7 +1789,7 @@
* ClientHello.Random + ServerHello.Random,
* and the label is "master secret" or "extended master secret".
*
- * For example, `PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA256)` represents the
+ * For example, `PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256)` represents the
* TLS-1.2 PSK to MasterSecret derivation PRF using HMAC-SHA-256.
*
* \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index fb0b5e1..fd3a3e7 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -204,15 +204,15 @@
if(USE_SHARED_MBEDTLS_LIBRARY)
set(CMAKE_LIBRARY_PATH ${CMAKE_CURRENT_BINARY_DIR})
add_library(${mbedcrypto_target} SHARED ${src_crypto})
- set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 2.28.1 SOVERSION 7)
+ set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 2.28.2 SOVERSION 7)
target_link_libraries(${mbedcrypto_target} PUBLIC ${libs})
add_library(${mbedx509_target} SHARED ${src_x509})
- set_target_properties(${mbedx509_target} PROPERTIES VERSION 2.28.1 SOVERSION 1)
+ set_target_properties(${mbedx509_target} PROPERTIES VERSION 2.28.2 SOVERSION 1)
target_link_libraries(${mbedx509_target} PUBLIC ${libs} ${mbedcrypto_target})
add_library(${mbedtls_target} SHARED ${src_tls})
- set_target_properties(${mbedtls_target} PROPERTIES VERSION 2.28.1 SOVERSION 14)
+ set_target_properties(${mbedtls_target} PROPERTIES VERSION 2.28.2 SOVERSION 14)
target_link_libraries(${mbedtls_target} PUBLIC ${libs} ${mbedx509_target})
endif(USE_SHARED_MBEDTLS_LIBRARY)
diff --git a/library/bignum.c b/library/bignum.c
index 7b851ca..37193f5 100644
--- a/library/bignum.c
+++ b/library/bignum.c
@@ -2005,11 +2005,11 @@
mbedtls_mpi *prec_RR )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
- size_t wbits, wsize, one = 1;
+ size_t window_bitsize;
size_t i, j, nblimbs;
size_t bufsize, nbits;
mbedtls_mpi_uint ei, mm, state;
- mbedtls_mpi RR, T, W[ 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
+ mbedtls_mpi RR, T, W[ (size_t) 1 << MBEDTLS_MPI_WINDOW_SIZE ], WW, Apos;
int neg;
MPI_VALIDATE_RET( X != NULL );
@@ -2038,21 +2038,59 @@
i = mbedtls_mpi_bitlen( E );
- wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
+ window_bitsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
#if( MBEDTLS_MPI_WINDOW_SIZE < 6 )
- if( wsize > MBEDTLS_MPI_WINDOW_SIZE )
- wsize = MBEDTLS_MPI_WINDOW_SIZE;
+ if( window_bitsize > MBEDTLS_MPI_WINDOW_SIZE )
+ window_bitsize = MBEDTLS_MPI_WINDOW_SIZE;
#endif
+ const size_t w_table_used_size = (size_t) 1 << window_bitsize;
+
+ /*
+ * This function is not constant-trace: its memory accesses depend on the
+ * exponent value. To defend against timing attacks, callers (such as RSA
+ * and DHM) should use exponent blinding. However this is not enough if the
+ * adversary can find the exponent in a single trace, so this function
+ * takes extra precautions against adversaries who can observe memory
+ * access patterns.
+ *
+ * This function performs a series of multiplications by table elements and
+ * squarings, and we want the prevent the adversary from finding out which
+ * table element was used, and from distinguishing between multiplications
+ * and squarings. Firstly, when multiplying by an element of the window
+ * W[i], we do a constant-trace table lookup to obfuscate i. This leaves
+ * squarings as having a different memory access patterns from other
+ * multiplications. So secondly, we put the accumulator X in the table as
+ * well, and also do a constant-trace table lookup to multiply by X.
+ *
+ * This way, all multiplications take the form of a lookup-and-multiply.
+ * The number of lookup-and-multiply operations inside each iteration of
+ * the main loop still depends on the bits of the exponent, but since the
+ * other operations in the loop don't have an easily recognizable memory
+ * trace, an adversary is unlikely to be able to observe the exact
+ * patterns.
+ *
+ * An adversary may still be able to recover the exponent if they can
+ * observe both memory accesses and branches. However, branch prediction
+ * exploitation typically requires many traces of execution over the same
+ * data, which is defeated by randomized blinding.
+ *
+ * To achieve this, we make a copy of X and we use the table entry in each
+ * calculation from this point on.
+ */
+ const size_t x_index = 0;
+ mbedtls_mpi_init( &W[x_index] );
+ mbedtls_mpi_copy( &W[x_index], X );
+
j = N->n + 1;
/* All W[i] and X must have at least N->n limbs for the mpi_montmul()
* and mpi_montred() calls later. Here we ensure that W[1] and X are
* large enough, and later we'll grow other W[i] to the same length.
* They must not be shrunk midway through this function!
*/
- MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, j ) );
+ MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[x_index], j ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[1], j ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &T, j * 2 ) );
@@ -2101,28 +2139,36 @@
mpi_montmul( &W[1], &RR, N, mm, &T );
/*
- * X = R^2 * R^-1 mod N = R mod N
+ * W[x_index] = R^2 * R^-1 mod N = R mod N
*/
- MBEDTLS_MPI_CHK( mbedtls_mpi_copy( X, &RR ) );
- mpi_montred( X, N, mm, &T );
+ MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[x_index], &RR ) );
+ mpi_montred( &W[x_index], N, mm, &T );
- if( wsize > 1 )
+
+ if( window_bitsize > 1 )
{
/*
- * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
+ * W[i] = W[1] ^ i
+ *
+ * The first bit of the sliding window is always 1 and therefore we
+ * only need to store the second half of the table.
+ *
+ * (There are two special elements in the table: W[0] for the
+ * accumulator/result and W[1] for A in Montgomery form. Both of these
+ * are already set at this point.)
*/
- j = one << ( wsize - 1 );
+ j = w_table_used_size / 2;
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[j], N->n + 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[j], &W[1] ) );
- for( i = 0; i < wsize - 1; i++ )
+ for( i = 0; i < window_bitsize - 1; i++ )
mpi_montmul( &W[j], &W[j], N, mm, &T );
/*
* W[i] = W[i - 1] * W[1]
*/
- for( i = j + 1; i < ( one << wsize ); i++ )
+ for( i = j + 1; i < w_table_used_size; i++ )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( &W[i], N->n + 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &W[i], &W[i - 1] ) );
@@ -2134,7 +2180,7 @@
nblimbs = E->n;
bufsize = 0;
nbits = 0;
- wbits = 0;
+ size_t exponent_bits_in_window = 0;
state = 0;
while( 1 )
@@ -2162,9 +2208,10 @@
if( ei == 0 && state == 1 )
{
/*
- * out of window, square X
+ * out of window, square W[x_index]
*/
- mpi_montmul( X, X, N, mm, &T );
+ MBEDTLS_MPI_CHK( mpi_select( &WW, W, w_table_used_size, x_index ) );
+ mpi_montmul( &W[x_index], &WW, N, mm, &T );
continue;
}
@@ -2174,25 +2221,30 @@
state = 2;
nbits++;
- wbits |= ( ei << ( wsize - nbits ) );
+ exponent_bits_in_window |= ( ei << ( window_bitsize - nbits ) );
- if( nbits == wsize )
+ if( nbits == window_bitsize )
{
/*
- * X = X^wsize R^-1 mod N
+ * W[x_index] = W[x_index]^window_bitsize R^-1 mod N
*/
- for( i = 0; i < wsize; i++ )
- mpi_montmul( X, X, N, mm, &T );
+ for( i = 0; i < window_bitsize; i++ )
+ {
+ MBEDTLS_MPI_CHK( mpi_select( &WW, W, w_table_used_size,
+ x_index ) );
+ mpi_montmul( &W[x_index], &WW, N, mm, &T );
+ }
/*
- * X = X * W[wbits] R^-1 mod N
+ * W[x_index] = W[x_index] * W[exponent_bits_in_window] R^-1 mod N
*/
- MBEDTLS_MPI_CHK( mpi_select( &WW, W, (size_t) 1 << wsize, wbits ) );
- mpi_montmul( X, &WW, N, mm, &T );
+ MBEDTLS_MPI_CHK( mpi_select( &WW, W, w_table_used_size,
+ exponent_bits_in_window ) );
+ mpi_montmul( &W[x_index], &WW, N, mm, &T );
state--;
nbits = 0;
- wbits = 0;
+ exponent_bits_in_window = 0;
}
}
@@ -2201,31 +2253,45 @@
*/
for( i = 0; i < nbits; i++ )
{
- mpi_montmul( X, X, N, mm, &T );
+ MBEDTLS_MPI_CHK( mpi_select( &WW, W, w_table_used_size, x_index ) );
+ mpi_montmul( &W[x_index], &WW, N, mm, &T );
- wbits <<= 1;
+ exponent_bits_in_window <<= 1;
- if( ( wbits & ( one << wsize ) ) != 0 )
- mpi_montmul( X, &W[1], N, mm, &T );
+ if( ( exponent_bits_in_window & ( (size_t) 1 << window_bitsize ) ) != 0 )
+ {
+ MBEDTLS_MPI_CHK( mpi_select( &WW, W, w_table_used_size, 1 ) );
+ mpi_montmul( &W[x_index], &WW, N, mm, &T );
+ }
}
/*
- * X = A^E * R * R^-1 mod N = A^E mod N
+ * W[x_index] = A^E * R * R^-1 mod N = A^E mod N
*/
- mpi_montred( X, N, mm, &T );
+ mpi_montred( &W[x_index], N, mm, &T );
if( neg && E->n != 0 && ( E->p[0] & 1 ) != 0 )
{
- X->s = -1;
- MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, N, X ) );
+ W[x_index].s = -1;
+ MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &W[x_index], N, &W[x_index] ) );
}
+ /*
+ * Load the result in the output variable.
+ */
+ mbedtls_mpi_copy( X, &W[x_index] );
+
cleanup:
- for( i = ( one << ( wsize - 1 ) ); i < ( one << wsize ); i++ )
+ /* The first bit of the sliding window is always 1 and therefore the first
+ * half of the table was unused. */
+ for( i = w_table_used_size/2; i < w_table_used_size; i++ )
mbedtls_mpi_free( &W[i] );
- mbedtls_mpi_free( &W[1] ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &Apos );
+ mbedtls_mpi_free( &W[x_index] );
+ mbedtls_mpi_free( &W[1] );
+ mbedtls_mpi_free( &T );
+ mbedtls_mpi_free( &Apos );
mbedtls_mpi_free( &WW );
if( prec_RR == NULL || prec_RR->p == NULL )
diff --git a/library/entropy.c b/library/entropy.c
index e3b337f..77e2bfd 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -590,7 +590,7 @@
}
/*
- * A test to ensure hat the entropy sources are functioning correctly
+ * A test to ensure that the entropy sources are functioning correctly
* and there is no obvious failure. The test performs the following checks:
* - The entropy source is not providing only 0s (all bits unset) or 1s (all
* bits set).
diff --git a/library/psa_crypto_aead.h b/library/psa_crypto_aead.h
index aab0f83..e18e85d 100644
--- a/library/psa_crypto_aead.h
+++ b/library/psa_crypto_aead.h
@@ -148,4 +148,4 @@
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length );
-#endif /* PSA_CRYPTO_AEAD */
+#endif /* PSA_CRYPTO_AEAD_H */
diff --git a/library/psa_crypto_driver_wrappers.c b/library/psa_crypto_driver_wrappers.c
index c455ecb..c9b86fe 100644
--- a/library/psa_crypto_driver_wrappers.c
+++ b/library/psa_crypto_driver_wrappers.c
@@ -275,7 +275,7 @@
alg, hash, hash_length,
signature, signature_size, signature_length ) );
}
-#endif /* PSA_CRYPTO_SE_C */
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_location_t location =
@@ -359,7 +359,7 @@
alg, hash, hash_length,
signature, signature_length ) );
}
-#endif /* PSA_CRYPTO_SE_C */
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_location_t location =
@@ -579,7 +579,7 @@
return( PSA_SUCCESS );
}
-#endif /* PSA_CRYPTO_SE_C */
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
switch( location )
{
@@ -641,7 +641,7 @@
*( (psa_key_slot_number_t *)key_buffer ),
data, data_size, data_length ) );
}
-#endif /* PSA_CRYPTO_SE_C */
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
switch( location )
{
diff --git a/library/psa_crypto_its.h b/library/psa_crypto_its.h
index 3a3f49a..1b8dc20 100644
--- a/library/psa_crypto_its.h
+++ b/library/psa_crypto_its.h
@@ -73,7 +73,7 @@
* \return A status indicating the success/failure of the operation
*
* \retval #PSA_SUCCESS The operation completed successfully
- * \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided `uid` value was already created with PSA_STORAGE_WRITE_ONCE_FLAG
+ * \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided `uid` value was already created with PSA_STORAGE_FLAG_WRITE_ONCE
* \retval #PSA_ERROR_NOT_SUPPORTED The operation failed because one or more of the flags provided in `create_flags` is not supported or is not valid
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE The operation failed because there was insufficient space on the storage medium
* \retval #PSA_ERROR_STORAGE_FAILURE The operation failed because the physical storage has failed (Fatal error)
@@ -137,7 +137,7 @@
*
* \retval #PSA_SUCCESS The operation completed successfully
* \retval #PSA_ERROR_DOES_NOT_EXIST The operation failed because the provided key value was not found in the storage
- * \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided key value was created with PSA_STORAGE_WRITE_ONCE_FLAG
+ * \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided key value was created with PSA_STORAGE_FLAG_WRITE_ONCE
* \retval #PSA_ERROR_STORAGE_FAILURE The operation failed because the physical storage has failed (Fatal error)
*/
psa_status_t psa_its_remove(psa_storage_uid_t uid);
diff --git a/library/ssl_srv.c b/library/ssl_srv.c
index 0563c0b..8efccce 100644
--- a/library/ssl_srv.c
+++ b/library/ssl_srv.c
@@ -1363,10 +1363,6 @@
#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
for( i = 0; ciphersuites[i] != 0; i++ )
-#else
- for( i = 0; ciphersuites[i] != 0; i++ )
- for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
-#endif
{
if( p[0] != 0 ||
MBEDTLS_GET_UINT16_BE(p, 1) != ciphersuites[i] )
@@ -1381,6 +1377,24 @@
if( ciphersuite_info != NULL )
goto have_ciphersuite_v2;
}
+#else
+ for( i = 0; ciphersuites[i] != 0; i++ )
+ for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
+ {
+ if( p[0] != 0 ||
+ MBEDTLS_GET_UINT16_BE(p, 1) != ciphersuites[i] )
+ continue;
+
+ got_common_suite = 1;
+
+ if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
+ &ciphersuite_info ) ) != 0 )
+ return( ret );
+
+ if( ciphersuite_info != NULL )
+ goto have_ciphersuite_v2;
+ }
+#endif
if( got_common_suite )
{
@@ -2233,10 +2247,6 @@
#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
for( i = 0; ciphersuites[i] != 0; i++ )
-#else
- for( i = 0; ciphersuites[i] != 0; i++ )
- for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
-#endif
{
if( MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i] )
continue;
@@ -2250,6 +2260,23 @@
if( ciphersuite_info != NULL )
goto have_ciphersuite;
}
+#else
+ for( i = 0; ciphersuites[i] != 0; i++ )
+ for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
+ {
+ if( MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i] )
+ continue;
+
+ got_common_suite = 1;
+
+ if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
+ &ciphersuite_info ) ) != 0 )
+ return( ret );
+
+ if( ciphersuite_info != NULL )
+ goto have_ciphersuite;
+ }
+#endif
if( got_common_suite )
{
diff --git a/programs/fuzz/Makefile b/programs/fuzz/Makefile
index 084fc24..0eb2baf 100644
--- a/programs/fuzz/Makefile
+++ b/programs/fuzz/Makefile
@@ -1,7 +1,9 @@
MBEDTLS_TEST_PATH:=../../tests/src
MBEDTLS_TEST_OBJS:=$(patsubst %.c,%.o,$(wildcard ${MBEDTLS_TEST_PATH}/*.c ${MBEDTLS_TEST_PATH}/drivers/*.c))
-LOCAL_CFLAGS = -I../../tests/include -I../../include -D_FILE_OFFSET_BITS=64
+CFLAGS ?= -O2
+WARNING_CFLAGS ?= -Wall -Wextra
+LOCAL_CFLAGS = $(WARNING_CFLAGS) -I../../tests/include -I../../include -D_FILE_OFFSET_BITS=64
LOCAL_LDFLAGS = ${MBEDTLS_TEST_OBJS} \
-L../../library \
-lmbedtls$(SHARED_SUFFIX) \
diff --git a/programs/psa/key_ladder_demo.c b/programs/psa/key_ladder_demo.c
index 5d64349..bc1cd12 100644
--- a/programs/psa/key_ladder_demo.c
+++ b/programs/psa/key_ladder_demo.c
@@ -704,4 +704,6 @@
usage( );
return( EXIT_FAILURE );
}
-#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */
+#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C &&
+ MBEDTLS_AES_C && MBEDTLS_CCM_C &&
+ MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */
diff --git a/scripts/code_style.py b/scripts/code_style.py
new file mode 100755
index 0000000..68cd556
--- /dev/null
+++ b/scripts/code_style.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""Check or fix the code style by running Uncrustify.
+
+Note: The code style enforced by this script is not yet introduced to
+Mbed TLS. At present this script will only be used to prepare for a future
+change of code style.
+"""
+# Copyright The Mbed TLS Contributors
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import argparse
+import io
+import os
+import subprocess
+import sys
+from typing import List
+
+UNCRUSTIFY_SUPPORTED_VERSION = "0.75.1"
+CONFIG_FILE = ".uncrustify.cfg"
+UNCRUSTIFY_EXE = "uncrustify"
+UNCRUSTIFY_ARGS = ["-c", CONFIG_FILE]
+STDOUT_UTF8 = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
+STDERR_UTF8 = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
+
+def print_err(*args):
+ print("Error: ", *args, file=STDERR_UTF8)
+
+def get_src_files() -> List[str]:
+ """
+ Use git ls-files to get a list of the source files
+ """
+ git_ls_files_cmd = ["git", "ls-files",
+ "*.[hc]",
+ "tests/suites/*.function",
+ "scripts/data_files/*.fmt"]
+
+ result = subprocess.run(git_ls_files_cmd, stdout=subprocess.PIPE, \
+ stderr=STDERR_UTF8, check=False)
+
+ if result.returncode != 0:
+ print_err("git ls-files returned: " + str(result.returncode))
+ return []
+ else:
+ src_files = str(result.stdout, "utf-8").split()
+ # Don't correct style for files in 3rdparty/
+ src_files = list(filter( \
+ lambda filename: not filename.startswith("3rdparty/"), \
+ src_files))
+ return src_files
+
+def get_uncrustify_version() -> str:
+ """
+ Get the version string from Uncrustify
+ """
+ result = subprocess.run([UNCRUSTIFY_EXE, "--version"], \
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
+ if result.returncode != 0:
+ print_err("Could not get Uncrustify version:", str(result.stderr, "utf-8"))
+ return ""
+ else:
+ return str(result.stdout, "utf-8")
+
+def check_style_is_correct(src_file_list: List[str]) -> bool:
+ """
+ Check the code style and output a diff for each file whose style is
+ incorrect.
+ """
+ style_correct = True
+ for src_file in src_file_list:
+ uncrustify_cmd = [UNCRUSTIFY_EXE] + UNCRUSTIFY_ARGS + [src_file]
+ subprocess.run(uncrustify_cmd, stdout=subprocess.PIPE, \
+ stderr=subprocess.PIPE, check=False)
+
+ # Uncrustify makes changes to the code and places the result in a new
+ # file with the extension ".uncrustify". To get the changes (if any)
+ # simply diff the 2 files.
+ diff_cmd = ["diff", "-u", src_file, src_file + ".uncrustify"]
+ result = subprocess.run(diff_cmd, stdout=subprocess.PIPE, \
+ stderr=STDERR_UTF8, check=False)
+ if len(result.stdout) > 0:
+ print(src_file + " - Incorrect code style.", file=STDOUT_UTF8)
+ print("File changed - diff:", file=STDOUT_UTF8)
+ print(str(result.stdout, "utf-8"), file=STDOUT_UTF8)
+ style_correct = False
+ else:
+ print(src_file + " - OK.", file=STDOUT_UTF8)
+
+ # Tidy up artifact
+ os.remove(src_file + ".uncrustify")
+
+ return style_correct
+
+def fix_style_single_pass(src_file_list: List[str]) -> None:
+ """
+ Run Uncrustify once over the source files.
+ """
+ code_change_args = UNCRUSTIFY_ARGS + ["--no-backup"]
+ for src_file in src_file_list:
+ uncrustify_cmd = [UNCRUSTIFY_EXE] + code_change_args + [src_file]
+ subprocess.run(uncrustify_cmd, check=False, stdout=STDOUT_UTF8, \
+ stderr=STDERR_UTF8)
+
+def fix_style(src_file_list: List[str]) -> int:
+ """
+ Fix the code style. This takes 2 passes of Uncrustify.
+ """
+ fix_style_single_pass(src_file_list)
+ fix_style_single_pass(src_file_list)
+
+ # Guard against future changes that cause the codebase to require
+ # more passes.
+ if not check_style_is_correct(src_file_list):
+ print("Code style still incorrect after second run of Uncrustify.")
+ return 1
+ else:
+ return 0
+
+def main() -> int:
+ """
+ Main with command line arguments.
+ """
+ uncrustify_version = get_uncrustify_version().strip()
+ if UNCRUSTIFY_SUPPORTED_VERSION not in uncrustify_version:
+ print("Warning: Using unsupported Uncrustify version '" \
+ + uncrustify_version + "' (Note: The only supported version" \
+ "is " + UNCRUSTIFY_SUPPORTED_VERSION + ")", file=STDOUT_UTF8)
+
+ src_files = get_src_files()
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument('-f', '--fix', action='store_true', \
+ help='modify source files to fix the code style')
+
+ args = parser.parse_args()
+
+ if args.fix:
+ # Fix mode
+ return fix_style(src_files)
+ else:
+ # Check mode
+ if check_style_is_correct(src_files):
+ return 0
+ else:
+ return 1
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/lcov.sh b/scripts/lcov.sh
new file mode 100755
index 0000000..8d141ee
--- /dev/null
+++ b/scripts/lcov.sh
@@ -0,0 +1,81 @@
+#!/bin/sh
+
+help () {
+ cat <<EOF
+Usage: $0 [-r]
+Collect coverage statistics of library code into an HTML report.
+
+General instructions:
+1. Build the library with CFLAGS="--coverage -O0 -g3" and link the test
+ programs with LDFLAGS="--coverage".
+ This can be an out-of-tree build.
+ For example (in-tree):
+ make CFLAGS="--coverage -O0 -g3" LDFLAGS="--coverage"
+ Or (out-of-tree):
+ mkdir build-coverage && cd build-coverage &&
+ cmake -D CMAKE_BUILD_TYPE=Coverage .. && make
+2. Run whatever tests you want.
+3. Run this script from the parent of the directory containing the library
+ object files and coverage statistics files.
+4. Browse the coverage report in Coverage/index.html.
+5. After rework, run "$0 -r", then re-test and run "$0" to get a fresh report.
+
+Options
+ -r Reset traces. Run this before re-testing to get fresh measurements.
+EOF
+}
+
+# Copyright The Mbed TLS Contributors
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+set -eu
+
+# Collect stats and build a HTML report.
+lcov_library_report () {
+ rm -rf Coverage
+ mkdir Coverage Coverage/tmp
+ lcov --capture --initial --directory library -o Coverage/tmp/files.info
+ lcov --rc lcov_branch_coverage=1 --capture --directory library -o Coverage/tmp/tests.info
+ lcov --rc lcov_branch_coverage=1 --add-tracefile Coverage/tmp/files.info --add-tracefile Coverage/tmp/tests.info -o Coverage/tmp/all.info
+ lcov --rc lcov_branch_coverage=1 --remove Coverage/tmp/all.info -o Coverage/tmp/final.info '*.h'
+ gendesc tests/Descriptions.txt -o Coverage/tmp/descriptions
+ genhtml --title "mbed TLS" --description-file Coverage/tmp/descriptions --keep-descriptions --legend --branch-coverage -o Coverage Coverage/tmp/final.info
+ rm -f Coverage/tmp/*.info Coverage/tmp/descriptions
+ echo "Coverage report in: Coverage/index.html"
+}
+
+# Reset the traces to 0.
+lcov_reset_traces () {
+ # Location with plain make
+ rm -f library/*.gcda
+ # Location with CMake
+ rm -f library/CMakeFiles/*.dir/*.gcda
+}
+
+if [ $# -gt 0 ] && [ "$1" = "--help" ]; then
+ help
+ exit
+fi
+
+main=lcov_library_report
+while getopts r OPTLET; do
+ case $OPTLET in
+ r) main=lcov_reset_traces;;
+ *) help 2>&1; exit 120;;
+ esac
+done
+shift $((OPTIND - 1))
+
+"$main" "$@"
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index bc02627..ca477ac 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -97,6 +97,7 @@
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/seedfile")
link_to_source(seedfile)
endif()
+ link_to_source(Descriptions.txt)
link_to_source(compat.sh)
link_to_source(context-info.sh)
link_to_source(data_files)
diff --git a/tests/Makefile b/tests/Makefile
index 6e232c9..44ff43c 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -108,6 +108,7 @@
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
C_FILES := $(addsuffix .c,$(APPS))
+c: $(C_FILES)
# Wildcard target for test code generation:
# A .c file is generated for each .data file in the suites/ directory. Each .c
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index 3426cf1..ba37e33 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -185,7 +185,8 @@
export CTEST_OUTPUT_ON_FAILURE=1
# CFLAGS and LDFLAGS for Asan builds that don't use CMake
- ASAN_CFLAGS='-Werror -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=all'
+ # default to -O2, use -Ox _after_ this if you want another level
+ ASAN_CFLAGS='-O2 -Werror -fsanitize=address,undefined -fno-sanitize-recover=all'
# Gather the list of available components. These are the functions
# defined in this script whose name starts with "component_".
@@ -3353,6 +3354,26 @@
[ "$ver_major" -eq 3 ] && [ "$ver_minor" -ge 10 ]
}
+component_test_corrected_code_style () {
+ ./scripts/code_style.py --fix
+
+ msg "build: make, default config (out-of-box), corrected code style"
+ make
+
+ msg "test: main suites make, default config (out-of-box), corrected code style"
+ make test
+
+ # Clean up code-style corrections
+ git checkout -- .
+}
+
+support_test_corrected_code_style() {
+ case $(uncrustify --version) in
+ *0.75.1*) true;;
+ *) false;;
+ esac
+}
+
component_check_python_files () {
msg "Lint: Python scripts"
tests/scripts/check-python-files.sh
diff --git a/tests/scripts/check_names.py b/tests/scripts/check_names.py
index 096da96..414ce43 100755
--- a/tests/scripts/check_names.py
+++ b/tests/scripts/check_names.py
@@ -36,7 +36,7 @@
declared in the header files. This uses the nm command.
- All macros, constants, and identifiers (function names, struct names, etc)
follow the required regex pattern.
-- Typo checking: All words that begin with MBED exist as macros or constants.
+- Typo checking: All words that begin with MBED|PSA exist as macros or constants.
The script returns 0 on success, 1 on test failure, and 2 if there is a script
error. It must be run from Mbed TLS root.
@@ -190,11 +190,12 @@
class Typo(Problem): # pylint: disable=too-few-public-methods
"""
- A problem that occurs when a word using MBED doesn't appear to be defined as
- constants nor enum values. Created with NameCheck.check_for_typos()
+ A problem that occurs when a word using MBED or PSA doesn't
+ appear to be defined as constants nor enum values. Created with
+ NameCheck.check_for_typos()
Fields:
- * match: the Match object of the MBED name in question.
+ * match: the Match object of the MBED|PSA name in question.
"""
def __init__(self, match):
self.match = match
@@ -252,9 +253,14 @@
"3rdparty/everest/include/everest/everest.h",
"3rdparty/everest/include/everest/x25519.h"
])
+ private_macros = self.parse_macros([
+ "library/*.c",
+ ])
enum_consts = self.parse_enum_consts([
"include/mbedtls/*.h",
+ "include/psa/*.h",
"library/*.h",
+ "library/*.c",
"3rdparty/everest/include/everest/everest.h",
"3rdparty/everest/include/everest/x25519.h"
])
@@ -265,7 +271,7 @@
"3rdparty/everest/include/everest/everest.h",
"3rdparty/everest/include/everest/x25519.h"
])
- mbed_words = self.parse_mbed_words([
+ mbed_psa_words = self.parse_mbed_psa_words([
"include/mbedtls/*.h",
"include/psa/*.h",
"library/*.h",
@@ -293,10 +299,11 @@
self.log.debug(" {:4} Exported Symbols".format(len(symbols)))
return {
"macros": actual_macros,
+ "private_macros": private_macros,
"enum_consts": enum_consts,
"identifiers": identifiers,
"symbols": symbols,
- "mbed_words": mbed_words
+ "mbed_psa_words": mbed_psa_words
}
def is_file_excluded(self, path, exclude_wildcards):
@@ -364,25 +371,28 @@
return macros
- def parse_mbed_words(self, include, exclude=None):
+ def parse_mbed_psa_words(self, include, exclude=None):
"""
- Parse all words in the file that begin with MBED, in and out of macros,
- comments, anything.
+ Parse all words in the file that begin with MBED|PSA, in and out of
+ macros, comments, anything.
Args:
* include: A List of glob expressions to look for files through.
* exclude: A List of glob expressions for excluding files.
- Returns a List of Match objects for words beginning with MBED.
+ Returns a List of Match objects for words beginning with MBED|PSA.
"""
# Typos of TLS are common, hence the broader check below than MBEDTLS.
- mbed_regex = re.compile(r"\bMBED.+?_[A-Z0-9_]*")
+ mbed_regex = re.compile(r"\b(MBED.+?|PSA)_[A-Z0-9_]*")
exclusions = re.compile(r"// *no-check-names|#error")
files = self.get_files(include, exclude)
- self.log.debug("Looking for MBED words in {} files".format(len(files)))
+ self.log.debug(
+ "Looking for MBED|PSA words in {} files"
+ .format(len(files))
+ )
- mbed_words = []
+ mbed_psa_words = []
for filename in files:
with open(filename, "r", encoding="utf-8") as fp:
for line_no, line in enumerate(fp):
@@ -390,14 +400,14 @@
continue
for name in mbed_regex.finditer(line):
- mbed_words.append(Match(
+ mbed_psa_words.append(Match(
filename,
line,
line_no,
name.span(0),
name.group(0)))
- return mbed_words
+ return mbed_psa_words
def parse_enum_consts(self, include, exclude=None):
"""
@@ -820,11 +830,15 @@
all_caps_names = {
match.name
for match
- in self.parse_result["macros"] + self.parse_result["enum_consts"]}
+ in self.parse_result["macros"] +
+ self.parse_result["private_macros"] +
+ self.parse_result["enum_consts"]
+ }
typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$|"
- r"MBEDTLS_TEST_LIBTESTDRIVER*")
+ r"MBEDTLS_TEST_LIBTESTDRIVER*|"
+ r"PSA_CRYPTO_DRIVER_TEST")
- for name_match in self.parse_result["mbed_words"]:
+ for name_match in self.parse_result["mbed_psa_words"]:
found = name_match.name in all_caps_names
# Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
diff --git a/tests/scripts/generate_test_code.py b/tests/scripts/generate_test_code.py
index 938f24c..f19d30b 100755
--- a/tests/scripts/generate_test_code.py
+++ b/tests/scripts/generate_test_code.py
@@ -220,25 +220,17 @@
:param file_name: File path to open.
"""
- super(FileWrapper, self).__init__(file_name, 'r')
+ super().__init__(file_name, 'r')
self._line_no = 0
- def next(self):
+ def __next__(self):
"""
- Python 2 iterator method. This method overrides base class's
- next method and extends the next method to count the line
- numbers as each line is read.
-
- It works for both Python 2 and Python 3 by checking iterator
- method name in the base iterator object.
+ This method overrides base class's __next__ method and extends it
+ method to count the line numbers as each line is read.
:return: Line read from file.
"""
- parent = super(FileWrapper, self)
- if hasattr(parent, '__next__'):
- line = parent.__next__() # Python 3
- else:
- line = parent.next() # Python 2 # pylint: disable=no-member
+ line = super().__next__()
if line is not None:
self._line_no += 1
# Convert byte array to string with correct encoding and
@@ -246,9 +238,6 @@
return line.decode(sys.getdefaultencoding()).rstrip() + '\n'
return None
- # Python 3 iterator method
- __next__ = next
-
def get_line_no(self):
"""
Gives current line number.
@@ -530,6 +519,50 @@
gen_dependencies(dependencies)
return preprocessor_check_start + code + preprocessor_check_end
+COMMENT_START_REGEX = re.compile(r'/[*/]')
+
+def skip_comments(line, stream):
+ """Remove comments in line.
+
+ If the line contains an unfinished comment, read more lines from stream
+ until the line that contains the comment.
+
+ :return: The original line with inner comments replaced by spaces.
+ Trailing comments and whitespace may be removed completely.
+ """
+ pos = 0
+ while True:
+ opening = COMMENT_START_REGEX.search(line, pos)
+ if not opening:
+ break
+ if line[opening.start(0) + 1] == '/': # //...
+ continuation = line
+ # Count the number of line breaks, to keep line numbers aligned
+ # in the output.
+ line_count = 1
+ while continuation.endswith('\\\n'):
+ # This errors out if the file ends with an unfinished line
+ # comment. That's acceptable to not complicate the code further.
+ continuation = next(stream)
+ line_count += 1
+ return line[:opening.start(0)].rstrip() + '\n' * line_count
+ # Parsing /*...*/, looking for the end
+ closing = line.find('*/', opening.end(0))
+ while closing == -1:
+ # This errors out if the file ends with an unfinished block
+ # comment. That's acceptable to not complicate the code further.
+ line += next(stream)
+ closing = line.find('*/', opening.end(0))
+ pos = closing + 2
+ # Replace inner comment by spaces. There needs to be at least one space
+ # for things like 'int/*ihatespaces*/foo'. Go further and preserve the
+ # width of the comment and line breaks, this way positions in error
+ # messages remain correct.
+ line = (line[:opening.start(0)] +
+ re.sub(r'.', r' ', line[opening.start(0):pos]) +
+ line[pos:])
+ # Strip whitespace at the end of lines (it's irrelevant to error messages).
+ return re.sub(r' +(\n|\Z)', r'\1', line)
def parse_function_code(funcs_f, dependencies, suite_dependencies):
"""
@@ -549,6 +582,7 @@
# across multiple lines. Here we try to find the start of
# arguments list, then remove '\n's and apply the regex to
# detect function start.
+ line = skip_comments(line, funcs_f)
up_to_arg_list_start = code + line[:line.find('(') + 1]
match = re.match(TEST_FUNCTION_VALIDATION_REGEX,
up_to_arg_list_start.replace('\n', ' '), re.I)
@@ -557,7 +591,7 @@
name = match.group('func_name')
if not re.match(FUNCTION_ARG_LIST_END_REGEX, line):
for lin in funcs_f:
- line += lin
+ line += skip_comments(lin, funcs_f)
if re.search(FUNCTION_ARG_LIST_END_REGEX, line):
break
args, local_vars, args_dispatch = parse_function_arguments(
diff --git a/tests/scripts/test_generate_test_code.py b/tests/scripts/test_generate_test_code.py
index 9bf66f1..d23d742 100755
--- a/tests/scripts/test_generate_test_code.py
+++ b/tests/scripts/test_generate_test_code.py
@@ -682,12 +682,12 @@
@patch("generate_test_code.gen_dependencies")
@patch("generate_test_code.gen_function_wrapper")
@patch("generate_test_code.parse_function_arguments")
- def test_functio_name_on_newline(self, parse_function_arguments_mock,
- gen_function_wrapper_mock,
- gen_dependencies_mock,
- gen_dispatch_mock):
+ def test_function_name_on_newline(self, parse_function_arguments_mock,
+ gen_function_wrapper_mock,
+ gen_dependencies_mock,
+ gen_dispatch_mock):
"""
- Test when exit label is present.
+ Test with line break before the function name.
:return:
"""
parse_function_arguments_mock.return_value = ([], '', [])
@@ -727,6 +727,194 @@
'''
self.assertEqual(code, expected)
+ @patch("generate_test_code.gen_dispatch")
+ @patch("generate_test_code.gen_dependencies")
+ @patch("generate_test_code.gen_function_wrapper")
+ @patch("generate_test_code.parse_function_arguments")
+ def test_case_starting_with_comment(self, parse_function_arguments_mock,
+ gen_function_wrapper_mock,
+ gen_dependencies_mock,
+ gen_dispatch_mock):
+ """
+ Test with comments before the function signature
+ :return:
+ """
+ parse_function_arguments_mock.return_value = ([], '', [])
+ gen_function_wrapper_mock.return_value = ''
+ gen_dependencies_mock.side_effect = gen_dependencies
+ gen_dispatch_mock.side_effect = gen_dispatch
+ data = '''/* comment */
+/* more
+ * comment */
+// this is\\
+still \\
+a comment
+void func()
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+/* END_CASE */
+'''
+ stream = StringIOWrapper('test_suite_ut.function', data)
+ _, _, code, _ = parse_function_code(stream, [], [])
+
+ expected = '''#line 1 "test_suite_ut.function"
+
+
+
+
+
+
+void test_func()
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+'''
+ self.assertEqual(code, expected)
+
+ @patch("generate_test_code.gen_dispatch")
+ @patch("generate_test_code.gen_dependencies")
+ @patch("generate_test_code.gen_function_wrapper")
+ @patch("generate_test_code.parse_function_arguments")
+ def test_comment_in_prototype(self, parse_function_arguments_mock,
+ gen_function_wrapper_mock,
+ gen_dependencies_mock,
+ gen_dispatch_mock):
+ """
+ Test with comments in the function prototype
+ :return:
+ """
+ parse_function_arguments_mock.return_value = ([], '', [])
+ gen_function_wrapper_mock.return_value = ''
+ gen_dependencies_mock.side_effect = gen_dependencies
+ gen_dispatch_mock.side_effect = gen_dispatch
+ data = '''
+void func( int x, // (line \\
+ comment)
+ int y /* lone closing parenthesis) */ )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+/* END_CASE */
+'''
+ stream = StringIOWrapper('test_suite_ut.function', data)
+ _, _, code, _ = parse_function_code(stream, [], [])
+
+ expected = '''#line 1 "test_suite_ut.function"
+
+void test_func( int x,
+
+ int y )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+'''
+ self.assertEqual(code, expected)
+
+ @patch("generate_test_code.gen_dispatch")
+ @patch("generate_test_code.gen_dependencies")
+ @patch("generate_test_code.gen_function_wrapper")
+ @patch("generate_test_code.parse_function_arguments")
+ def test_line_comment_in_block_comment(self, parse_function_arguments_mock,
+ gen_function_wrapper_mock,
+ gen_dependencies_mock,
+ gen_dispatch_mock):
+ """
+ Test with line comment in block comment.
+ :return:
+ """
+ parse_function_arguments_mock.return_value = ([], '', [])
+ gen_function_wrapper_mock.return_value = ''
+ gen_dependencies_mock.side_effect = gen_dependencies
+ gen_dispatch_mock.side_effect = gen_dispatch
+ data = '''
+void func( int x /* // */ )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+/* END_CASE */
+'''
+ stream = StringIOWrapper('test_suite_ut.function', data)
+ _, _, code, _ = parse_function_code(stream, [], [])
+
+ expected = '''#line 1 "test_suite_ut.function"
+
+void test_func( int x )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+'''
+ self.assertEqual(code, expected)
+
+ @patch("generate_test_code.gen_dispatch")
+ @patch("generate_test_code.gen_dependencies")
+ @patch("generate_test_code.gen_function_wrapper")
+ @patch("generate_test_code.parse_function_arguments")
+ def test_block_comment_in_line_comment(self, parse_function_arguments_mock,
+ gen_function_wrapper_mock,
+ gen_dependencies_mock,
+ gen_dispatch_mock):
+ """
+ Test with block comment in line comment.
+ :return:
+ """
+ parse_function_arguments_mock.return_value = ([], '', [])
+ gen_function_wrapper_mock.return_value = ''
+ gen_dependencies_mock.side_effect = gen_dependencies
+ gen_dispatch_mock.side_effect = gen_dispatch
+ data = '''
+// /*
+void func( int x )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+/* END_CASE */
+'''
+ stream = StringIOWrapper('test_suite_ut.function', data)
+ _, _, code, _ = parse_function_code(stream, [], [])
+
+ expected = '''#line 1 "test_suite_ut.function"
+
+
+void test_func( int x )
+{
+ ba ba black sheep
+ have you any wool
+exit:
+ yes sir yes sir
+ 3 bags full
+}
+'''
+ self.assertEqual(code, expected)
+
class ParseFunction(TestCase):
"""
diff --git a/tests/suites/test_suite_ecp.data b/tests/suites/test_suite_ecp.data
index 5277bc3..6211fb7 100644
--- a/tests/suites/test_suite_ecp.data
+++ b/tests/suites/test_suite_ecp.data
@@ -288,6 +288,58 @@
depends_on:MBEDTLS_ECP_DP_SECP521R1_ENABLED
ecp_tls_write_read_point:MBEDTLS_ECP_DP_SECP521R1
+Check ECP group metadata #1 secp192k1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP192K1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP192K1:192:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"fffffffffffffffffffffffffffffffffffffffeffffee37":"000000000000000000000000000000000000000000000000":"000000000000000000000000000000000000000000000003":"db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d":"9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d":"fffffffffffffffffffffffe26f2fc170f69466a74defd8d":18
+
+Check ECP group metadata #2 secp192r1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP192R1:192:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"fffffffffffffffffffffffffffffffeffffffffffffffff":"":"64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1":"188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012":"07192b95ffc8da78631011ed6b24cdd573f977a11e794811":"ffffffffffffffffffffffff99def836146bc9b1b4d22831":19
+
+Check ECP group metadata #3 secp224k1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP224K1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP224K1:224:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"fffffffffffffffffffffffffffffffffffffffffffffffeffffe56d":"00000000000000000000000000000000000000000000000000000000":"00000000000000000000000000000000000000000000000000000005":"a1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c":"7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5":"010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7":20
+
+Check ECP group metadata #4 secp224r1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP224R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP224R1:224:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"ffffffffffffffffffffffffffffffff000000000000000000000001":"":"b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4":"b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21":"bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34":"ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d":21
+
+Check ECP group metadata #5 secp256k1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP256K1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP256K1:256:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f":"0000000000000000000000000000000000000000000000000000000000000000":"0000000000000000000000000000000000000000000000000000000000000007":"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798":"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8":"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141":22
+
+Check ECP group metadata #6 secp256r1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP256R1:256:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff":"":"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b":"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296":"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5":"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551":23
+
+Check ECP group metadata #7 secp384r1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP384R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP384R1:384:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff":"":"b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef":"aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7":"3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f":"ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973":24
+
+Check ECP group metadata #8 secp521r1 (SEC 2)
+depends_on:MBEDTLS_ECP_DP_SECP521R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_SECP521R1:521:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff":"":"0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00":"00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66":"011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650":"01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409":25
+
+Check ECP group metadata #9 bp256r1 (RFC 5639)
+depends_on:MBEDTLS_ECP_DP_BP256R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_BP256R1:256:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377":"7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9":"26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6":"8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262":"547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997":"a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7":26
+
+Check ECP group metadata #10 bp384r1 (RFC 5639)
+depends_on:MBEDTLS_ECP_DP_BP384R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_BP384R1:384:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53":"7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826":"04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11":"1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e":"8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315":"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565":27
+
+Check ECP group metadata #11 bp512r1 (RFC 5639)
+depends_on:MBEDTLS_ECP_DP_BP512R1_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_BP512R1:512:MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS:"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3":"7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca":"3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723":"81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822":"7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892":"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069":28
+
+Check ECP group metadata #12 curve25519 (RFC 7748)
+depends_on:MBEDTLS_ECP_DP_CURVE25519_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_CURVE25519:256:MBEDTLS_ECP_TYPE_MONTGOMERY:"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed":"76d06":"":"9":"":"1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed":29
+
+Check ECP group metadata #13 curve448 (RFC 7748)
+depends_on:MBEDTLS_ECP_DP_CURVE448_ENABLED
+mbedtls_ecp_group_metadata:MBEDTLS_ECP_DP_CURVE448:448:MBEDTLS_ECP_TYPE_MONTGOMERY:"fffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff":"262a6":"":"5":"":"3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3":30
+
ECP tls read group #1 (record too short)
mbedtls_ecp_tls_read_group:"0313":MBEDTLS_ERR_ECP_BAD_INPUT_DATA:0:0
diff --git a/tests/suites/test_suite_ecp.function b/tests/suites/test_suite_ecp.function
index 7e9c6d2..0bce782 100644
--- a/tests/suites/test_suite_ecp.function
+++ b/tests/suites/test_suite_ecp.function
@@ -1,5 +1,7 @@
/* BEGIN_HEADER */
#include "mbedtls/ecp.h"
+#include "mbedtls/ecdsa.h"
+#include "mbedtls/ecdh.h"
#include "ecp_invasive.h"
@@ -16,6 +18,44 @@
mbedtls_ecp_point_free( x ); \
mbedtls_ecp_point_init( x );
+/* Auxiliary function to compare two mbedtls_ecp_group objects. */
+inline static int mbedtls_ecp_group_cmp( mbedtls_ecp_group *grp1,
+ mbedtls_ecp_group *grp2 )
+{
+ if( mbedtls_mpi_cmp_mpi( &grp1->P, &grp2->P ) != 0 )
+ return 1;
+ if( mbedtls_mpi_cmp_mpi( &grp1->A, &grp2->A ) != 0 )
+ return 1;
+ if( mbedtls_mpi_cmp_mpi( &grp1->B, &grp2->B ) != 0 )
+ return 1;
+ if( mbedtls_mpi_cmp_mpi( &grp1->N, &grp2->N ) != 0 )
+ return 1;
+ if( mbedtls_ecp_point_cmp( &grp1->G, &grp2->G ) != 0 )
+ return 1;
+ if( grp1->id != grp2->id )
+ return 1;
+ if( grp1->pbits != grp2->pbits )
+ return 1;
+ if( grp1->nbits != grp2->nbits )
+ return 1;
+ if( grp1->h != grp2->h )
+ return 1;
+ if( grp1->modp != grp2->modp )
+ return 1;
+ if( grp1->t_pre != grp2->t_pre )
+ return 1;
+ if( grp1->t_post != grp2->t_post )
+ return 1;
+ if( grp1->t_data != grp2->t_data )
+ return 1;
+ if( grp1->T_size != grp2->T_size )
+ return 1;
+ if( grp1->T != grp2->T )
+ return 1;
+
+ return 0;
+}
+
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@@ -1065,6 +1105,124 @@
}
/* END_CASE */
+/* BEGIN_CASE depends_on:MBEDTLS_ECDH_C:MBEDTLS_ECDSA_C */
+void mbedtls_ecp_group_metadata( int id, int bit_size, int crv_type,
+ char* P, char* A, char* B,
+ char* G_x, char* G_y, char* N,
+ int tls_id )
+{
+ mbedtls_ecp_group grp, grp_read, grp_cpy;
+ const mbedtls_ecp_group_id *g_id;
+ mbedtls_ecp_group_id read_g_id;
+ const mbedtls_ecp_curve_info *crv, *crv_tls_id, *crv_name;
+
+ mbedtls_mpi exp_P, exp_A, exp_B, exp_G_x, exp_G_y, exp_N;
+
+ unsigned char buf[3], ecparameters[3] = { 3, 0, tls_id };
+ const unsigned char *vbuf = buf;
+ size_t olen;
+
+ mbedtls_ecp_group_init( &grp );
+ mbedtls_ecp_group_init( &grp_read );
+ mbedtls_ecp_group_init( &grp_cpy );
+
+ mbedtls_mpi_init( &exp_P );
+ mbedtls_mpi_init( &exp_A );
+ mbedtls_mpi_init( &exp_B );
+ mbedtls_mpi_init( &exp_G_x );
+ mbedtls_mpi_init( &exp_G_y );
+ mbedtls_mpi_init( &exp_N );
+
+ // Read expected parameters
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_P, P ), 0 );
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_A, A ), 0 );
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_G_x, G_x ), 0 );
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_N, N ), 0 );
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_B, B ), 0 );
+ TEST_EQUAL( mbedtls_test_read_mpi( &exp_G_y, G_y ), 0 );
+
+ // Convert exp_A to internal representation (A+2)/4
+ if( crv_type == MBEDTLS_ECP_TYPE_MONTGOMERY )
+ {
+ TEST_EQUAL( mbedtls_mpi_add_int( &exp_A, &exp_A, 2 ), 0 );
+ TEST_EQUAL( mbedtls_mpi_div_int( &exp_A, NULL, &exp_A, 4 ), 0 );
+ }
+
+ // Load group
+ TEST_EQUAL( mbedtls_ecp_group_load( &grp, id ), 0 );
+
+ // Compare group with expected parameters
+ // A is NULL for SECPxxxR1 curves
+ // B and G_y are NULL for curve25519 and curve448
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_P, &grp.P ), 0 );
+ if( *A != 0 )
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_A, &grp.A ), 0 );
+ if( *B != 0 )
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_B, &grp.B ), 0 );
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_G_x, &grp.G.X ), 0 );
+ if( *G_y != 0 )
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_G_y, &grp.G.Y ), 0 );
+ TEST_EQUAL( mbedtls_mpi_cmp_mpi( &exp_N, &grp.N ), 0 );
+
+ // Load curve info and compare with known values
+ crv = mbedtls_ecp_curve_info_from_grp_id( id );
+ TEST_EQUAL( crv->grp_id, id );
+ TEST_EQUAL( crv->bit_size, bit_size );
+ TEST_EQUAL( crv->tls_id, tls_id );
+
+ // Load curve from TLS ID and name, and compare IDs
+ crv_tls_id = mbedtls_ecp_curve_info_from_tls_id( crv->tls_id );
+ crv_name = mbedtls_ecp_curve_info_from_name( crv->name );
+ TEST_EQUAL( crv_tls_id->grp_id, id );
+ TEST_EQUAL( crv_name->grp_id, id );
+
+ // Validate write_group against test data
+ TEST_EQUAL( mbedtls_ecp_tls_write_group( &grp, &olen,
+ buf, sizeof( buf ) ),
+ 0 );
+ TEST_EQUAL( mbedtls_test_hexcmp( buf, ecparameters, olen,
+ sizeof( ecparameters ) ),
+ 0 );
+
+ // Read group from buffer and compare with expected ID
+ TEST_EQUAL( mbedtls_ecp_tls_read_group_id( &read_g_id, &vbuf, olen ),
+ 0 );
+ TEST_EQUAL( read_g_id, id );
+ vbuf = buf;
+ TEST_EQUAL( mbedtls_ecp_tls_read_group( &grp_read, &vbuf, olen ),
+ 0 );
+ TEST_EQUAL( grp_read.id, id );
+
+ // Check curve type, and if it can be used for ECDH/ECDSA
+ TEST_EQUAL( mbedtls_ecp_get_type( &grp ), crv_type );
+ TEST_EQUAL( mbedtls_ecdh_can_do( id ), 1 );
+ TEST_EQUAL( mbedtls_ecdsa_can_do( id ),
+ crv_type == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS );
+
+ // Copy group and compare with original
+ TEST_EQUAL( mbedtls_ecp_group_copy( &grp_cpy, &grp ), 0 );
+ TEST_EQUAL( mbedtls_ecp_group_cmp( &grp, &grp_cpy ), 0 );
+
+ // Check curve is in curve list and group ID list
+ for( crv = mbedtls_ecp_curve_list( );
+ crv->grp_id != MBEDTLS_ECP_DP_NONE &&
+ crv->grp_id != (unsigned) id;
+ crv++ );
+ TEST_EQUAL( crv->grp_id, id );
+ for( g_id = mbedtls_ecp_grp_id_list( );
+ *g_id != MBEDTLS_ECP_DP_NONE && *g_id != (unsigned) id;
+ g_id++ );
+ TEST_EQUAL( *g_id, (unsigned) id );
+
+exit:
+ mbedtls_ecp_group_free( &grp ); mbedtls_ecp_group_free( &grp_cpy );
+ mbedtls_ecp_group_free( &grp_read );
+ mbedtls_mpi_free( &exp_P ); mbedtls_mpi_free( &exp_A );
+ mbedtls_mpi_free( &exp_B ); mbedtls_mpi_free( &exp_G_x );
+ mbedtls_mpi_free( &exp_G_y ); mbedtls_mpi_free( &exp_N );
+}
+/* END_CASE */
+
/* BEGIN_CASE */
void mbedtls_ecp_check_privkey( int id, char * key_hex, int ret )
{
diff --git a/tests/suites/test_suite_psa_crypto.function b/tests/suites/test_suite_psa_crypto.function
index 0f4e313..5f489f9 100644
--- a/tests/suites/test_suite_psa_crypto.function
+++ b/tests/suites/test_suite_psa_crypto.function
@@ -450,6 +450,7 @@
/* END_CASE */
/* BEGIN_CASE */
+/* Construct and attempt to import a large unstructured key. */
void import_large_key( int type_arg, int byte_size_arg,
int expected_status_arg )
{
@@ -506,6 +507,9 @@
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ASN1_WRITE_C */
+/* Import an RSA key with a valid structure (but not valid numbers
+ * inside, beyond having sensible size and parity). This is expected to
+ * fail for large keys. */
void import_rsa_made_up( int bits_arg, int keypair, int expected_status_arg )
{
mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
@@ -550,6 +554,7 @@
int expected_bits,
int export_size_delta,
int expected_export_status_arg,
+ /*whether reexport must give the original input exactly*/
int canonical_input )
{
mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
@@ -649,7 +654,7 @@
/* BEGIN_CASE */
void import_export_public_key( data_t *data,
- int type_arg,
+ int type_arg, // key pair or public key
int alg_arg,
int export_size_delta,
int expected_export_status_arg,
diff --git a/tests/suites/test_suite_version.data b/tests/suites/test_suite_version.data
index b0a20b5..69f8a84 100644
--- a/tests/suites/test_suite_version.data
+++ b/tests/suites/test_suite_version.data
@@ -1,8 +1,8 @@
Check compile time library version
-check_compiletime_version:"2.28.1"
+check_compiletime_version:"2.28.2"
Check runtime library version
-check_runtime_version:"2.28.1"
+check_runtime_version:"2.28.2"
Check for MBEDTLS_VERSION_C
check_feature:"MBEDTLS_VERSION_C":0