Compare commits

..

294 Commits

Author SHA1 Message Date
David Horstmann
3bb3738679
Merge pull request #10820 from minosgalanakis/tools/fix-auto-generated-files
Fix generate_errors.pl
2026-07-20 09:55:59 +00:00
David Horstmann
12556bc2a2
Merge pull request #10804 from valeriosetti/improve-rsa-pubkey-import-err-code
pk: improve error code failure reporting when RSA public key parsing fails (1/2)
2026-07-15 11:09:33 +00:00
Minos Galanakis
32ae7d92d6 Fix generate_errors.pl
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-07-09 15:20:32 +01:00
Ronald Cron
9e9eb069d6
Merge pull request #10817 from Mbed-TLS/mbedtls-4.2.0_mergeback
Mbedtls 4.2.0 mergeback
2026-07-08 13:16:51 +00:00
Minos Galanakis
bacdd16661 Updated framework
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-07-08 10:44:21 +01:00
Minos Galanakis
53aaf3215b Updated tf-psa-crypto submodule
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-07-08 10:43:26 +01:00
Valerio Setti
a5b83aea58 tests: x509parse: add temporary fallback mechanism for PK error codes
Add a temporary fallback mechanism in 'x509parse_crt' while crypto#827
is merged.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-07-07 22:56:30 +02:00
Minos Galanakis
970ccc59b0 Merge tag 'mbedtls-4.2.0' into mbedtls-4.2.0_mergeback
Mbed TLS 4.2.0

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-07-07 16:51:57 +01:00
Valerio Setti
8607628249 tests: x509parse: adjust some PK related error codes
After crypto#827 some PK error codes changed from
MBEDTLS_ERR_PK_INVALID_PUBKEY to MBEDTLS_ERR_PK_INVALID_ALG.
This commit adjusts failing test cases.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-07-02 14:05:15 +02:00
Minos Galanakis
ece41aa84d ChangeLog: Removed CVE-ID
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-07-01 12:00:14 +01:00
Valerio Setti
47e9e61020
Merge pull request #10656 from bjwtaylor/unused-variable-ret
Fix variable set but not used warning
2026-07-01 08:26:29 +00:00
Minos Galanakis
b4ee2d4277 Update BRANCHES.md
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:16:27 +01:00
Minos Galanakis
c1cc0ed3ed ChangeLog: Removed todo placeholder for CVE
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:16:27 +01:00
Minos Galanakis
7f64d9609b Changelog: Added reference to tf-psa-crypto update
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:16:27 +01:00
Minos Galanakis
f3c2896076 Assemble ChangeLog
./framework/scripts/assemble_changelog.py

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:12:41 +01:00
Minos Galanakis
b11a07f274 Bump version --version 4.2.0
./scripts/bump_version.sh --version 4.2.0

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:12:41 +01:00
Minos Galanakis
97a9420455 Updated tf-psa-crypto submodule
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-29 18:12:41 +01:00
Minos Galanakis
d156cf4c02 Merge remote-tracking branch 'development-restricted' into mbedtls-4.2.0.rc 2026-06-26 22:23:37 +01:00
Ronald Cron
41a8bdf109
Merge pull request #1619 from valeriosetti/issue1585
[development] Stale DTLS- SRTP negotiation state after session_reset() (ARM-RZ7EMQAA)
2026-06-26 12:17:06 +02:00
Ronald Cron
3bb1c69f7e
Merge pull request #1685 from minosgalanakis/security/mlfbyt4c_tls13_policy_bypass_changelog
Add Attribution CVE mbedtls:development-restricted
2026-06-25 15:54:46 +02:00
Ronald Cron
05e0dfbe99
Merge pull request #10786 from minosgalanakis/mbedtls-release-sync
Mbedtls 4.2.0 release sync
2026-06-25 12:16:45 +00:00
Minos Galanakis
66e3648745 Updated tf-psa-crypto pointer
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-25 00:50:42 +01:00
Minos Galanakis
0aaa58b438 Updated framework pointer
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-25 00:50:26 +01:00
Gilles Peskine
1a4f04b0c4
Merge pull request #10788 from bensze01/readthedocs
Upgrade readthedocs builder to Ubuntu 26.04
2026-06-24 18:18:42 +00:00
Gilles Peskine
9baa16385d
Merge pull request #1652 from ronald-cron-arm/hsm-do-not-span-key-change
Hsm do not span key change
2026-06-24 19:22:01 +02:00
Bence Szépkúti
98413e8b70 Upgrade readthedocs builder to Ubuntu 26.04
The 20.04 runner is no longer supported.

Signed-off-by: Bence Szépkúti <bence.szepkuti@arm.com>
2026-06-24 16:43:16 +02:00
Ronald Cron
b188f399f9 Check ServerHello record boundary alignment only in TLS 1.3 case
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
74b9ab2008 tls13_fetch_handshake_msg(): Remove require_record_boundary parameter
Deduce it from the handshake message type

Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
e08cea612f tls13_record_boundary_alignement: Append empty hs msg
Append an empty handshake message to expand
the record instead of just a zero byte.

Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
1a58c59470 Various improvements of tls13_(drop_early_data|record_boundary_alignment)()
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
6c557a70f6 tls13: Rework mbedtls_ssl_tls13_fetch_handshake_msg()
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
0c9d3d4a0f tls13: Improve argument name
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
86315b62a8 test_suite_ssl: Add initialization to all zeroes of test endpoint structs
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
c494497256 Fix typos
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
e55d0b76ed Add change log
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
2de65b79a3 test_suite_ssl: Test EndOfEarlyData on record boundary enforcement
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
cbef7256ce test_suite_ssl: Test client Finished on record boundary enforcement
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
53ac018b24 test_suite_ssl: Test server Finished on record boundary enforcement
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
93eb43ed4f test_suite_ssl: Test ServerHello on record boundary enforcement
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
c8fefcde05 test_suite_ssl: Test ClientHello on record boundary check
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
3861588b47 tls13: Add record boundary checks
RFC 8446 (TLS 1.3 specification), Section 5.1, states:

Handshake messages MAY be coalesced into a single TLSPlaintext record
or fragmented across several records, provided that:
    ...
    -Handshake messages MUST NOT span key changes. Implementations
    MUST verify that all messages immediately preceding a key change
    align with a record boundary; if not, then they MUST terminate the
    connection with an "unexpected_message" alert. Because the
    ClientHello, EndOfEarlyData, ServerHello, Finished, and KeyUpdate
    messages can immediately precede a key change, implementations
    MUST send these messages in alignment with a record boundary.

Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:33 +02:00
Ronald Cron
b340e27847 test_suite_ssl: Add early data drop tests
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-24 15:51:30 +02:00
Valerio Setti
4f92a63e4a tests: ssl_helpers: run ssl_context reset check only when the SSL context is setup
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 15:37:00 +02:00
Minos Galanakis
f722436e46 Changelog. Added attribution/CVE for 1569
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-24 14:36:00 +01:00
Ronald Cron
f74ef9b3ab
Merge pull request #1599 from bjwtaylor/ssl-ignores-failure-restricted
Fix issues in ssl where it ignores the failure return
2026-06-24 15:02:34 +02:00
Valerio Setti
c668f4e68e framework: update reference
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:31:20 +02:00
Valerio Setti
4c8a9b7a5e tests: generate_ssl_session_reset_check: remove trailing whitespace
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
dce45a7cfe tests: generate_ssl_session_reset_check: pacify pylint
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
508e9b1ca4 tests: generate_ssl_session_reset_check: order rules as fields in the struct
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
d70169b85c tests: ssl_helpers: fix documentation of mbedtls_test_ssl_check_context_after_session_reset
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
365544616d tests: ssl_context_reset_verifier: add missing semicolon in generated file
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
b55e820fd1 tests: generate_ssl_session_reset_check: add missing semicolon in generated file
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
4b57c243bb changelog: add note for documentation fix for mbedtls_ssl_set_cid
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
3bd3e47100 include: ssl: fix documentation of mbedtls_ssl_set_cid
Specify that the configured CID will apply to all subsequent handshakes
not just to the next one.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
931b983159 changelog: add reset for some fields of the SSL context structure
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
a2338a21fa library: ssl: reset some SSL context's fields in mbedtls_ssl_session_reset
Following fields were not properly reset when mbedtls_ssl_session_reset
was called:

