Compare commits

..

No commits in common. "development" and "v4.1.0" have entirely different histories.

79 changed files with 2142 additions and 2738 deletions

View File

@ -9,14 +9,13 @@ Please write a few sentences describing the overall goals of the pull request's
Please remove the segment/s on either side of the | symbol as appropriate, and add any relevant link/s to the end of the line.
If the provided content is part of the present PR remove the # symbol.
- [ ] **changelog** provided | not required because:
- [ ] **changelog** provided | not required because:
- [ ] **development PR** provided # | not required because:
- [ ] **TF-PSA-Crypto PR** provided # | not required because:
- [ ] **framework PR** provided Mbed-TLS/mbedtls-framework# | not required
- [ ] **TF-PSA-Crypto development PR** provided Mbed-TLS/TF-PSA-Crypto# | not required because:
- [ ] **TF-PSA-Crypto 1.1 PR** provided Mbed-TLS/TF-PSA-Crypto# | not required because:
- [ ] **mbedtls development PR** provided # | not required because:
- [ ] **mbedtls 4.1 PR** provided # | not required because:
- [ ] **mbedtls 3.6 PR** provided # | not required because:
- **tests** provided | not required because:
- [ ] **3.6 PR** provided # | not required because:
- **tests** provided | not required because:
## Notes for the submitter

View File

@ -1,4 +1,4 @@
[mypy]
mypy_path = framework/scripts:scripts:tf-psa-crypto/scripts/project_knowledge
mypy_path = framework/scripts:scripts
namespace_packages = True
warn_unused_configs = True

View File

@ -1,5 +1,5 @@
[MASTER]
init-hook='import sys; sys.path += ["scripts", "framework/scripts", "tf-psa-crypto/scripts/project_knowledge"]'
init-hook='import sys; sys.path.append("scripts"); sys.path.append("framework/scripts")'
min-similarity-lines=10
[BASIC]

View File

@ -12,7 +12,7 @@ submodules:
# Set the version of Python and other tools you might need
build:
os: ubuntu-26.04
os: ubuntu-20.04
apt_packages:
- cmake
tools:

View File

@ -88,9 +88,9 @@ The following branches are currently maintained:
- [`development`](https://github.com/Mbed-TLS/mbedtls/)
- [`mbedtls-3.6`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-3.6)
maintained until March 2027, see
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v3.6.7>.
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v3.6.6>.
- [`mbedtls-4.1`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-4.1)
maintained until March 2029, see
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v4.1.1>.
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v4.1.0>.
Users are urged to always use the latest version of a maintained branch.

View File

@ -37,7 +37,7 @@ cmake_policy(SET CMP0011 NEW)
# is deprecated and will be removed in future versions.
cmake_policy(SET CMP0012 NEW)
set(MBEDTLS_VERSION 4.2.0)
set(MBEDTLS_VERSION 4.1.0)
set(MBEDTLS_CRYPTO_SOVERSION 18)
set(MBEDTLS_X509_SOVERSION 9)
set(MBEDTLS_TLS_SOVERSION 23)
@ -122,7 +122,7 @@ endif()
# We now potentially need to link all executables against PThreads, if available
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads QUIET)
find_package(Threads)
# If this is the root project add longer list of available CMAKE_BUILD_TYPE values
if(NOT MBEDTLS_AS_SUBPROJECT)

102
ChangeLog
View File