- badmac_seen
- dtls_srtp_info
- alert_reason
- alert_type

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
fbd49c0c4e tests|programs: call check_context_after_session_reset whenever mbedtls_ssl_session_reset
Call mbedtls_test_ssl_check_context_after_session_reset both in programs
(ssl_client2 and ssl_server2) and tests to ensure that the SSL context
has been properly handled when mbedtls_ssl_session_reset was called.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
a4dbd999c0 tests: add prototype and implementation of mbedtls_test_ssl_check_context_after_session_reset
Ideally the implementation shouldn't be checked in git, but for the time
being there is no support in building source code for tests from the
binary folder, so it's accepted as a temporary solution.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
8294a8fd67 tests: scripts: add generate_ssl_session_reset_check.py
Togethere with the framework counterpart ('ssl_session_reset_check.py')
this script is used to automatically generate the function
'mbedtls_test_ssl_check_context_after_session_reset()'.
The goal of this function is to verify that 'mbedtls_ssl_session_reset()'
properly handled (reset or keep) all the fields of the
'mbedtls_ssl_context' structure.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
0a48608651 tests: ssl: split ssl_helpers between public and internal functions
Move functions in "ssl_helpers.h" that depend on internal headers to
"ssl_helpers_internal.h". This allows to include "ssl_helpers.h" also
in programs (which do not have access to internal headers).

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Valerio Setti
3e191be15a include: ssl: add a typedef for unused data in mbedtls_ssl_config and mbedtls_ssl_context
Add mbedtls_ssl_unused_data_t type instead of embedding the union inside
both structures.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-24 14:30:59 +02:00
Ben Taylor
c438b0b9a9 Correct error handling in mbedtls_ssl_reset_checksum
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
82bba7ef61 Fix error codes for tls_transcript_error_propagation
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-24 09:33:33 +01:00
Ben Taylor
e98a0a84c3 Improve tls_transcript_error_propagation testing to check for error codes
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
414d284f4a Update regression test
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-24 09:33:33 +01:00
Ben Taylor
0bf015a43b restore missing ext_len set
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
dc555d19ec remove trailing whitespace
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
fa003af204 Update ChangeLog with CVE number
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-24 09:33:33 +01:00
Ben Taylor
75bdaa35c3 Update ChangeLog to add CVE
Co-authored-by: Gilles Peskine <gilles.peskine@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-24 09:33:33 +01:00
Ben Taylor
fc2f108dfb Update dependencies for skipped test
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
14b2bdc8ce fix code style
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
86b94d411c Improve ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
2e95cb7baa Update error handling of return from ssl_write_ecjpake_kkpp_ext
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
629df9f5fb Improve testing
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
835226c59a Update ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
d32397563e Fix reporters in ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
f63a0058d3 Remove check for NULL pointer
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
f487bd2e07 Tidy up ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
795eb3ee95 Add Reported by to ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
1c68ca14fb Fix code style issues
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
48593c23a0 Add fix for missing return from ssl_write_ecjpake_kkpp_ext
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
f6aeb4c8e4 Add additional fix for return with error
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
1e098f3ae9 Add client tests for RMS computation error
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
e9779ccaa3 Add unsupported trigger check
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
ed70149de3 Add further documentation to tls_abort_transcript_context
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:33 +01:00
Ben Taylor
3565231081 Fix issues with hanging seed length
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
c2a26a989f Fixed code style
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
8e9e821ce8 refactor initialisation in tls_transcript_error_propagation, so that the variables are initialised straight after they are declared
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
d137f35665 Add additional guard for sha256 in tests
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
e8f3c920ed Improve layout of the code for debugging with breakpoints
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
ceaa75b899 Add security impact
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
b35f870331 Update ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ben Taylor
c7f07e9288 Add ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:32 +01:00
Ronald Cron
ae6b06ce4c Improve dependencies and error handling
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:33:30 +01:00
Ben Taylor
5871216afc tests: ssl: add regression tests for EMS/RMS error propagation
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:30:05 +01:00
Ben Taylor
9063aca165 ssl: propagate transcript-hash computation failures
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-24 09:17:14 +01:00
Gilles Peskine
98e4a7b02a
Merge pull request #1595 from bjwtaylor/info-leak-in-ssl_write_new_session_ticket
Info leak in ssl write new session ticket
2026-06-24 09:42:13 +02:00
Gilles Peskine
8300fd0a65
Merge pull request #1638 from valeriosetti/issue1598
[development] PKCS7 accepts weak hashes
2026-06-23 16:40:47 +02:00
Minos Galanakis
567a3a443d Added attribution
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-23 10:52:37 +01:00
Minos Galanakis
de8a0d3fdb Added CVE
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-22 22:29:15 +01:00
Ronald Cron
27fcc8e3a0
Merge pull request #1582 from bjwtaylor/pkcs-free-stale-pointers
Add fix for stale pointer after mbedtls_pkcs7_free
2026-06-22 17:54:17 +02:00
Valerio Setti
f155d9fefd framework: update reference
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:40:07 +02:00
Valerio Setti
869bd519fb tests: pkcs7: adjust test dependencies
Newly added tests for RIPEMD160 and MD5 still require SHA-256 for the
certificate being used. SHA-1 is instead useless in this case.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
feb2c53009 pkcs7: update documentation adding a note about rejecting weak hash algs
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
f065e47b18 changelog: update documentation for PKCS7 changes
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
00a2677b1e test_suite_pkcs7: adjust numbering of tests
Some newly added tests had duplicate numbers with what was already there.
This commit fixes the duplication problem.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
64d8776ea9 pkcs7: replace MBEDTLS_ERR_PKCS7_VERIFY_FAIL with MBEDTLS_ERR_PKCS7_VERIFY_FAIL
This also updates test data.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
45654b0246 pkcs7: split MD/PK check in mbedtls_pkcs7_data_or_hash_verify
Follow the default Mbed TLS coding style and ease debugging (i.e. placing
of breakpoints).

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
930b87a87e tests: pkcs7: add negative tests using MD5 and RIPEMD160
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
394d8e6a6f changelog: add note for PKCS7 rejecting weak hash algorithms
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
632c4fce0e tests: pkcs7: adjust return code in SHA-1 based PKCS7 test
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
c25e7654ea pkcs7: fail verification if MD alg or sig_alg are not secure
Add a check on mbedtls_pkcs7_data_or_hash_verify() so that the verification
fails if the MD alg specified in PKCS7 structure or the signature
algorithm specified in the X.509 certificate are not in the list of
secure algorithms (i.e. mbedtls_x509_crt_profile_default).

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
395bc86df8 x509: make profile checking functions internally available
Following functions

- x509_profile_check_md_alg
- x509_profile_check_pk_alg

are made non-static and moved to x509_internal.h so that other library
files can used them.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
24a184ad36 x509_crt: add SHA3 algs to mbedtls_x509_crt_profile_default
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Valerio Setti
4e057619a9 x509_crt: remove old invalid comment
ssl_preset_default_hashes was removed in
f0cda410a4bca0f45f66bdbf0714cd0eb2ea4718 but the comment in 'x509_crt.c'
wasn't updated.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-06-22 11:39:49 +02:00
Ronald Cron
2beeff6a8e
Merge pull request #1671 from gilles-peskine-arm/badmac_seen_or_in_hsfraglen-test-dev
test badmac_seen with renegotiation #1667
2026-06-22 10:29:05 +02:00
Gilles Peskine
55bd327bad
Merge pull request #1630 from gilles-peskine-arm/basic-constaints-sequence-check-dev
Fix CA bit forgery through invalid basicConstraints
2026-06-18 15:36:41 +02:00
Ronald Cron
45ad2fc5ee
Merge pull request #10715 from Nadav0077/harden-tls13-session-load
Harden TLS 1.3 serialized session loading
2026-06-18 10:36:47 +00:00
Gilles Peskine
94370bc4e4 Remove some test cases that are not really meaningful
Remove the "srv" variant of "DTLS proxy: server: get invalid AD record then
accept renego", where the server initiates the renegotiation process by
sending a HelloRequest. The HelloRequest message is not relevant to this
test. The first message of the actual renegotiation is the ClientHello
message from the client, and the interesting part of the test happens when
the client receives the server's response.

Remove "DTLS proxy: server: get invalid AD record then accept early
renego (cli)" and the corresponding "reject" control. This test case doesn't
really do what it is advertised to do, and in particular does not lead to a
call to `ssl_consume_current_message()` in the server. What happens is that
the client sends a ClientHello message to start the renegotiation, then it
blocks until the server has replied. So there is nothing to delay that
ClientHello after:(unlike what happens in the corresponding client-side
test, where the first flight of the renegotiation protocol contains multiple
messages, so we can delay the first of these messages after the second one).
What happens in practice is that the client times out, then resends its
ClientHello, and the proxy sends the delayed ClientHello immediately after
the resent one, which does not cause any interesting behavior in the server.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
c2f9cf3416 Explain the "get invalid AD record .*renego" tests better
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
bba465154a Don't pass badmac_limit when it would have no effect
Only set `badmac_limit` on the side that actually receives a message with a
bad MAC/tag (injected by the proxy).

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
41ee1448ba Add DTLS handshake test with badmac_seen=1
Add a test entry point for a handshake with a specially crafted context.
This can be used for defense in depths for scenarios that we think can't
happen, but might actually happen due to a bug, or due to a new feature that
is insufficiently tested. This can also be a proxy for testing aspects of
renegotiation or session resumption in circumstances that are hard to
arrange.

In this commit, use it to test a DTLS handshake with `ssl->badmac_seen`
:(actually `ssl->badmac_seen_or_in_hsfraglen` in the 3.6 branch) set to a
nonzero value. This can't happen, as far as I know (`badmac_seen` can only
be nonzero during renegotiation, not during a nominal handshake or in
session resumption). But it could happen, for example, if
`mbedtls_ssl_session_reset()` failed to reset `badmac_seen`, as was the case
in Mbed TLS 4.0.0 to 4.1.0.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
a4e7d2b11e Add tests for renegotiation with badmac_seen=1 on the server
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
05fa79dc43 Add renegotiate=2 option to ssl_client2
In `ssl_client2`, the existing option `renegotiate=1` causes the client to
initiate renegotiation immediately after the initial handshake. Add a
variant `renegotiate=2` that initiates renegotiation after one data exchange.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
ed39c7b394 Add tests for renegotiation with badmac_seen=1 on the client
After a message with a bad MAC (invalid application data record), try to
renegotiate:

* Test cases where renegotiation (nominal or delayed) is rejected.
  Nothing bad happens.
* A test where renegotiation is misparsed and rejected.
  The subsequent parsing fails.
* A test where the renegotiation request is delayed.
  This causes a heap buffer overflow in `ssl_buffer_message()`.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
b1ba93460b Check "refusing renegotiation" log in more renegotiation tests
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
259de57a85 Add badmac_limit option to ssl_client2
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
3d088c90c4 Add one-shot bad AD options to udp_proxy
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
2475c617cb Add udp_proxy options to delay an encrypted handshake message
This can be used to simulate data messages received in the wrong epoch, or
to cause a handshake message to be buffered.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
3e76e77ee2 Test DTLS renegotiation when badmac_seen_or_in_hsfraglen != 0
Non-regression test for a bug introduced with TLS handshake defragmentation
support in Mbed TLS 3.6.3, whereby the confusion between the `badmac_seen`
meaning and the `in_hsfraglen` meaning of `ssl->badmac_seen_or_in_hsfraglen`
causes renegotiation to be processed incorrectly after receiving a message
with a bad MAC.

The bug doesn't affect Mbed TLS 4.0.0 and above, but it's still good to have
more testing.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
21df158961 Add some hooks in mbedtls_test_ssl_perform_handshake()
Let test code customize the kitchen sink function
`mbedtls_test_ssl_perform_handshake()` at a few points.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
639615337e Add a missing dependency
Needed by a test certificate.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-17 14:53:58 +02:00
Ronald Cron
5374a4124b Remove unnecessary dependency
Signed-off-by: Ronald Cron <ronald.cron@arm.com>
2026-06-17 14:53:58 +02:00
Gilles Peskine
e31c644041 Credit independent report
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-16 19:34:32 +02:00
Gilles Peskine
86b620ace3
Merge pull request #1586 from bjwtaylor/ECDHE-PSK-integer-overflow
Ecdhe psk integer overflow fix
2026-06-16 11:49:54 +02:00
Ronald Cron
9b2a6cc914
Merge pull request #1663 from minosgalanakis/public-sync/development-14062026
[Sync] Merge development into development-restricted
2026-06-16 08:44:06 +02:00
Ronald Cron
8efcd8d700
Merge pull request #1603 from bjwtaylor/oob-key-exchange-restricted
Add fix for OOB key exchange error
2026-06-15 22:42:08 +02:00
Ben Taylor
377aa4eff1 Add in the two additional checks that were dropped.
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-15 13:27:02 +01:00
Ben Taylor
10afc1ed5c Remove pkcs7_parse_free_resets_context as it duplicates pkcs7_parse_reuse
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
a798b5804e Add CVE ID to ChangeLog
Co-authored-by: Gilles Peskine <gilles.peskine@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-15 13:27:02 +01:00
Ben Taylor
74555884cc Remove whitespace in ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
351419f1ff Correct changelog style
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
84966c1bda Add further testing
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
6443590448 Update ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
4e797c14e0 Update ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
62162e6e4d Fix style issues
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
f60f5ba85c Remove redundant function from pkcs7_parse_reuse
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
e9ec4ce3ca Add ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Ben Taylor
67e696b430 Add fix for stale pointer after mbedtls_pkcs7_free
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-15 13:27:02 +01:00
Minos Galanakis
c508351e39 Merge remote-tracking branch 'public/development' into sync/development-14062026
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-06-14 19:32:58 +01:00
Ben Taylor
1aa1254546 Fix style issue
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-10 14:15:48 +01:00
Ronald Cron
1070ab8dd7
Merge pull request #1563 from minosgalanakis/security/mlfbyt4c_tls13_policy_bypass
TLS1.3 client HRR policy bypass[ARM-MLFBYT4C]
2026-06-10 13:04:24 +02:00
Ben Taylor
273c9b38b7 Correct syntax of MBEDTLS_GET_UINT32_BE in write_new_session_ticket_mem
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-10 08:38:36 +01:00
Ben Taylor
cecb4c2162 Correct ChangeLog style
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-10 08:21:05 +01:00
Ben Taylor
911b9b67db
Add CVE ID to ChangeLog
Co-authored-by: Gilles Peskine <gilles.peskine@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-08 15:48:14 +01:00
Ben Taylor
0c62b498bd Add ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-08 15:46:00 +01:00
Ben Taylor
33c55a90e3 Improve test of non-initilisation of lifetime
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-08 15:39:17 +01:00
Ben Taylor
38185e2308 Improve robustness of tlen and lifetime variables
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-08 15:39:17 +01:00
Ben Taylor
a5c2e02198 Add fix for leak
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-08 15:39:17 +01:00
Ben Taylor
f5675fd064 Add test for leak
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-08 15:39:17 +01:00
Ben Taylor
5e04a32840
Add CVE to ChangeLog
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-08 15:13:37 +01:00
Ben Taylor
4b32430d3c
Improve the wording of the ChangeLog
Co-authored-by: Ronald Cron <ronald.cron@arm.com>
Signed-off-by: Ben Taylor <32939606+bjwtaylor@users.noreply.github.com>
2026-06-08 15:13:02 +01:00
Ronald Cron
5cd633798c
Merge pull request #10769 from mpg/security-link-dev
Update broken link in SECURITY.md
2026-06-05 15:44:33 +00:00
Gilles Peskine
e94a7a2d22 Add CVE-ID
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
ca89089968 Add attribution for the second bug
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
402592db1d Update dependencies in forward port from 3.6
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
f624adff2e Switch to MBEDTLS_ERROR_ADD for combining X509 and ASN1 error codes
Since Mbed TLS 4.0, this is just the low-level error code. But keep the
combination for uniformity with the rest of the file, and to reduce the
differences with the 3.6 branch.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
045cede1b8 basicConstraints with leading INTEGER field: document the behavior change
Announce the security fix together with the overflow fix, since the two bugs
are pretty much indistinguishable from a black-box perspective, despite
being due to independent problems in the code.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
0d6060d644 Stop accepting basicConstraints with only pathLenConstraint
In an X.509 certificate, a basicConstraints extension where the cA
field (BOOLEAN) is omitted but the pathLenConstraint field (INTEGER )is
present is syntactically valid, but RFC 5280 states that CAs MUST NOT emit
such a certificate.

Historically, since XySSL 0.9 in 2008, if a basicConstraints extension
started with an INTEGER field, we interpreted that field as a cA value. This
was a deliberate change:

> Fixed x509_get_ext() to accept some rare certificates (like
> www.openssl.org:443) which have an INTEGER instead of a BOOLEAN for
> Extension::BasicConstraints::cA.

However, 18 years later, this does not seem to be relevant, and the details
seem to have been lost. Furthermore, major implementations follow RFC 5280
and interpret `SEQUENCE { INTEGER n }` with cA being set to its default
value (FALSE) and pathLenConstraint set to `n`. This means that such a
certificate with n != 0 would be interpreted as a CA certificate in Mbed TLS
but as a leaf certificate elsewhere, which is dangerous.

Since CAs are not supposed to emit such certificates, stop accepting them
altogether.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
5cc6fb22c6 basicConstraints pathLenConstraint tests: use standard cA type
In test cases for pathLenConstraint parsing in a basicConstraints extension
of an X.509 certificate, use the standard type for the leading cA field,
namely BOOLEAN. The test data was encoding that field as INTEGER, which was
accepted as a deviation from the standard since XySSL 0.9.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:46 +02:00
Gilles Peskine
eb051b501a Remove unreachable CSR extensionRequest check
It is now unreachable because:

- end_set == end_attr_data is enforced at library/x509_csr.c:236.
- end_exts == end_set is enforced at library/x509_csr.c:248.
- x509_csr_parse_extensions() only returns success if *p == end_exts, enforced
  at library/x509_csr.c:188.

So after a successful x509_csr_parse_extensions() call, *p == end_exts ==
end_set == end_attr_data. The condition at line 257 cannot be true.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:41 +02:00
Gilles Peskine
cc794d8501 Tighten CSR extensionRequest bounds
Don't allow parts of a compound (SEQUENCE or SET) to go beyond the
containing compound.

The inline CSR regression test is derived from the existing "X509 CSR
ASN.1 (OK)" DER test vector. In the extensionRequest attribute, the original
well-formed fragment is:

    a029 3027 06092a864886f70d01090e 311a 3018 ...

where 31 1a is the SET containing the Extensions sequence and 30 18 is the
contained Extensions sequence. The malformed test changes only the SET
length byte, from 1a to 19:

    a029 3027 06092a864886f70d01090e 3119 3018 ...

The attribute SEQUENCE length and the inner Extensions sequence length are
left unchanged. This makes the SET one byte too short for its containing
attribute, so the parser must reject it with
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH instead of parsing the trailing byte as
data outside the SET.

There is no known security impact, just some risk reduction.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-06-05 11:35:38 +02:00
Ben Taylor
a7c0d83354 Add improvements to ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-05 10:22:49 +01:00
Ben Taylor
ab2a7d5a34 Add reported by and CVE placeholder
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Ben Taylor
0501e447cc Correct style of ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Ben Taylor
c567299ee6 Add in tests for ECDHE-PSK integer overflow
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Ben Taylor
c058818451 Improve ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Ben Taylor
e71e49e634 Add ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Ben Taylor
baf449db7e Added fix for Integer overflow using a large ECDHE Identity
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-06-04 14:22:38 +01:00
Manuel Pégourié-Gonnard
af15f6e244 Update broken link
I believe the existing link was to the TF wiki which has been retired
for some time now.

Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
2026-06-03 10:33:29 +02:00
Ronald Cron
5ca2218a28
Merge pull request #1589 from gilles-peskine-arm/ssl_tls13_prepare_new_session_ticket-psa_get_random-4.1
Fix ssl_tls13_prepare_new_session_ticket returning 1 on an RNG failure
2026-05-29 16:20:27 +02:00
Ronald Cron
05bd7f6429
Merge pull request #1612 from valeriosetti/issue1569
[development] TLS 1.3 certificate chain signature algorithm policy gap
2026-05-29 13:35:32 +02:00
Gilles Peskine
b05434c1b1 Improve changelog wording
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-05-28 16:32:35 +02:00
Gilles Peskine
6c8ae1ea48 Fix lax basicConstraints parsing
When parsing the basicConstraints extension, 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).