@ -1,105 +1,5 @@
Mbed TLS ChangeLog (Sorted per branch, date)
= Mbed TLS 4.2.0 branch released 2026-07-07
Features
* Restore DESTDIR support for CMake installs of compatibility
libmbedcrypto symlinks. Fixes #10627.
* SHA3-256, SHA3-384 and SHA3-512 are now accepted in the default X.509
certificate profile.
Security
* Added advice about compiler options in SECURITY.md.
* Fix a bug where transcript-hash computation errors during TLS 1.2
extended master secret calculation could be ignored instead of causing the
handshake to fail. This could allow a handshake to continue with a master
secret that was not correctly bound to the handshake transcript,
undermining the security guarantees of the extended master secret
extension. Report by Mathew Gretton-Dann. CVE-2026-50581
* Fix a TLS 1.3 server-side error-handling bug affecting session ticket
generation. Under rare conditions, such as memory allocation failures
while computing the resumption master secret, the server could issue
invalid session tickets instead of failing the handshake. Clients
presented with such tickets would fail session resumption and fall back to
a full handshake. In deployments relying on session resumption, repeated
occurrences could increase the frequency of full handshakes and amplify
resource consumption during periods of resource exhaustion or other
transient failures. Reported by jjfz123.
CVE-2026-50640
* Fixed a TLS 1.3 record-boundary validation issue that could allow
unauthenticated plaintext data to be processed across a key change. In
servers with MBEDTLS_SSL_EARLY_DATA enabled, this could be exploited by a
man-in-the-middle attacker to cause loss of 0-RTT early data.
Reported by Ben Smyth.
* Fix a remote buffer overflow in (D)TLS with ECDHE-PSK cipher suites when
CBC is disabled. Reported by Karnakar Reddy. CVE-2026-50580
* Fix a potential information disclosure in TLS 1.2 servers using session
tickets. If the session ticket write callback failed without setting the
lifetime output parameter, Mbed TLS could send 4 bytes of uninitialized
stack memory to the peer in the NewSessionTicket message. Fixes #1570.
Reported by James Love. CVE-2026-50586.
* Fix an out-of-bounds read when parsing TLS 1.2 ECJPAKE ServerKeyExchange
messages. Reported-by Biniam Demissie.
CVE-2026-50588
* Fix a use-after-free/double-free risk in mbedtls_pkcs7_free() when reusing
an mbedtls_pkcs7 context across parse -> free -> parse -> free cycles. The
function now resets the context after freeing it, ensuring stale
signed_data.signers.next pointers cannot be walked by a later free
operation. CVE-2026-50579
* PKCS7 now rejects weak hash algorithms (RIPEMD160, MD5, SHA-1, SHA-224,
SHA3-224) on signature verification.
* Improved documentation of mbedtls_ssl_conf_sig_algs() to emphasize that
this function only sets signature algorithms that are enforced during
TLS key exchange and not on certificate verification. Reported by
Xiangdong Li, Beijing University of Posts and Telecommunications (BUPT).
CVE-2026-54441
* Ensure 'badmac_seen' and 'dtls_srtp_info' fields from 'mbedtls_ssl_context'
are properly zeroized when mbedtls_ssl_session_reset() is called. This
could cause premature DTLS connection failure or incorrect DTLS-SRTP
parameter inheritance for applications reusing an SSL context.
Reported by jjfz123. CVE-2026-50585.
* Fix a bug where mbedtls_ssl_read() and mbedtls_ssl_write() could return
1 instead of an error code if the random generator failed when a server
called these functions before the end of a TLS 1.3 handshake.
Reported by Mohammad Seet (mhdsait101).
* Fix TLS 1.3 clients to reject a HelloRetryRequest whose selected group was
not advertised in the original ClientHello. Reported independently by
Din Asotić / Xiangdong Li, Beijing University of Posts and
Telecommunications (BUPT), and NVIDIA Project Vanessa.
CVE-2026-25832.
* Fix two bugs in the X.509 certificate parser that caused some inputs
with a malformed basicConstraints extension to be accepted. This
could have dangerous results, in particular causing some certificates
to be parsed as CA certificates when other X.509 implementations would
parse them as end-entity certificates. Reported by Mohammad Seet
(mhdsait101), Pablo Ruiz García and NVIDIA Project Vanessa. CVE-2026-49300
Bugfix
* Fix a TLS 1.2 regression that caused clients to reject valid
ServerKeyExchange signatures using RSA-PSS signature algorithms.
Fixes #10668.
* Fix a build error using the LLVM based MinGW toolchain.
Bug reported and fix contributed by valord577.
* Fixed a bug which prevented the inclusion of standard C library header
files from the user provided configuration file. Fixes #10740.
* Reject malformed TLS 1.3 serialized sessions instead of accepting
unterminated strings or extra trailing data.
* Reject serialized SSL contexts whose DTLS Connection ID length exceeds
the maximum supported size, instead of overflowing the internal buffer.
* Fixed documentation of mbedtls_ssl_set_cid(): the set CID configuration
is applied to all subsequent handshakes, not just to the next one.
* Reject malformed X.509 CSRs where the extensionRequest attribute
wrappers do not exactly contain the requested extensions.
Changes
* Upgraded TF-PSA-Crypto from 1.1.0 to 1.2.0. See tf-psa-crypto/ChangeLog.
* X.509 certificates with a basicConstraints extension starting with an
INTEGER field are no longer accepted. According to RFC 5280, such
certificates are syntactically valid and the first field is the
pathLenConstraint value, but certificate authorities must not emit such
certificates. Mbed TLS interpreted it as a cA value, which was nonstandard
and dangerous.
= Mbed TLS 4.1.0 branch released 2026-03-31
API changes
@ -243,7 +143,7 @@ Removals
in favour of mbedtls_ssl_conf_groups() since Mbed TLS 3.1.
* Remove support for the DHE-PSK key exchange in TLS 1.2.
* Remove support for the DHE-RSA key exchange in TLS 1.2.
* Following the removal of DHM module (#9972 and Mbed-TLS/TF-PSA-Crypto#175) the
* Following the removal of DHM module (#9972 and TF-PSA-Crypto#175) the
following SSL functions are removed:
- mbedtls_ssl_conf_dh_param_bin
- mbedtls_ssl_conf_dh_param_ctx

View File

@ -7,8 +7,8 @@ send an email to the security team at
## Security Incident Handling Process
Our security process is detailed in our
[online
documentation](https://mbed-tls.readthedocs.io/en/latest/project/vulnerabilities/).
[security
center](https://developer.trustedfirmware.org/w/mbed-tls/security-center/).
Its primary goal is to ensure fixes are ready to be deployed when the issue
goes public.
@ -107,12 +107,6 @@ model, they need to be mitigated by physical countermeasures.
### Caveats
#### Compiler-induced side channels
Mbed TLS is mostly written in C. We use standard C except with known compilers, so we do not expect compilers to introduce direct vulnerabilities. However, compilers can introduce [timing side channels](#timing-attacks) in code that was intended to be constant-time. Mbed TLS includes countermeasures to try to prevent this. But given the diversity of compilers, compiler options and target platforms, this prevention may not be complete.
We recommend compiling Mbed TLS with commonly used levels of optimizations, such as `-O2` or `-Os`. We will generally treat exploitable timing side channels as a vulnerability if they appear with a common compiler at a common level of optimization. Higher levels of optimization such as `-O3` or `-Oz` are still likely to be safe but are less scrutinized. We do not recommend using individual options that might introduce data-dependent timing, and we will not try to work around such optimizations if they are not part of a commonly used level.
#### Out-of-scope countermeasures
Mbed TLS has evolved organically and a well defined threat model hasn't always

View File

@ -10,7 +10,7 @@
*/
/**
* @mainpage Mbed TLS v4.2.0 API Documentation
* @mainpage Mbed TLS v4.1.0 API Documentation
*
* This documentation describes the application programming interface (API)
* of Mbed TLS.

View File

@ -1,4 +1,4 @@
PROJECT_NAME = "Mbed TLS v4.2.0"
PROJECT_NAME = "Mbed TLS v4.1.0"
OUTPUT_DIRECTORY = ../apidoc/
FULL_PATH_NAMES = NO
OPTIMIZE_OUTPUT_FOR_C = YES

@ -1 +1 @@
Subproject commit a3079552234917a9831dd70693983af5e62c70de
Subproject commit dff9da04438d712f7647fd995bc90fadd0c0e2ce

View File

@ -27,7 +27,7 @@
* Major, Minor, Patchlevel
*/
#define MBEDTLS_VERSION_MAJOR 4
#define MBEDTLS_VERSION_MINOR 2
#define MBEDTLS_VERSION_MINOR 1
#define MBEDTLS_VERSION_PATCH 0
/**
@ -35,9 +35,9 @@
* MMNNPP00
* Major version | Minor version | Patch version
*/
#define MBEDTLS_VERSION_NUMBER 0x04020000
#define MBEDTLS_VERSION_STRING "4.2.0"
#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 4.2.0"
#define MBEDTLS_VERSION_NUMBER 0x04010000
#define MBEDTLS_VERSION_STRING "4.1.0"
#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 4.1.0"
#if defined(MBEDTLS_CONFIG_FILES_READ)
#error "Something went wrong: MBEDTLS_CONFIG_FILES_READ defined before reading the config files!"

View File

@ -59,7 +59,7 @@
*/
#if defined(__has_attribute)
#if __has_attribute(format)
#if defined(__MINGW32__) && !defined(__clang__)
#if defined(__MINGW32__)
#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__(gnu_printf, string_index, first_to_check)))
#else /* defined(__MINGW32__) */

View File

@ -31,10 +31,6 @@
* assumed these fields are empty.
* - The RFC allows for the signed Data type to contain contentInfo. This
* implementation assumes the type is DATA and the content is empty.
* - The RFC doesn't put any constrain on the hash algorithm to be used, but
* this implementation rejects weak hash algorithms (i.e. RIPEMD160, MD5,
* SHA-1, SHA-224, SHA3-224). In general accepted hash and PK algorithms are
* the ones belonging to `mbedtls_x509_crt_profile_default`.
*/
#ifndef MBEDTLS_PKCS7_H
@ -194,9 +190,6 @@ int mbedtls_pkcs7_parse_der(mbedtls_pkcs7 *pkcs7, const unsigned char *buf,
* \note This function internally calculates the hash on the supplied
* plain data for signature verification.
*
* \note For limitation on the supported hash algorithms, please refer
* to the note at the top of this document.
*
* \return 0 if the signature verifies, or a negative error code on failure.
*/
int mbedtls_pkcs7_signed_data_verify(mbedtls_pkcs7 *pkcs7,
@ -226,9 +219,6 @@ int mbedtls_pkcs7_signed_data_verify(mbedtls_pkcs7 *pkcs7,
* \note This function is different from mbedtls_pkcs7_signed_data_verify()
* in that it is directly passed the hash of the data.
*
* \note For limitation on the supported hash algorithms, please refer
* to the note at the top of this document.
*
* \return 0 if the signature verifies, or a negative error code on failure.
*/
int mbedtls_pkcs7_signed_hash_verify(mbedtls_pkcs7 *pkcs7,

View File

@ -1324,15 +1324,6 @@ typedef union {
void *p; /* typically a pointer to extra data */
} mbedtls_ssl_user_data_t;
/**
* Added at the end of "struct mbedtls_ssl_config" and "struct mbedtls_ssl_context"
* to reserve a field for future use.
*/
typedef union {
size_t number;
void *ptr;
} mbedtls_ssl_unused_data_t;
/**
* SSL/TLS configuration to be shared between mbedtls_ssl_context structures.
*/
@ -1581,20 +1572,13 @@ struct mbedtls_ssl_config {
const mbedtls_x509_crt *MBEDTLS_PRIVATE(dn_hints);/*!< acceptable client cert issuers */
#endif
mbedtls_ssl_unused_data_t MBEDTLS_PRIVATE(unused);
/* Unused field reserved for future use */
union {
size_t number;
void *ptr;
} MBEDTLS_PRIVATE(unused);
};
/*
* Warning: whenever a change is applied to "mbedtls_ssl_context" please re-run
* the script "tests/scripts/generate_ssl_session_reset_check.py".
* Please note that this script has some limitation that should be considered
* when modifing "mbedtls_ssl_context":
* - Parsed structure must start with struct "mbedtls_ssl_context {"
* (not "typedef struct {").
* - It must end with "}}" in column 0.
* - Must not contain "#else" or "#elif" conditionals.
* - Must not contain nested struct/union/enum definitions.
*/
struct mbedtls_ssl_context {
const mbedtls_ssl_config *MBEDTLS_PRIVATE(conf); /*!< configuration information */
@ -1877,7 +1861,11 @@ struct mbedtls_ssl_context {
*/
mbedtls_ssl_user_data_t MBEDTLS_PRIVATE(user_data);
mbedtls_ssl_unused_data_t MBEDTLS_PRIVATE(unused);
/* Unused field reserved for future use */
union {
size_t number;
void *ptr;
} MBEDTLS_PRIVATE(unused);
};
/**
@ -2181,7 +2169,7 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
/**
* \brief Configure the use of the Connection ID (CID)
* extension in subsequent handshakes.
* extension in the next handshake.
*
* Reference: RFC 9146 (or draft-ietf-tls-dtls-connection-id-05
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
@ -2202,7 +2190,7 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
* headers of outgoing messages.
*
* This API enables or disables the use of the CID extension
* in subsequent handshakes and sets the value of the CID to
* in the next handshake and sets the value of the CID to
* be used for incoming messages.
*
* \param ssl The SSL context to configure. This must be initialized.
@ -2233,11 +2221,11 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
* successful call to this function to run the handshake.
*
* \note This call cannot guarantee that the use of the CID
* will be successfully negotiated in subsequent handshakes,
* will be successfully negotiated in the next handshake,
* because the peer might not support it. Specifically:
* - On the Client, enabling the use of the CID through
* this call implies that the `ClientHello` in subsequent
* handshakes will include the CID extension, thereby
* this call implies that the `ClientHello` in the next
* handshake will include the CID extension, thereby
* offering the use of the CID to the server. Only if
* the `ServerHello` contains the CID extension, too,
* the CID extension will actually be put to use.
@ -2260,7 +2248,7 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
* Mbed TLS.
*
* \return \c 0 on success. In this case, the CID configuration
* applies to subsequent handshakes.
* applies to the next handshake.
* \return A negative error code on failure.
*/
int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
@ -3423,7 +3411,7 @@ int mbedtls_ssl_conf_cid(mbedtls_ssl_config *conf, size_t len,
*
* \note The restrictions are enforced for all certificates in the
* chain. However, signatures in the handshake are not covered
* by this setting but by \c mbedtls_ssl_conf_sig_algs().
* by this setting but by \b mbedtls_ssl_conf_sig_algs().
*
* \param conf SSL configuration
* \param profile Profile to use
@ -3911,12 +3899,7 @@ void mbedtls_ssl_conf_groups(mbedtls_ssl_config *conf,
#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
/**
* \brief Configure allowed signature algorithms for use in TLS key
* exchange.
*
* \note This only covers signature algorithms used in the key
* exchange. To also enforce restrictions in certificate verification
* refer to \c mbedtls_ssl_conf_cert_profile().
* \brief Configure allowed signature algorithms for use in TLS
*
* \param conf The SSL configuration to use.
* \param sig_algs List of allowed IANA values for TLS 1.3 signature algorithms,

View File

@ -361,7 +361,7 @@ foreach(target IN LISTS tf_psa_crypto_library_targets)
RENAME "libmbedcrypto.so.${MBEDTLS_VERSION}"
)
install(CODE "
set(_libdir \"\$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\")
set(_libdir \"\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\")
execute_process(COMMAND \"\${CMAKE_COMMAND}\" -E create_symlink
\"libmbedcrypto.so.${MBEDTLS_VERSION}\"

View File

@ -60,7 +60,7 @@
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
( !defined(MBEDTLS_CAN_ECDH) || !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) )
!defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(PSA_WANT_ALG_RSA_PKCS1V15_CRYPT) || !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) )
#error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites"
#endif
@ -138,19 +138,10 @@
defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) )
#error "TLS 1.2 protocol is enabled but no key exchange method is defined" \
"with MBEDTLS_KEY_EXCHANGE_xxxx"
#error "One or more versions of the TLS protocol are enabled " \
"but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx"
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
!(defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED) || \
defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) || \
defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) )
#error "TLS 1.3 protocol is enabled but no key exchange method is defined" \
"with MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_xxxx"
#endif
#if defined(MBEDTLS_SSL_EARLY_DATA) && \
( !defined(MBEDTLS_SSL_SESSION_TICKETS) || \
( !defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) && \

View File

@ -6,8 +6,6 @@
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls_platform_requirements.h"
/* We are a special snowflake: we don't include "mbedtls_common.h",
* because that would pull <mbedtls/build_info.h> and we need to
* tune the way it works. */

View File

@ -665,18 +665,6 @@ static int mbedtls_pkcs7_data_or_hash_verify(mbedtls_pkcs7 *pkcs7,
return ret;
}
/* Ensure the MD alg from the PKCS#7 context and signature algorithm from
* the certificate belong to the list of secure algorithms
* (i.e. mbedtls_x509_crt_profile_default). */
ret = mbedtls_x509_profile_check_md_alg(&mbedtls_x509_crt_profile_default, md_alg);
if (ret != 0) {
return MBEDTLS_ERR_PKCS7_INVALID_ALG;
}
ret = mbedtls_x509_profile_check_pk_alg(&mbedtls_x509_crt_profile_default, cert->sig_pk);
if (ret != 0) {
return MBEDTLS_ERR_PKCS7_INVALID_ALG;
}
md_info = mbedtls_md_info_from_type(md_alg);
if (md_info == NULL) {
return MBEDTLS_ERR_PKCS7_VERIFY_FAIL;
@ -778,7 +766,7 @@ void mbedtls_pkcs7_free(mbedtls_pkcs7 *pkcs7)
mbedtls_free(signer_prev);
}
mbedtls_platform_zeroize(pkcs7, sizeof(*pkcs7));
pkcs7->raw.p = NULL;
}
#endif

View File

@ -208,10 +208,6 @@ static int ssl_write_alpn_ext(mbedtls_ssl_context *ssl,
* generalization of the TLS 1.2 supported elliptic curves extension. They both
* share the same extension identifier.
*
* If the TLS 1.3 logic for selecting proposed groups changes, the TLS 1.3
* group filtering in the function `ssl_tls13_parse_hrr_key_share_ext()` must
* be updated accordingly.
*
*/
#define SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_2_FLAG 1
#define SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_3_FLAG 2
@ -255,8 +251,8 @@ static int ssl_write_supported_groups_ext(mbedtls_ssl_context *ssl,
if (flags & SSL_WRITE_SUPPORTED_GROUPS_EXT_TLS1_3_FLAG) {
#if defined(PSA_WANT_ALG_ECDH)
if (mbedtls_ssl_tls13_named_group_is_ecdhe(*group_list) &&
mbedtls_ssl_get_psa_curve_info_from_tls_id(
*group_list, NULL, NULL) == PSA_SUCCESS) {
(mbedtls_ssl_get_ecp_group_id_from_tls_id(*group_list) !=
MBEDTLS_ECP_DP_NONE)) {
propose_group = 1;
}
#endif

View File

@ -29,6 +29,7 @@
#include <string.h>
#include "mbedtls/psa_util.h"
#include "md_psa.h" // for mbedtls_md_error_from_psa()
#include "psa/crypto.h"
#if defined(MBEDTLS_X509_CRT_PARSE_C)
@ -845,21 +846,21 @@ int mbedtls_ssl_reset_checksum(mbedtls_ssl_context *ssl)
#if defined(PSA_WANT_ALG_SHA_256)
status = psa_hash_abort(&ssl->handshake->fin_sha256_psa);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
status = psa_hash_setup(&ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#endif
#if defined(PSA_WANT_ALG_SHA_384)
status = psa_hash_abort(&ssl->handshake->fin_sha384_psa);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
status = psa_hash_setup(&ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#endif
return 0;
@ -879,13 +880,13 @@ static int ssl_update_checksum_start(mbedtls_ssl_context *ssl,
#if defined(PSA_WANT_ALG_SHA_256)
status = psa_hash_update(&ssl->handshake->fin_sha256_psa, buf, len);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#endif
#if defined(PSA_WANT_ALG_SHA_384)
status = psa_hash_update(&ssl->handshake->fin_sha384_psa, buf, len);
if (status != PSA_SUCCESS) {
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#endif
return 0;
@ -895,8 +896,8 @@ static int ssl_update_checksum_start(mbedtls_ssl_context *ssl,
static int ssl_update_checksum_sha256(mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len)
{
return PSA_TO_MBEDTLS_ERR(psa_hash_update(
&ssl->handshake->fin_sha256_psa, buf, len));
return mbedtls_md_error_from_psa(psa_hash_update(
&ssl->handshake->fin_sha256_psa, buf, len));
}
#endif
@ -904,8 +905,8 @@ static int ssl_update_checksum_sha256(mbedtls_ssl_context *ssl,
static int ssl_update_checksum_sha384(mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len)
{
return PSA_TO_MBEDTLS_ERR(psa_hash_update(
&ssl->handshake->fin_sha384_psa, buf, len));
return mbedtls_md_error_from_psa(psa_hash_update(
&ssl->handshake->fin_sha384_psa, buf, len));
}
#endif
@ -1308,8 +1309,6 @@ void mbedtls_ssl_session_reset_msg_layer(mbedtls_ssl_context *ssl,
ssl->in_fatal_alert_recv = 0;
ssl->in_fatal_alert_type = 0;
ssl->send_alert = 0;
ssl->alert_reason = 0;
ssl->alert_type = 0;
/* Reset outgoing message writing */
ssl->out_msgtype = 0;
@ -1359,8 +1358,6 @@ int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial)
ssl->flags &= MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION;
ssl->tls_version = ssl->conf->max_tls_version;
ssl->badmac_seen = 0;
mbedtls_ssl_session_reset_msg_layer(ssl, partial);
/* Reset renegotiation state */
@ -1386,10 +1383,6 @@ int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial)
ssl->alpn_chosen = NULL;
#endif
#if defined(MBEDTLS_SSL_DTLS_SRTP)
memset(&ssl->dtls_srtp_info, 0, sizeof(ssl->dtls_srtp_info));
#endif /* MBEDTLS_SSL_DTLS_SRTP */
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
int free_cli_id = 1;
#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
@ -3641,12 +3634,6 @@ static int ssl_tls13_session_load(mbedtls_ssl_session *session,
}
if (alpn_len > 0) {
/* The data is about to be used as a null-terminated string, so
* check that it actually is one. */
if (p[alpn_len - 1] != '\0') {
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
int ret = mbedtls_ssl_session_set_ticket_alpn(session, (char *) p);
if (ret != 0) {
return ret;
@ -3672,16 +3659,11 @@ static int ssl_tls13_session_load(mbedtls_ssl_session *session,
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
if (hostname_len > 0) {
/* The data is about to be used as a null-terminated string, so
* check that it actually is one. */
if (p[hostname_len - 1] != '\0') {
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
int ret = mbedtls_ssl_session_set_hostname(session, (const char *) p);
if (ret != 0) {
return ret;
session->hostname = mbedtls_calloc(1, hostname_len);
if (session->hostname == NULL) {
return MBEDTLS_ERR_SSL_ALLOC_FAILED;
}
memcpy(session->hostname, p, hostname_len);
p += hostname_len;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
@ -3719,10 +3701,6 @@ static int ssl_tls13_session_load(mbedtls_ssl_session *session,
}
#endif /* MBEDTLS_SSL_CLI_C */
if (p != end) {
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
return 0;
}
@ -5021,10 +4999,6 @@ static int ssl_context_load(mbedtls_ssl_context *ssl,
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
if (ssl->transform->in_cid_len > sizeof(ssl->transform->in_cid)) {
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
memcpy(ssl->transform->in_cid, p, ssl->transform->in_cid_len);
p += ssl->transform->in_cid_len;
@ -5034,10 +5008,6 @@ static int ssl_context_load(mbedtls_ssl_context *ssl,
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
if (ssl->transform->out_cid_len > sizeof(ssl->transform->out_cid)) {
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
memcpy(ssl->transform->out_cid, p, ssl->transform->out_cid_len);
p += ssl->transform->out_cid_len;
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
@ -6323,16 +6293,11 @@ static int ssl_compute_master(mbedtls_ssl_handshake_params *handshake,
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
if (handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED) {
lbl = "extended master secret";
seed = session_hash;
ret = handshake->calc_verify(ssl, session_hash, &seed_len);
if (ret != 0) {
MBEDTLS_SSL_DEBUG_RET(1, "calc_verify", ret);
return ret;
}
if (seed_len > sizeof(session_hash)) {
MBEDTLS_SSL_DEBUG_MSG(1, ("bad session hash length"));
return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
}
seed = session_hash;
MBEDTLS_SSL_DEBUG_BUF(3, "session hash for extended master secret",
session_hash, seed_len);
@ -6599,7 +6564,7 @@ static int ssl_calc_verify_tls_psa(const mbedtls_ssl_context *ssl,
exit:
psa_hash_abort(&cloned_op);
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#if defined(PSA_WANT_ALG_SHA_256)
@ -7292,7 +7257,7 @@ static int ssl_calc_finished_tls_generic(mbedtls_ssl_context *ssl, void *ctx,
exit:
psa_hash_abort(&cloned_op);
return PSA_TO_MBEDTLS_ERR(status);
return mbedtls_md_error_from_psa(status);
}
#if defined(PSA_WANT_ALG_SHA_256)

View File

@ -12,7 +12,6 @@
#include "mbedtls/platform.h"
#include "mbedtls/ssl.h"
#include "ssl_debug_helpers.h"
#include "ssl_client.h"
#include "debug_internal.h"
#include "mbedtls/error.h"
@ -1743,77 +1742,32 @@ static int ssl_parse_signature_algorithm(mbedtls_ssl_context *ssl,
{
if (mbedtls_ssl_get_pk_sigalg_and_md_alg_from_sig_alg(sig_alg, pk_alg, md_alg) != 0) {
MBEDTLS_SSL_DEBUG_MSG(1,
("Server used unsupported %s signature algorithm",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
("Server used unsupported value in SigAlg extension 0x%04x",
sig_alg));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
/*
* mbedtls_ssl_get_pk_sigalg_and_md_alg_from_sig_alg() understands
* signature algorithm code points from both TLS 1.2 and TLS 1.3. Make sure
* that the selected signature algorithm is acceptable when TLS 1.2 is
* negotiated.
*
* In TLS 1.2, RSA-PSS signature algorithms (rsa_pss_rsae_*) are not
* defined by RFC 5246. However, RFC 8446 Section 4.2.3 requires that
* implementations which advertise support for RSASSA-PSS must be
* prepared to accept such signatures even when TLS 1.2 is negotiated,
* provided they were offered in the signature_algorithms extension.
*
* Therefore, we allow rsa_pss_rsae_* here if:
* - the implementation supports them, and
* - they were offered in the signature_algorithms extension (checked by
* `mbedtls_ssl_sig_alg_is_offered()` below).
*
* If we were to add full support for rsa_pss_rsae_* signature algorithms
* in TLS 1.2 (not defined by RFC 5246; RFC 8446 requires implementations
* that advertise RSASSA-PSS to accept such signatures even when TLS 1.2
* is negotiated; in practice, several TLS implementations also offer and
* use these algorithms in TLS 1.2-only configurations), we should then
* integrate RSA-PSS into the TLS 1.2 signature algorithm support logic
* (`mbedtls_ssl_tls12_sig_alg_is_supported()`) instead of handling it as a
* special case here.
* mbedtls_ssl_get_pk_sigalg_and_md_alg_from_sig_alg() understands sig_alg code points across
* TLS versions. Make sure that the received sig_alg extension is valid in TLS 1.2.
*/
if (!mbedtls_ssl_sig_alg_is_supported(ssl, sig_alg)) {
switch (sig_alg) {
#if defined(PSA_WANT_ALG_RSA_PSS)
#if defined(PSA_WANT_ALG_SHA_256)
case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
#endif
#if defined(PSA_WANT_ALG_SHA_384)
case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
#endif
#if defined(PSA_WANT_ALG_SHA_512)
case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
#endif
#if defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384) || defined(PSA_WANT_ALG_SHA_512)
MBEDTLS_SSL_DEBUG_MSG(3,
(
"Accepting TLS 1.2 RSA-PSS signature algorithm %s via compatibility exception",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
break;
#endif
#endif /* PSA_WANT_ALG_RSA_PSS */
default:
MBEDTLS_SSL_DEBUG_MSG(1,
("Server used unsupported %s signature algorithm",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
MBEDTLS_SSL_DEBUG_MSG(1,
("Server used unsupported value in SigAlg extension 0x%04x",
sig_alg));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
/*
* Check if the signature algorithm is acceptable
*/
if (!mbedtls_ssl_sig_alg_is_offered(ssl, sig_alg)) {
MBEDTLS_SSL_DEBUG_MSG(1,
("Server used the signature algorithm %s that was not offered",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
MBEDTLS_SSL_DEBUG_MSG(1, ("Server used SigAlg value 0x%04x that was not offered", sig_alg));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used the signature algorithm %s",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used SignatureAlgorithm %d", sig_alg & 0x00FF));
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used HashAlgorithm %d", sig_alg >> 8));
return 0;
}
@ -1931,8 +1885,6 @@ start_processing:
* However since we only support secp256r1 for now, we check only
* that TLS ID here
*/
MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 3);
uint16_t read_tls_id = MBEDTLS_GET_UINT16_BE(p, 1);
uint16_t exp_tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(
MBEDTLS_ECP_DP_SECP256R1);
@ -2472,16 +2424,11 @@ static int ssl_write_client_key_exchange(mbedtls_ssl_context *ssl)
/* uint16 to store content length */
const size_t content_len_size = 2;
const size_t ecpoint_len_size = 1;
const size_t ecpoint_max_len =
PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(handshake->xxdh_psa_type,
handshake->xxdh_psa_bits);
header_len = 4;
if (ecpoint_max_len > MBEDTLS_SSL_OUT_CONTENT_LEN - ecpoint_len_size ||
header_len + content_len_size + ssl->conf->psk_identity_len
> MBEDTLS_SSL_OUT_CONTENT_LEN - ecpoint_len_size - ecpoint_max_len) {
if (header_len + content_len_size + ssl->conf->psk_identity_len
> MBEDTLS_SSL_OUT_CONTENT_LEN) {
MBEDTLS_SSL_DEBUG_MSG(1,
("psk identity too long or SSL buffer too short"));
return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;

View File

@ -1746,9 +1746,9 @@ static void ssl_write_supported_point_formats_ext(mbedtls_ssl_context *ssl,
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen)
static void ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p = buf;
@ -1760,14 +1760,14 @@ static int ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
/* Skip costly computation if not needed */
if (ssl->handshake->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
return 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, ecjpake kkpp extension"));
if (end - p < 4) {
MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
return;
}
MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
@ -1780,14 +1780,13 @@ static int ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
psa_destroy_key(ssl->handshake->psa_pake_password);
psa_pake_abort(&ssl->handshake->psa_pake_ctx);
MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
return ret;
return;
}
MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
p += 2;
*olen = kkpp_len + 4;
return 0;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
@ -2170,11 +2169,7 @@ static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ret = ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
if (ret != 0) {
MBEDTLS_SSL_DEBUG_RET(1, "ssl_write_ecjpake_kkpp_ext", ret);
return ret;
}
ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
ext_len += olen;
#endif
@ -3372,8 +3367,8 @@ MBEDTLS_CHECK_RETURN_CRITICAL
static int ssl_write_new_session_ticket(mbedtls_ssl_context *ssl)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t tlen = 0;
uint32_t lifetime = 0;
size_t tlen;
uint32_t lifetime;
MBEDTLS_SSL_DEBUG_MSG(2, ("=> write new session ticket"));
@ -3400,6 +3395,7 @@ static int ssl_write_new_session_ticket(mbedtls_ssl_context *ssl)
ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
&tlen, &lifetime)) != 0) {
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_write", ret);
tlen = 0;
}
MBEDTLS_PUT_UINT32_BE(lifetime, ssl->out_msg, 4);

View File

@ -404,18 +404,14 @@ static int ssl_tls13_parse_hrr_key_share_ext(mbedtls_ssl_context *ssl,
* then the client MUST abort the handshake with an "illegal_parameter" alert.
*/
for (; *group_list != 0; group_list++) {
if (*group_list != selected_group) {
continue;
}
#if defined(PSA_WANT_ALG_ECDH)
if (mbedtls_ssl_tls13_named_group_is_ecdhe(*group_list)) {
if (mbedtls_ssl_get_psa_curve_info_from_tls_id(
*group_list, NULL, NULL) == PSA_ERROR_NOT_SUPPORTED) {
continue;
if ((mbedtls_ssl_get_psa_curve_info_from_tls_id(
*group_list, NULL, NULL) == PSA_ERROR_NOT_SUPPORTED) ||
*group_list != selected_group) {
found = 1;
break;
}
/* Found only if psa_curve is supported and group_list == selected_group */
found = 1;
break;
}
#endif /* PSA_WANT_ALG_ECDH */
#if defined(PSA_WANT_ALG_FFDH)
@ -2016,19 +2012,6 @@ static int ssl_tls13_process_server_hello(mbedtls_ssl_context *ssl)
goto cleanup;
}
/*
* TLS 1.3 is negotiated. Check that ServerHello/HRR ends at a record
* boundary. For HRR, which does not trigger a key update, this checks
* that HRR terminates the server flight.
*/
if (ssl->in_hslen != ssl->in_msglen) {
MBEDTLS_SSL_DEBUG_MSG(1, ("ServerHello end not aligned with a record boundary"));
ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
goto cleanup;
}
MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_server_hello(ssl, buf,
buf + buf_len,
is_hrr));
@ -2817,7 +2800,6 @@ static int ssl_tls13_parse_new_session_ticket_exts(mbedtls_ssl_context *ssl,
MBEDTLS_SSL_DEBUG_RET(
1, "ssl_tls13_parse_new_session_ticket_early_data_ext",
ret);
return ret;
}
break;
#endif /* MBEDTLS_SSL_EARLY_DATA */

View File

@ -50,55 +50,20 @@ int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
unsigned char **buf,
size_t *buf_len)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int require_record_boundary;
int ret;
/* Require record-boundary alignment by default. The exceptions below are
* handshake messages that may legitimately be followed by additional
* handshake messages in the same record. Using the default behaviour for a
* message that should be exempt is an interoperability bug; exempting a
* message that should not be exempt may have security implications.
*/
switch (hs_type) {
case MBEDTLS_SSL_HS_NEW_SESSION_TICKET:
case MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS:
case MBEDTLS_SSL_HS_CERTIFICATE:
case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST:
case MBEDTLS_SSL_HS_CERTIFICATE_VERIFY:
/*
* For TLS 1.3, ServerHello (including HelloRetryRequest) must end at a
* record boundary, but not for TLS 1.2. At this point the ServerHello
* has not yet been processed, so we do not know whether it negotiates
* TLS 1.3 or TLS 1.2. Defer the boundary check until the protocol
* version is known to be TLS 1.3.
*/
case MBEDTLS_SSL_HS_SERVER_HELLO:
require_record_boundary = 0;
break;
default:
/* ClientHello, EndOfEarlyData, Finished, and KeyUpdate.
*/
require_record_boundary = 1;
}
ret = mbedtls_ssl_read_record(ssl, 0);
if (ret != 0) {
if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
goto error;
goto cleanup;
}
ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
ssl->in_msg[0] != hs_type) {
MBEDTLS_SSL_DEBUG_MSG(1, ("Receive unexpected handshake message."));
goto error;
}
if (require_record_boundary && (ssl->in_hslen != ssl->in_msglen)) {
MBEDTLS_SSL_DEBUG_MSG(1, ("Handshake message %s end not aligned with a record boundary",
mbedtls_ssl_get_hs_msg_name(hs_type)));
goto error;
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
goto cleanup;
}
/*
@ -108,15 +73,11 @@ int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
* uint24 length;
* ...
*/
*buf = ssl->in_msg + 4;
*buf = ssl->in_msg + 4;
*buf_len = ssl->in_hslen - 4;
return 0;
error:
if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) {
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
}
cleanup:
return ret;
}
@ -341,12 +302,11 @@ static int ssl_tls13_parse_certificate_verify(mbedtls_ssl_context *ssl,
MBEDTLS_SSL_DEBUG_BUF(3, "verify hash", verify_hash, verify_hash_len);
ret = mbedtls_pk_verify_ext((mbedtls_pk_sigalg_t) sig_alg,
&ssl->session_negotiate->peer_cert->pk,
md_alg, verify_hash, verify_hash_len,
p, signature_len);
if (ret == 0) {
return ret;
if ((ret = mbedtls_pk_verify_ext((mbedtls_pk_sigalg_t) sig_alg,
&ssl->session_negotiate->peer_cert->pk,
md_alg, verify_hash, verify_hash_len,
p, signature_len)) == 0) {
return 0;
}
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify_ext", ret);

View File

@ -3077,7 +3077,6 @@ static int ssl_tls13_process_client_finished(mbedtls_ssl_context *ssl)
if (ret != 0) {
MBEDTLS_SSL_DEBUG_RET(
1, "mbedtls_ssl_tls13_compute_resumption_master_secret", ret);
return ret;
}
mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP);
@ -3184,9 +3183,8 @@ static int ssl_tls13_prepare_new_session_ticket(mbedtls_ssl_context *ssl,
#endif
/* Generate ticket_age_add */
ret = psa_generate_random((unsigned char *) &session->ticket_age_add,
sizeof(session->ticket_age_add));
if (ret != 0) {
if ((ret = psa_generate_random((unsigned char *) &session->ticket_age_add,
sizeof(session->ticket_age_add)) != 0)) {
MBEDTLS_SSL_DEBUG_RET(1, "generate_ticket_age_add", ret);
return ret;
}

View File

@ -87,13 +87,11 @@ typedef struct {
* concerns. */
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
/* Hashes from SHA-256 and above. */
/* Hashes from SHA-256 and above. Note that this selection
* should be aligned with ssl_preset_default_hashes in ssl_tls.c. */
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512) |
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA3_256) |
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA3_384) |
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA3_512),
MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
0xFFFFFFF, /* Any PK alg */
#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
/* Curves at or above 128-bit security level. Note that this selection
@ -167,8 +165,12 @@ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none =
(uint32_t) -1,
};
int mbedtls_x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg)
/*
* Check md_alg against profile
* Return 0 if md_alg is acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg)
{
if (md_alg == MBEDTLS_MD_NONE) {
return -1;
@ -181,8 +183,12 @@ int mbedtls_x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
return -1;
}
int mbedtls_x509_profile_check_pk_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_pk_sigalg_t pk_alg)
/*
* Check pk_alg against profile
* Return 0 if pk_alg is acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_pk_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_pk_sigalg_t pk_alg)
{
if (pk_alg == MBEDTLS_PK_SIGALG_NONE) {
return -1;
@ -506,33 +512,22 @@ static int x509_get_basic_constraints(unsigned char **p,
}
if (*p == end) {
/* Empty basicConstraints: valid, not a CA. */
return 0;
}
if ((size_t) (end - *p) != len) {
/* Reject junk after the SEQUENCE inside the extension (which is
* probably benign), and reject a SEQUENCE that extends beyond
* the extension (could be very dangerous). */
return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
}
if ((ret = mbedtls_asn1_get_bool(p, end, ca_istrue)) != 0) {
/* If the SEQUENCE starts with an INTEGER and not a BOOLEAN,
* according to RFC 5280, it's syntactically valid, but it's
* something that a CA MUST NOT produce. So we reject it.
*
* Note: historically, from XySSL 0.9 to Mbed TLS 3.6.6/4.1.0,
* `SEQUENCE { INTEGER n }` was interpreted as cA=FALSE if n == 0
* and cA=TRUE if n != 0. This was dangerous since
* `SEQUENCE { INTEGER n }` should be parsed as cA=FALSE
* according to RFC 5280, so we stopped doing it.
*/
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
if (ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
ret = mbedtls_asn1_get_int(p, end, ca_istrue);
}
if (ret != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
}
if (*ca_istrue != 0) {
*ca_istrue = 1;
}
}
/* `SEQUENCE { BOOLEAN FALSE }` is not DER since default-value fields
* must be omitted in DER. But it seems harmless, and Mbed TLS has
* always accepted it, so we continue to accept it. */
if (*p == end) {
return 0;
@ -2042,11 +2037,11 @@ static int x509_crt_verifycrl(mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
/*
* Check if CRL is correctly signed by the trusted CA
*/
if (mbedtls_x509_profile_check_md_alg(profile, crl_list->sig_md) != 0) {
if (x509_profile_check_md_alg(profile, crl_list->sig_md) != 0) {
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
}
if (mbedtls_x509_profile_check_pk_alg(profile, crl_list->sig_pk) != 0) {
if (x509_profile_check_pk_alg(profile, crl_list->sig_pk) != 0) {
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
}
@ -2555,11 +2550,11 @@ static int x509_crt_verify_chain(
}
/* Check signature algorithm: MD & PK algs */
if (mbedtls_x509_profile_check_md_alg(profile, child->sig_md) != 0) {
if (x509_profile_check_md_alg(profile, child->sig_md) != 0) {
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
}
if (mbedtls_x509_profile_check_pk_alg(profile, child->sig_pk) != 0) {
if (x509_profile_check_pk_alg(profile, child->sig_pk) != 0) {
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
}
@ -3067,7 +3062,7 @@ static int x509_crt_verify_restartable_ca_cb(mbedtls_x509_crt *crt,
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type(&crt->pk);
if (mbedtls_x509_profile_check_pk_alg(profile, (mbedtls_pk_sigalg_t) pk_type) != 0) {
if (x509_profile_check_pk_alg(profile, (mbedtls_pk_sigalg_t) pk_type) != 0) {
ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
}

View File

@ -227,34 +227,25 @@ static int x509_csr_parse_attributes(mbedtls_x509_csr *csr,
/* Check that this is an extension-request attribute */
if (MBEDTLS_OID_CMP(MBEDTLS_OID_PKCS9_CSR_EXT_REQ, &attr_oid) == 0) {
if ((ret = mbedtls_asn1_get_tag(p, end_attr_data, &len,
if ((ret = mbedtls_asn1_get_tag(p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
}
const unsigned char *end_set = *p + len;
if (end_set != end_attr_data) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
}
if ((ret = mbedtls_asn1_get_tag(p, end_set, &len,
if ((ret = mbedtls_asn1_get_tag(p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) !=
0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
}
const unsigned char *end_exts = *p + len;
if (end_exts != end_set) {
if ((ret = x509_csr_parse_extensions(csr, p, *p + len, cb, p_ctx)) != 0) {
return ret;
}
if (*p != end_attr_data) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
}
if ((ret = x509_csr_parse_extensions(csr, p, end_exts, cb, p_ctx)) != 0) {
return ret;
}
/* x509_csr_parse_extensions() guarantees *p == end_exts
* on success */
}
*p = end_attr_data;

View File

@ -15,7 +15,6 @@
#include "mbedtls/private_access.h"
#include "mbedtls/x509.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/asn1.h"
#include "pk_internal.h" // for a lot of things, including in SSL
@ -80,18 +79,4 @@ int mbedtls_x509_info_key_usage(char **buf, size_t *size,
int mbedtls_x509_write_set_san_common(mbedtls_asn1_named_data **extensions,
const mbedtls_x509_san_list *san_list);
/*
* Check md_alg against profile
* Return 0 if md_alg is acceptable for this profile, -1 otherwise
*/
int mbedtls_x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg);
/*
* Check pk_alg against profile
* Return 0 if pk_alg is acceptable for this profile, -1 otherwise
*/
int mbedtls_x509_profile_check_pk_alg(const mbedtls_x509_crt_profile *profile,
mbedtls_pk_sigalg_t pk_alg);
#endif /* MBEDTLS_X509_INTERNAL_H */

View File

@ -8,6 +8,9 @@ else
DLOPEN_LDFLAGS ?=
endif
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
LOCAL_CFLAGS += -Werror -DRECORD_PSA_STATUS_COVERAGE_LOG
endif
DEP=${MBEDLIBS} ${MBEDTLS_TEST_OBJS}
# Only build the dlopen test in shared library builds, and not when building

View File

@ -22,7 +22,6 @@ int main(void)
#else /* !MBEDTLS_SSL_TEST_IMPOSSIBLE && MBEDTLS_SSL_CLI_C */
#include "test/psa_crypto_helpers.h"
#include "test/ssl_helpers.h"
/* Size of memory to be allocated for the heap, when using the library's memory
* management and MBEDTLS_MEMORY_BUFFER_ALLOC_C is enabled. */
@ -87,7 +86,6 @@ int main(void)
#define DFL_HS_TO_MIN 0
#define DFL_HS_TO_MAX 0
#define DFL_DTLS_MTU -1
#define DFL_BADMAC_LIMIT -1
#define DFL_DGRAM_PACKING 1
#define DFL_FALLBACK -1
#define DFL_EXTENDED_MS -1
@ -271,8 +269,7 @@ int main(void)
" mtu=%%d default: (library default: unlimited)\n" \
" dgram_packing=%%d default: 1 (allowed)\n" \
" allow or forbid packing of multiple\n" \
" records within a single datagram.\n" \
" badmac_limit=%%d default: (library default: disabled)\n"
" records within a single datgram.\n"
#else
#define USAGE_DTLS ""
#endif
@ -297,7 +294,7 @@ int main(void)
#if defined(MBEDTLS_SSL_RENEGOTIATION)
#define USAGE_RENEGO \
" renegotiation=%%d default: 0 (disabled)\n" \
" renegotiate=%%d default: 0 (disabled), 1 immediately, 2 after first exchange\n" \
" renegotiate=%%d default: 0 (disabled)\n" \
" renego_delay=%%d default: -2 (library default)\n"
#else
#define USAGE_RENEGO ""
@ -494,7 +491,7 @@ struct options {
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
int renegotiation; /* enable / disable renegotiation */
int allow_legacy; /* allow legacy renegotiation */
int renegotiate; /* attempt renegotiation? 1: before data, 2: after first exchange */
int renegotiate; /* attempt renegotiation? */
int renego_delay; /* delay before enforcing renegotiation */
int exchanges; /* number of data exchanges */
int min_version; /* minimum protocol version accepted */
@ -521,7 +518,6 @@ struct options {
int dtls_mtu; /* UDP Maximum transport unit for DTLS */
int fallback; /* is this a fallback connection? */
int dgram_packing; /* allow/forbid datagram packing */
int badmac_limit; /* Limit of records with bad MAC */
int extended_ms; /* negotiate extended master secret? */
int etm; /* negotiate encrypt then mac? */
int context_crt_cb; /* use context-specific CRT verify callback */
@ -963,7 +959,6 @@ int main(int argc, char *argv[])
opt.extended_ms = DFL_EXTENDED_MS;
opt.etm = DFL_ETM;
opt.dgram_packing = DFL_DGRAM_PACKING;
opt.badmac_limit = DFL_BADMAC_LIMIT;
opt.serialize = DFL_SERIALIZE;
opt.context_file = DFL_CONTEXT_FILE;
opt.eap_tls = DFL_EAP_TLS;
@ -1169,7 +1164,7 @@ usage:
opt.renego_delay = (atoi(q));
} else if (strcmp(p, "renegotiate") == 0) {
opt.renegotiate = atoi(q);
if (opt.renegotiate < 0 || opt.renegotiate > 2) {
if (opt.renegotiate < 0 || opt.renegotiate > 1) {
goto usage;
}
} else if (strcmp(p, "exchanges") == 0) {
@ -1377,11 +1372,6 @@ usage:
opt.dgram_packing != 1) {
goto usage;
}
} else if (strcmp(p, "badmac_limit") == 0) {
opt.badmac_limit = atoi(q);
if (opt.badmac_limit < 0) {
goto usage;
}
} else if (strcmp(p, "recsplit") == 0) {
opt.recsplit = atoi(q);
if (opt.recsplit < 0 || opt.recsplit > 1) {
@ -1845,10 +1835,6 @@ usage:
if (opt.dgram_packing != DFL_DGRAM_PACKING) {
mbedtls_ssl_set_datagram_packing(&ssl, opt.dgram_packing);
}
if (opt.badmac_limit != DFL_BADMAC_LIMIT) {
mbedtls_ssl_conf_dtls_badmac_limit(&conf, opt.badmac_limit);
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
@ -2456,7 +2442,7 @@ usage:
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if (opt.renegotiate == 1) {
if (opt.renegotiate) {
/*
* Perform renegotiation (this must be done when the server is waiting
* for input from our side).
@ -2801,21 +2787,12 @@ send_request:
memset(peer_crt_info, 0, sizeof(peer_crt_info));
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
/* Dump the SSL context before resetting it. This will be used below
* to check if the reset function worked properly. */
mbedtls_ssl_context ssl_before = ssl;
if ((ret = mbedtls_ssl_session_reset(&ssl)) != 0) {
mbedtls_printf(" failed\n ! mbedtls_ssl_session_reset returned -0x%x\n\n",
(unsigned int) -ret);
goto exit;
}
if (mbedtls_test_ssl_check_context_after_session_reset(&ssl_before, &ssl) != 0) {
mbedtls_printf(
" failed\n ! mbedtls_ssl_session_reset didn't properly reset ssl context\n\n");
goto exit;
}
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
@ -2840,44 +2817,6 @@ send_request:
goto send_request;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if (opt.renegotiate == 2) {
/* Perform renegotiation after the first data exchange.
* This is a one-time thing, we won't renegotiate even if there are
* more data exchanges that cause a `goto send_request` later.
*/
opt.renegotiate = 0;
mbedtls_printf(" . Performing renegotiation...");
fflush(stdout);
while ((ret = mbedtls_ssl_renegotiate(&ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
ret != MBEDTLS_ERR_SSL_WANT_WRITE &&
ret != MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
mbedtls_printf(" failed\n ! mbedtls_ssl_renegotiate returned %d\n\n",
ret);
goto exit;
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
continue;
}
#endif
/* For event-driven IO, wait for socket to become available */
if (opt.event == 1 /* level triggered IO */) {
#if defined(MBEDTLS_TIMING_C)
idle(&server_fd, &timer, ret);
#else
idle(&server_fd, ret);
#endif
}
}
mbedtls_printf(" ok\n");
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* 7c. Simulate serialize/deserialize and go back to data exchange
*/

View File

@ -52,7 +52,6 @@ int main(void)
#endif
#include "test/psa_crypto_helpers.h"
#include "test/ssl_helpers.h"
#include "mbedtls/pk.h"
#if defined(MBEDTLS_PK_HAVE_PRIVATE_HEADER)
@ -368,6 +367,9 @@ int main(void)
#define USAGE_ANTI_REPLAY ""
#endif
#define USAGE_BADMAC_LIMIT \
" badmac_limit=%%d default: (library default: disabled)\n"
#if defined(MBEDTLS_SSL_PROTO_DTLS)
#define USAGE_DTLS \
" dtls=%%d default: 0 (TLS)\n" \
@ -376,8 +378,7 @@ int main(void)
" mtu=%%d default: (library default: unlimited)\n" \
" dgram_packing=%%d default: 1 (allowed)\n" \
" allow or forbid packing of multiple\n" \
" records within a single datagram.\n" \
" badmac_limit=%%d default: (library default: disabled)\n"
" records within a single datgram.\n"
#else
#define USAGE_DTLS ""
#endif
@ -523,6 +524,7 @@ int main(void)
USAGE_SRTP \
USAGE_COOKIES \
USAGE_ANTI_REPLAY \
USAGE_BADMAC_LIMIT \
"\n"
#define USAGE2 \
" auth_mode=%%s default: (library default: none)\n" \
@ -3272,15 +3274,7 @@ reset:
mbedtls_net_free(&client_fd);
/* Dump the SSL context before resetting it. This will be used below
* to check if the reset function worked properly. */
mbedtls_ssl_context ssl_before = ssl;
mbedtls_ssl_session_reset(&ssl);
if (mbedtls_test_ssl_check_context_after_session_reset(&ssl_before, &ssl) != 0) {
mbedtls_printf(
" failed\n ! mbedtls_ssl_session_reset didn't properly reset ssl context\n\n");
goto exit;
}
/*
* 3. Wait until a client connects

View File

@ -103,12 +103,6 @@ int main(void)
" May be used multiple times, even for the same\n" \
" message, in which case the respective message\n" \
" gets delayed multiple times.\n" \
" delay_encrypted_hs_cli=%%d default: 0 (don't delay)\n" \
" delay the Nth encrypted handshake message from\n" \
" client to server.\n" \
" delay_encrypted_hs_srv=%%d default: 0 (don't delay)\n" \
" delay the Nth encrypted handshake message from\n" \
" server to client.\n" \
" delay_srv=%%s Handshake message from server that should be\n" \
" delayed. Possible values are 'HelloRequest',\n" \
" 'ServerHello', 'ServerHelloDone', 'Certificate'\n" \
@ -122,12 +116,6 @@ int main(void)
" mtu=%%d default: 0 (unlimited)\n" \
" drop packets larger than N bytes\n" \
" bad_ad=0/1 default: 0 (don't add bad ApplicationData)\n" \
" bad_ad_cli_once=%%d default: 0 (don't add bad ApplicationData)\n" \
" add bad ApplicationData before the Nth\n" \
" ApplicationData from client to server.\n" \
" bad_ad_srv_once=%%d default: 0 (don't add bad ApplicationData)\n" \
" add bad ApplicationData before the Nth\n" \
" ApplicationData from server to client.\n" \
" bad_cid=%%d default: 0 (don't corrupt Connection IDs)\n" \
" duplicate 1:N packets containing a CID,\n" \
" modifying CID in first instance of the packet.\n" \
@ -160,13 +148,9 @@ static struct options {
char *delay_srv[MAX_DELAYED_HS]; /* handshake types of messages from
* server that should be delayed. */
uint8_t delay_srv_cnt; /* Number of entries in delay_srv. */
int delay_encrypted_hs_cli; /* Delay Nth encrypted HS from client. */
int delay_encrypted_hs_srv; /* Delay Nth encrypted HS from server. */
int drop; /* drop 1 packet in N (none if 0) */
int mtu; /* drop packets larger than this */
int bad_ad; /* inject corrupted ApplicationData record */
int bad_ad_cli_once; /* Inject corrupted Nth AD from client. */
int bad_ad_srv_once; /* Inject corrupted Nth AD from server. */
unsigned bad_cid; /* inject corrupted CID record */
int protect_hvr; /* never drop or delay HelloVerifyRequest */
int protect_len; /* never drop/delay packet of the given size*/
@ -235,16 +219,6 @@ static void get_options(int argc, char *argv[])
if (opt.delay_ccs < 0 || opt.delay_ccs > 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay_encrypted_hs_cli") == 0) {
opt.delay_encrypted_hs_cli = atoi(q);
if (opt.delay_encrypted_hs_cli < 0) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay_encrypted_hs_srv") == 0) {
opt.delay_encrypted_hs_srv = atoi(q);
if (opt.delay_encrypted_hs_srv < 0) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay_cli") == 0 ||
strcmp(p, "delay_srv") == 0) {
uint8_t *delay_cnt;
@ -297,16 +271,6 @@ static void get_options(int argc, char *argv[])
if (opt.bad_ad < 0 || opt.bad_ad > 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "bad_ad_cli_once") == 0) {
opt.bad_ad_cli_once = atoi(q);
if (opt.bad_ad_cli_once < 0) {
exit_usage(p, q);
}
} else if (strcmp(p, "bad_ad_srv_once") == 0) {
opt.bad_ad_srv_once = atoi(q);
if (opt.bad_ad_srv_once < 0) {
exit_usage(p, q);
}
}
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
else if (strcmp(p, "bad_cid") == 0) {
@ -564,35 +528,6 @@ typedef enum {
static inject_clihlo_state_t inject_clihlo_state;
static packet initial_clihlo;
static unsigned bad_ad_cli_seen;
static unsigned bad_ad_srv_seen;
static int bad_ad_once(const packet *p)
{
unsigned *seen;
int bad_ad_at;
if (strcmp(p->type, "ApplicationData") != 0) {
return 0;
}
if (strcmp(p->way, "S <- C") == 0) {
seen = &bad_ad_cli_seen;
bad_ad_at = opt.bad_ad_cli_once;
} else {
seen = &bad_ad_srv_seen;
bad_ad_at = opt.bad_ad_srv_once;
}
if (bad_ad_at <= 0) {
return 0;
}
++*seen;
return *seen == (unsigned) bad_ad_at;
}
static int send_packet(const packet *p, const char *why)
{
int ret;
@ -624,7 +559,7 @@ static int send_packet(const packet *p, const char *why)
}
/* insert corrupted ApplicationData record? */
if ((bad_ad_once(p) || opt.bad_ad) &&
if (opt.bad_ad &&
strcmp(p->type, "ApplicationData") == 0) {
unsigned char buf[MAX_MSG_SIZE];
memcpy(buf, p->buf, p->len);
@ -729,31 +664,6 @@ static int send_delayed(void)
static unsigned char held[2048] = { 0 };
#define HOLD_MAX 2
static unsigned encrypted_hs_cli_seen;
static unsigned encrypted_hs_srv_seen;
static int delay_encrypted_hs(const packet *p)
{
unsigned *seen;
int delay_at;
if (strcmp(p->type, "Encrypted handshake") != 0) {
return 0;
}
if (strcmp(p->way, "S <- C") == 0) {
seen = &encrypted_hs_cli_seen;
delay_at = opt.delay_encrypted_hs_cli;
} else {
seen = &encrypted_hs_srv_seen;
delay_at = opt.delay_encrypted_hs_srv;
}
++*seen;
return delay_at > 0 && *seen == (unsigned) delay_at;
}
static int handle_message(const char *way,
mbedtls_net_context *dst,
mbedtls_net_context *src)
@ -807,11 +717,6 @@ static int handle_message(const char *way,
}
}
if (delay_encrypted_hs(&cur)) {
delay_packet(&cur);
return 0;
}
/* do we want to drop, delay, or forward it? */
if ((opt.mtu != 0 &&
cur.len > (unsigned) opt.mtu) ||
@ -946,10 +851,6 @@ accept:
*/
clear_pending();
memset(held, 0, sizeof(held));
encrypted_hs_cli_seen = 0;
encrypted_hs_srv_seen = 0;
bad_ad_cli_seen = 0;
bad_ad_srv_seen = 0;
nb_fds = client_fd.fd;
if (nb_fds < server_fd.fd) {

View File

@ -1,7 +1,6 @@
# Python package requirements for Mbed TLS testing.
-r driver.requirements.txt
-r ../framework/scripts/ci.requirements.txt
# The dependencies below are only used in scripts that we run on the Linux CI.
@ -18,8 +17,12 @@ pylint == 2.4.4; platform_system == 'Linux'
# mypy 0.942 is the version in Ubuntu 22.04.
mypy == 0.942; platform_system == 'Linux'
# More requirements for scripts in the framework that might not work in
# older versions of Python. Note that requirements that are not available
# in the oldest version of Python on our CI must be annodated with
# "python >= ...".
-r ../framework/util/requirements.txt
# At the time of writing, only needed for tests/scripts/audit-validity-dates.py.
# It needs >=35.0.0 for correct operation, and that requires Python >=3.6.
# >=35.0.0 also requires Rust to build from source, which we are forced to do on
# FreeBSD, since PyPI doesn't carry binary wheels for the BSDs.
cryptography >= 35.0.0; platform_system == 'Linux'
# For building `framework/data_files/server9-bad-saltlen.crt` and check python
# files.
asn1crypto; platform_system == 'Linux'

237
scripts/ecp_comb_table.py Executable file
View File

@ -0,0 +1,237 @@
#!/usr/bin/env python3
"""
Purpose
This script dumps comb table of ec curve. When you add a new ec curve, you
can use this script to generate codes to define `<curve>_T` in ecp_curves.c
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import os
import subprocess
import sys
import tempfile
HOW_TO_ADD_NEW_CURVE = """
If you are trying to add new curve, you can follow these steps:
1. Define curve parameters (<curve>_p, <curve>_gx, etc...) in ecp_curves.c.
2. Add a macro to define <curve>_T to NULL following these parameters.
3. Build mbedcrypto
4. Run this script with an argument of new curve
5. Copy the output of this script into ecp_curves.c and replace the macro added
in Step 2
6. Rebuild and test if everything is ok
Replace the <curve> in the above with the name of the curve you want to add."""
CC = os.getenv('CC', 'cc')
MBEDTLS_LIBRARY_PATH = os.getenv('MBEDTLS_LIBRARY_PATH', "library")
SRC_DUMP_COMB_TABLE = r'''
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/ecp.h"
#include "mbedtls/error.h"
static void dump_mpi_initialize( const char *name, const mbedtls_mpi *d )
{
uint8_t buf[128] = {0};
size_t olen;
uint8_t *p;
olen = mbedtls_mpi_size( d );
mbedtls_mpi_write_binary_le( d, buf, olen );
printf("static const mbedtls_mpi_uint %s[] = {\n", name);
for (p = buf; p < buf + olen; p += 8) {
printf( " BYTES_TO_T_UINT_8( 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X ),\n",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7] );
}
printf("};\n");
}
static void dump_T( const mbedtls_ecp_group *grp )
{
char name[128];
printf( "#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1\n" );
for (size_t i = 0; i < grp->T_size; ++i) {
snprintf( name, sizeof(name), "%s_T_%zu_X", CURVE_NAME, i );
dump_mpi_initialize( name, &grp->T[i].X );
snprintf( name, sizeof(name), "%s_T_%zu_Y", CURVE_NAME, i );
dump_mpi_initialize( name, &grp->T[i].Y );
}
printf( "static const mbedtls_ecp_point %s_T[%zu] = {\n", CURVE_NAME, grp->T_size );
size_t olen;
for (size_t i = 0; i < grp->T_size; ++i) {
int z;
if ( mbedtls_mpi_cmp_int(&grp->T[i].Z, 0) == 0 ) {
z = 0;
} else if ( mbedtls_mpi_cmp_int(&grp->T[i].Z, 1) == 0 ) {
z = 1;
} else {
fprintf( stderr, "Unexpected value of Z (i = %d)\n", (int)i );
exit( 1 );
}
printf( " ECP_POINT_INIT_XY_Z%d(%s_T_%zu_X, %s_T_%zu_Y),\n",
z,
CURVE_NAME, i,
CURVE_NAME, i
);
}
printf("};\n#endif\n\n");
}
int main()
{
int rc;
mbedtls_mpi m;
mbedtls_ecp_point R;
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
rc = mbedtls_ecp_group_load( &grp, CURVE_ID );
if (rc != 0) {
char buf[100];
mbedtls_strerror( rc, buf, sizeof(buf) );
fprintf( stderr, "mbedtls_ecp_group_load: %s (-0x%x)\n", buf, -rc );
return 1;
}
grp.T = NULL;
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &m);
mbedtls_mpi_lset( &m, 1 );
rc = mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL );
if ( rc != 0 ) {
char buf[100];
mbedtls_strerror( rc, buf, sizeof(buf) );
fprintf( stderr, "mbedtls_ecp_mul: %s (-0x%x)\n", buf, -rc );
return 1;
}
if ( grp.T == NULL ) {
fprintf( stderr, "grp.T is not generated. Please make sure"
"MBEDTLS_ECP_FIXED_POINT_OPTIM is enabled in mbedtls_config.h\n" );
return 1;
}
dump_T( &grp );
return 0;
}
'''
SRC_DUMP_KNOWN_CURVE = r'''
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/ecp.h"
int main() {
const mbedtls_ecp_curve_info *info = mbedtls_ecp_curve_list();
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
while ( info->name != NULL ) {
mbedtls_ecp_group_load( &grp, info->grp_id );
if ( mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) {
printf( " %s", info->name );
}
info++;
}
printf( "\n" );
return 0;
}
'''
def join_src_path(*args):
return os.path.normpath(os.path.join(os.path.dirname(__file__), "..", *args))
def run_c_source(src, cflags):
"""
Compile and run C source code
:param src: the c language code to run
:param cflags: additional cflags passing to compiler
:return:
"""
binname = tempfile.mktemp(prefix="mbedtls")
fd, srcname = tempfile.mkstemp(prefix="mbedtls", suffix=".c")
srcfile = os.fdopen(fd, mode="w")
srcfile.write(src)
srcfile.close()
args = [CC,
*cflags,
'-I' + join_src_path("include"),
"-o", binname,
'-L' + MBEDTLS_LIBRARY_PATH,
srcname,
'-lmbedcrypto']
p = subprocess.run(args=args, check=False)
if p.returncode != 0:
return False
p = subprocess.run(args=[binname], check=False, env={
'LD_LIBRARY_PATH': MBEDTLS_LIBRARY_PATH
})
if p.returncode != 0:
return False
os.unlink(srcname)
os.unlink(binname)
return True
def compute_curve(curve):
"""compute comb table for curve"""
r = run_c_source(
SRC_DUMP_COMB_TABLE,
[
'-g',
'-DCURVE_ID=MBEDTLS_ECP_DP_%s' % curve.upper(),
'-DCURVE_NAME="%s"' % curve.lower(),
])
if not r:
print("""\
Unable to compile and run utility.""", file=sys.stderr)
sys.exit(1)
def usage():
print("""
Usage: python %s <curve>...
Arguments:
curve Specify one or more curve names (e.g secp256r1)
All possible curves: """ % sys.argv[0])
run_c_source(SRC_DUMP_KNOWN_CURVE, [])
print("""
Environment Variable:
CC Specify which c compile to use to compile utility.
MBEDTLS_LIBRARY_PATH
Specify the path to mbedcrypto library. (e.g. build/library/)
How to add a new curve: %s""" % HOW_TO_ADD_NEW_CURVE)
def run_main():
shared_lib_path = os.path.normpath(os.path.join(MBEDTLS_LIBRARY_PATH, "libmbedcrypto.so"))
static_lib_path = os.path.normpath(os.path.join(MBEDTLS_LIBRARY_PATH, "libmbedcrypto.a"))
if not os.path.exists(shared_lib_path) and not os.path.exists(static_lib_path):
print("Warning: both '%s' and '%s' are not exists. This script will use "
"the library from your system instead of the library compiled by "
"this source directory.\n"
"You can specify library path using environment variable "
"'MBEDTLS_LIBRARY_PATH'." % (shared_lib_path, static_lib_path),
file=sys.stderr)
if len(sys.argv) <= 1:
usage()
else:
for curve in sys.argv[1:]:
compute_curve(curve)
if __name__ == '__main__':
run_main()

View File

@ -15,6 +15,3 @@ import sys
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir,
'framework', 'scripts'))
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir,
'tf-psa-crypto', 'scripts', 'project_knowledge'))

View File

@ -188,7 +188,7 @@ foreach my $match (@matches)
$first = 0;
foreach my $dep (split(/,/, ${$old_define_name}))
{
${$code_check} .= " ||\n " if ($first++);
${$code_check} .= " || \n " if ($first++);
${$code_check} .= "${$old_define_prefix}${dep}${$old_define_suffix}";
}
${$code_check} .= " */\n\n";
@ -229,7 +229,7 @@ if ($ll_old_define[0] ne "")
my $first = 0;
foreach my $dep (split(/,/, $ll_old_define[0]))
{
$ll_code_check .= " ||\n " if ($first++);
$ll_code_check .= " || \n " if ($first++);
$ll_code_check .= "${ll_old_define[1]}${dep}${ll_old_define[2]}";
}
$ll_code_check .= " */\n";
@ -240,7 +240,7 @@ if ($hl_old_define[0] ne "")
my $first = 0;
foreach my $dep (split(/,/, $hl_old_define[0]))
{
$hl_code_check .= " ||\n " if ($first++);
$hl_code_check .= " || \n " if ($first++);
$hl_code_check .= "${hl_old_define[1]}${dep}${hl_old_define[2]}";
}
$hl_code_check .= " */\n";

View File

@ -1,20 +0,0 @@
"""Add our Python library directories for maintainer scripts to the module search path.
Usage:
import maintainer_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, os.path.pardir,
'framework', 'scripts'))
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir, os.path.pardir,
'framework', 'util'))

36
scripts/massif_max.pl Executable file
View File

@ -0,0 +1,36 @@
#!/usr/bin/env perl
# Parse a massif.out.xxx file and output peak total memory usage
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use warnings;
use strict;
use utf8;
use open qw(:std utf8);
die unless @ARGV == 1;
my @snaps;
open my $fh, '<', $ARGV[0] or die;
{ local $/ = 'snapshot='; @snaps = <$fh>; }
close $fh or die;
my ($max, $max_heap, $max_he, $max_stack) = (0, 0, 0, 0);
for (@snaps)
{
my ($heap, $heap_extra, $stack) = m{
mem_heap_B=(\d+)\n
mem_heap_extra_B=(\d+)\n
mem_stacks_B=(\d+)
}xm;
next unless defined $heap;
my $total = $heap + $heap_extra + $stack;
if( $total > $max ) {
($max, $max_heap, $max_he, $max_stack) = ($total, $heap, $heap_extra, $stack);
}
}
printf "$max (heap $max_heap+$max_he, stack $max_stack)\n";

View File

@ -90,7 +90,7 @@ do_config()
kill $SRV_PID
wait $SRV_PID
framework/scripts/massif_max.pl massif.out.*
scripts/massif_max.pl massif.out.*
mv massif.out.* massif-$NAME.$$
}

View File

@ -19,6 +19,10 @@ LOCAL_CFLAGS += $(TF_PSA_CRYPTO_LIBRARY_PRIVATE_INCLUDE)
# on non-POSIX platforms.
LOCAL_CFLAGS += -D_POSIX_C_SOURCE=200809L
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
LOCAL_CFLAGS += -Werror -DRECORD_PSA_STATUS_COVERAGE_LOG
endif
GENERATED_MBEDTLS_CONFIG_DATA_FILES := $(patsubst tests/%,%,$(shell \
$(PYTHON) ../framework/scripts/generate_config_tests.py --list || \
echo FAILED \
@ -106,6 +110,12 @@ include/test/test_keys.h: ../framework/scripts/generate_test_keys.py
$(PYTHON) ../framework/scripts/generate_test_keys.py --output $@
TEST_OBJS_DEPS = $(wildcard include/test/*.h include/test/*/*.h)
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
# Explicitly depend on this header because on a clean copy of the source tree,
# it doesn't exist yet and must be generated as part of the build, and
# therefore the wildcard enumeration above doesn't include it.
TEST_OBJS_DEPS += ../framework/tests/include/test/instrument_record_status.h
endif
TEST_OBJS_DEPS += include/test/test_certs.h include/test/test_keys.h \
../tf-psa-crypto/tests/include/test/test_keys.h
@ -301,3 +311,9 @@ libtestdriver1.a:
fi
$(MAKE) -C ./libtestdriver1/library CFLAGS="-I../../ $(CFLAGS)" LDFLAGS="$(LDFLAGS)" libmbedcrypto.a
cp ./libtestdriver1/library/libmbedcrypto.a ../library/libtestdriver1.a
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
../framework/tests/include/test/instrument_record_status.h: ../tf-psa-crypto/include/psa/crypto.h Makefile
echo " Gen $@"
sed <../tf-psa-crypto/include/psa/crypto.h >$@ -n 's/^psa_status_t \([A-Za-z0-9_]*\)(.*/#define \1(...) RECORD_STATUS("\1", \1(__VA_ARGS__))/p'
endif

View File

@ -541,6 +541,19 @@ setup_arguments()
G_SERVER_ARGS="-p $PORT --http $G_MODE"
G_SERVER_PRIO="NORMAL:${G_PRIO_CCM}+NULL:+MD5:+PSK:+ECDHE-PSK:+SHA256:+SHA384:-VERS-TLS-ALL:$G_PRIO_MODE"
# The default prime for `openssl s_server` depends on the version:
# * OpenSSL <= 1.0.2a: 512-bit
# * OpenSSL 1.0.2b to 1.1.1b: 1024-bit
# * OpenSSL >= 1.1.1c: 2048-bit
# Mbed TLS wants >=1024, so force that for older versions. Don't force
# it for newer versions, which reject a 1024-bit prime. Indifferently
# force it or not for intermediate versions.
case $($OPENSSL version) in
"OpenSSL 1.0"*)
O_SERVER_ARGS="$O_SERVER_ARGS -dhparam $DATA_FILES_PATH/dhparams.pem"
;;
esac
# with OpenSSL 1.0.1h, -www, -WWW and -HTTP break DTLS handshakes
if is_dtls "$MODE"; then
O_SERVER_ARGS="$O_SERVER_ARGS"

View File

@ -16,10 +16,12 @@
#include <string.h>
#include <test/helpers.h>
#include <test/macros.h>
#include <test/random.h>
#include <test/psa_crypto_helpers.h>
#if defined(MBEDTLS_SSL_TLS_C)
#include <ssl_misc.h>
#include <mbedtls/timing.h>
#include <mbedtls/debug.h>
@ -29,6 +31,10 @@
#include "mbedtls/ssl_cache.h"
#endif
#define PSA_TO_MBEDTLS_ERR(status) PSA_TO_MBEDTLS_ERR_LIST(status, \
psa_to_ssl_errors, \
psa_generic_status_to_mbedtls)
#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
#if defined(PSA_WANT_KEY_TYPE_AES)
#if defined(PSA_WANT_ALG_GCM)
@ -100,13 +106,17 @@
#define MBEDTLS_TEST_HAS_ADDITIONAL_HASH
#endif
enum {
#define MBEDTLS_SSL_TLS1_3_LABEL(name, string) \
tls13_label_ ## name,
MBEDTLS_SSL_TLS1_3_LABEL_LIST
#undef MBEDTLS_SSL_TLS1_3_LABEL
};
#if defined(MBEDTLS_SSL_ALPN)
#define MBEDTLS_TEST_MAX_ALPN_LIST_SIZE 10
#endif
/* Forward declaration. Defined below. */
struct mbedtls_test_ssl_endpoint;
typedef struct mbedtls_test_ssl_log_pattern {
const char *pattern;
size_t counter;
@ -137,35 +147,6 @@ typedef struct mbedtls_test_handshake_test_options {
int expected_srv_fragments;
int renegotiate;
int legacy_renegotiation;
/** Hook that mbedtls_test_ssl_perform_handshake() runs just before
* the initial handshake. */
void (*pre_handshake_fun)(struct mbedtls_test_ssl_endpoint *client,
struct mbedtls_test_ssl_endpoint *server,
void *param);
/** Value passed to ::pre_handshake_fun. */
void *pre_handshake_param;
/** Hook that mbedtls_test_ssl_perform_handshake() runs after
* the initial handshake succeeds. */
void (*post_handshake_fun)(struct mbedtls_test_ssl_endpoint *client,
struct mbedtls_test_ssl_endpoint *server,
void *param);
/** Value passed to ::post_handshake_fun. */
void *post_handshake_param;
/** Hook that mbedtls_test_ssl_perform_handshake() runs after
* exchanging some data, before testing additional features such as
* serialization and renegotiation. */
void (*post_data_fun)(struct mbedtls_test_ssl_endpoint *client,
struct mbedtls_test_ssl_endpoint *server,
void *param);
/** Value passed to ::post_data_fun. */
void *post_data_param;
/** Hook that mbedtls_test_ssl_perform_handshake() runs after a successful
* connection, just before closing down. */
void (*pre_shutdown_fun)(struct mbedtls_test_ssl_endpoint *client,
struct mbedtls_test_ssl_endpoint *server,
void *param);
/** Value passed to ::pre_shutdown_fun. */
void *pre_shutdown_param;
void *srv_log_obj;
void *cli_log_obj;
void (*srv_log_fun)(void *, int, const char *, int, const char *);
@ -601,6 +582,68 @@ int mbedtls_test_move_handshake_to_state(mbedtls_ssl_context *ssl,
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
/*
* Helper function setting up inverse record transformations
* using given cipher, hash, EtM mode, authentication tag length,
* and version.
*/
#define CHK(x) \
do \
{ \
if (!(x)) \
{ \
ret = -1; \
goto cleanup; \
} \
} while (0)
#if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_IN_LEN_MAX
#else
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_OUT_LEN_MAX
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(PSA_WANT_ALG_CBC_NO_PADDING) && defined(PSA_WANT_KEY_TYPE_AES)
int mbedtls_test_psa_cipher_encrypt_helper(mbedtls_ssl_transform *transform,
const unsigned char *iv,
size_t iv_len,
const unsigned char *input,
size_t ilen,
unsigned char *output,
size_t *olen);
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && PSA_WANT_ALG_CBC_NO_PADDING &&
PSA_WANT_KEY_TYPE_AES */
int mbedtls_test_ssl_build_transforms(mbedtls_ssl_transform *t_in,
mbedtls_ssl_transform *t_out,
int cipher_type, int hash_id,
int etm, int tag_mode,
mbedtls_ssl_protocol_version tls_version,
size_t cid0_len,
size_t cid1_len);
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
/**
* \param[in,out] record The record to prepare.
* It must contain the data to MAC at offset
* `record->data_offset`, of length
* `record->data_length`.
* On success, write the MAC immediately
* after the data and increment
* `record->data_length` accordingly.
* \param[in,out] transform_out The out transform, typically prepared by
* mbedtls_test_ssl_build_transforms().
* Its HMAC context may be used. Other than that
* it is treated as an input parameter.
*
* \return 0 on success, an `MBEDTLS_ERR_xxx` error code
* or -1 on error.
*/
int mbedtls_test_ssl_prepare_record_mac(mbedtls_record *record,
mbedtls_ssl_transform *transform_out);
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
/*
* Populate a session structure for serialization tests.
* Choose dummy values, mostly non-0 to distinguish from the init default.
@ -700,6 +743,23 @@ void mbedtls_test_ssl_perform_handshake(
const mbedtls_test_handshake_test_options *options);
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
#if defined(MBEDTLS_TEST_HOOKS)
/*
* Tweak vector lengths in a TLS 1.3 Certificate message
*
* \param[in] buf Buffer containing the Certificate message to tweak
* \param[in]]out] end End of the buffer to parse
* \param tweak Tweak identifier (from 1 to the number of tweaks).
* \param[out] expected_result Error code expected from the parsing function
* \param[out] args Arguments of the MBEDTLS_SSL_CHK_BUF_READ_PTR call that
* is expected to fail. All zeroes if no
* MBEDTLS_SSL_CHK_BUF_READ_PTR failure is expected.
*/
int mbedtls_test_tweak_tls13_certificate_msg_vector_len(
unsigned char *buf, unsigned char **end, int tweak,
int *expected_result, mbedtls_ssl_chk_buf_ptr_args *args);
#endif /* MBEDTLS_TEST_HOOKS */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
int mbedtls_test_ticket_write(
void *p_ticket, const mbedtls_ssl_session *session,
@ -746,23 +806,6 @@ int mbedtls_test_get_tls13_ticket(
&psa_type, &psa_bits), \
PSA_ERROR_NOT_SUPPORTED);
/**
* Verify that mbedtls_ssl_session_reset() properly managed fields of the
* mbedtls_ssl_context structure. The expected action on reset depends on the
* specific field.
*
* Note: the code is automatically generated from the python script
* "tests/scripts/generate_ssl_session_reset_check.py".
*
* \param[in] before The SSL context before mbedtls_ssl_session_reset()
* is called on it. This is used for fields that
* should be kept untouched during the reset.
* \param[in] after The SSL context after mbedtls_ssl_session_reset()
* has been called on it.
*/
int mbedtls_test_ssl_check_context_after_session_reset(const mbedtls_ssl_context *before,
const mbedtls_ssl_context *after);
#endif /* MBEDTLS_SSL_TLS_C */
#endif /* SSL_HELPERS_H */

View File

@ -1,110 +0,0 @@
/** \file ssl_helpers.h
*
* \brief This file contains helper functions for TLS that rely on private
* headers.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef SSL_HELPERS_INTERNAL_H
#define SSL_HELPERS_INTERNAL_H
#if defined(MBEDTLS_SSL_TLS_C)
#include <ssl_misc.h>
#define PSA_TO_MBEDTLS_ERR(status) PSA_TO_MBEDTLS_ERR_LIST(status, \
psa_to_ssl_errors, \
psa_generic_status_to_mbedtls)
enum {
#define MBEDTLS_SSL_TLS1_3_LABEL(name, string) \
tls13_label_ ## name,
MBEDTLS_SSL_TLS1_3_LABEL_LIST
#undef MBEDTLS_SSL_TLS1_3_LABEL
};
/*
* Helper function setting up inverse record transformations
* using given cipher, hash, EtM mode, authentication tag length,
* and version.
*/
#define CHK(x) \
do \
{ \
if (!(x)) \
{ \
ret = -1; \
goto cleanup; \
} \
} while (0)
#if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_IN_LEN_MAX
#else
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_OUT_LEN_MAX
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(PSA_WANT_ALG_CBC_NO_PADDING) && defined(PSA_WANT_KEY_TYPE_AES)
int mbedtls_test_psa_cipher_encrypt_helper(mbedtls_ssl_transform *transform,
const unsigned char *iv,
size_t iv_len,
const unsigned char *input,
size_t ilen,
unsigned char *output,
size_t *olen);
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && PSA_WANT_ALG_CBC_NO_PADDING &&
PSA_WANT_KEY_TYPE_AES */
int mbedtls_test_ssl_build_transforms(mbedtls_ssl_transform *t_in,
mbedtls_ssl_transform *t_out,
int cipher_type, int hash_id,
int etm, int tag_mode,
mbedtls_ssl_protocol_version tls_version,
size_t cid0_len,
size_t cid1_len);
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
/**
* \param[in,out] record The record to prepare.
* It must contain the data to MAC at offset
* `record->data_offset`, of length
* `record->data_length`.
* On success, write the MAC immediately
* after the data and increment
* `record->data_length` accordingly.
* \param[in,out] transform_out The out transform, typically prepared by
* mbedtls_test_ssl_build_transforms().
* Its HMAC context may be used. Other than that
* it is treated as an input parameter.
*
* \return 0 on success, an `MBEDTLS_ERR_xxx` error code
* or -1 on error.
*/
int mbedtls_test_ssl_prepare_record_mac(mbedtls_record *record,
mbedtls_ssl_transform *transform_out);
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
#if defined(MBEDTLS_TEST_HOOKS)
/*
* Tweak vector lengths in a TLS 1.3 Certificate message
*
* \param[in] buf Buffer containing the Certificate message to tweak
* \param[in]]out] end End of the buffer to parse
* \param tweak Tweak identifier (from 1 to the number of tweaks).
* \param[out] expected_result Error code expected from the parsing function
* \param[out] args Arguments of the MBEDTLS_SSL_CHK_BUF_READ_PTR call that
* is expected to fail. All zeroes if no
* MBEDTLS_SSL_CHK_BUF_READ_PTR failure is expected.
*/
int mbedtls_test_tweak_tls13_certificate_msg_vector_len(
unsigned char *buf, unsigned char **end, int tweak,
int *expected_result, mbedtls_ssl_chk_buf_ptr_args *args);
#endif /* MBEDTLS_TEST_HOOKS */
#endif /* MBEDTLS_SSL_TLS_C */
#endif /* SSL_HELPERS_INTERNAL_H */

View File

@ -6,35 +6,34 @@ This script can also run on outcomes from a partial run, but the results are
less likely to be useful.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import importlib
import importlib.machinery
import importlib.util
import os
import re
import sys
import types
import typing
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import outcome_analysis
# Until all TF-PSA-Crypto branches we care about have
# scripts/project_knowledge/tf_psa_crypto_test_case_info.py,
# fall back to its previous location where we load it manually
# (see the _load_crypto_module method below).
try:
import tf_psa_crypto_test_case_info #type: ignore #pylint: disable=unused-import
except ImportError:
pass
class CoverageTask(outcome_analysis.CoverageTask):
"""Justify test cases that are never executed."""
UNCOVERED_TESTS = {
@staticmethod
def _has_word_re(words: typing.Iterable[str],
exclude: typing.Optional[str] = None) -> typing.Pattern:
"""Construct a regex that matches if any of the words appears.
The occurrence must start and end at a word boundary.
If exclude is specified, strings containing a match for that
regular expression will not match the returned pattern.
"""
exclude_clause = r''
if exclude:
exclude_clause = r'(?!.*' + exclude + ')'
return re.compile(exclude_clause +
r'.*\b(?:' + r'|'.join(words) + r')\b.*',
re.DOTALL)
IGNORED_TESTS = {
'ssl-opt': [
# We don't run ssl-opt.sh with Valgrind on the CI because
# it's extremely slow. We don't intend to change this.
@ -72,6 +71,12 @@ class CoverageTask(outcome_analysis.CoverageTask):
# https://github.com/Mbed-TLS/mbedtls/issues/9586
'Config: !MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED',
],
'test_suite_config.crypto_combinations': [
# New thing in crypto. Not intended to be tested separately
# in mbedtls.
# https://github.com/Mbed-TLS/mbedtls/issues/10300
'Config: entropy: NV seed only',
],
'test_suite_config.psa_boolean': [
# We don't test with HMAC disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9591
@ -222,57 +227,6 @@ class CoverageTask(outcome_analysis.CoverageTask):
],
}
@staticmethod
def _load_crypto_module() -> typing.Optional[types.ModuleType]:
"""Try to load the information about test cases from the tf-psa-crypto submodule.."""
# All this complexity is because we didn't want to add
# `tf-psa-crypto/tests/scripts/` to the import path.
# The new location `tf-psa-crypto/scripts/project_knowledge` is
# on the import path. So once we can assume that all crypto
# branches have the new location, this whole function can go away.
# https://github.com/Mbed-TLS/mbedtls/issues/10699.
if 'tf_psa_crypto_test_case_info' in sys.modules:
return sys.modules['tf_psa_crypto_test_case_info']
crypto_script_path = 'tf-psa-crypto/tests/scripts/tf_psa_crypto_test_case_info.py'
if not os.path.exists(crypto_script_path):
# During a transition period, while the crypto script is not
# yet present in all branches we care about, allow it not to
# exist.
return None
crypto_spec = importlib.util.spec_from_file_location(
'tf_psa_crypto_test_case_info',
crypto_script_path)
# Assertions and type annotation to help mypy.
assert crypto_spec is not None
assert crypto_spec.loader is not None
crypto_module = importlib.util.module_from_spec(crypto_spec)
crypto_spec.loader.exec_module(crypto_module)
sys.modules['tf_psa_crypto_test_case_info'] = crypto_module
return crypto_module
def _load_crypto_instructions(self) -> None:
"""Try to load instructions from the tf-psa-crypto submodule's outcome analysis."""
crypto_module = self._load_crypto_module()
if crypto_module is not None:
crypto_internal_test_cases = crypto_module.INTERNAL_TEST_CASES
else:
# Legacy set of tests covered by TF-PSA-Crypto only,
# from before Mbed TLS's outcome analysis read that information
# from TF-PSA-Crypto. This branch can be removed once
# the presence of the crypto module becomes mandatory.
crypto_internal_test_cases = {
'test_suite_config.crypto_combinations': [
'Config: entropy: NV seed only',
],
}
self.ignored_tests.extend(crypto_internal_test_cases)
def __init__(self, options) -> None:
super().__init__(options)
self.crypto_module = None # declared with a type in _load_crypto_module above
self._load_crypto_instructions()
# List of tasks with a function that can handle this task and additional arguments if required
KNOWN_TASKS: typing.Dict[str, typing.Type[outcome_analysis.Task]] = {
'analyze_coverage': CoverageTask,

View File

@ -0,0 +1,469 @@
#!/usr/bin/env python3
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""Audit validity date of X509 crt/crl/csr.
This script is used to audit the validity date of crt/crl/csr used for testing.
It prints the information about X.509 objects excluding the objects that
are valid throughout the desired validity period. The data are collected
from framework/data_files/ and tests/suites/*.data files by default.
"""
import os
import re
import typing
import argparse
import datetime
import glob
import logging
import hashlib
from enum import Enum
# The script requires cryptography >= 35.0.0 which is only available
# for Python >= 3.6.
import cryptography
from cryptography import x509
from generate_test_code import FileWrapper
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
from mbedtls_framework import logging_util
def check_cryptography_version():
match = re.match(r'^[0-9]+', cryptography.__version__)
if match is None or int(match.group(0)) < 35:
raise Exception("audit-validity-dates requires cryptography >= 35.0.0"
+ "({} is too old)".format(cryptography.__version__))
class DataType(Enum):
CRT = 1 # Certificate
CRL = 2 # Certificate Revocation List
CSR = 3 # Certificate Signing Request
class DataFormat(Enum):
PEM = 1 # Privacy-Enhanced Mail
DER = 2 # Distinguished Encoding Rules
class AuditData:
"""Store data location, type and validity period of X.509 objects."""
#pylint: disable=too-few-public-methods
def __init__(self, data_type: DataType, x509_obj):
self.data_type = data_type
# the locations that the x509 object could be found
self.locations = [] # type: typing.List[str]
self.fill_validity_duration(x509_obj)
self._obj = x509_obj
encoding = cryptography.hazmat.primitives.serialization.Encoding.DER
self._identifier = hashlib.sha1(self._obj.public_bytes(encoding)).hexdigest()
@property
def identifier(self):
"""
Identifier of the underlying X.509 object, which is consistent across
different runs.
"""
return self._identifier
def fill_validity_duration(self, x509_obj):
"""Read validity period from an X.509 object."""
# Certificate expires after "not_valid_after"
# Certificate is invalid before "not_valid_before"
if self.data_type == DataType.CRT:
self.not_valid_after = x509_obj.not_valid_after
self.not_valid_before = x509_obj.not_valid_before
# CertificateRevocationList expires after "next_update"
# CertificateRevocationList is invalid before "last_update"
elif self.data_type == DataType.CRL:
self.not_valid_after = x509_obj.next_update
self.not_valid_before = x509_obj.last_update
# CertificateSigningRequest is always valid.
elif self.data_type == DataType.CSR:
self.not_valid_after = datetime.datetime.max
self.not_valid_before = datetime.datetime.min
else:
raise ValueError("Unsupported file_type: {}".format(self.data_type))
class X509Parser:
"""A parser class to parse crt/crl/csr file or data in PEM/DER format."""
PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}(?P<data>.*?)-{5}END (?P=type)-{5}'
PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
PEM_TAGS = {
DataType.CRT: 'CERTIFICATE',
DataType.CRL: 'X509 CRL',
DataType.CSR: 'CERTIFICATE REQUEST'
}
def __init__(self,
backends:
typing.Dict[DataType,
typing.Dict[DataFormat,
typing.Callable[[bytes], object]]]) \
-> None:
self.backends = backends
self.__generate_parsers()
def __generate_parser(self, data_type: DataType):
"""Parser generator for a specific DataType"""
tag = self.PEM_TAGS[data_type]
pem_loader = self.backends[data_type][DataFormat.PEM]
der_loader = self.backends[data_type][DataFormat.DER]
def wrapper(data: bytes):
pem_type = X509Parser.pem_data_type(data)
# It is in PEM format with target tag
if pem_type == tag:
return pem_loader(data)
# It is in PEM format without target tag
if pem_type:
return None
# It might be in DER format
try:
result = der_loader(data)
except ValueError:
result = None
return result
wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
return wrapper
def __generate_parsers(self):
"""Generate parsers for all support DataType"""
self.parsers = {}
for data_type, _ in self.PEM_TAGS.items():
self.parsers[data_type] = self.__generate_parser(data_type)
def __getitem__(self, item):
return self.parsers[item]
@staticmethod
def pem_data_type(data: bytes) -> typing.Optional[str]:
"""Get the tag from the data in PEM format
:param data: data to be checked in binary mode.
:return: PEM tag or "" when no tag detected.
"""
m = re.search(X509Parser.PEM_TAG_REGEX, data)
if m is not None:
return m.group('type').decode('UTF-8')
else:
return None
@staticmethod
def check_hex_string(hex_str: str) -> bool:
"""Check if the hex string is possibly DER data."""
hex_len = len(hex_str)
# At least 6 hex char for 3 bytes: Type + Length + Content
if hex_len < 6:
return False
# Check if Type (1 byte) is SEQUENCE.
if hex_str[0:2] != '30':
return False
# Check LENGTH (1 byte) value
content_len = int(hex_str[2:4], base=16)
consumed = 4
if content_len in (128, 255):
# Indefinite or Reserved
return False
elif content_len > 127:
# Definite, Long
length_len = (content_len - 128) * 2
content_len = int(hex_str[consumed:consumed+length_len], base=16)
consumed += length_len
# Check LENGTH
if hex_len != content_len * 2 + consumed:
return False
return True
class Auditor:
"""
A base class that uses X509Parser to parse files to a list of AuditData.
A subclass must implement the following methods:
- collect_default_files: Return a list of file names that are defaultly
used for parsing (auditing). The list will be stored in
Auditor.default_files.
- parse_file: Method that parses a single file to a list of AuditData.
A subclass may override the following methods:
- parse_bytes: Defaultly, it parses `bytes` that contains only one valid
X.509 data(DER/PEM format) to an X.509 object.
- walk_all: Defaultly, it iterates over all the files in the provided
file name list, calls `parse_file` for each file and stores the results
by extending the `results` passed to the function.
"""
def __init__(self, logger):
self.logger = logger
self.default_files = self.collect_default_files()
self.parser = X509Parser({
DataType.CRT: {
DataFormat.PEM: x509.load_pem_x509_certificate,
DataFormat.DER: x509.load_der_x509_certificate
},
DataType.CRL: {
DataFormat.PEM: x509.load_pem_x509_crl,
DataFormat.DER: x509.load_der_x509_crl
},
DataType.CSR: {
DataFormat.PEM: x509.load_pem_x509_csr,
DataFormat.DER: x509.load_der_x509_csr
},
})
def collect_default_files(self) -> typing.List[str]:
"""Collect the default files for parsing."""
raise NotImplementedError
def parse_file(self, filename: str) -> typing.List[AuditData]:
"""
Parse a list of AuditData from file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
raise NotImplementedError
def parse_bytes(self, data: bytes):
"""Parse AuditData from bytes."""
for data_type in list(DataType):
try:
result = self.parser[data_type](data)
except ValueError as val_error:
result = None
self.logger.warning(val_error)
if result is not None:
audit_data = AuditData(data_type, result)
return audit_data
return None
def walk_all(self,
results: typing.Dict[str, AuditData],
file_list: typing.Optional[typing.List[str]] = None) \
-> None:
"""
Iterate over all the files in the list and get audit data. The
results will be written to `results` passed to this function.
:param results: The dictionary used to store the parsed
AuditData. The keys of this dictionary should
be the identifier of the AuditData.
"""
if file_list is None:
file_list = self.default_files
for filename in file_list:
data_list = self.parse_file(filename)
for d in data_list:
if d.identifier in results:
results[d.identifier].locations.extend(d.locations)
else:
results[d.identifier] = d
@staticmethod
def find_test_dir():
"""Get the relative path for the Mbed TLS test directory."""
return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
class TestDataAuditor(Auditor):
"""Class for auditing files in `framework/data_files/`"""
def collect_default_files(self):
"""Collect all files in `framework/data_files/`"""
test_data_glob = os.path.join(build_tree.guess_mbedtls_root(),
'framework', 'data_files/**')
data_files = [f for f in glob.glob(test_data_glob, recursive=True)
if os.path.isfile(f)]
return data_files
def parse_file(self, filename: str) -> typing.List[AuditData]:
"""
Parse a list of AuditData from data file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
with open(filename, 'rb') as f:
data = f.read()
results = []
# Try to parse all PEM blocks.
is_pem = False
for idx, m in enumerate(re.finditer(X509Parser.PEM_REGEX, data, flags=re.S), 1):
is_pem = True
result = self.parse_bytes(data[m.start():m.end()])
if result is not None:
result.locations.append("{}#{}".format(filename, idx))
results.append(result)
# Might be DER format.
if not is_pem:
result = self.parse_bytes(data)
if result is not None:
result.locations.append("{}".format(filename))
results.append(result)
return results
def parse_suite_data(data_f):
"""
Parses .data file for test arguments that possiblly have a
valid X.509 data. If you need a more precise parser, please
use generate_test_code.parse_test_data instead.
:param data_f: file object of the data file.
:return: Generator that yields test function argument list.
"""
for line in data_f:
line = line.strip()
# Skip comments
if line.startswith('#'):
continue
# Check parameters line
match = re.search(r'\A\w+(.*:)?\"', line)
if match:
# Read test vectors
parts = re.split(r'(?<!\\):', line)
parts = [x for x in parts if x]
args = parts[1:]
yield args
class SuiteDataAuditor(Auditor):
"""Class for auditing files in `tests/suites/*.data`"""
def collect_default_files(self):
"""Collect all files in `tests/suites/*.data`"""
test_dir = self.find_test_dir()
suites_data_folder = os.path.join(test_dir, 'suites')
data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
return data_files
def parse_file(self, filename: str):
"""
Parse a list of AuditData from test suite data file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
audit_data_list = []
data_f = FileWrapper(filename)
for test_args in parse_suite_data(data_f):
for idx, test_arg in enumerate(test_args):
match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
if not match:
continue
if not X509Parser.check_hex_string(match.group('data')):
continue
audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
if audit_data is None:
continue
audit_data.locations.append("{}:{}:#{}".format(filename,
data_f.line_no,
idx + 1))
audit_data_list.append(audit_data)
return audit_data_list
def list_all(audit_data: AuditData):
for loc in audit_data.locations:
print("{}\t{:20}\t{:20}\t{:3}\t{}".format(
audit_data.identifier,
audit_data.not_valid_before.isoformat(timespec='seconds'),
audit_data.not_valid_after.isoformat(timespec='seconds'),
audit_data.data_type.name,
loc))
def main():
"""
Perform argument parsing.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-a', '--all',
action='store_true',
help='list the information of all the files')
parser.add_argument('-v', '--verbose',
action='store_true', dest='verbose',
help='show logs')
parser.add_argument('--from', dest='start_date',
help=('Start of desired validity period (UTC, YYYY-MM-DD). '
'Default: today'),
metavar='DATE')
parser.add_argument('--to', dest='end_date',
help=('End of desired validity period (UTC, YYYY-MM-DD). '
'Default: --from'),
metavar='DATE')
parser.add_argument('--data-files', action='append', nargs='*',
help='data files to audit',
metavar='FILE')
parser.add_argument('--suite-data-files', action='append', nargs='*',
help='suite data files to audit',
metavar='FILE')
args = parser.parse_args()
# start main routine
# setup logger
logger = logging.getLogger()
logging_util.configure_logger(logger)
logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
td_auditor = TestDataAuditor(logger)
sd_auditor = SuiteDataAuditor(logger)
data_files = []
suite_data_files = []
if args.data_files is None and args.suite_data_files is None:
data_files = td_auditor.default_files
suite_data_files = sd_auditor.default_files
else:
if args.data_files is not None:
data_files = [x for l in args.data_files for x in l]
if args.suite_data_files is not None:
suite_data_files = [x for l in args.suite_data_files for x in l]
# validity period start date
if args.start_date:
start_date = datetime.datetime.fromisoformat(args.start_date)
else:
start_date = datetime.datetime.today()
# validity period end date
if args.end_date:
end_date = datetime.datetime.fromisoformat(args.end_date)
else:
end_date = start_date
# go through all the files
audit_results = {}
td_auditor.walk_all(audit_results, data_files)
sd_auditor.walk_all(audit_results, suite_data_files)
logger.info("Total: {} objects found!".format(len(audit_results)))
# we filter out the files whose validity duration covers the provided
# duration.
filter_func = lambda d: (start_date < d.not_valid_before) or \
(d.not_valid_after < end_date)
sortby_end = lambda d: d.not_valid_after
if args.all:
filter_func = None
# filter and output the results
for d in sorted(filter(filter_func, audit_results.values()), key=sortby_end):
list_all(d)
logger.debug("Done!")
check_cryptography_version()
if __name__ == "__main__":
main()

View File

@ -1,20 +0,0 @@
#!/usr/bin/env python3
"""
Check that TF-PSA-Crypto files that can be regenerated are up-to-date, or update them.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import config_macros
from mbedtls_framework import generate_files_helper
GENERATORS = [
config_macros.Current(shadow_missing_ok=True),
]
if __name__ == '__main__':
generate_files_helper.main(generators=GENERATORS,
description=__doc__)

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""
Check that files with lists of config options are up-to-date, or update them.
This script checks the following file:
scripts/data_files/config-options-current.txt
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import argparse
import sys
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import config_macros
def main():
parser = argparse.ArgumentParser(description=__doc__)
# For now this script only acts on one target file.
# If we check/update more files, we should add a way to select which
# file(s) to operate on.
parser.add_argument('--always-update', '-U',
action='store_true',
help=('Update target files unconditionally '
'(overrides --update)'))
parser.add_argument('--update', '-u',
action='store_true',
help='Update target files if needed')
args = parser.parse_args()
data = config_macros.Current(shadow_missing_ok=True)
if args.update or args.always_update:
data.update_shadow_file(args.always_update)
else:
up_to_date = True
if not data.is_shadow_file_up_to_date():
print(f'{data.shadow_file_path()} is out of date')
print(f'After adding or removing a config option, you need to run')
print(f'{sys.argv[0]} -u and commit the result.')
up_to_date = False
sys.exit(0 if up_to_date else 1)
if __name__ == "__main__":
main()

View File

@ -45,21 +45,9 @@ component_check_generated_files () {
# This component ends with the generated files present in the source tree.
# This is necessary for subsequent components!
}
support_check_committed_generated_files () {
# Add requirements on the Python installation here for
# the sake of check_committed_generated_files.py in mbedtls.
#
# Check the Python version, not the presence of the package,
# because the CI runs `all.sh --list-components` outside of the
# venv that has our desired packages.
:
}
component_check_committed_generated_files () {
msg "Check committed generated files"
tests/scripts/check_committed_generated_files.py
tests/scripts/check_option_lists.py
}
component_check_doxy_blocks () {

View File

@ -155,60 +155,6 @@ support_test_cmake_as_package_install () {
support_test_cmake_out_of_source
}
component_test_cmake_install_with_destdir () {
# Remove existing generated files so that we use the ones CMake
# generates
$MAKE_COMMAND neat
msg "install: cmake with DESTDIR staging"
MBEDTLS_ROOT_DIR="$PWD"
mkdir "$OUT_OF_SOURCE_DIR"
cd "$OUT_OF_SOURCE_DIR"
cmake -DGEN_FILES=ON -DENABLE_PROGRAMS=OFF -DENABLE_TESTING=OFF -DUSE_SHARED_MBEDTLS_LIBRARY=ON -DCMAKE_INSTALL_PREFIX:PATH=/usr "$MBEDTLS_ROOT_DIR"
make
DESTDIR="$OUT_OF_SOURCE_DIR/stage" make install
install_lib_subdir="$(sed -n 's/^CMAKE_INSTALL_LIBDIR:PATH=//p' CMakeCache.txt)"
[ -n "$install_lib_subdir" ] # Failed to read CMAKE_INSTALL_LIBDIR from CMakeCache.txt
install_lib_path="$OUT_OF_SOURCE_DIR/stage/usr/${install_lib_subdir}"
if [[ "$OSTYPE" == darwin* ]]; then
# On macOS the custom install logic installs libmbedcrypto.dylib
# directly without a versioned symlink chain.
for lib in tfpsacrypto mbedcrypto mbedx509 mbedtls; do
[ -f "$install_lib_path/lib${lib}.a" ]
[ -e "$install_lib_path/lib${lib}.dylib" ]
done
else
# library/CMakeLists.txt installs libmbedcrypto.so with a versioned
# symlink chain on Linux.
for lib in tfpsacrypto mbedcrypto mbedx509 mbedtls; do
if [ "$QUIET" -eq 0 ]; then
echo "Checking lib=$lib"
fi
[ -f "$install_lib_path/lib${lib}.a" ]
[ -L "$install_lib_path/lib${lib}.so" ]
[ -e "$install_lib_path/lib${lib}.so" ]
# Match ABI-version names such as libxxx.so.17
# and check that symlink.
versioned=( "$install_lib_path/lib${lib}.so".+([0-9]) )
if [ "$QUIET" -eq 0 ]; then
declare -p versioned
fi
[ "${#versioned[@]}" -eq 1 ]
[ -L "${versioned[0]}" ]
[ -e "${versioned[0]}" ]
done
fi
}
support_test_cmake_install_with_destdir () {
support_test_cmake_out_of_source
}
component_build_cmake_custom_config_file () {
# Make a copy of config file to use for the in-tree test
cp "$CONFIG_H" include/mbedtls_config_in_tree_copy.h

View File

@ -462,7 +462,7 @@ component_test_everest () {
make test
msg "test: metatests (clang, ASan)"
framework/scripts/run-metatests.sh any asan poison
tests/scripts/run-metatests.sh any asan poison
msg "test: Everest ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s
tests/ssl-opt.sh -f ECDH
@ -493,6 +493,15 @@ component_test_everest_curve25519_only () {
ctest
}
component_test_psa_collect_statuses () {
msg "build+test: psa_collect_statuses" # ~30s
scripts/config.py full
tests/scripts/psa_collect_statuses.py
# Check that psa_crypto_init() succeeded at least once
grep -q '^0:psa_crypto_init:' tests/statuses.log
rm -f tests/statuses.log
}
# Check that the specified libraries exist and are empty.
are_empty_libraries () {
nm "$@" >/dev/null 2>/dev/null

View File

@ -22,7 +22,7 @@ component_test_default_out_of_box () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~10s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
component_test_default_cmake_gcc_asan () {
@ -34,13 +34,13 @@ component_test_default_cmake_gcc_asan () {
make test
msg "program demos (ASan build)" # ~10s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
msg "test: selftest (ASan build)" # ~ 10s
programs/test/selftest
msg "test: metatests (GCC, ASan build)"
framework/scripts/run-metatests.sh any asan poison
tests/scripts/run-metatests.sh any asan poison
msg "test: ssl-opt.sh (ASan build)" # ~ 1 min
tests/ssl-opt.sh
@ -143,10 +143,10 @@ component_test_full_cmake_clang () {
programs/test/cpp_dummy_build
msg "test: metatests (clang)"
framework/scripts/run-metatests.sh any pthread
tests/scripts/run-metatests.sh any pthread
msg "program demos (full config, clang)" # ~10s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
msg "test: psa_constant_names (full config, clang)" # ~ 1s
$FRAMEWORK/scripts/test_psa_constant_names.py
@ -214,7 +214,7 @@ component_test_full_deprecated_warning () {
$MAKE_COMMAND test
msg "program demos: full config + MBEDTLS_TEST_DEPRECATED" # ~10s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
component_build_baremetal () {

View File

@ -330,7 +330,7 @@ component_test_arm_linux_gnueabi_gcc_arm5vte () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_arm5vte () {
@ -350,7 +350,7 @@ component_test_arm_linux_gnueabi_gcc_thumb_1_opt_0 () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_thumb_1_opt_0 () {
@ -368,7 +368,7 @@ component_test_arm_linux_gnueabi_gcc_thumb_1_opt_s () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_thumb_1_opt_s () {
@ -386,7 +386,7 @@ component_test_arm_linux_gnueabihf_gcc_armv7 () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabihf_gcc_armv7 () {
@ -404,7 +404,7 @@ component_test_arm_linux_gnueabihf_gcc_thumb_2 () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabihf_gcc_thumb_2 () {
@ -422,7 +422,7 @@ component_test_aarch64_linux_gnu_gcc () {
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
}
support_test_aarch64_linux_gnu_gcc () {

View File

@ -132,10 +132,10 @@ component_test_memsan () {
make test
msg "test: metatests (MSan)"
framework/scripts/run-metatests.sh any msan
tests/scripts/run-metatests.sh any msan
msg "program demos (MSan)" # ~20s
framework/scripts/run_demos.py
tests/scripts/run_demos.py
msg "test: ssl-opt.sh (MSan)" # ~ 1 min
tests/ssl-opt.sh

View File

@ -274,9 +274,9 @@ REVERSE_DEPENDENCIES = {
'PSA_WANT_ALG_JPAKE': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
'PSA_WANT_ALG_RSA_OAEP': ['PSA_WANT_ALG_RSA_PSS',
'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
'PSA_WANT_ALG_RSA_PKCS1V15_SIGN': ['MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED'],
'PSA_WANT_ALG_RSA_PKCS1V15_CRYPT': ['PSA_WANT_ALG_RSA_PKCS1V15_SIGN',
'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED'],
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC': [
'PSA_WANT_ALG_RSA_PKCS1V15_SIGN',
'PSA_WANT_ALG_RSA_PKCS1V15_CRYPT',
'PSA_WANT_ALG_RSA_OAEP',
'PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY',
@ -495,7 +495,6 @@ class DomainData:
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC',
'PSA_WANT_ALG_RSA_OAEP',
'PSA_WANT_ALG_RSA_PKCS1V15_CRYPT',
'PSA_WANT_ALG_RSA_PKCS1V15_SIGN',
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC',
'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
build_and_test),

96
tests/scripts/gen_ctr_drbg.pl Executable file
View File

@ -0,0 +1,96 @@
#!/usr/bin/env perl
#
# Based on NIST CTR_DRBG.rsp validation file
# Only uses AES-256-CTR cases that use a Derivation function
# and concats nonce and personalization for initialization.
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
my $line = <TEST_DATA>;
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
next if ($line !~ /^\[AES-256 use df/);
my $PredictionResistanceStr = get_suite_val("PredictionResistance");
my $PredictionResistance = 0;
$PredictionResistance = 1 if ($PredictionResistanceStr eq 'True');
my $EntropyInputLen = get_suite_val("EntropyInputLen");
my $NonceLen = get_suite_val("NonceLen");
my $PersonalizationStringLen = get_suite_val("PersonalizationStringLen");
my $AdditionalInputLen = get_suite_val("AdditionalInputLen");
for ($cnt = 0; $cnt < 15; $cnt++)
{
my $Count = get_val("COUNT");
my $EntropyInput = get_val("EntropyInput");
my $Nonce = get_val("Nonce");
my $PersonalizationString = get_val("PersonalizationString");
my $AdditionalInput1 = get_val("AdditionalInput");
my $EntropyInputPR1 = get_val("EntropyInputPR") if ($PredictionResistance == 1);
my $EntropyInputReseed = get_val("EntropyInputReseed") if ($PredictionResistance == 0);
my $AdditionalInputReseed = get_val("AdditionalInputReseed") if ($PredictionResistance == 0);
my $AdditionalInput2 = get_val("AdditionalInput");
my $EntropyInputPR2 = get_val("EntropyInputPR") if ($PredictionResistance == 1);
my $ReturnedBits = get_val("ReturnedBits");
if ($PredictionResistance == 1)
{
print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n");
print("ctr_drbg_validate_pr");
print(":\"$Nonce$PersonalizationString\"");
print(":\"$EntropyInput$EntropyInputPR1$EntropyInputPR2\"");
print(":\"$AdditionalInput1\"");
print(":\"$AdditionalInput2\"");
print(":\"$ReturnedBits\"");
print("\n\n");
}
else
{
print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n");
print("ctr_drbg_validate_nopr");
print(":\"$Nonce$PersonalizationString\"");
print(":\"$EntropyInput$EntropyInputReseed\"");
print(":\"$AdditionalInput1\"");
print(":\"$AdditionalInputReseed\"");
print(":\"$AdditionalInput2\"");
print(":\"$ReturnedBits\"");
print("\n\n");
}
}
}
close(TEST_DATA);

101
tests/scripts/gen_gcm_decrypt.pl Executable file
View File

@ -0,0 +1,101 @@
#!/usr/bin/env perl
#
# Based on NIST gcmDecryptxxx.rsp validation files
# Only first 3 of every set used for compile time saving
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if ($line !~ /^\[/);
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
last;
}
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
sub get_val_or_fail($)
{
my $name = shift;
my $val = "FAIL";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/ && $line !~ /FAIL/);
last;
}
($val) = ($line =~ /^$name = (\w+)/) if ($line =~ /=/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
my $key_len = get_suite_val("Keylen");
next if ($key_len !~ /\d+/);
my $iv_len = get_suite_val("IVlen");
my $pt_len = get_suite_val("PTlen");
my $add_len = get_suite_val("AADlen");
my $tag_len = get_suite_val("Taglen");
for ($cnt = 0; $cnt < 3; $cnt++)
{
my $Count = get_val("Count");
my $key = get_val("Key");
my $iv = get_val("IV");
my $ct = get_val("CT");
my $add = get_val("AAD");
my $tag = get_val("Tag");
my $pt = get_val_or_fail("PT");
print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n");
print("gcm_decrypt_and_verify");
print(":\"$key\"");
print(":\"$ct\"");
print(":\"$iv\"");
print(":\"$add\"");
print(":$tag_len");
print(":\"$tag\"");
print(":\"$pt\"");
print(":0");
print("\n\n");
}
}
print("GCM Selftest\n");
print("gcm_selftest:\n\n");
close(TEST_DATA);

View File

@ -0,0 +1,84 @@
#!/usr/bin/env perl
#
# Based on NIST gcmEncryptIntIVxxx.rsp validation files
# Only first 3 of every set used for compile time saving
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if ($line !~ /^\[/);
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
last;
}
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
my $key_len = get_suite_val("Keylen");
next if ($key_len !~ /\d+/);
my $iv_len = get_suite_val("IVlen");
my $pt_len = get_suite_val("PTlen");
my $add_len = get_suite_val("AADlen");
my $tag_len = get_suite_val("Taglen");
for ($cnt = 0; $cnt < 3; $cnt++)
{
my $Count = get_val("Count");
my $key = get_val("Key");
my $pt = get_val("PT");
my $add = get_val("AAD");
my $iv = get_val("IV");
my $ct = get_val("CT");
my $tag = get_val("Tag");
print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n");
print("gcm_encrypt_and_tag");
print(":\"$key\"");
print(":\"$pt\"");
print(":\"$iv\"");
print(":\"$add\"");
print(":\"$ct\"");
print(":$tag_len");
print(":\"$tag\"");
print(":0");
print("\n\n");
}
}
print("GCM Selftest\n");
print("gcm_selftest:\n\n");
close(TEST_DATA);

View File

@ -0,0 +1,74 @@
#!/usr/bin/env perl
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_val($$)
{
my $str = shift;
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if($line !~ /^# $str/);
last;
}
while(my $line = <TEST_DATA>)
{
last if($line eq "\r\n");
$val .= $line;
}
$val =~ s/[ \r\n]//g;
return $val;
}
my $state = 0;
my $val_n = "";
my $val_e = "";
my $val_p = "";
my $val_q = "";
my $mod = 0;
my $cnt = 1;
while (my $line = <TEST_DATA>)
{
next if ($line !~ /^# Example/);
( $mod ) = ($line =~ /A (\d+)/);
$val_n = get_val("RSA modulus n", "N");
$val_e = get_val("RSA public exponent e", "E");
$val_p = get_val("Prime p", "P");
$val_q = get_val("Prime q", "Q");
for(my $i = 1; $i <= 6; $i++)
{
my $val_m = get_val("Message to be", "M");
my $val_salt = get_val("Salt", "Salt");
my $val_sig = get_val("Signature", "Sig");
print("RSASSA-PSS Signature Example ${cnt}_${i}\n");
print("pkcs1_rsassa_pss_sign:$mod:16:\"$val_p\":16:\"$val_q\":16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1");
print(":\"$val_m\"");
print(":\"$val_salt\"");
print(":\"$val_sig\":0");
print("\n\n");
print("RSASSA-PSS Signature Example ${cnt}_${i} (verify)\n");
print("pkcs1_rsassa_pss_verify:$mod:16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1");
print(":\"$val_m\"");
print(":\"$val_salt\"");
print(":\"$val_sig\":0");
print("\n\n");
}
$cnt++;
}
close(TEST_DATA);

View File

@ -0,0 +1,71 @@
#!/bin/sh
# This script splits the data test files containing the test cases into
# individual files (one test case per file) suitable for use with afl
# (American Fuzzy Lop). http://lcamtuf.coredump.cx/afl/
#
# Usage: generate-afl-tests.sh <test data file path>
# <test data file path> - should be the path to one of the test suite files
# such as 'test_suite_rsa.data'
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# Abort on errors
set -e
if [ -z $1 ]
then
echo " [!] No test file specified" >&2
echo "Usage: $0 <test data file>" >&2
exit 1
fi
SRC_FILEPATH=$(dirname $1)/$(basename $1)
TESTSUITE=$(basename $1 .data)
THIS_DIR=$(basename $PWD)
if [ -d ../library -a -d ../include -a -d ../tests -a $THIS_DIR == "tests" ];
then :;
else
echo " [!] Must be run from Mbed TLS tests directory" >&2
exit 1
fi
DEST_TESTCASE_DIR=$TESTSUITE-afl-tests
DEST_OUTPUT_DIR=$TESTSUITE-afl-out
echo " [+] Creating output directories" >&2
if [ -e $DEST_OUTPUT_DIR/* ];
then :
echo " [!] Test output files already exist." >&2
exit 1
else
mkdir -p $DEST_OUTPUT_DIR
fi
if [ -e $DEST_TESTCASE_DIR/* ];
then :
echo " [!] Test output files already exist." >&2
else
mkdir -p $DEST_TESTCASE_DIR
fi
echo " [+] Creating test cases" >&2
cd $DEST_TESTCASE_DIR
split -p '^\s*$' ../$SRC_FILEPATH
for f in *;
do
# Strip out any blank lines (no trim on OS X)
sed '/^\s*$/d' $f >testcase_$f
rm $f
done
cd ..
echo " [+] Test cases in $DEST_TESTCASE_DIR" >&2

View File

@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Generate server9-bad-saltlen.crt
Generate a certificate signed with RSA-PSS, with an incorrect salt length.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import subprocess
import argparse
from asn1crypto import pem, x509, core #type: ignore #pylint: disable=import-error
OPENSSL_RSA_PSS_CERT_COMMAND = r'''
openssl x509 -req -CA {ca_name}.crt -CAkey {ca_name}.key -set_serial 24 {ca_password} \
{openssl_extfile} -days 3650 -outform DER -in {csr} \
-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{anounce_saltlen} \
-sigopt rsa_mgf1_md:sha256
'''
SIG_OPT = \
r'-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{saltlen} -sigopt rsa_mgf1_md:sha256'
OPENSSL_RSA_PSS_DGST_COMMAND = r'''openssl dgst -sign {ca_name}.key {ca_password} \
-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{actual_saltlen} \
-sigopt rsa_mgf1_md:sha256'''
def auto_int(x):
return int(x, 0)
def build_argparser(parser):
"""Build argument parser"""
parser.description = __doc__
parser.add_argument('--ca-name', type=str, required=True,
help='Basename of CA files')
parser.add_argument('--ca-password', type=str,
required=True, help='CA key file password')
parser.add_argument('--csr', type=str, required=True,
help='CSR file for generating certificate')
parser.add_argument('--openssl-extfile', type=str,
required=True, help='X905 v3 extension config file')
parser.add_argument('--anounce_saltlen', type=auto_int,
required=True, help='Announced salt length')
parser.add_argument('--actual_saltlen', type=auto_int,
required=True, help='Actual salt length')
parser.add_argument('--output', type=str, required=True)
def main():
parser = argparse.ArgumentParser()
build_argparser(parser)
args = parser.parse_args()
return generate(**vars(args))
def generate(**kwargs):
"""Generate different salt length certificate file."""
ca_password = kwargs.get('ca_password', '')
if ca_password:
kwargs['ca_password'] = r'-passin "pass:{ca_password}"'.format(
**kwargs)
else:
kwargs['ca_password'] = ''
extfile = kwargs.get('openssl_extfile', '')
if extfile:
kwargs['openssl_extfile'] = '-extfile {openssl_extfile}'.format(
**kwargs)
else:
kwargs['openssl_extfile'] = ''
cmd = OPENSSL_RSA_PSS_CERT_COMMAND.format(**kwargs)
der_bytes = subprocess.check_output(cmd, shell=True)
target_certificate = x509.Certificate.load(der_bytes)
cmd = OPENSSL_RSA_PSS_DGST_COMMAND.format(**kwargs)
#pylint: disable=unexpected-keyword-arg
der_bytes = subprocess.check_output(cmd,
input=target_certificate['tbs_certificate'].dump(),
shell=True)
with open(kwargs.get('output'), 'wb') as f:
target_certificate['signature_value'] = core.OctetBitString(der_bytes)
f.write(pem.armor('CERTIFICATE', target_certificate.dump()))
if __name__ == '__main__':
main()

View File

@ -1,118 +0,0 @@
#!/usr/bin/env python3
"""Generate test code to validate mbedtls_ssl_session_reset().
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import ssl_session_reset_check
RULES = {
'conf': ssl_session_reset_check.ResetBehavior.KEEP,
'state': ssl_session_reset_check.ResetBehavior.RESET,
'flags': ssl_session_reset_check.ResetBehavior.SPECIAL,
'renego_status': ssl_session_reset_check.ResetBehavior.RESET,
'renego_records_seen': ssl_session_reset_check.ResetBehavior.RESET,
'tls_version': ssl_session_reset_check.ResetBehavior.SPECIAL,
'early_data_state': ssl_session_reset_check.ResetBehavior.RESET,
'badmac_seen': ssl_session_reset_check.ResetBehavior.RESET,
'f_vrfy': ssl_session_reset_check.ResetBehavior.KEEP,
'p_vrfy': ssl_session_reset_check.ResetBehavior.KEEP,
'f_send': ssl_session_reset_check.ResetBehavior.KEEP,
'f_recv': ssl_session_reset_check.ResetBehavior.KEEP,
'f_recv_timeout': ssl_session_reset_check.ResetBehavior.KEEP,
'p_bio': ssl_session_reset_check.ResetBehavior.KEEP,
'session_in': ssl_session_reset_check.ResetBehavior.RESET,
'session_out': ssl_session_reset_check.ResetBehavior.RESET,
'session': ssl_session_reset_check.ResetBehavior.RESET,
'session_negotiate': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'handshake': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'transform_in': ssl_session_reset_check.ResetBehavior.RESET,
'transform_out': ssl_session_reset_check.ResetBehavior.RESET,
'transform': ssl_session_reset_check.ResetBehavior.RESET,
'transform_negotiate': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'transform_application': ssl_session_reset_check.ResetBehavior.RESET,
'p_timer': ssl_session_reset_check.ResetBehavior.KEEP,
'f_set_timer': ssl_session_reset_check.ResetBehavior.KEEP,
'f_get_timer': ssl_session_reset_check.ResetBehavior.KEEP,
'in_buf': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_ctr': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_hdr': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_cid': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_len': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_iv': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_msg': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'in_offt': ssl_session_reset_check.ResetBehavior.RESET,
'in_msgtype': ssl_session_reset_check.ResetBehavior.RESET,
'in_msglen': ssl_session_reset_check.ResetBehavior.RESET,
'in_left': ssl_session_reset_check.ResetBehavior.RESET,
'in_buf_len': ssl_session_reset_check.ResetBehavior.SPECIAL,
'in_epoch': ssl_session_reset_check.ResetBehavior.RESET,
'next_record_offset': ssl_session_reset_check.ResetBehavior.RESET,
'in_window_top': ssl_session_reset_check.ResetBehavior.RESET,
'in_window': ssl_session_reset_check.ResetBehavior.RESET,
'in_hslen': ssl_session_reset_check.ResetBehavior.RESET,
'in_hsfraglen': ssl_session_reset_check.ResetBehavior.RESET,
'nb_zero': ssl_session_reset_check.ResetBehavior.RESET,
'keep_current_message': ssl_session_reset_check.ResetBehavior.RESET,
'in_fatal_alert_recv': ssl_session_reset_check.ResetBehavior.RESET,
'in_fatal_alert_type': ssl_session_reset_check.ResetBehavior.RESET,
'send_alert': ssl_session_reset_check.ResetBehavior.RESET,
'alert_type': ssl_session_reset_check.ResetBehavior.RESET,
'alert_reason': ssl_session_reset_check.ResetBehavior.RESET,
'disable_datagram_packing': ssl_session_reset_check.ResetBehavior.KEEP,
'discard_early_data_record': ssl_session_reset_check.ResetBehavior.RESET,
'total_early_data_size': ssl_session_reset_check.ResetBehavior.RESET,
'out_buf': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_ctr': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_hdr': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_cid': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_len': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_iv': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_msg': ssl_session_reset_check.ResetBehavior.REALLOCATE,
'out_msgtype': ssl_session_reset_check.ResetBehavior.RESET,
'out_msglen': ssl_session_reset_check.ResetBehavior.RESET,
'out_left': ssl_session_reset_check.ResetBehavior.RESET,
'out_buf_len': ssl_session_reset_check.ResetBehavior.SPECIAL,
'cur_out_ctr': ssl_session_reset_check.ResetBehavior.RESET,
'mtu': ssl_session_reset_check.ResetBehavior.KEEP,
'hostname': ssl_session_reset_check.ResetBehavior.KEEP,
'alpn_chosen': ssl_session_reset_check.ResetBehavior.RESET,
'dtls_srtp_info': ssl_session_reset_check.ResetBehavior.RESET,
'cli_id': ssl_session_reset_check.ResetBehavior.RESET,
'cli_id_len': ssl_session_reset_check.ResetBehavior.RESET,
'secure_renegotiation': ssl_session_reset_check.ResetBehavior.RESET,
'verify_data_len': ssl_session_reset_check.ResetBehavior.RESET,
'own_verify_data': ssl_session_reset_check.ResetBehavior.RESET,
'peer_verify_data': ssl_session_reset_check.ResetBehavior.RESET,
'own_cid': ssl_session_reset_check.ResetBehavior.KEEP,
'own_cid_len': ssl_session_reset_check.ResetBehavior.KEEP,
'negotiate_cid': ssl_session_reset_check.ResetBehavior.KEEP,
'f_export_keys': ssl_session_reset_check.ResetBehavior.KEEP,
'p_export_keys': ssl_session_reset_check.ResetBehavior.KEEP,
'user_data': ssl_session_reset_check.ResetBehavior.SPECIAL,
'unused': ssl_session_reset_check.ResetBehavior.IGNORE,
}
SPECIAL_BEHAVIORS = {
'flags': ['TEST_EQUAL((after->flags & ~(MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION)), ' +
'initial.flags);',
'TEST_EQUAL((before->flags & MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION), ' +
'(after->flags & MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION));'],
'tls_version': ['TEST_ASSERT(after->tls_version == after->conf->max_tls_version);'],
'user_data': ['TEST_ASSERT(before->user_data.n == after->user_data.n);'],
'in_buf_len': ['TEST_ASSERT(after->in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);'],
'out_buf_len': ['TEST_ASSERT(after->out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);'],
}
NAMED_STRUCTURES = frozenset([
'dtls_srtp_info',
])
FIELDS_INFO = ssl_session_reset_check.FieldsInfo(RULES,
SPECIAL_BEHAVIORS,
NAMED_STRUCTURES)
if __name__ == '__main__':
ssl_session_reset_check.main(FIELDS_INFO)

View File

@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Describe the test coverage of PSA functions in terms of return statuses.
1. Build Mbed TLS with -DRECORD_PSA_STATUS_COVERAGE_LOG
2. Run psa_collect_statuses.py
The output is a series of line of the form "psa_foo PSA_ERROR_XXX". Each
function/status combination appears only once.
This script must be run from the top of an Mbed TLS source tree.
The build command is "make -DRECORD_PSA_STATUS_COVERAGE_LOG", which is
only supported with make (as opposed to CMake or other build methods).
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import argparse
import os
import subprocess
import sys
DEFAULT_STATUS_LOG_FILE = 'tests/statuses.log'
DEFAULT_PSA_CONSTANT_NAMES = 'tf-psa-crypto/programs/psa/psa_constant_names'
class Statuses:
"""Information about observed return statues of API functions."""
def __init__(self):
self.functions = {}
self.codes = set()
self.status_names = {}
def collect_log(self, log_file_name):
"""Read logs from RECORD_PSA_STATUS_COVERAGE_LOG.
Read logs produced by running Mbed TLS test suites built with
-DRECORD_PSA_STATUS_COVERAGE_LOG.
"""
with open(log_file_name) as log:
for line in log:
value, function, tail = line.split(':', 2)
if function not in self.functions:
self.functions[function] = {}
fdata = self.functions[function]
if value not in self.functions[function]:
fdata[value] = []
fdata[value].append(tail)
self.codes.add(int(value))
def get_constant_names(self, psa_constant_names):
"""Run psa_constant_names to obtain names for observed numerical values."""
values = [str(value) for value in self.codes]
cmd = [psa_constant_names, 'status'] + values
output = subprocess.check_output(cmd).decode('ascii')
for value, name in zip(values, output.rstrip().split('\n')):
self.status_names[value] = name
def report(self):
"""Report observed return values for each function.
The report is a series of line of the form "psa_foo PSA_ERROR_XXX".
"""
for function in sorted(self.functions.keys()):
fdata = self.functions[function]
names = [self.status_names[value] for value in fdata.keys()]
for name in sorted(names):
sys.stdout.write('{} {}\n'.format(function, name))
def collect_status_logs(options):
"""Build and run unit tests and report observed function return statuses.
Build Mbed TLS with -DRECORD_PSA_STATUS_COVERAGE_LOG, run the
test suites and display information about observed return statuses.
"""
rebuilt = False
if not options.use_existing_log and os.path.exists(options.log_file):
os.remove(options.log_file)
if not os.path.exists(options.log_file):
if options.clean_before:
subprocess.check_call(['make', '-f', 'scripts/legacy.make', 'clean'],
cwd='tests',
stdout=sys.stderr)
with open(os.devnull, 'w') as devnull:
make_q_ret = subprocess.call(['make', '-f', 'scripts/legacy.make',
'-q', 'lib', 'tests'],
stdout=devnull, stderr=devnull)
if make_q_ret != 0:
subprocess.check_call(['make', '-f', 'scripts/legacy.make',
'RECORD_PSA_STATUS_COVERAGE_LOG=1'],
stdout=sys.stderr)
rebuilt = True
subprocess.check_call(['make', '-f', 'scripts/legacy.make', 'test'],
stdout=sys.stderr)
data = Statuses()
data.collect_log(options.log_file)
data.get_constant_names(options.psa_constant_names)
if rebuilt and options.clean_after:
subprocess.check_call(['make', '-f', 'scripts/legacy.make', 'clean'],
cwd='tests',
stdout=sys.stderr)
return data
def main():
parser = argparse.ArgumentParser(description=globals()['__doc__'])
parser.add_argument('--clean-after',
action='store_true',
help='Run "make clean" after rebuilding')
parser.add_argument('--clean-before',
action='store_true',
help='Run "make clean" before regenerating the log file)')
parser.add_argument('--log-file', metavar='FILE',
default=DEFAULT_STATUS_LOG_FILE,
help='Log file location (default: {})'.format(
DEFAULT_STATUS_LOG_FILE
))
parser.add_argument('--psa-constant-names', metavar='PROGRAM',
default=DEFAULT_PSA_CONSTANT_NAMES,
help='Path to psa_constant_names (default: {})'.format(
DEFAULT_PSA_CONSTANT_NAMES
))
parser.add_argument('--use-existing-log', '-e',
action='store_true',
help='Don\'t regenerate the log file if it exists')
options = parser.parse_args()
data = collect_status_logs(options)
data.report()
if __name__ == '__main__':
main()

89
tests/scripts/run-metatests.sh Executable file
View File

@ -0,0 +1,89 @@
#!/bin/sh
help () {
cat <<EOF
Usage: $0 [OPTION] [PLATFORM]...
Run all the metatests whose platform matches any of the given PLATFORM.
A PLATFORM can contain shell wildcards.
Expected output: a lot of scary-looking error messages, since each
metatest is expected to report a failure. The final line should be
"Ran N metatests, all good."
If something goes wrong: the final line should be
"Ran N metatests, X unexpected successes". Look for "Unexpected success"
in the logs above.
-l List the available metatests, don't run them.
EOF
}
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -e -u
if [ -d programs ]; then
METATEST_PROGRAM=programs/test/metatest
elif [ -d ../programs ]; then
METATEST_PROGRAM=../programs/test/metatest
elif [ -d ../../programs ]; then
METATEST_PROGRAM=../../programs/test/metatest
else
echo >&2 "$0: FATAL: programs/test/metatest not found"
exit 120
fi
LIST_ONLY=
while getopts hl OPTLET; do
case $OPTLET in
h) help; exit;;
l) LIST_ONLY=1;;
\?) help >&2; exit 120;;
esac
done
shift $((OPTIND - 1))
list_matches () {
while read name platform junk; do
for pattern in "$@"; do
case $platform in
$pattern) echo "$name"; break;;
esac
done
done
}
count=0
errors=0
run_metatest () {
ret=0
"$METATEST_PROGRAM" "$1" || ret=$?
if [ $ret -eq 0 ]; then
echo >&2 "$0: Unexpected success: $1"
errors=$((errors + 1))
fi
count=$((count + 1))
}
# Don't pipe the output of metatest so that if it fails, this script exits
# immediately with a failure status.
full_list=$("$METATEST_PROGRAM" list)
matching_list=$(printf '%s\n' "$full_list" | list_matches "$@")
if [ -n "$LIST_ONLY" ]; then
printf '%s\n' $matching_list
exit
fi
for name in $matching_list; do
run_metatest "$name"
done
if [ $errors -eq 0 ]; then
echo "Ran $count metatests, all good."
exit 0
else
echo "Ran $count metatests, $errors unexpected successes."
exit 1
fi

65
tests/scripts/run_demos.py Executable file
View File

@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Run the Mbed TLS demo scripts.
"""
import argparse
import glob
import subprocess
import sys
def run_demo(demo, quiet=False):
"""Run the specified demo script. Return True if it succeeds."""
args = {}
if quiet:
args['stdout'] = subprocess.DEVNULL
args['stderr'] = subprocess.DEVNULL
returncode = subprocess.call([demo], **args)
return returncode == 0
def run_demos(demos, quiet=False):
"""Run the specified demos and print summary information about failures.
Return True if all demos passed and False if a demo fails.
"""
failures = []
for demo in demos:
if not quiet:
print('#### {} ####'.format(demo))
success = run_demo(demo, quiet=quiet)
if not success:
failures.append(demo)
if not quiet:
print('{}: FAIL'.format(demo))
if quiet:
print('{}: {}'.format(demo, 'PASS' if success else 'FAIL'))
else:
print('')
successes = len(demos) - len(failures)
print('{}/{} demos passed'.format(successes, len(demos)))
if failures and not quiet:
print('Failures:', *failures)
return not failures
def run_all_demos(quiet=False):
"""Run all the available demos.
Return True if all demos passed and False if a demo fails.
"""
mbedtls_demos = glob.glob('programs/*/*_demo.sh')
tf_psa_crypto_demos = glob.glob('tf-psa-crypto/programs/*/*_demo.sh')
all_demos = mbedtls_demos + tf_psa_crypto_demos
if not all_demos:
# Keep the message on one line. pylint: disable=line-too-long
raise Exception('No demos found. run_demos needs to operate from the Mbed TLS toplevel directory.')
return run_demos(all_demos, quiet=quiet)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--quiet', '-q',
action='store_true',
help="suppress the output of demos")
options = parser.parse_args()
success = run_all_demos(quiet=options.quiet)
sys.exit(0 if success else 1)
if __name__ == '__main__':
main()

View File

@ -18,6 +18,3 @@ sys.path.append(os.path.join(os.path.dirname(__file__),
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir, os.path.pardir,
'framework', 'scripts'))
sys.path.append(os.path.join(os.path.dirname(__file__),
os.path.pardir, os.path.pardir,
'tf-psa-crypto', 'scripts', 'project_knowledge'))

View File

@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""Test helper for the Mbed TLS configuration file tool
Run config.py with various parameters and write the results to files.
This is a harness to help regression testing, not a functional tester.
Sample usage:
test_config_script.py -d old
## Modify config.py and/or mbedtls_config.h ##
test_config_script.py -d new
diff -ru old new
"""
## Copyright The Mbed TLS Contributors
## SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
##
import argparse
import glob
import os
import re
import shutil
import subprocess
OUTPUT_FILE_PREFIX = 'config-'
def output_file_name(directory, stem, extension):
return os.path.join(directory,
'{}{}.{}'.format(OUTPUT_FILE_PREFIX,
stem, extension))
def cleanup_directory(directory):
"""Remove old output files."""
for extension in []:
pattern = output_file_name(directory, '*', extension)
filenames = glob.glob(pattern)
for filename in filenames:
os.remove(filename)
def prepare_directory(directory):
"""Create the output directory if it doesn't exist yet.
If there are old output files, remove them.
"""
if os.path.exists(directory):
cleanup_directory(directory)
else:
os.makedirs(directory)
def guess_presets_from_help(help_text):
"""Figure out what presets the script supports.
help_text should be the output from running the script with --help.
"""
# Try the output format from config.py
hits = re.findall(r'\{([-\w,]+)\}', help_text)
for hit in hits:
words = set(hit.split(','))
if 'get' in words and 'set' in words and 'unset' in words:
words.remove('get')
words.remove('set')
words.remove('unset')
return words
# Try the output format from config.pl
hits = re.findall(r'\n +([-\w]+) +- ', help_text)
if hits:
return hits
raise Exception("Unable to figure out supported presets. Pass the '-p' option.")
def list_presets(options):
"""Return the list of presets to test.
The list is taken from the command line if present, otherwise it is
extracted from running the config script with --help.
"""
if options.presets:
return re.split(r'[ ,]+', options.presets)
else:
help_text = subprocess.run([options.script, '--help'],
check=False, # config.pl --help returns 255
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).stdout
return guess_presets_from_help(help_text.decode('ascii'))
def run_one(options, args, stem_prefix='', input_file=None):
"""Run the config script with the given arguments.
Take the original content from input_file if specified, defaulting
to options.input_file if input_file is None.
Write the following files, where xxx contains stem_prefix followed by
a filename-friendly encoding of args:
* config-xxx.h: modified file.
* config-xxx.out: standard output.
* config-xxx.err: standard output.
* config-xxx.status: exit code.
Return ("xxx+", "path/to/config-xxx.h") which can be used as
stem_prefix and input_file to call this function again with new args.
"""
if input_file is None:
input_file = options.input_file
stem = stem_prefix + '-'.join(args)
data_filename = output_file_name(options.output_directory, stem, 'h')
stdout_filename = output_file_name(options.output_directory, stem, 'out')
stderr_filename = output_file_name(options.output_directory, stem, 'err')
status_filename = output_file_name(options.output_directory, stem, 'status')
shutil.copy(input_file, data_filename)
# Pass only the file basename, not the full path, to avoid getting the
# directory name in error messages, which would make comparisons
# between output directories more difficult.
cmd = [os.path.abspath(options.script),
'-f', os.path.basename(data_filename)]
with open(stdout_filename, 'wb') as out:
with open(stderr_filename, 'wb') as err:
status = subprocess.call(cmd + args,
cwd=options.output_directory,
stdin=subprocess.DEVNULL,
stdout=out, stderr=err)
with open(status_filename, 'w') as status_file:
status_file.write('{}\n'.format(status))
return stem + "+", data_filename
### A list of symbols to test with.
### This script currently tests what happens when you change a symbol from
### having a value to not having a value or vice versa. This is not
### necessarily useful behavior, and we may not consider it a bug if
### config.py stops handling that case correctly.
TEST_SYMBOLS = [
'CUSTOM_SYMBOL', # does not exist
'PSA_WANT_KEY_TYPE_AES', # set, no value
'MBEDTLS_MPI_MAX_SIZE', # unset, has a value
'MBEDTLS_NO_UDBL_DIVISION', # unset, in "System support"
'MBEDTLS_PLATFORM_ZEROIZE_ALT', # unset, in "Customisation configuration options"
]
def run_all(options):
"""Run all the command lines to test."""
presets = list_presets(options)
for preset in presets:
run_one(options, [preset])
for symbol in TEST_SYMBOLS:
run_one(options, ['get', symbol])
(stem, filename) = run_one(options, ['set', symbol])
run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename)
run_one(options, ['--force', 'set', symbol])
(stem, filename) = run_one(options, ['set', symbol, 'value'])
run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename)
run_one(options, ['--force', 'set', symbol, 'value'])
run_one(options, ['unset', symbol])
def main():
"""Command line entry point."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-d', metavar='DIR',
dest='output_directory', required=True,
help="""Output directory.""")
parser.add_argument('-f', metavar='FILE',
dest='input_file', default='include/mbedtls/mbedtls_config.h',
help="""Config file (default: %(default)s).""")
parser.add_argument('-p', metavar='PRESET,...',
dest='presets',
help="""Presets to test (default: guessed from --help).""")
parser.add_argument('-s', metavar='FILE',
dest='script', default='scripts/config.py',
help="""Configuration script (default: %(default)s).""")
options = parser.parse_args()
prepare_directory(options.output_directory)
run_all(options)
if __name__ == '__main__':
main()

View File

@ -1,190 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/*
* The following function was automatically generated through the script
* ./tests/scripts/generate_ssl_session_reset_check.py.
*/
#include <test/ssl_helpers.h>
#include <test/ssl_helpers_internal.h>
#include "mbedtls/psa_util.h"
#include <test/macros.h>
#include <limits.h>
#if defined(MBEDTLS_SSL_TLS_C)
int mbedtls_test_ssl_check_context_after_session_reset(const mbedtls_ssl_context *before,
const mbedtls_ssl_context *after)
{
mbedtls_ssl_context initial;
int ret = -1;
/* Create a freshly initialized SSL context*/
memset(&initial, 0, sizeof(initial));
mbedtls_ssl_init(&initial);
TEST_EQUAL(mbedtls_ssl_setup(&initial, after->conf), 0);
/* *INDENT-OFF* */
TEST_ASSERT(before->conf == after->conf);
TEST_ASSERT(after->state == initial.state);
TEST_EQUAL((after->flags & ~(MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION)), initial.flags);
TEST_EQUAL((before->flags & MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION), (after->flags & MBEDTLS_SSL_CONTEXT_FLAGS_KEEP_AT_SESSION));
#if defined(MBEDTLS_SSL_RENEGOTIATION)
TEST_ASSERT(after->renego_status == initial.renego_status);
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
TEST_ASSERT(after->renego_records_seen == initial.renego_records_seen);
#endif
TEST_ASSERT(after->tls_version == after->conf->max_tls_version);
#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
TEST_ASSERT(after->early_data_state == initial.early_data_state);
#endif
TEST_ASSERT(after->badmac_seen == initial.badmac_seen);
#if defined(MBEDTLS_X509_CRT_PARSE_C)
TEST_ASSERT(before->f_vrfy == after->f_vrfy);
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
TEST_ASSERT(before->p_vrfy == after->p_vrfy);
#endif
TEST_ASSERT(before->f_send == after->f_send);
TEST_ASSERT(before->f_recv == after->f_recv);
TEST_ASSERT(before->f_recv_timeout == after->f_recv_timeout);
TEST_ASSERT(before->p_bio == after->p_bio);
TEST_ASSERT(after->session_in == initial.session_in);
TEST_ASSERT(after->session_out == initial.session_out);
TEST_ASSERT(after->session == initial.session);
TEST_ASSERT(after->session_negotiate != NULL);
TEST_ASSERT(after->handshake != NULL);
TEST_ASSERT(after->transform_in == initial.transform_in);
TEST_ASSERT(after->transform_out == initial.transform_out);
TEST_ASSERT(after->transform == initial.transform);
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
TEST_ASSERT(after->transform_negotiate != NULL);
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
TEST_ASSERT(after->transform_application == initial.transform_application);
#endif
TEST_ASSERT(before->p_timer == after->p_timer);
TEST_ASSERT(before->f_set_timer == after->f_set_timer);
TEST_ASSERT(before->f_get_timer == after->f_get_timer);
TEST_ASSERT(after->in_buf != NULL);
TEST_ASSERT(after->in_ctr != NULL);
TEST_ASSERT(after->in_hdr != NULL);
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
TEST_ASSERT(after->in_cid != NULL);
#endif
TEST_ASSERT(after->in_len != NULL);
TEST_ASSERT(after->in_iv != NULL);
TEST_ASSERT(after->in_msg != NULL);
TEST_ASSERT(after->in_offt == initial.in_offt);
TEST_ASSERT(after->in_msgtype == initial.in_msgtype);
TEST_ASSERT(after->in_msglen == initial.in_msglen);
TEST_ASSERT(after->in_left == initial.in_left);
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
TEST_ASSERT(after->in_buf_len == MBEDTLS_SSL_IN_BUFFER_LEN);
#endif
#if defined(MBEDTLS_SSL_PROTO_DTLS)
TEST_ASSERT(after->in_epoch == initial.in_epoch);
#endif
#if defined(MBEDTLS_SSL_PROTO_DTLS)
TEST_ASSERT(after->next_record_offset == initial.next_record_offset);
#endif
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
TEST_ASSERT(after->in_window_top == initial.in_window_top);
#endif
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
TEST_ASSERT(after->in_window == initial.in_window);
#endif
TEST_ASSERT(after->in_hslen == initial.in_hslen);
TEST_ASSERT(after->in_hsfraglen == initial.in_hsfraglen);
TEST_ASSERT(after->nb_zero == initial.nb_zero);
TEST_ASSERT(after->keep_current_message == initial.keep_current_message);
TEST_ASSERT(after->in_fatal_alert_recv == initial.in_fatal_alert_recv);
TEST_ASSERT(after->in_fatal_alert_type == initial.in_fatal_alert_type);
TEST_ASSERT(after->send_alert == initial.send_alert);
TEST_ASSERT(after->alert_type == initial.alert_type);
TEST_ASSERT(after->alert_reason == initial.alert_reason);
#if defined(MBEDTLS_SSL_PROTO_DTLS)
TEST_EQUAL(before->disable_datagram_packing, after->disable_datagram_packing);
#endif
#if defined(MBEDTLS_SSL_EARLY_DATA)
#if defined(MBEDTLS_SSL_SRV_C)
TEST_ASSERT(after->discard_early_data_record == initial.discard_early_data_record);
#endif
#endif
#if defined(MBEDTLS_SSL_EARLY_DATA)
TEST_ASSERT(after->total_early_data_size == initial.total_early_data_size);
#endif
TEST_ASSERT(after->out_buf != NULL);
TEST_ASSERT(after->out_ctr != NULL);
TEST_ASSERT(after->out_hdr != NULL);
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
TEST_ASSERT(after->out_cid != NULL);
#endif
TEST_ASSERT(after->out_len != NULL);
TEST_ASSERT(after->out_iv != NULL);
TEST_ASSERT(after->out_msg != NULL);
TEST_ASSERT(after->out_msgtype == initial.out_msgtype);
TEST_ASSERT(after->out_msglen == initial.out_msglen);
TEST_ASSERT(after->out_left == initial.out_left);
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
TEST_ASSERT(after->out_buf_len == MBEDTLS_SSL_OUT_BUFFER_LEN);
#endif
TEST_MEMORY_COMPARE(after->cur_out_ctr, sizeof(after->cur_out_ctr), initial.cur_out_ctr, sizeof(initial.cur_out_ctr));
#if defined(MBEDTLS_SSL_PROTO_DTLS)
TEST_EQUAL(before->mtu, after->mtu);
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
TEST_ASSERT(before->hostname == after->hostname);
#endif
#if defined(MBEDTLS_SSL_ALPN)
TEST_ASSERT(after->alpn_chosen == initial.alpn_chosen);
#endif
#if defined(MBEDTLS_SSL_DTLS_SRTP)
TEST_MEMORY_COMPARE(&(after->dtls_srtp_info), sizeof(after->dtls_srtp_info), &(initial.dtls_srtp_info), sizeof(initial.dtls_srtp_info));
#endif
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
TEST_ASSERT(after->cli_id == initial.cli_id);
#endif
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
TEST_ASSERT(after->cli_id_len == initial.cli_id_len);
#endif
TEST_ASSERT(after->secure_renegotiation == initial.secure_renegotiation);
#if defined(MBEDTLS_SSL_RENEGOTIATION)
TEST_ASSERT(after->verify_data_len == initial.verify_data_len);
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
TEST_MEMORY_COMPARE(after->own_verify_data, sizeof(after->own_verify_data), initial.own_verify_data, sizeof(initial.own_verify_data));
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
TEST_MEMORY_COMPARE(after->peer_verify_data, sizeof(after->peer_verify_data), initial.peer_verify_data, sizeof(initial.peer_verify_data));
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
TEST_MEMORY_COMPARE(before->own_cid, sizeof(before->own_cid), after->own_cid, sizeof(after->own_cid));
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
TEST_EQUAL(before->own_cid_len, after->own_cid_len);
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
TEST_EQUAL(before->negotiate_cid, after->negotiate_cid);
#endif
TEST_ASSERT(before->f_export_keys == after->f_export_keys);
TEST_ASSERT(before->p_export_keys == after->p_export_keys);
TEST_ASSERT(before->user_data.n == after->user_data.n);
/* unused is ignored */
/* *INDENT-ON* */
ret = 0;
exit:
mbedtls_ssl_free(&initial);
return ret;
}
#endif /* MBEDTLS_SSL_TLS_C */

View File

@ -9,8 +9,6 @@
*/
#include <test/ssl_helpers.h>
#include <test/ssl_helpers_internal.h>
#include <test/macros.h>
#include "mbedtls/psa_util.h"
#include <limits.h>
@ -1035,17 +1033,6 @@ int mbedtls_test_ssl_endpoint_init(
void mbedtls_test_ssl_endpoint_free(
mbedtls_test_ssl_endpoint *ep)
{
// mbedtls_ssl_session_reset() requires the SSL to be setup.
if (ep->ssl.conf != NULL) {
mbedtls_ssl_context ssl_before;
/* Dump the SSL context before resetting it */
memcpy(&ssl_before, &(ep->ssl), sizeof(mbedtls_ssl_context));
mbedtls_ssl_session_reset(&(ep->ssl));
/* Check that required fields were properly reset */
mbedtls_test_ssl_check_context_after_session_reset(&ssl_before, &(ep->ssl));
}
mbedtls_ssl_free(&(ep->ssl));
mbedtls_ssl_config_free(&(ep->conf));
@ -2295,10 +2282,6 @@ int mbedtls_test_ssl_perform_connection(
expected_handshake_result = MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
}
if (options->pre_handshake_fun != NULL) {
options->pre_handshake_fun(client, server, options->pre_handshake_param);
}
TEST_EQUAL(mbedtls_test_move_handshake_to_state(&(client->ssl),
&(server->ssl),
MBEDTLS_SSL_HANDSHAKE_OVER),
@ -2330,10 +2313,6 @@ int mbedtls_test_ssl_perform_connection(
options->expected_ciphersuite);
}
if (options->post_handshake_fun != NULL) {
options->post_handshake_fun(client, server, options->post_handshake_param);
}
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
if (options->resize_buffers != 0) {
/* A server, when using DTLS, might delay a buffer resize to happen
@ -2360,11 +2339,6 @@ int mbedtls_test_ssl_perform_connection(
options->expected_srv_fragments),
0);
}
if (options->post_data_fun != NULL) {
options->post_data_fun(client, server, options->post_data_param);
}
#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
if (options->serialize == 1) {
TEST_ASSERT(test_serialization(options, client, server));
@ -2422,10 +2396,6 @@ void mbedtls_test_ssl_perform_handshake(
TEST_ASSERT(mbedtls_ssl_conf_get_user_data_p(&server->conf) == server);
TEST_ASSERT(mbedtls_ssl_get_user_data_p(&server->ssl) == server);
if (options->pre_shutdown_fun != NULL) {
options->pre_shutdown_fun(client, server, options->pre_shutdown_param);
}
exit:
mbedtls_test_ssl_endpoint_free(client);
mbedtls_test_ssl_endpoint_free(server);

View File

@ -5269,7 +5269,6 @@ run_test "Renegotiation: client-initiated, server-rejected" \
-c "=> renegotiate" \
-S "=> renegotiate" \
-S "write hello request" \
-s "refusing renegotiation" \
-c "SSL - Unexpected message at ServerHello in renegotiation" \
-c "failed"
@ -5286,7 +5285,6 @@ run_test "Renegotiation: server-initiated, client-rejected, default" \
-C "=> renegotiate" \
-S "=> renegotiate" \
-s "write hello request" \
-c "refusing renegotiation" \
-S "SSL - An unexpected message was received from our peer" \
-S "failed"
@ -5304,7 +5302,6 @@ run_test "Renegotiation: server-initiated, client-rejected, not enforced" \
-C "=> renegotiate" \
-S "=> renegotiate" \
-s "write hello request" \
-c "refusing renegotiation" \
-S "SSL - An unexpected message was received from our peer" \
-S "failed"
@ -5323,7 +5320,6 @@ run_test "Renegotiation: server-initiated, client-rejected, delay 2" \
-C "=> renegotiate" \
-S "=> renegotiate" \
-s "write hello request" \
-c "refusing renegotiation" \
-S "SSL - An unexpected message was received from our peer" \
-S "failed"
@ -5341,7 +5337,6 @@ run_test "Renegotiation: server-initiated, client-rejected, delay 0" \
-C "=> renegotiate" \
-S "=> renegotiate" \
-s "write hello request" \
-c "refusing renegotiation" \
-s "SSL - An unexpected message was received from our peer"
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
@ -5358,7 +5353,6 @@ run_test "Renegotiation: server-initiated, client-accepted, delay 0" \
-c "=> renegotiate" \
-s "=> renegotiate" \
-s "write hello request" \
-C "refusing renegotiation" \
-S "SSL - An unexpected message was received from our peer" \
-S "failed"
@ -8388,37 +8382,6 @@ run_test "extKeyUsage cli-auth 1.3: codeSign -> fail (hard)" \
-s "Processing of the Certificate handshake message failed"
# MBEDTLS_X509_BADCERT_EXT_KEY_USAGE -> MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT
# Miscellaneous PSK-related tests
psk_identity_max_minus_10=a$(printf "%$((MAX_OUT_LEN - 11))s" z | tr ' ' .)
run_test "Large PSK identity (MBEDTLS_SSL_OUT_CONTENT_LEN - 7)" \
"$P_SRV debug_level=3 \
psk_identity=${psk_identity_max_minus_10}987 psk=73776f726466697368" \
"$P_CLI force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256 debug_level=3 \
psk_identity=${psk_identity_max_minus_10}987 psk=73776f726466697368" \
1 \
-s "! mbedtls_ssl_handshake returned" \
-c "! mbedtls_ssl_handshake returned"
run_test "Large PSK identity (MBEDTLS_SSL_OUT_CONTENT_LEN - 6)" \
"$P_SRV debug_level=3 \
psk_identity=${psk_identity_max_minus_10}9876 psk=73776f726466697368" \
"$P_CLI force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256 debug_level=3 \
psk_identity=${psk_identity_max_minus_10}9876 psk=73776f726466697368" \
1 \
-s "! mbedtls_ssl_handshake returned" \
-c "! mbedtls_ssl_handshake returned"
run_test "Large PSK identity (MBEDTLS_SSL_OUT_CONTENT_LEN - 5)" \
"$P_SRV debug_level=3 \
psk_identity=${psk_identity_max_minus_10}98765 psk=73776f726466697368" \
"$P_CLI force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256 debug_level=3 \
psk_identity=${psk_identity_max_minus_10}98765 psk=73776f726466697368" \
1 \
-s "! mbedtls_ssl_handshake returned" \
-c "! mbedtls_ssl_handshake returned"
# Tests for PSK callback
run_test "PSK callback: psk, no callback" \
@ -11806,147 +11769,6 @@ run_test "DTLS proxy: inject invalid AD record, badmac_limit 2, exchanges 2"\
-s "too many records with bad MAC" \
-s "Verification of the message MAC failed"
# The next few tests exercise renegotiation in DTLS when `ssl->badmac_seen != 0`.
#
# This seems unrelated, but was the location of a bug in Mbed TLS 3.6.3 to
# 3.6.6 (CVE-2026-50713) due to `ssl->badmac_seen` being unified with
# `ssl->in_hsfraglen` (to preserve the ABI when adding support for handshake
# defragmentation in TLS in 3.6.3), with some mistakes in using the unified
# field that were fixed in 3.6.7.
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: client: get invalid AD record then reject renego" \
-p "$P_PXY bad_ad_srv_once=1" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiate=1 renegotiation=1 exchanges=4 \
debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
exchanges=4 badmac_limit=99 debug_level=3" \
0 \
-s "write hello request" \
-c "refusing renegotiation" \
-S "=> renegotiate" \
-C "=> renegotiate" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-c "discarding invalid record (mac)" \
-C "too many records with bad MAC" \
-C "Verification of the message MAC failed" \
-C "Consume: waiting for more handshake fragments"
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: server: get invalid AD record then reject renego" \
-p "$P_PXY bad_ad_cli_once=1" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=0 exchanges=4 \
badmac_limit=99 debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=1 renegotiate=2 exchanges=4 debug_level=3" \
1 \
-s "discarding invalid record (mac)" \
-c "=> renegotiate" \
-S "=> renegotiate" \
-s "refusing renegotiation" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-S "too many records with bad MAC" \
-S "Verification of the message MAC failed" \
-S "Consume: waiting for more handshake fragments"
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: client: get invalid AD record then accept renego" \
-p "$P_PXY bad_ad_srv_once=1" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiate=1 renegotiation=1 exchanges=4 \
debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=1 exchanges=4 badmac_limit=99 debug_level=3" \
0 \
-s "=> renegotiate" \
-c "=> renegotiate" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-c "discarding invalid record (mac)" \
-C "too many records with bad MAC" \
-C "Verification of the message MAC failed" \
-C "Consume: waiting for more handshake fragments"
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: server: get invalid AD record then accept renego" \
-p "$P_PXY bad_ad_cli_once=1" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=1 exchanges=4 \
badmac_limit=99 debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=1 renegotiate=2 exchanges=4 debug_level=3" \
0 \
-s "discarding invalid record (mac)" \
-c "=> renegotiate" \
-s "=> renegotiate" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-S "too many records with bad MAC" \
-S "Verification of the message MAC failed" \
-S "Consume: waiting for more handshake fragments"
# The next few tests have "early renego". A DTLS handshake message is delayed
# past another handshake message. From the perspective of the recipient,
# this means that a DTLS handshake arrives early (its epoch number is still
# in the future) and needs to be queued.
#
# In Mbed TLS 3.6.3 through 3.6.6, due to the fields `ssl->badmac_seen`
# and `ssl->in_hsfraglen` being unified, the early message was parsed
# incorrectly, leading to heap corruption.
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: client: get invalid AD record then reject early renego" \
-p "$P_PXY bad_ad_srv_once=1 delay_encrypted_hs_srv=3" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiate=1 renegotiation=1 exchanges=4 \
debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
exchanges=4 badmac_limit=99 debug_level=3" \
0 \
-S "=> renegotiate" \
-C "=> renegotiate" \
-s "write hello request" \
-c "refusing renegotiation" \
-C "=> ssl_buffer_message" \
-C "initialize reassembly, total length = 0" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-c "discarding invalid record (mac)" \
-C "too many records with bad MAC" \
-C "Verification of the message MAC failed" \
-C "Consume: waiting for more handshake fragments"
# Delay the third encrypted handshake message from the server:
# 1. Finished message of the initial handshake.
# 2. HelloRequest to request renegotiation.
# 3. ServerHello of renegotiation, delayed.
# 4. Subsequent handshake message, which the client receives and enqueues.
#
# In Mbed TLS 3.6.3 though 3.6.6, the processing of (4) caused heap corruption.
requires_config_enabled MBEDTLS_SSL_RENEGOTIATION
run_test "DTLS proxy: client: get invalid AD record then accept early renego" \
-p "$P_PXY bad_ad_srv_once=1 delay_encrypted_hs_srv=3" \
"$P_SRV dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiate=1 renegotiation=1 exchanges=4 \
debug_level=3" \
"$P_CLI dtls=1 dgram_packing=0 hs_timeout=500-10000 \
renegotiation=1 exchanges=4 badmac_limit=99 debug_level=3" \
0 \
-s "=> renegotiate" \
-c "=> renegotiate" \
-c "=> ssl_buffer_message" \
-C "initialize reassembly, total length = 0" \
-s "Extra-header:" \
-c "HTTP/1.0 200 OK" \
-c "discarding invalid record (mac)" \
-C "too many records with bad MAC" \
-C "Verification of the message MAC failed" \
-C "Consume: waiting for more handshake fragments"
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
run_test "DTLS proxy: delay ChangeCipherSpec" \
-p "$P_PXY delay_ccs=1" \
@ -14116,6 +13938,7 @@ run_test "TLS 1.2: Check rsa_pss_rsae compatibility issue, m->O" \
-c "Protocol is TLSv1.2" \
-c "HTTP/1.0 200 [Oo][Kk]"
requires_gnutls_tls1_3
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
requires_config_enabled MBEDTLS_DEBUG_C
@ -14131,43 +13954,6 @@ run_test "TLS 1.2: Check rsa_pss_rsae compatibility issue, m->G" \
-c "Protocol is TLSv1.2" \
-c "HTTP/1.0 200 [Oo][Kk]"
requires_openssl_tls1_3_with_compatible_ephemeral
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
requires_config_enabled MBEDTLS_DEBUG_C
requires_config_enabled MBEDTLS_SSL_CLI_C
requires_config_enabled PSA_WANT_ALG_RSA_PSS
requires_config_enabled PSA_WANT_ALG_SHA_256
run_test "TLS 1.2: Server forces TLS 1.2 and rsa_pss_rsae_sha256, m->O" \
"$O_NEXT_SRV_NO_CERT -cert $DATA_FILES_PATH/server2-sha256.crt -key $DATA_FILES_PATH/server2.key
-tls1_2 -sigalgs rsa_pss_rsae_sha256 " \
"$P_CLI debug_level=3" \
0 \
-c "sent signature scheme \\[804\\] rsa_pss_rsae_sha256" \
-c "Perform .* computation of digest of ServerKeyExchange" \
-c "Server used the signature algorithm rsa_pss_rsae_sha256" \
-c "Protocol is TLSv1.2" \
-c "HTTP/1.0 200 [Oo][Kk]"
requires_gnutls_tls1_3
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
requires_config_enabled MBEDTLS_DEBUG_C
requires_config_enabled MBEDTLS_SSL_CLI_C
requires_config_enabled PSA_WANT_ALG_RSA_PSS
requires_config_enabled PSA_WANT_ALG_SHA_256
run_test "TLS 1.2: Server forces TLS 1.2 and rsa_pss_rsae_sha256, m->G" \
"$G_NEXT_SRV_NO_CERT --x509certfile $DATA_FILES_PATH/server2-sha256.crt --x509keyfile $DATA_FILES_PATH/server2.key
--disable-client-cert
--priority=NORMAL:-VERS-ALL:+VERS-TLS1.2:-SIGN-ALL:+SIGN-RSA-PSS-RSAE-SHA256" \
"$P_CLI debug_level=3" \
0 \
-c "sent signature scheme \\[804\\] rsa_pss_rsae_sha256" \
-c "Perform .* computation of digest of ServerKeyExchange" \
-c "Server used the signature algorithm rsa_pss_rsae_sha256" \
-c "Protocol is TLSv1.2" \
-c "HTTP/1.0 200 [Oo][Kk]"
requires_config_enabled MBEDTLS_SSL_SRV_C
requires_config_enabled MBEDTLS_DEBUG_C
requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED

View File

@ -14,14 +14,6 @@ PKCS7 Signed Data Parse with zero signers
depends_on:PSA_WANT_ALG_SHA_256
pkcs7_parse:"../framework/data_files/pkcs7_data_no_signers.der":MBEDTLS_PKCS7_SIGNED_DATA
PKCS7 Signed Data Parse reused object after multiple signers
depends_on:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY
pkcs7_parse_reuse:"../framework/data_files/pkcs7_data_multiple_signed.der":"../framework/data_files/pkcs7_data_no_signers.der":MBEDTLS_PKCS7_SIGNED_DATA
PKCS7 Signed Data Parse reused object from multiple signers to one signer
depends_on:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY
pkcs7_parse_reuse:"../framework/data_files/pkcs7_data_multiple_signed.der":"../framework/data_files/pkcs7_data_cert_signed_sha256.der":MBEDTLS_PKCS7_SIGNED_DATA
PKCS7 Signed Data Parse Fail with multiple certs #4
depends_on:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY
pkcs7_parse:"../framework/data_files/pkcs7_data_multiple_certs_signed.der":MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE
@ -94,17 +86,9 @@ PKCS7 Signed Data Verification Pass SHA256 #9.1
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_RSA_PKCS1V15_VERIFY
pkcs7_verify:"../framework/data_files/pkcs7_data_cert_signed_sha256.der":"../framework/data_files/pkcs7-rsa-sha256-1.der":"../framework/data_files/pkcs7_data.bin":MBEDTLS_MD_SHA256:0
PKCS7 Signed Data Verification Fail SHA1 #10
PKCS7 Signed Data Verification Pass SHA1 #10
depends_on:PSA_WANT_ALG_SHA_1:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_RSA_PKCS1V15_VERIFY
pkcs7_verify:"../framework/data_files/pkcs7_data_cert_signed_sha1.der":"../framework/data_files/pkcs7-rsa-sha256-1.der":"../framework/data_files/pkcs7_data.bin":0:MBEDTLS_ERR_PKCS7_INVALID_ALG
PKCS7 Signed Data Verification Fail MD5 #10.1
depends_on:PSA_WANT_ALG_MD5:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_RSA_PKCS1V15_VERIFY
pkcs7_verify:"../framework/data_files/pkcs7_data_cert_signed_md5.der":"../framework/data_files/pkcs7-rsa-sha256-1.der":"../framework/data_files/pkcs7_data.bin":0:MBEDTLS_ERR_PKCS7_INVALID_ALG
PKCS7 Signed Data Verification Fail RIPEMD160 #10.2
depends_on:PSA_WANT_ALG_RIPEMD160:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_RSA_PKCS1V15_VERIFY
pkcs7_verify:"../framework/data_files/pkcs7_data_cert_signed_ripemd160.der":"../framework/data_files/pkcs7-rsa-sha256-1.der":"../framework/data_files/pkcs7_data.bin":0:MBEDTLS_ERR_PKCS7_INVALID_ALG
pkcs7_verify:"../framework/data_files/pkcs7_data_cert_signed_sha1.der":"../framework/data_files/pkcs7-rsa-sha256-1.der":"../framework/data_files/pkcs7_data.bin":0:0
PKCS7 Signed Data Verification Pass SHA512 #11
depends_on:PSA_WANT_ALG_SHA_512:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_RSA_PKCS1V15_VERIFY

View File

@ -25,10 +25,8 @@ static int pkcs7_parse_buffer(unsigned char *pkcs7_buf, int buflen)
mbedtls_pkcs7_init(&pkcs7);
res = mbedtls_pkcs7_parse_der(&pkcs7, pkcs7_buf, buflen);
mbedtls_pkcs7_free(&pkcs7);
return res;
}
/* END_SUITE_HELPERS */
/* BEGIN_CASE */
@ -73,48 +71,6 @@ exit:
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_FS_IO */
void pkcs7_parse_reuse(char *first_pkcs7_file, char *second_pkcs7_file,
int res_expect)
{
unsigned char *first_pkcs7_buf = NULL;
unsigned char *second_pkcs7_buf = NULL;
mbedtls_pkcs7 pkcs7;
size_t first_buflen;
size_t second_buflen;
mbedtls_pkcs7_init(&pkcs7);
/* PKCS7 uses X509 which itself relies on PK under the hood and the latter
* can use PSA to store keys and perform operations so psa_crypto_init()
* must be called before. */
USE_PSA_INIT();
TEST_EQUAL(mbedtls_pk_load_file(first_pkcs7_file, &first_pkcs7_buf,
&first_buflen), 0);
TEST_EQUAL(mbedtls_pk_load_file(second_pkcs7_file, &second_pkcs7_buf,
&second_buflen), 0);
TEST_EQUAL(mbedtls_pkcs7_parse_der(&pkcs7, first_pkcs7_buf,
first_buflen),
MBEDTLS_PKCS7_SIGNED_DATA);
mbedtls_pkcs7_free(&pkcs7);
TEST_ASSERT(pkcs7.raw.p == NULL);
TEST_ASSERT(pkcs7.signed_data.signers.next == NULL);
TEST_EQUAL(mbedtls_pkcs7_parse_der(&pkcs7, second_pkcs7_buf,
second_buflen),
res_expect);
exit:
mbedtls_free(first_pkcs7_buf);
mbedtls_free(second_pkcs7_buf);
mbedtls_pkcs7_free(&pkcs7);
USE_PSA_DONE();
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_FS_IO:MBEDTLS_X509_CRT_PARSE_C:PSA_HAVE_ALG_SOME_RSA_VERIFY */
void pkcs7_verify(char *pkcs7_file,
char *crt_files,

View File

@ -471,14 +471,6 @@ Handshake, select ECDHE-ECDSA-WITH-AES-256-CCM, opaque, bad usage
depends_on:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_AES:PSA_WANT_ALG_CCM:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ECC_SECP_R1_384:MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED:!MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
handshake_ciphersuite_select:"TLS-ECDHE-ECDSA-WITH-AES-256-CCM":MBEDTLS_PK_ECDSA:"":PSA_ALG_ECDSA(PSA_ALG_ANY_HASH):PSA_ALG_NONE:PSA_KEY_USAGE_DERIVE:MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE:0
Handshake: DTLS 1.2, badmac_seen on client
depends_on:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_PROTO_TLS1_2
handshake_with_forced_context:1:MBEDTLS_SSL_VERSION_TLS1_2:PRE_HANDSHAKE_BADMAC_SEEN:0
Handshake: DTLS 1.2, badmac_seen on server
depends_on:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_PROTO_TLS1_2
handshake_with_forced_context:1:MBEDTLS_SSL_VERSION_TLS1_2:0:PRE_HANDSHAKE_BADMAC_SEEN
Sending app data via TLS, MFL=512 without fragmentation
depends_on:MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
app_data_tls:MBEDTLS_SSL_MAX_FRAG_LEN_512:400:512:1:1
@ -556,19 +548,13 @@ Sending app data via DTLS, without MFL and with fragmentation
app_data_dtls:MBEDTLS_SSL_MAX_FRAG_LEN_NONE:16385:100000:0:0
DTLS renegotiation: no legacy renegotiation
renegotiation:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:-1
renegotiation:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION
DTLS renegotiation: legacy renegotiation
renegotiation:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:-1
renegotiation:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION
DTLS renegotiation: legacy break handshake
renegotiation:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:-1
DTLS renegotiation: after bad MAC on client
renegotiation:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:MBEDTLS_SSL_IS_CLIENT
DTLS renegotiation: after bad MAC on server
renegotiation:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:MBEDTLS_SSL_IS_SERVER
renegotiation:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE
DTLS serialization with MFL=512
resize_buffers_serialize_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512
@ -3042,22 +3028,6 @@ TLS 1.3: SRV: Session serialization, load buffer size
depends_on:MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_SSL_SESSION_TICKETS:MBEDTLS_SSL_SRV_C
ssl_serialize_session_load_buf_size:0:"":MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_VERSION_TLS1_3
TLS 1.3: Session serialization rejects trailing data
depends_on:MBEDTLS_SSL_CLI_C
ssl_tls13_session_load_rejects_bad_serialized_data:MBEDTLS_SSL_IS_CLIENT:TEST_TLS13_SESSION_LOAD_TRAILING_DATA
TLS 1.3: Session serialization rejects hostname without terminator
depends_on:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SERVER_NAME_INDICATION
ssl_tls13_session_load_rejects_bad_serialized_data:MBEDTLS_SSL_IS_CLIENT:TEST_TLS13_SESSION_LOAD_HOSTNAME_NO_NUL
TLS 1.3: Session serialization rejects ALPN without terminator
depends_on:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_ALPN
ssl_tls13_session_load_rejects_bad_serialized_data:MBEDTLS_SSL_IS_SERVER:TEST_TLS13_SESSION_LOAD_ALPN_NO_NUL
SSL context serialization rejects out-of-bounds DTLS CID length
depends_on:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_DTLS_CONNECTION_ID:MBEDTLS_SSL_CONTEXT_SERIALIZATION:PSA_HAVE_ALG_SOME_RSA_SIGN:PSA_WANT_ECC_SECP_R1_384:PSA_WANT_ALG_SHA_256:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY:TEST_GCM_OR_CHACHAPOLY_ENABLED
ssl_context_load_rejects_oob_cid_length:
Test configuration of EC groups through mbedtls_ssl_conf_groups()
conf_group:
@ -3377,9 +3347,6 @@ cookie_parsing:"16fefd0000000000000000002F010000de000000000000011efefd7b72727272
TLS 1.3 srv Certificate msg - wrong vector lengths
tls13_server_certificate_msg_invalid_vector_len
TLS 1.3 cli rejects HRR selecting an un-offered group
reject_hrr_selecting_unoffered_group
EC-JPAKE set password
depends_on:MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
ssl_ecjpake_set_password:0
@ -3394,22 +3361,6 @@ elliptic_curve_get_properties
TLS 1.3 resume session with ticket
tls13_resume_session_with_ticket
TLS 1.3 server propagates RMS computation error
depends_on:MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_X509_RSASSA_PSS_SUPPORT:PSA_WANT_ALG_RSA_PKCS1V15_SIGN
tls_transcript_error_propagation:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_VERSION_TLS1_3:"<= parse finished message":MBEDTLS_SSL_CLIENT_FINISHED:MBEDTLS_SSL_FLUSH_BUFFERS:MBEDTLS_ERR_SSL_INTERNAL_ERROR
TLS 1.3 client propagates RMS computation error
depends_on:MBEDTLS_SSL_PROTO_TLS1_3:MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE:MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED:MBEDTLS_X509_RSASSA_PSS_SUPPORT:PSA_WANT_ALG_RSA_PKCS1V15_SIGN
tls_transcript_error_propagation:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_VERSION_TLS1_3:"<= write finished message":MBEDTLS_SSL_CLIENT_FINISHED:-1:MBEDTLS_ERR_SSL_INTERNAL_ERROR
TLS 1.2 server propagates EMS computation error
depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
tls_transcript_error_propagation:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_VERSION_TLS1_2:"=> derive keys":MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:MBEDTLS_SSL_CERTIFICATE_VERIFY:MBEDTLS_ERR_SSL_INTERNAL_ERROR
TLS 1.2 client propagates EMS computation error
depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
tls_transcript_error_propagation:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_VERSION_TLS1_2:"=> derive keys":MBEDTLS_SSL_CERTIFICATE_VERIFY:-1:MBEDTLS_ERR_SSL_INTERNAL_ERROR
TLS 1.3 read early data, early data accepted
tls13_read_early_data:TEST_EARLY_DATA_ACCEPTED
@ -3598,29 +3549,3 @@ send_invalid_sig_alg:MBEDTLS_SSL_SIG_ECDSA:MBEDTLS_SSL_HASH_SHA512:0
Negative Test: Server using sig_alg not offered by the client - ECDSA with SHA512
depends_on:MBEDTLS_CAN_HANDLE_ECDSA_TEST_KEY:MBEDTLS_CAN_HANDLE_ECDSA_CLIENT_TEST_KEY:PSA_WANT_ALG_SHA_512
send_invalid_sig_alg:MBEDTLS_SSL_SIG_ECDSA:MBEDTLS_SSL_HASH_SHA512:MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER
TLS 1.2 NewSessionTicket: failing ticket callback leaves lifetime unset
depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_SESSION_TICKETS:MBEDTLS_SSL_CLI_C:MBEDTLS_SSL_SRV_C:MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED:PSA_HAVE_ALG_SOME_RSA_SIGN:PSA_WANT_ECC_SECP_R1_384:PSA_WANT_ALG_SHA_256:PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
write_new_session_ticket_mem
TLS 1.3 drop early data
tls13_drop_early_data:0
TLS 1.3 drop early data and insert an EndOfEarlyData
tls13_drop_early_data:1
TLS 1.3 ClientHello record boundary alignment enforcement
tls13_record_boundary_alignment:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_HS_CLIENT_HELLO
TLS 1.3 ServerHello record boundary alignment enforcement
tls13_record_boundary_alignment:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_HS_SERVER_HELLO
TLS 1.3 server Finished record boundary alignment enforcement
tls13_record_boundary_alignment:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_HS_FINISHED
TLS 1.3 client Finished record boundary alignment enforcement
tls13_record_boundary_alignment:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_HS_FINISHED
TLS 1.3 EndOfEarlyData record boundary alignment enforcement
depends_on:MBEDTLS_SSL_EARLY_DATA:MBEDTLS_SSL_SESSION_TICKETS
tls13_record_boundary_alignment:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_HS_END_OF_EARLY_DATA

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@
#include <mbedtls/ssl.h>
#include <ssl_misc.h>
#include <test/ssl_helpers.h>
#include <test/ssl_helpers_internal.h>
/* END_HEADER */

View File

@ -1,8 +1,8 @@
Check compile time library version
check_compiletime_version:"4.2.0"
check_compiletime_version:"4.1.0"
Check runtime library version
check_runtime_version:"4.2.0"
check_runtime_version:"4.1.0"
Check for MBEDTLS_VERSION_C
check_feature:"MBEDTLS_VERSION_C":0

View File

@ -1769,15 +1769,15 @@ x509parse_crt:"307d3068a0030201008204deadbeef300d06092a864886f70d01010b0500300c3
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, inv internal bitstring length)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400300000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400300000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_PUBKEY
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, inv internal bitstring tag)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400310000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400310000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_PUBKEY
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, inv RSA modulus)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0302ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0302ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_PUBKEY
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, total length mismatch)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
@ -1785,11 +1785,11 @@ x509parse_crt:"3081893074a0030201008204deadbeef300d06092a864886f70d01010b0500300
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, check failed)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_PUBKEY
X509 CRT ASN1 (TBS, inv SubPubKeyInfo, check failed, expanded length notation)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"308196308180a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210fffffffffffffffffffffffffffffffe0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
x509parse_crt:"308196308180a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210fffffffffffffffffffffffffffffffe0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_PUBKEY
# We expect an extension parsing error here because the IssuerID is optional.
# Hence, if we find an ASN.1 tag doesn't match the IssuerID, we assume the
@ -2052,25 +2052,9 @@ X509 CRT ASN1 (TBSCertificate v3, inv CertificatePolicies, policy qualifier leng
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b030819aa0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092a864886f70d01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a314301230100603551d200409300730050601003001300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CRT ASN1: basicConstraints overflow would make CA=1 (bad signature)
depends_on:PSA_HAVE_ALG_ECDSA_VERIFY:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_256
mbedtls_x509_crt_parse_file:"../framework/data_files/parse_input/server5.basic-constraints-sequence-overflow.badsign.crt":MBEDTLS_ERR_X509_INVALID_EXTENSIONS:0
X509 CRT ASN1: basicConstraints overflow would make CA=1 (good self signature)
depends_on:PSA_HAVE_ALG_ECDSA_VERIFY:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_256
mbedtls_x509_crt_parse_file:"../framework/data_files/parse_input/server5.basic-constraints-sequence-overflow.selfsigned.crt":MBEDTLS_ERR_X509_INVALID_EXTENSIONS:0
X509 CRT ASN1: basicConstraints: no cA but pathLenConstraint (bad signature)
depends_on:PSA_HAVE_ALG_ECDSA_VERIFY:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_256
mbedtls_x509_crt_parse_file:"../framework/data_files/parse_input/server5.basic-constraints-integer-first.badsign.crt":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_UNEXPECTED_TAG):0
X509 CRT ASN1: basicConstraints: no cA but pathLenConstraint (good self signature)
depends_on:PSA_HAVE_ALG_ECDSA_VERIFY:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_256
mbedtls_x509_crt_parse_file:"../framework/data_files/parse_input/server5.basic-constraints-integer-first.selfsigned.crt":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_UNEXPECTED_TAG):0
X509 CRT ASN1 (TBS, inv extBasicConstraint, no pathlen length)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b030819aa0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a314301230100603551d13010101040630040101ff02300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
x509parse_crt:"3081b030819aa0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a314301230100603551d130101010406300402010102300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CRT ASN1 (inv extBasicConstraint, pathlen is INT_MAX)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256:PSA_WANT_ALG_SHA_1
@ -2082,19 +2066,19 @@ mbedtls_x509_crt_parse_file:"../framework/data_files/parse_input/server1_pathlen
X509 CRT ASN1 (TBS, inv extBasicConstraint, pathlen inv length encoding)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0285300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010285300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
X509 CRT ASN1 (TBS, inv extBasicConstraint, pathlen length out of bounds)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CRT ASN1 (TBS, inv extBasicConstraint, pathlen empty)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0200300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010200300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
X509 CRT ASN1 (TBS, inv extBasicConstraint, pathlen length mismatch)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
x509parse_crt:"3081b430819ea0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a318301630140603551d13010101040a30080101ff0201010500300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
x509parse_crt:"3081b430819ea0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a318301630140603551d13010101040a30080201010201010500300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
X509 CRT ASN1 (TBS, inv v3Ext, ExtKeyUsage bad second tag)
depends_on:PSA_HAVE_ALG_SOME_RSA_VERIFY:PSA_WANT_ALG_SHA_256
@ -2963,10 +2947,6 @@ X509 CSR ASN.1 (OK)
depends_on:PSA_HAVE_ALG_SOME_ECDSA:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_1:!MBEDTLS_X509_REMOVE_INFO
mbedtls_x509_csr_parse:"308201183081bf0201003034310b3009060355040613024e4c3111300f060355040a1308506f6c617253534c31123010060355040313096c6f63616c686f73743059301306072a8648ce3d020106082a8648ce3d0301070342000437cc56d976091e5a723ec7592dff206eee7cf9069174d0ad14b5f768225962924ee500d82311ffea2fd2345d5d16bd8a88c26b770d55cd8a2a0efa01c8b4edffa029302706092a864886f70d01090e311a301830090603551d1304023000300b0603551d0f0404030205e0300906072a8648ce3d04010349003046022100b49fd8c8f77abfa871908dfbe684a08a793d0f490a43d86fcf2086e4f24bb0c2022100f829d5ccd3742369299e6294394717c4b723a0f68b44e831b6e6c3bcabf97243":"CSR version \: 1\nsubject name \: C=NL, O=PolarSSL, CN=localhost\nsigned using \: ECDSA with SHA1\nEC key size \: 256 bits\n\nkey usage \: Digital Signature, Non Repudiation, Key Encipherment\n":0
X509 CSR ASN.1 (extensionRequest SET length too short)
depends_on:PSA_HAVE_ALG_ECDSA_VERIFY:PSA_WANT_ECC_SECP_R1_256
mbedtls_x509_csr_parse:"308201183081bf0201003034310b3009060355040613024e4c3111300f060355040a1308506f6c617253534c31123010060355040313096c6f63616c686f73743059301306072a8648ce3d020106082a8648ce3d0301070342000437cc56d976091e5a723ec7592dff206eee7cf9069174d0ad14b5f768225962924ee500d82311ffea2fd2345d5d16bd8a88c26b770d55cd8a2a0efa01c8b4edffa029302706092a864886f70d01090e3119301830090603551d1304023000300b0603551d0f0404030205e0300906072a8648ce3d04010349003046022100b49fd8c8f77abfa871908dfbe684a08a793d0f490a43d86fcf2086e4f24bb0c2022100f829d5ccd3742369299e6294394717c4b723a0f68b44e831b6e6c3bcabf97243":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
X509 CSR ASN.1 (Unsupported critical extension, critical=true)
depends_on:PSA_HAVE_ALG_SOME_ECDSA:PSA_WANT_ECC_SECP_R1_256:PSA_WANT_ALG_SHA_256:!MBEDTLS_X509_REMOVE_INFO
mbedtls_x509_csr_parse:"308201233081cb02010030413119301706035504030c1053656c66207369676e65642074657374310b300906035504061302444531173015060355040a0c0e41757468437274444220546573743059301306072a8648ce3d020106082a8648ce3d03010703420004c11ebb9951848a436ca2c8a73382f24bbb6c28a92e401d4889b0c361f377b92a8b0497ff2f5a5f6057ae85f704ab1850bef075914f68ed3aeb15a1ff1ebc0dc6a028302606092a864886f70d01090e311930173015060b2b0601040183890c8622020101ff0403010101300a06082a8648ce3d040302034700304402200c4108fd098525993d3fd5b113f0a1ead8750852baf55a2f8e670a22cabc0ba1022034db93a0fcb993912adcf2ea8cb4b66389af30e264d43c0daea03255e45d2ccc":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_UNEXPECTED_TAG)
@ -3102,17 +3082,17 @@ X509 CSR ASN.1 (attributes: invalid len (len > data))
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_len1.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CSR ASN.1 (attributes: extensionRequest SET extends past attribute)
X509 CSR ASN.1 (attributes: invalid len (len < data))
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_len2.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_len2.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
X509 CSR ASN.1 (attributes: extension request invalid len (len > data))
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_extension_request_sequence_len1.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CSR ASN.1 (attributes: extensionRequest sequence shorter than SET)
X509 CSR ASN.1 (attributes: extension request invalid len (len < data))
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_extension_request_sequence_len2.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
mbedtls_x509_csr_parse_file:"../framework/data_files/parse_input/test_csr_v3_all_malformed_attributes_extension_request_sequence_len2.csr.der":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
X509 CSR ASN.1 (extensions: invalid sequence tag)
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY

View File

@ -1136,15 +1136,12 @@ void x509parse_crt(data_t *buf, char *result_str, int result)
#else
((void) result_str);
#endif
int res;
/* After psa#827 some failing tests that were returning MBEDTLS_ERR_PK_INVALID_PUBKEY
* will return MBEDTLS_ERR_PK_INVALID_ALG instead. We need a temporary
* backward compatibility fix until psa#827 is merged.
*/
/* Tests whose result is MBEDTLS_ERR_PK_INVALID_PUBKEY might return
* MBEDTLS_ERR_ASN1_UNEXPECTED_TAG until psa#308 is merged. This variable
* is therefore used for backward compatiblity and will be removed in
* mbedtls#10229. */
int result_back_comp = result;
if (result == MBEDTLS_ERR_PK_INVALID_ALG) {
result_back_comp = MBEDTLS_ERR_PK_INVALID_PUBKEY;
}
int res;
mbedtls_x509_crt_init(&crt);
USE_PSA_INIT();

@ -1 +1 @@
Subproject commit a92cb6a97d84762d2f4355eae99af7b9ff5c6ae1
Subproject commit 29160dd877d29658279fd683b2ae57b320ddcf09