Add a non-regression test where a certificate that is technically malformed,
but accepted as a leaf certificate by OpenSSL and other X.509
implementations, to be accepted as a CA certificate by Mbed TLS.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-05-26 21:07:09 +02:00
Gilles Peskine
22dccc1d83 Update framework with test certificate with basicConstraints overflow
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-05-26 21:07:09 +02:00
Janos Follath
545d1b77a2
Merge pull request #10741 from valeriosetti/fix-mbedtls_config
mbedtls_config.c missing mbedtls_platform_requirements.h
2026-05-26 09:24:54 +00:00
Minos Galanakis
e2a6f05640 ssl_write_supported_groups_ext: Updated documentation
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-26 10:17:11 +01:00
Nadav0077
fc34e72fc2
Address review: symbolic mutation constants and CID bounds-check test
Signed-off-by: Nadav0077 <18245584+Nadav0077@users.noreply.github.com>
2026-05-21 13:58:17 +03:00
Minos Galanakis
84667a048f test_suite_ssl: Added MBEDTLS_DEBUG_C guards to logs
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-20 12:25:42 +01:00
Minos Galanakis
95ad8b45ed test_suite_ssl: Restructured reject_hrr_selecting_unoffered_group
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-19 22:28:56 +01:00
Minos Galanakis
3d3de630db test_suite_ssl: Renamed hrr_reject_selecting_unoffered_group
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-19 17:36:12 +01:00
Minos Galanakis
7a232d0822 sll_client: align TLS 1.3 supported_groups filtering with PSA curve support
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-19 17:31:47 +01:00
Nadav0077
72f767da31
Address review comments on serialized data hardening
Signed-off-by: Nadav0077 <18245584+Nadav0077@users.noreply.github.com>
2026-05-19 14:15:02 +03:00
Nadav0077
fea00c3e51
Reject out-of-bounds DTLS CID length in ssl_context_load
Signed-off-by: Nadav0077 <18245584+Nadav0077@users.noreply.github.com>
2026-05-19 14:15:01 +03:00
Valerio Setti
147ad72669 changelog: fix typos
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-05-19 12:37:30 +02:00
Valerio Setti
c53e78796a changelog: add note about issue 1569 resolution
Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-05-18 11:08:23 +02:00
Valerio Setti
a3ae8be611 ssl: improve documentation of mbedtls_ssl_conf_sig_algs()
Clarify that the 'sig_algs' set through this function are only enforced
during the key exchange and that 'mbedtls_ssl_conf_cert_profile()' should
instead be used to enforce the same algorithms when verifying certificates.

Signed-off-by: Valerio Setti <vsetti@baylibre.com>
2026-05-18 11:04:59 +02:00
minosgalanakis
701132e5b3
Merge pull request #10663 from yiwu0b11/remove_unused_ffdh_code
Remove FFDH-specific code from compat.sh
2026-05-13 16:49:20 +00:00
Minos Galanakis
848ddaaedb test_suite_ssl: doc fixes
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-13 11:33:40 +01:00
Ben Taylor
ea9dc9c396 Add ChangeLog
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-05-13 11:16:49 +01:00
Nadav0077
3f972d014d
Use block-local ret to avoid unused-variable in restricted configs
Signed-off-by: Nadav0077 <18245584+Nadav0077@users.noreply.github.com>
2026-05-12 19:32:50 +03:00
Minos Galanakis
5936ba523d Added ChangeLog
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-12 14:59:18 +01:00
Ronald Cron
00be9c9b67
Merge pull request #10700 from gilles-peskine-arm/python-project-knowledge-directory-mbedtls-dev
Create Python project knowledge directory
2026-05-12 13:38:23 +00:00
Manuel Pégourié-Gonnard
4a1d150cdf
Merge pull request #1600 from mpg/development-restricted
Merge public development into -restricted
2026-05-12 08:59:49 +02:00
Ben Taylor
08e3e3f81e Add fix for OOB key exchange error
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-05-11 15:22:09 +01:00
Manuel Pégourié-Gonnard
00dfa64627 Merge branch 'development' into development-restricted
* development: (46 commits)
  Update tf-psa-crypto pointer to bring in fix for python imports
  Update framework pointer to bring in fix for python imports
  check_config: fix error message for missing TLS 1.2 key exchanges
  check_config: add check for TLS 1.3 key exchanges
  update ChangeLog
  Pacify uncrustify
  ChangeLog: Fixed a reference to TF-PSA-Crypto
  ssl: add TLS 1.2 RSA-PSS debug trace
  add ChangeLog
  Fix build warning/error using llvm-mingw
  ssl: narrow TLS 1.2 RSA-PSS handling and add interop coverage
  test: improve symlink checks
  test: versioned symlink order fix
  test: reorder if-else structure
  test: add debug output and fix for win config
  ChangeLog fix
  Unify TF-PSA-Crypto and mbedtls templates
  tests: fix DESTDIR install checks and add macOS compatibility
  ChangeLog fixes
  Update crypto submodule with analyze_outcomes.py
  ...
2026-05-11 12:04:15 +02:00
Manuel Pégourié-Gonnard
902b012537
Merge pull request #10749 from bjwtaylor/broken-build
Update framework pointer to bring in fix for python imports
2026-05-07 19:13:19 +00:00
Ben Taylor
954e236500 Update tf-psa-crypto pointer to bring in fix for python imports
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-05-07 14:17:54 +01:00
Ben Taylor
02fb4c75cb Update framework pointer to bring in fix for python imports
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-05-07 08:14:43 +01:00
Minos Galanakis
89a0606118 Adjusted dependecies for hrr_reject_unadvertised_group
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-05-06 11:19:39 +01:00
Gilles Peskine
465d6e9669 Fix ssl_tls13_prepare_new_session_ticket returning 1 on an RNG failure
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-05-04 18:44:05 +02:00
Valerio Setti
cd8b3878c5 changelog: add note about fix of issue 10740
Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-04-29 17:05:51 +02:00
Valerio Setti
b155a58ab5 include mbedtls_platform_requirements.h in mbedtls_config.c
This is required because if the user defined configuration file (not the
default one provided by mbedtls) includes files from the standard
C library then __STDC_WANT_LIB_EXT1__ won't be defined there which
cause weird build failures.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-04-29 16:57:55 +02:00
minosgalanakis
d12fbb991c
Merge pull request #10695 from valord577/patch-1
Fix build warning/error using llvm-mingw
2026-04-29 14:52:00 +00:00
Gilles Peskine
a314ada082
Merge pull request #10631 from yiwu0b11/destdir_install_env_support
Support DESTDIR for install and add build-system test
2026-04-29 14:37:29 +00:00
Nadav0077
3ab4fce1a0
Harden TLS 1.3 serialized session loading
Signed-off-by: Nadav0077 <18245584+Nadav0077@users.noreply.github.com>
2026-04-25 15:19:30 +03:00
Valerio Setti
ae8579f2a2
Merge pull request #10650 from valeriosetti/fix-tls13-guard
check_config: add missing check for TLS 1.3 key exchanges
2026-04-24 14:32:36 +00:00
Minos Galanakis
a9a8385747 test_suite_ssl: Introduced hrr_reject_unadvertised_group
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-04-24 12:04:36 +01:00
Valerio Setti
51b62060de
Merge pull request #10639 from valeriosetti/ecdhe-rsa-fix-check
library: check_config: remove RSA encryption requirement from ECDHE-RSA
2026-04-24 07:30:47 +00:00
Gilles Peskine
52ca15362b Update comment
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-22 17:38:48 +02:00
Valerio Setti
c3d52b905b check_config: fix error message for missing TLS 1.2 key exchanges
Align the error message to the one used for the same check in TLS 1.3.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-04-22 15:00:55 +02:00
Valerio Setti
5ea77200d9 check_config: add check for TLS 1.3 key exchanges
When MBEDTLS_SSL_PROTO_TLS1_3 is enabled ensure that at least one of the
related key exchanges is also enabled.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-04-22 15:00:54 +02:00
valord577
68319cbc80 update ChangeLog
Signed-off-by: valord577 <valord577@gmail.com>
2026-04-22 11:05:04 +08:00
valord577
e022733f9f
Merge branch 'Mbed-TLS:development' into patch-1 2026-04-22 10:41:51 +08:00
Minos Galanakis
9027620393 tls13_client: fix HRR selected_group validation
Reject HRR selected_group unless it matches the client’s original
supported_groups and is locally supported, so unadvertised groups are not
accepted in the second ClientHello.

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-04-21 17:07:36 +01:00
Ronald Cron
391af7c976
Merge pull request #10701 from minosgalanakis/docs/4.1.0_changelog_fixes
ChangeLog: Fixed a reference to TF-PSA-Crypto
2026-04-20 09:38:38 +00:00
Ronald Cron
518ed0337d
Merge pull request #10672 from Maokaman1/fix/tls12-rsa-pss-sigalgs
ssl: accept TLS 1.2 rsa_pss_rsae signature algorithms
2026-04-20 08:03:39 +00:00
Viktor Sokolovskiy
f90e81c7f8 Pacify uncrustify
Signed-off-by: Viktor Sokolovskiy <maokaman@gmail.com>
2026-04-18 01:51:17 +03:00
Maokaman1
78336bb5bd
Merge branch 'Mbed-TLS:development' into fix/tls12-rsa-pss-sigalgs 2026-04-17 19:13:43 +03:00
Minos Galanakis
935eb1a53b ChangeLog: Fixed a reference to TF-PSA-Crypto
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-04-17 16:59:05 +01:00
Viktor Sokolovskiy
3d61c38ea0 ssl: add TLS 1.2 RSA-PSS debug trace
Signed-off-by: Viktor Sokolovskiy <maokaman@gmail.com>
2026-04-17 17:36:31 +03:00
Gilles Peskine
cf0bbfd024 Prefer to load tf_psa_crypto_test_case_info from project_knowledge
Try to load the list of tests that TF-PSA-Crypto wants us to ignore in three
ways, depending on the age of the tf-psa-crypto submodule:

* Modern: import `tf_psa_crypto_test_case_info` as an ordinary module,
  expected to be found in `tf-psa-crypto/scripts/project_knowledge`.
* First location, quickly superseded: load
  `tf-psa-crypto/tests/scripts/tf_psa_crypto_test_case_info.py`,
  in a hackish way because we don't want to put that directory on the
  load path.
* Oldest: there is no `tf_psa_crypto_test_case_info.py`. Use a hard-coded
  list.

Once all the TF-PSA-Crypto branches we care about (e.g. pull requests
in progress) are updated with
`tf-psa-crypto/scripts/project_knowledge/tf_psa_crypto_test_case_info.py`,
we can drop the backward compatibilty hacks and simply
`import tf_psa_crypto_test_case_info` unconditionally and use
`tf_psa_crypto_test_case_info.INTERNAL_TEST_CASES` unconditionally.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-16 19:17:02 +02:00
Gilles Peskine
d934b7b751 Add tf-psa-crypto/scripts/project_knowledge to Python load path
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-16 19:16:30 +02:00
valord577
37b81f13c7 add ChangeLog
Signed-off-by: valord577 <valord577@gmail.com>
2026-04-16 15:17:32 +08:00
valord577
a3d3ede9d6
Fix build warning/error using llvm-mingw
error logs refs: https://github.com/valord577/nativepkgs/actions/runs/24490614774/job/71574726128

Signed-off-by: valord577 <valord577@gmail.com>
2026-04-16 14:31:55 +08:00
Viktor Sokolovskiy
2168fe9cda ssl: narrow TLS 1.2 RSA-PSS handling and add interop coverage
Signed-off-by: Viktor Sokolovskiy <maokaman@gmail.com>
2026-04-16 04:36:48 +03:00
Yi Wu
970df30a8f test: improve symlink checks
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-15 12:13:09 +01:00
Gilles Peskine
8426c9bc51
Merge pull request #10684 from gilles-peskine-arm/maintainer-scripts-create-directory-dev
development: Create a directory for maintainer-only Python scripts
2026-04-15 08:19:36 +00:00
Gilles Peskine
8bf89416cf
Merge pull request #10647 from gilles-peskine-arm/github-pr-template-add-4.1-mbedtls
Add 1.1 line to the PR template
2026-04-15 08:17:24 +00:00
Yi Wu
0c02d74a48 test: versioned symlink order fix
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-14 11:06:16 +01:00
Yi Wu
f38b17e7a0 test: reorder if-else structure
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-14 10:12:44 +01:00
Yi Wu
331ad77fe2 test: add debug output and fix for win config
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-13 15:13:52 +01:00
Yi Wu
6fb557c31a ChangeLog fix
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-13 15:00:44 +01:00
Gilles Peskine
6b31bc6885 Unify TF-PSA-Crypto and mbedtls templates
Following the team discussion, don't suggest "prerequisite" or "consuming"
in the template. Suggest linking all the pull requests in a group
everywhere.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-13 14:57:07 +02:00
Yi Wu
e9e0409b11 tests: fix DESTDIR install checks and add macOS compatibility
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-13 12:48:01 +01:00
Yi Wu
15be9e9048 ChangeLog fixes
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-13 12:12:24 +01:00
Gilles Peskine
2a7d1ece77
Merge pull request #10676 from gilles-peskine-arm/analyze_outcomes-read_crypto
Let TF-PSA-Crypto define test cases that Mbed TLS does not need to cover
2026-04-13 09:24:21 +00:00
Gilles Peskine
cc134b0b94 Update crypto submodule with analyze_outcomes.py
Update framework to match.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-10 14:49:14 +02:00
Yi Wu
f14f28ce75 ChangeLog padding space fix
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-04-10 10:27:09 +01:00
Gilles Peskine
9248af96b1 Create a directory for maintainer-only Python scripts
This directory is currently excluded from `check-python-files.sh`, because
we run it on the CI in an old Python version that doesn't support some of
our new maintainer scripts.

There are no such scripts in mbedtls for now (only in TF-PSA-Crypto), but be
ready if we want to add some.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-09 19:39:42 +02:00
Gilles Peskine
806e1d365b Documentation improvements
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-08 17:22:10 +02:00
Gilles Peskine
d25f03919a INTERNAL_TEST_CASES moved to a separate data-only module
This way, when Mbed TLS's `analyze_outcomes.py` loads the python module from
TF-PSA-Crypto (because it needs to know the value of `INTERNAL_TEST_CASES`),
there's no risk that the subproject and the superproject will have different
requirements on auxiliary modules such as `mbedtls_framework.outcome_analysis`.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-08 15:47:49 +02:00
Gilles Peskine
16a90a556e Add copyright line
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-08 15:31:52 +02:00
Viktor Sokolovskiy
f75c033ead ssl: add TLS 1.2 RSA-PSS regression coverage
Signed-off-by: Viktor Sokolovskiy <maokaman@gmail.com>
2026-04-07 20:20:09 +03:00
Gilles Peskine
667a3f6442 Move test currently covered by crypto from uncovered list to ignored list
If we can't read `INTERNAL_TEST_CASES` from
`tf-psa-crypto/tests/scripts/analyze_outcomes.py` because the script doesn't
exist, hard-code the legacy value of that information.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-07 11:47:24 +02:00
Gilles Peskine
1978e1bd6b Ignore test cases that TF-PSA-Crypto tells us to ignore
If the `tf-psa-crypto` submodule has `tests/scripts/analyze_outcomes.py`,
require it to define a global variable `INTERNAL_TEST_CASES`. Those test
cases will be ignored in Mbed TLS's coverage analysis.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-07 11:47:13 +02:00
Gilles Peskine
bb5cfbbdec Move _has_word_re to the framework
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-07 11:06:39 +02:00
Gilles Peskine
68d6b07287 Rename IGNORED_TESTS to UNCOVERED_TESTS
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-07 11:06:39 +02:00
Gilles Peskine
619f1acd75 Update framework with UNCOVERED_TESTS in outcome analysis
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-07 11:06:39 +02:00
Viktor Sokolovskiy
c064ba0edb ssl: accept TLS 1.2 rsa_pss_rsae signature schemes
Signed-off-by: Viktor Sokolovskiy <maokaman@gmail.com>
2026-04-04 03:57:04 +03:00
minosgalanakis
f7e0f0e22e
Merge pull request #1546 from minosgalanakis/merge-development-restricted
Merge restricted/development into development/restricted
2026-04-02 11:19:02 +01:00
David Horstmann
0333486837
Merge pull request #10670 from gilles-peskine-arm/security-md-mention-compiler-4.x
mbedtls: Mention compiler optimization in the threat model
2026-04-01 15:43:26 +00:00
Gilles Peskine
d1f0ce8493 Be more specific about what compiler options we consider legitimate
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-01 11:08:46 +02:00
Gilles Peskine
54ebb9b42d Mention the new advice about compiler options in the changelog
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-01 11:08:46 +02:00
Gilles Peskine
be18f3f4a5 Add a section about compiler-introduced timing side channels
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-04-01 11:08:46 +02:00
Minos Galanakis
0cfd96499d Updated tf-psa-crypto submodule
Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-03-31 15:36:07 +01:00
Minos Galanakis
6804c92d7d Merge tag 'mbedtls-4.1.0' into mbedtls-4.1.0_mergeback
Mbed TLS 4.1.0

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
2026-03-31 15:35:49 +01:00
Yi Wu
3df1f043be tests: remove remaining FFDH code in compat.sh
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-30 16:07:45 +01:00
Valerio Setti
32a3d5209c
Merge pull request #10626 from gilles-peskine-arm/check_committed_generated_files-create
Add check_committed_generated_files.py
2026-03-30 10:50:04 +00:00
Yi Wu
532db3d49e Test: add symlinks and dangling link check
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-26 09:27:41 +00:00
Ben Taylor
5554a33fb2 Add ret return pattern to avoid variable ret was set but never used warning
Signed-off-by: Ben Taylor <ben.taylor@linaro.org>
2026-03-25 15:27:58 +00:00
Valerio Setti
63d1f7f6ef
Merge pull request #10649 from valeriosetti/skip-thread-cmake-search
cmake: make Thread package search quiet
2026-03-23 23:34:05 +00:00
Valerio Setti
92cfa4e70e cmake: make Threads package search quiet
This prevents printing message

"-- Could NOT find Threads (missing: Threads_FOUND)"

on platforms like Zephyr where threading is not provided by standard
libraries.

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-03-23 15:43:46 +01:00
Gilles Peskine
aa40ca90d9 Move check_committed_generated_files to its own component
This will probably help when a framework change causes the content of these
files to change. See https://github.com/Mbed-TLS/mbedtls-test/issues/252

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-23 15:38:32 +01:00
Gilles Peskine
61cf7bdc90 Add Python requirements from framework/util
Any `all.sh` component that runs a script that requires a more recent
version of Python must have a `support_xxx` function that checks for the
requisite Python version or package. At this time, there is no such
requirement yet in the mbedtls repository.

The directory `framework/util` is not yet checked by `pylint` or `mypy`,
because we use older versions of these tools that don't work well with
modern Python versions.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-23 15:38:28 +01:00
Gilles Peskine
260992c0f4 check_committed_generated_files.py: use the new generate_files_helper module
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-23 15:37:45 +01:00
Gilles Peskine
4a21496d6f Prepare to generalize check_option_lists.py
We're going to have more committed generated files.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-23 15:37:45 +01:00
Valerio Setti
a201a74b7d tests: depends.py: extend pkalgs including PSA_WANT_ALG_RSA_PKCS1V15_SIGN
Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-03-19 17:50:26 +01:00
Valerio Setti
63df2f79a4 tests: depends.py: fix reverse dependency for RSA
Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-03-19 17:50:26 +01:00
Valerio Setti
52379636c5 library: check_config: remove RSA encryption requirement from ECDHE-RSA
ECDHE-RSA only requires RSA signature, not encryption. This commits fixes
guards in "mbedtls_check_config.h".

Signed-off-by: Valerio Setti <valerio.setti@nordicsemi.no>
2026-03-19 17:50:26 +01:00
Gilles Peskine
c2139f8887 Add repository shortcut suggestion
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-19 16:39:08 +01:00
Gilles Peskine
10988b0477 Clarify prerequisite, consuming or side PR
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-19 15:29:08 +01:00
Gilles Peskine
72330cac94 Add 4.1 backport line to the PR template
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-19 15:25:14 +01:00
Gilles Peskine
7f4fe3943d
Merge pull request #10624 from gilles-peskine-arm/audit_validity_dates-move-to-framework
Move some scripts to the framework
2026-03-19 12:19:00 +00:00
Yi Wu
a8a1111827 ChangeLog fix
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-13 10:16:30 +00:00
Yi Wu
287d0a8d3c ChangeLog newline fix
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-13 10:11:42 +00:00
Gilles Peskine
931fc8c406 Update massif_max.pl location
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 15:49:21 +01:00
Gilles Peskine
f840cb16e5 Update paths after moving some scripts to the framework
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 10:18:52 +01:00
Gilles Peskine
c4d40c2de3 Move requirements to the framework for scripts in the framework
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 10:18:52 +01:00
Gilles Peskine
702b389645 Update framework with moved scripts
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 10:18:52 +01:00
Gilles Peskine
326fb18585 Move some scripts from mbedtls into the framework
Move a bunch of files from `scripts` and `mbedtls/scripts` to the framework.
Most are not called from any scripts invoked by the CI, but a couple are.
A subsequent commit will adapt the scripts. None of these scripts are
referenced from other repositories except in documentation.

The following files will be removed, and added to `mbedtls-framework`:

* `scripts/ecp_comb_table.py`
* `scripts/massif_max.pl`
* `tests/scripts/audit-validity-dates.py` (moved to `scripts/`)
* `tests/scripts/gen_ctr_drbg.pl` (moved to `scripts/`)
* `tests/scripts/gen_gcm_decrypt.pl` (moved to `scripts/`)
* `tests/scripts/gen_gcm_encrypt.pl` (moved to `scripts/`)
* `tests/scripts/gen_pkcs1_v21_sign_verify.pl` (moved to `scripts/`)
* `tests/scripts/generate-afl-tests.sh` (moved to `scripts/`)
* `tests/scripts/generate_server9_bad_saltlen.py` (moved to `scripts/`)
* `tests/scripts/run-metatests.sh` (moved to `scripts/`)
* `tests/scripts/run_demos.py` (moved to `scripts/`)
* `tests/scripts/test_config_script.py` (moved to `scripts/`)

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 10:18:33 +01:00
Gilles Peskine
23318bde24 Remove PSA status coverage log test
We haven't used this in years. It's obsolete because this functionality
should now be provided by the more general PSA function
wrappers (`PSALoggingWrapper` generator), although that work is unfinished.
It belongs in TF-PSA-Crypto anyway. So remove it, it's one less little
amount of baggage.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
2026-03-12 10:18:33 +01:00
Yi Wu
d9fa082e30 Add changelog
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-10 11:04:06 +00:00
Yi Wu
b6ef9ec78f Support DESTDIR for install and add build-system test
Signed-off-by: Yi Wu <yi.wu2@arm.com>
2026-03-05 17:32:51 +00:00
79 changed files with 2740 additions and 2144 deletions

View File

@ -9,13 +9,14 @@ 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:
- [ ] **development PR** provided # | not required because:
- [ ] **TF-PSA-Crypto PR** provided # | not required because:
- [ ] **changelog** provided | not required because:
- [ ] **framework PR** provided Mbed-TLS/mbedtls-framework# | not required
- [ ] **3.6 PR** provided # | not required because:
- **tests** provided | not required because:
- [ ] **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:
## Notes for the submitter

View File

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

View File

@ -1,5 +1,5 @@
[MASTER]
init-hook='import sys; sys.path.append("scripts"); sys.path.append("framework/scripts")'
init-hook='import sys; sys.path += ["scripts", "framework/scripts", "tf-psa-crypto/scripts/project_knowledge"]'
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-20.04
os: ubuntu-26.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.6>.
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v3.6.7>.
- [`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.0>.
<https://github.com/Mbed-TLS/mbedtls/releases/tag/v4.1.1>.
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.1.0)
set(MBEDTLS_VERSION 4.2.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)
find_package(Threads QUIET)
# 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,5 +1,105 @@
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
@ -143,7 +243,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 TF-PSA-Crypto#175) the
* Following the removal of DHM module (#9972 and Mbed-TLS/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
[security
center](https://developer.trustedfirmware.org/w/mbed-tls/security-center/).
[online
documentation](https://mbed-tls.readthedocs.io/en/latest/project/vulnerabilities/).
Its primary goal is to ensure fixes are ready to be deployed when the issue
goes public.
@ -107,6 +107,12 @@ 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.1.0 API Documentation
* @mainpage Mbed TLS v4.2.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.1.0"
PROJECT_NAME = "Mbed TLS v4.2.0"
OUTPUT_DIRECTORY = ../apidoc/
FULL_PATH_NAMES = NO
OPTIMIZE_OUTPUT_FOR_C = YES

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

View File

@ -27,7 +27,7 @@
* Major, Minor, Patchlevel
*/
#define MBEDTLS_VERSION_MAJOR 4
#define MBEDTLS_VERSION_MINOR 1
#define MBEDTLS_VERSION_MINOR 2
#define MBEDTLS_VERSION_PATCH 0
/**
@ -35,9 +35,9 @@
* MMNNPP00
* Major version | Minor version | Patch version
*/
#define MBEDTLS_VERSION_NUMBER 0x04010000
#define MBEDTLS_VERSION_STRING "4.1.0"
#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 4.1.0"
#define MBEDTLS_VERSION_NUMBER 0x04020000
#define MBEDTLS_VERSION_STRING "4.2.0"
#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 4.2.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__)
#if defined(__MINGW32__) && !defined(__clang__)
#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) \
__attribute__((__format__(gnu_printf, string_index, first_to_check)))
#else /* defined(__MINGW32__) */

View File

@ -31,6 +31,10 @@
* 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
@ -190,6 +194,9 @@ 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,
@ -219,6 +226,9 @@ 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,6 +1324,15 @@ 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.
*/
@ -1572,13 +1581,20 @@ struct mbedtls_ssl_config {
const mbedtls_x509_crt *MBEDTLS_PRIVATE(dn_hints);/*!< acceptable client cert issuers */
#endif
/* Unused field reserved for future use */
union {
size_t number;
void *ptr;
} MBEDTLS_PRIVATE(unused);
mbedtls_ssl_unused_data_t 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 */
@ -1861,11 +1877,7 @@ struct mbedtls_ssl_context {
*/
mbedtls_ssl_user_data_t MBEDTLS_PRIVATE(user_data);
/* Unused field reserved for future use */
union {
size_t number;
void *ptr;
} MBEDTLS_PRIVATE(unused);
mbedtls_ssl_unused_data_t MBEDTLS_PRIVATE(unused);
};
/**
@ -2169,7 +2181,7 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
/**
* \brief Configure the use of the Connection ID (CID)
* extension in the next handshake.
* extension in subsequent handshakes.
*
* Reference: RFC 9146 (or draft-ietf-tls-dtls-connection-id-05
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
@ -2190,7 +2202,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 the next handshake and sets the value of the CID to
* in subsequent handshakes and sets the value of the CID to
* be used for incoming messages.
*
* \param ssl The SSL context to configure. This must be initialized.
@ -2221,11 +2233,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 the next handshake,
* will be successfully negotiated in subsequent handshakes,
* 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 the next
* handshake will include the CID extension, thereby
* this call implies that the `ClientHello` in subsequent
* handshakes 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.
@ -2248,7 +2260,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 the next handshake.
* applies to subsequent handshakes.
* \return A negative error code on failure.
*/
int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
@ -3411,7 +3423,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 \b mbedtls_ssl_conf_sig_algs().
* by this setting but by \c mbedtls_ssl_conf_sig_algs().
*
* \param conf SSL configuration
* \param profile Profile to use
@ -3899,7 +3911,12 @@ 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
* \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().
*
* \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 \"\${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\")
set(_libdir \"\$ENV{DESTDIR}${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_CRYPT) || !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) )
!defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) )
#error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites"
#endif
@ -138,10 +138,19 @@
defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) )
#error "One or more versions of the TLS protocol are enabled " \
"but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx"
#error "TLS 1.2 protocol is enabled but no key exchange method is 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,6 +6,8 @@
* 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,6 +665,18 @@ 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;
@ -766,7 +778,7 @@ void mbedtls_pkcs7_free(mbedtls_pkcs7 *pkcs7)
mbedtls_free(signer_prev);
}
pkcs7->raw.p = NULL;
mbedtls_platform_zeroize(pkcs7, sizeof(*pkcs7));
}
#endif

View File

@ -208,6 +208,10 @@ 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
@ -251,8 +255,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_ecp_group_id_from_tls_id(*group_list) !=
MBEDTLS_ECP_DP_NONE)) {
mbedtls_ssl_get_psa_curve_info_from_tls_id(
*group_list, NULL, NULL) == PSA_SUCCESS) {
propose_group = 1;
}
#endif

View File

@ -29,7 +29,6 @@
#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)
@ -846,21 +845,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 mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
status = psa_hash_setup(&ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256);
if (status != PSA_SUCCESS) {
return mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
#endif
#if defined(PSA_WANT_ALG_SHA_384)
status = psa_hash_abort(&ssl->handshake->fin_sha384_psa);
if (status != PSA_SUCCESS) {
return mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
status = psa_hash_setup(&ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384);
if (status != PSA_SUCCESS) {
return mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
#endif
return 0;
@ -880,13 +879,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 mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(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 mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
#endif
return 0;
@ -896,8 +895,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 mbedtls_md_error_from_psa(psa_hash_update(
&ssl->handshake->fin_sha256_psa, buf, len));
return PSA_TO_MBEDTLS_ERR(psa_hash_update(
&ssl->handshake->fin_sha256_psa, buf, len));
}
#endif
@ -905,8 +904,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 mbedtls_md_error_from_psa(psa_hash_update(
&ssl->handshake->fin_sha384_psa, buf, len));
return PSA_TO_MBEDTLS_ERR(psa_hash_update(
&ssl->handshake->fin_sha384_psa, buf, len));
}
#endif
@ -1309,6 +1308,8 @@ 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;
@ -1358,6 +1359,8 @@ 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 */
@ -1383,6 +1386,10 @@ 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)
@ -3634,6 +3641,12 @@ 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;
@ -3659,11 +3672,16 @@ static int ssl_tls13_session_load(mbedtls_ssl_session *session,
return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
}
if (hostname_len > 0) {
session->hostname = mbedtls_calloc(1, hostname_len);
if (session->hostname == NULL) {
return MBEDTLS_ERR_SSL_ALLOC_FAILED;
/* 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;
}
memcpy(session->hostname, p, hostname_len);
p += hostname_len;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
@ -3701,6 +3719,10 @@ 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;
}
@ -4999,6 +5021,10 @@ 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;
@ -5008,6 +5034,10 @@ 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 */
@ -6293,11 +6323,16 @@ 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);
@ -6564,7 +6599,7 @@ static int ssl_calc_verify_tls_psa(const mbedtls_ssl_context *ssl,
exit:
psa_hash_abort(&cloned_op);
return mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
#if defined(PSA_WANT_ALG_SHA_256)
@ -7257,7 +7292,7 @@ static int ssl_calc_finished_tls_generic(mbedtls_ssl_context *ssl, void *ctx,
exit:
psa_hash_abort(&cloned_op);
return mbedtls_md_error_from_psa(status);
return PSA_TO_MBEDTLS_ERR(status);
}
#if defined(PSA_WANT_ALG_SHA_256)

View File

@ -12,6 +12,7 @@
#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"
@ -1742,32 +1743,77 @@ 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 value in SigAlg extension 0x%04x",
sig_alg));
("Server used unsupported %s signature algorithm",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
/*
* 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.
* 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.
*/
if (!mbedtls_ssl_sig_alg_is_supported(ssl, sig_alg)) {
MBEDTLS_SSL_DEBUG_MSG(1,
("Server used unsupported value in SigAlg extension 0x%04x",
sig_alg));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
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;
}
}
/*
* Check if the signature algorithm is acceptable
*/
if (!mbedtls_ssl_sig_alg_is_offered(ssl, sig_alg)) {
MBEDTLS_SSL_DEBUG_MSG(1, ("Server used SigAlg value 0x%04x that was not offered", 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)));
return MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER;
}
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used SignatureAlgorithm %d", sig_alg & 0x00FF));
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used HashAlgorithm %d", sig_alg >> 8));
MBEDTLS_SSL_DEBUG_MSG(2, ("Server used the signature algorithm %s",
mbedtls_ssl_sig_alg_to_str(sig_alg)));
return 0;
}
@ -1885,6 +1931,8 @@ 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);
@ -2424,11 +2472,16 @@ 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 (header_len + content_len_size + ssl->conf->psk_identity_len
> MBEDTLS_SSL_OUT_CONTENT_LEN) {
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) {
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 void ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen)
static int ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p = buf;
@ -1760,14 +1760,14 @@ static void 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;
return 0;
}
MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, ecjpake kkpp extension"));
if (end - p < 4) {
MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
return;
return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
}
MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
@ -1780,13 +1780,14 @@ static void 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;
return ret;
}
MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
p += 2;
*olen = kkpp_len + 4;
return 0;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
@ -2169,7 +2170,11 @@ static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
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;
}
ext_len += olen;
#endif
@ -3367,8 +3372,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;
uint32_t lifetime;
size_t tlen = 0;
uint32_t lifetime = 0;
MBEDTLS_SSL_DEBUG_MSG(2, ("=> write new session ticket"));
@ -3395,7 +3400,6 @@ 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,14 +404,18 @@ 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) ||
*group_list != selected_group) {
found = 1;
break;
if (mbedtls_ssl_get_psa_curve_info_from_tls_id(
*group_list, NULL, NULL) == PSA_ERROR_NOT_SUPPORTED) {
continue;
}
/* 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)
@ -2012,6 +2016,19 @@ 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));
@ -2800,6 +2817,7 @@ 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,20 +50,55 @@ int mbedtls_ssl_tls13_fetch_handshake_msg(mbedtls_ssl_context *ssl,
unsigned char **buf,
size_t *buf_len)
{
int ret;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int require_record_boundary;
if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
goto cleanup;
/* 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) {
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
goto error;
}
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."));
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
goto cleanup;
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;
}
/*
@ -73,11 +108,15 @@ 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;
cleanup:
error:
if (ret == MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) {
MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
}
return ret;
}
@ -302,11 +341,12 @@ static int ssl_tls13_parse_certificate_verify(mbedtls_ssl_context *ssl,
MBEDTLS_SSL_DEBUG_BUF(3, "verify hash", verify_hash, verify_hash_len);
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;
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;
}
MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify_ext", ret);

View File

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

View File

@ -87,11 +87,13 @@ typedef struct {
* concerns. */
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
/* Hashes from SHA-256 and above. Note that this selection
* should be aligned with ssl_preset_default_hashes in ssl_tls.c. */
/* Hashes from SHA-256 and above. */
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_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),
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
@ -165,12 +167,8 @@ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none =
(uint32_t) -1,
};
/*
* 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)
int mbedtls_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;
@ -183,12 +181,8 @@ static int x509_profile_check_md_alg(const mbedtls_x509_crt_profile *profile,
return -1;
}
/*
* 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)
int mbedtls_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;
@ -512,23 +506,34 @@ static int x509_get_basic_constraints(unsigned char **p,
}
if (*p == end) {
/* Empty basicConstraints: valid, not a CA. */
return 0;
}
if ((ret = mbedtls_asn1_get_bool(p, end, ca_istrue)) != 0) {
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;
}
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);
}
/* `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;
}
@ -2037,11 +2042,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 (x509_profile_check_md_alg(profile, crl_list->sig_md) != 0) {
if (mbedtls_x509_profile_check_md_alg(profile, crl_list->sig_md) != 0) {
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
}
if (x509_profile_check_pk_alg(profile, crl_list->sig_pk) != 0) {
if (mbedtls_x509_profile_check_pk_alg(profile, crl_list->sig_pk) != 0) {
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
}
@ -2550,11 +2555,11 @@ static int x509_crt_verify_chain(
}
/* Check signature algorithm: MD & PK algs */
if (x509_profile_check_md_alg(profile, child->sig_md) != 0) {
if (mbedtls_x509_profile_check_md_alg(profile, child->sig_md) != 0) {
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
}
if (x509_profile_check_pk_alg(profile, child->sig_pk) != 0) {
if (mbedtls_x509_profile_check_pk_alg(profile, child->sig_pk) != 0) {
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
}
@ -3062,7 +3067,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 (x509_profile_check_pk_alg(profile, (mbedtls_pk_sigalg_t) pk_type) != 0) {
if (mbedtls_x509_profile_check_pk_alg(profile, (mbedtls_pk_sigalg_t) pk_type) != 0) {
ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
}

View File

@ -227,25 +227,34 @@ 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, &len,
if ((ret = mbedtls_asn1_get_tag(p, end_attr_data, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET)) != 0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
}
if ((ret = mbedtls_asn1_get_tag(p, end, &len,
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,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) !=
0) {
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
}
if ((ret = x509_csr_parse_extensions(csr, p, *p + len, cb, p_ctx)) != 0) {
return ret;
}
if (*p != end_attr_data) {
const unsigned char *end_exts = *p + len;
if (end_exts != end_set) {
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,6 +15,7 @@
#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
@ -79,4 +80,18 @@ 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,9 +8,6 @@ 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,6 +22,7 @@ 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. */
@ -86,6 +87,7 @@ 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
@ -269,7 +271,8 @@ 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 datgram.\n"
" records within a single datagram.\n" \
" badmac_limit=%%d default: (library default: disabled)\n"
#else
#define USAGE_DTLS ""
#endif
@ -294,7 +297,7 @@ int main(void)
#if defined(MBEDTLS_SSL_RENEGOTIATION)
#define USAGE_RENEGO \
" renegotiation=%%d default: 0 (disabled)\n" \
" renegotiate=%%d default: 0 (disabled)\n" \
" renegotiate=%%d default: 0 (disabled), 1 immediately, 2 after first exchange\n" \
" renego_delay=%%d default: -2 (library default)\n"
#else
#define USAGE_RENEGO ""
@ -491,7 +494,7 @@ struct options {
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
int renegotiation; /* enable / disable renegotiation */
int allow_legacy; /* allow legacy renegotiation */
int renegotiate; /* attempt renegotiation? */
int renegotiate; /* attempt renegotiation? 1: before data, 2: after first exchange */
int renego_delay; /* delay before enforcing renegotiation */
int exchanges; /* number of data exchanges */
int min_version; /* minimum protocol version accepted */
@ -518,6 +521,7 @@ 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 */
@ -959,6 +963,7 @@ 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;
@ -1164,7 +1169,7 @@ usage:
opt.renego_delay = (atoi(q));
} else if (strcmp(p, "renegotiate") == 0) {
opt.renegotiate = atoi(q);
if (opt.renegotiate < 0 || opt.renegotiate > 1) {
if (opt.renegotiate < 0 || opt.renegotiate > 2) {
goto usage;
}
} else if (strcmp(p, "exchanges") == 0) {
@ -1372,6 +1377,11 @@ 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) {
@ -1835,6 +1845,10 @@ 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)
@ -2442,7 +2456,7 @@ usage:
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if (opt.renegotiate) {
if (opt.renegotiate == 1) {
/*
* Perform renegotiation (this must be done when the server is waiting
* for input from our side).
@ -2787,12 +2801,21 @@ 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 &&
@ -2817,6 +2840,44 @@ 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,6 +52,7 @@ 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)
@ -367,9 +368,6 @@ 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" \
@ -378,7 +376,8 @@ 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 datgram.\n"
" records within a single datagram.\n" \
" badmac_limit=%%d default: (library default: disabled)\n"
#else
#define USAGE_DTLS ""
#endif
@ -524,7 +523,6 @@ int main(void)
USAGE_SRTP \
USAGE_COOKIES \
USAGE_ANTI_REPLAY \
USAGE_BADMAC_LIMIT \
"\n"
#define USAGE2 \
" auth_mode=%%s default: (library default: none)\n" \
@ -3274,7 +3272,15 @@ 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,6 +103,12 @@ 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" \
@ -116,6 +122,12 @@ 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" \
@ -148,9 +160,13 @@ 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*/
@ -219,6 +235,16 @@ 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;
@ -271,6 +297,16 @@ 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) {
@ -528,6 +564,35 @@ 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;
@ -559,7 +624,7 @@ static int send_packet(const packet *p, const char *why)
}
/* insert corrupted ApplicationData record? */
if (opt.bad_ad &&
if ((bad_ad_once(p) || opt.bad_ad) &&
strcmp(p->type, "ApplicationData") == 0) {
unsigned char buf[MAX_MSG_SIZE];
memcpy(buf, p->buf, p->len);
@ -664,6 +729,31 @@ 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)
@ -717,6 +807,11 @@ 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) ||
@ -851,6 +946,10 @@ 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,6 +1,7 @@
# 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.
@ -17,12 +18,8 @@ pylint == 2.4.4; platform_system == 'Linux'
# mypy 0.942 is the version in Ubuntu 22.04.
mypy == 0.942; platform_system == 'Linux'
# 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'
# 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

View File

@ -1,237 +0,0 @@
#!/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,3 +15,6 @@ 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

@ -0,0 +1,20 @@
"""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'))

View File

@ -1,36 +0,0 @@
#!/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
scripts/massif_max.pl massif.out.*
framework/scripts/massif_max.pl massif.out.*
mv massif.out.* massif-$NAME.$$
}

View File

@ -19,10 +19,6 @@ 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 \
@ -110,12 +106,6 @@ 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
@ -311,9 +301,3 @@ 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,19 +541,6 @@ 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,12 +16,10 @@
#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>
@ -31,10 +29,6 @@
#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)
@ -106,17 +100,13 @@
#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;
@ -147,6 +137,35 @@ 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 *);
@ -582,68 +601,6 @@ 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.
@ -743,23 +700,6 @@ 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,
@ -806,6 +746,23 @@ 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

@ -0,0 +1,110 @@
/** \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,34 +6,35 @@ 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."""
@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 = {
UNCOVERED_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.
@ -71,12 +72,6 @@ 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
@ -227,6 +222,57 @@ 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

@ -1,469 +0,0 @@
#!/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

@ -0,0 +1,20 @@
#!/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

@ -1,46 +0,0 @@
#!/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,9 +45,21 @@ 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_option_lists.py
tests/scripts/check_committed_generated_files.py
}
component_check_doxy_blocks () {

View File

@ -155,6 +155,60 @@ 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)"
tests/scripts/run-metatests.sh any asan poison
framework/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,15 +493,6 @@ 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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/scripts/run_demos.py
msg "test: selftest (ASan build)" # ~ 10s
programs/test/selftest
msg "test: metatests (GCC, ASan build)"
tests/scripts/run-metatests.sh any asan poison
framework/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)"
tests/scripts/run-metatests.sh any pthread
framework/scripts/run-metatests.sh any pthread
msg "program demos (full config, clang)" # ~10s
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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
tests/scripts/run_demos.py
framework/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)"
tests/scripts/run-metatests.sh any msan
framework/scripts/run-metatests.sh any msan
msg "program demos (MSan)" # ~20s
tests/scripts/run_demos.py
framework/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_CRYPT': ['PSA_WANT_ALG_RSA_PKCS1V15_SIGN',
'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED'],
'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,6 +495,7 @@ 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),

View File

@ -1,96 +0,0 @@
#!/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);

View File

@ -1,101 +0,0 @@
#!/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

@ -1,84 +0,0 @@
#!/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

@ -1,74 +0,0 @@
#!/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

@ -1,71 +0,0 @@
#!/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

@ -1,87 +0,0 @@
#!/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

@ -0,0 +1,118 @@
#!/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

@ -1,130 +0,0 @@
#!/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()

View File

@ -1,89 +0,0 @@
#!/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

View File

@ -1,65 +0,0 @@
#!/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,3 +18,6 @@ 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

@ -1,175 +0,0 @@
#!/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

@ -0,0 +1,190 @@
/*
* 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,6 +9,8 @@
*/
#include <test/ssl_helpers.h>
#include <test/ssl_helpers_internal.h>
#include <test/macros.h>
#include "mbedtls/psa_util.h"
#include <limits.h>
@ -1033,6 +1035,17 @@ 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));
@ -2282,6 +2295,10 @@ 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),
@ -2313,6 +2330,10 @@ 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
@ -2339,6 +2360,11 @@ 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));
@ -2396,6 +2422,10 @@ 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,6 +5269,7 @@ 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"
@ -5285,6 +5286,7 @@ 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"
@ -5302,6 +5304,7 @@ 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"
@ -5320,6 +5323,7 @@ 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"
@ -5337,6 +5341,7 @@ 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
@ -5353,6 +5358,7 @@ 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"
@ -8382,6 +8388,37 @@ 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" \
@ -11769,6 +11806,147 @@ 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" \
@ -13938,7 +14116,6 @@ 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
@ -13954,6 +14131,43 @@ 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,6 +14,14 @@ 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
@ -86,9 +94,17 @@ 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 Pass SHA1 #10
PKCS7 Signed Data Verification Fail 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:0
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 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,8 +25,10 @@ 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 */
@ -71,6 +73,48 @@ 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,6 +471,14 @@ 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
@ -548,13 +556,19 @@ 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
renegotiation:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:-1
DTLS renegotiation: legacy renegotiation
renegotiation:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION
renegotiation:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:-1
DTLS renegotiation: legacy break handshake
renegotiation:MBEDTLS_SSL_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
DTLS serialization with MFL=512
resize_buffers_serialize_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512
@ -3028,6 +3042,22 @@ 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:
@ -3347,6 +3377,9 @@ 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
@ -3361,6 +3394,22 @@ 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
@ -3549,3 +3598,29 @@ 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,6 +5,7 @@
#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.1.0"
check_compiletime_version:"4.2.0"
Check runtime library version
check_runtime_version:"4.1.0"
check_runtime_version:"4.2.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_PUBKEY
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400300000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
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_PUBKEY
x509parse_crt:"308180306ba0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a300806001304546573743015300d06092A864886F70D0101010500030400310000300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
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_PUBKEY
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0302ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
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_PUBKEY
x509parse_crt:"3081873072a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374301c300d06092A864886F70D0101010500030b0030080202ffff0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
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_PUBKEY
x509parse_crt:"308196308180a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210fffffffffffffffffffffffffffffffe0202ffff300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_PK_INVALID_ALG
# 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,9 +2052,25 @@ 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:"3081b030819aa0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a314301230100603551d130101010406300402010102300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
x509parse_crt:"3081b030819aa0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a314301230100603551d13010101040630040101ff02300d06092a864886f70d01010b0500030200ff":"":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
@ -2066,19 +2082,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:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010285300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0285300d06092a864886f70d01010b0500030200ff":"":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:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_OUT_OF_DATA)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0201300d06092a864886f70d01010b0500030200ff":"":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:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050201010200300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_INVALID_LENGTH)
x509parse_crt:"3081b130819ba0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a315301330110603551d13010101040730050101ff0200300d06092a864886f70d01010b0500030200ff":"":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:"3081b430819ea0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a318301630140603551d13010101040a30080201010201010500300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, MBEDTLS_ERR_ASN1_LENGTH_MISMATCH)
x509parse_crt:"3081b430819ea0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D01010105000319003016021100ffffffffffffffffffffffffffffffff020103a100a200a318301630140603551d13010101040a30080101ff0201010500300d06092a864886f70d01010b0500030200ff":"":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
@ -2947,6 +2963,10 @@ 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)
@ -3082,17 +3102,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: invalid len (len < data))
X509 CSR ASN.1 (attributes: extensionRequest SET extends past attribute)
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_LENGTH_MISMATCH)
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)
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: extension request invalid len (len < data))
X509 CSR ASN.1 (attributes: extensionRequest sequence shorter than SET)
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_OUT_OF_DATA)
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)
X509 CSR ASN.1 (extensions: invalid sequence tag)
depends_on:PSA_WANT_ALG_SHA_256:PSA_HAVE_ALG_SOME_RSA_VERIFY

View File

@ -1136,12 +1136,15 @@ void x509parse_crt(data_t *buf, char *result_str, int result)
#else
((void) result_str);
#endif
/* 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;
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.
*/
int result_back_comp = result;
if (result == MBEDTLS_ERR_PK_INVALID_ALG) {
result_back_comp = MBEDTLS_ERR_PK_INVALID_PUBKEY;
}
mbedtls_x509_crt_init(&crt);
USE_PSA_INIT();

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