Merge pull request #7336 from yanrayw/6500-gitignore-fix

fix: ignore *.o under tests/src/test_helpers
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
new file mode 100644
index 0000000..cef07bf
--- /dev/null
+++ b/.readthedocs.yaml
@@ -0,0 +1,26 @@
+# .readthedocs.yaml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+
+# Required
+version: 2
+
+# Set the version of Python and other tools you might need
+build:
+  os: ubuntu-20.04
+  tools:
+    python: "3.9"
+  jobs:
+    pre_build:
+      - make apidoc
+      - breathe-apidoc -o docs/api apidoc/xml
+
+# Build documentation in the docs/ directory with Sphinx
+sphinx:
+  builder: dirhtml
+  configuration: docs/conf.py
+
+# Optionally declare the Python requirements required to build your docs
+python:
+  install:
+  - requirements: docs/requirements.txt
diff --git a/.travis.yml b/.travis.yml
index 3d86681..bf5ccd9 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -79,6 +79,7 @@
         # Logs appear out of sequence on Windows. Give time to catch up.
         - sleep 5
         - scripts/windows_msbuild.bat v141 # Visual Studio 2017
+        - visualc/VS2013/x64/Release/selftest.exe
 
     - name: full configuration on arm64
       os: linux
diff --git a/BRANCHES.md b/BRANCHES.md
index c7a6082..a2ea074 100644
--- a/BRANCHES.md
+++ b/BRANCHES.md
@@ -101,6 +101,6 @@
 - [`development`](https://github.com/Mbed-TLS/mbedtls/)
 - [`mbedtls-2.28`](https://github.com/Mbed-TLS/mbedtls/tree/mbedtls-2.28)
  maintained until at least the end of 2024, see
-  <https://github.com/Mbed-TLS/mbedtls/releases/tag/v2.28.2>.
+  <https://github.com/Mbed-TLS/mbedtls/releases/tag/v2.28.3>.
 
 Users are urged to always use the latest version of a maintained branch.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7bd9189..8d27a82 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -354,7 +354,7 @@
     write_basic_package_version_file(
         "cmake/MbedTLSConfigVersion.cmake"
             COMPATIBILITY SameMajorVersion
-            VERSION 3.3.0)
+            VERSION 3.4.0)
 
     install(
         FILES "${CMAKE_CURRENT_BINARY_DIR}/cmake/MbedTLSConfig.cmake"
diff --git a/ChangeLog b/ChangeLog
index 639c8e9..9b30aff 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,216 @@
 Mbed TLS ChangeLog (Sorted per branch, date)
 
+= Mbed TLS 3.4.0 branch released 2023-03-28
+
+Default behavior changes
+   * The default priority order of TLS 1.3 cipher suites has been modified to
+     follow the same rules as the TLS 1.2 cipher suites (see
+     ssl_ciphersuites.c). The preferred cipher suite is now
+     TLS_CHACHA20_POLY1305_SHA256.
+
+New deprecations
+   * mbedtls_x509write_crt_set_serial() is now being deprecated in favor of
+     mbedtls_x509write_crt_set_serial_raw(). The goal here is to remove any
+     direct dependency of X509 on BIGNUM_C.
+   * PSA to mbedtls error translation is now unified in psa_util.h,
+     deprecating mbedtls_md_error_from_psa. Each file that performs error
+     translation should define its own version of PSA_TO_MBEDTLS_ERR,
+     optionally providing file-specific error pairs. Please see psa_util.h for
+     more details.
+
+Features
+   * Added partial support for parsing the PKCS #7 Cryptographic Message
+     Syntax, as defined in RFC 2315. Currently, support is limited to the
+     following:
+     - Only the signed-data content type, version 1 is supported.
+     - Only DER encoding is supported.
+     - Only a single digest algorithm per message is supported.
+     - Certificates must be in X.509 format. A message must have either 0
+       or 1 certificates.
+     - There is no support for certificate revocation lists.
+     - The authenticated and unauthenticated attribute fields of SignerInfo
+       must be empty.
+     Many thanks to Daniel Axtens, Nayna Jain, and Nick Child from IBM for
+     contributing this feature, and to Demi-Marie Obenour for contributing
+     various improvements, tests and bug fixes.
+   * General performance improvements by accessing multiple bytes at a time.
+     Fixes #1666.
+   * Improvements to use of unaligned and byte-swapped memory, reducing code
+     size and improving performance (depending on compiler and target
+     architecture).
+   * Add support for reading points in compressed format
+     (MBEDTLS_ECP_PF_COMPRESSED) with mbedtls_ecp_point_read_binary()
+     (and callers) for Short Weierstrass curves with prime p where p = 3 mod 4
+     (all mbedtls MBEDTLS_ECP_DP_SECP* and MBEDTLS_ECP_DP_BP* curves
+      except MBEDTLS_ECP_DP_SECP224R1 and MBEDTLS_ECP_DP_SECP224K1)
+   * SHA224_C/SHA384_C are now independent from SHA384_C/SHA512_C respectively.
+     This helps in saving code size when some of the above hashes are not
+     required.
+   * Add parsing of V3 extensions (key usage, Netscape cert-type,
+     Subject Alternative Names) in x509 Certificate Sign Requests.
+   * Use HOSTCC (if it is set) when compiling C code during generation of the
+     configuration-independent files. This allows them to be generated when
+     CC is set for cross compilation.
+   * Add parsing of uniformResourceIdentifier subtype for subjectAltName
+     extension in x509 certificates.
+   * Add an interruptible version of sign and verify hash to the PSA interface,
+     backed by internal library support for ECDSA signing and verification.
+   * Add parsing of rfc822Name subtype for subjectAltName
+     extension in x509 certificates.
+   * The configuration macros MBEDTLS_PSA_CRYPTO_PLATFORM_FILE and
+     MBEDTLS_PSA_CRYPTO_STRUCT_FILE specify alternative locations for
+     the headers "psa/crypto_platform.h" and "psa/crypto_struct.h".
+   * When a PSA driver for ECDSA is present, it is now possible to disable
+     MBEDTLS_ECDSA_C in the build in order to save code size. For PK, X.509
+     and TLS to fully work, this requires MBEDTLS_USE_PSA_CRYPTO to be enabled.
+     Restartable/interruptible ECDSA operations in PK, X.509 and TLS are not
+     supported in those builds yet, as driver support for interruptible ECDSA
+     operations is not present yet.
+   * Add a driver dispatch layer for EC J-PAKE, enabling alternative
+     implementations of EC J-PAKE through the driver entry points.
+   * Add new API mbedtls_ssl_cache_remove for cache entry removal by
+     its session id.
+   * Add support to include the SubjectAltName extension to a CSR.
+   * Add support for AES with the Armv8-A Cryptographic Extension on
+     64-bit Arm. A new configuration option, MBEDTLS_AESCE_C, can
+     be used to enable this feature. Run-time detection is supported
+     under Linux only.
+   * When a PSA driver for EC J-PAKE is present, it is now possible to disable
+     MBEDTLS_ECJPAKE_C in the build in order to save code size. For the
+     corresponding TLS 1.2 key exchange to work, MBEDTLS_USE_PSA_CRYPTO needs
+     to be enabled.
+   * Add functions mbedtls_rsa_get_padding_mode() and mbedtls_rsa_get_md_alg()
+     to read non-public fields for padding mode and hash id from
+     an mbedtls_rsa_context, as requested in #6917.
+   * AES-NI is now supported with Visual Studio.
+   * AES-NI is now supported in 32-bit builds, or when MBEDTLS_HAVE_ASM
+     is disabled, when compiling with GCC or Clang or a compatible compiler
+     for a target CPU that supports the requisite instructions (for example
+     gcc -m32 -msse2 -maes -mpclmul). (Generic x86 builds with GCC-like
+     compilers still require MBEDTLS_HAVE_ASM and a 64-bit target.)
+   * It is now possible to use a PSA-held (opaque) password with the TLS 1.2
+     ECJPAKE key exchange, using the new API function
+     mbedtls_ssl_set_hs_ecjpake_password_opaque().
+
+Security
+   * Use platform-provided secure zeroization function where possible, such as
+     explicit_bzero().
+   * Zeroize SSL cache entries when they are freed.
+   * Fix a potential heap buffer overread in TLS 1.3 client-side when
+     MBEDTLS_DEBUG_C is enabled. This may result in an application crash.
+   * Add support for AES with the Armv8-A Cryptographic Extension on 64-bit
+     Arm, so that these systems are no longer vulnerable to timing side-channel
+     attacks. This is configured by MBEDTLS_AESCE_C, which is on by default.
+     Reported by Demi Marie Obenour.
+   * MBEDTLS_AESNI_C, which is enabled by default, was silently ignored on
+     builds that couldn't compile the GCC-style assembly implementation
+     (most notably builds with Visual Studio), leaving them vulnerable to
+     timing side-channel attacks. There is now an intrinsics-based AES-NI
+     implementation as a fallback for when the assembly one cannot be used.
+
+Bugfix
+   * Fix possible integer overflow in mbedtls_timing_hardclock(), which
+     could cause a crash in programs/test/benchmark.
+   * Fix IAR compiler warnings. Fixes #6924.
+   * Fix a bug in the build where directory names containing spaces were
+     causing generate_errors.pl to error out resulting in a build failure.
+     Fixes issue #6879.
+   * In TLS 1.3, when using a ticket for session resumption, tweak its age
+     calculation on the client side. It prevents a server with more accurate
+     ticket timestamps (typically timestamps in milliseconds) compared to the
+     Mbed TLS ticket timestamps (in seconds) to compute a ticket age smaller
+     than the age computed and transmitted by the client and thus potentially
+     reject the ticket. Fix #6623.
+   * Fix compile error where MBEDTLS_RSA_C and MBEDTLS_X509_CRT_WRITE_C are
+     defined, but MBEDTLS_PK_RSA_ALT_SUPPORT is not defined. Fixes #3174.
+   * List PSA_WANT_ALG_CCM_STAR_NO_TAG in psa/crypto_config.h so that it can
+     be toggled with config.py.
+   * The key derivation algorithm PSA_ALG_TLS12_ECJPAKE_TO_PMS cannot be
+     used on a shared secret from a key agreement since its input must be
+     an ECC public key. Reject this properly.
+   * mbedtls_x509write_crt_set_serial() now explicitly rejects serial numbers
+     whose binary representation is longer than 20 bytes. This was already
+     forbidden by the standard (RFC5280 - section 4.1.2.2) and now it's being
+     enforced also at code level.
+   * Fix potential undefined behavior in mbedtls_mpi_sub_abs().  Reported by
+     Pascal Cuoq using TrustInSoft Analyzer in #6701; observed independently by
+     Aaron Ucko under Valgrind.
+   * Fix behavior of certain sample programs which could, when run with no
+     arguments, access uninitialized memory in some cases. Fixes #6700 (which
+     was found by TrustInSoft Analyzer during REDOCS'22) and #1120.
+   * Fix parsing of X.509 SubjectAlternativeName extension. Previously,
+     malformed alternative name components were not caught during initial
+     certificate parsing, but only on subsequent calls to
+     mbedtls_x509_parse_subject_alt_name(). Fixes #2838.
+   * Make the fields of mbedtls_pk_rsassa_pss_options public. This makes it
+     possible to verify RSA PSS signatures with the pk module, which was
+     inadvertently broken since Mbed TLS 3.0.
+   * Fix bug in conversion from OID to string in
+     mbedtls_oid_get_numeric_string(). OIDs such as 2.40.0.25 are now printed
+     correctly.
+   * Reject OIDs with overlong-encoded subidentifiers when converting
+     them to a string.
+   * Reject OIDs with subidentifier values exceeding UINT_MAX.  Such
+     subidentifiers can be valid, but Mbed TLS cannot currently handle them.
+   * Reject OIDs that have unterminated subidentifiers, or (equivalently)
+     have the most-significant bit set in their last byte.
+   * Silence warnings from clang -Wdocumentation about empty \retval
+     descriptions, which started appearing with Clang 15. Fixes #6960.
+   * Fix the handling of renegotiation attempts in TLS 1.3. They are now
+     systematically rejected.
+   * Fix an unused-variable warning in TLS 1.3-only builds if
+     MBEDTLS_SSL_RENEGOTIATION was enabled. Fixes #6200.
+   * Fix undefined behavior in mbedtls_ssl_read() and mbedtls_ssl_write() if
+     len argument is 0 and buffer is NULL.
+   * Allow setting user and peer identifiers for EC J-PAKE operation
+     instead of role in PAKE PSA Crypto API as described in the specification.
+     This is a partial fix that allows only "client" and "server" identifiers.
+   * Fix a compilation error when PSA Crypto is built with support for
+     TLS12_PRF but not TLS12_PSK_TO_MS. Reported by joerchan in #7125.
+   * In the TLS 1.3 server, select the preferred client cipher suite, not the
+     least preferred. The selection error was introduced in Mbed TLS 3.3.0.
+   * Fix TLS 1.3 session resumption when the established pre-shared key is
+     384 bits long. That is the length of pre-shared keys created under a
+     session where the cipher suite is TLS_AES_256_GCM_SHA384.
+   * Fix an issue when compiling with MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
+     enabled, which required specifying compiler flags enabling SHA3 Crypto
+     Extensions, where some compilers would emit EOR3 instructions in other
+     modules, which would then fail if run on a CPU without the SHA3
+     extensions. Fixes #5758.
+
+Changes
+   * Install the .cmake files into CMAKE_INSTALL_LIBDIR/cmake/MbedTLS,
+     typically /usr/lib/cmake/MbedTLS.
+   * Mixed-endian systems are explicitly not supported any more.
+   * When MBEDTLS_USE_PSA_CRYPTO and MBEDTLS_ECDSA_DETERMINISTIC are both
+     defined, mbedtls_pk_sign() now use deterministic ECDSA for ECDSA
+     signatures. This aligns the behaviour with MBEDTLS_USE_PSA_CRYPTO to
+     the behaviour without it, where deterministic ECDSA was already used.
+   * Visual Studio: Rename the directory containing Visual Studio files from
+     visualc/VS2010 to visualc/VS2013 as we do not support building with versions
+     older than 2013. Update the solution file to specify VS2013 as a minimum.
+   * programs/x509/cert_write:
+     - now it accepts the serial number in 2 different formats: decimal and
+       hex. They cannot be used simultaneously
+     - "serial" is used for the decimal format and it's limted in size to
+       unsigned long long int
+     - "serial_hex" is used for the hex format; max length here is
+       MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN*2
+   * The C code follows a new coding style. This is transparent for users but
+     affects contributors and maintainers of local patches. For more
+     information, see
+     https://mbed-tls.readthedocs.io/en/latest/kb/how-to/rewrite-branch-for-coding-style/
+   * Changed the default MBEDTLS_ECP_WINDOW_SIZE from 6 to 2.
+     As tested in issue 6790, the correlation between this define and
+     RSA decryption performance has changed lately due to security fixes.
+     To fix the performance degradation when using default values the
+     window was reduced from 6 to 2, a value that gives the best or close
+     to best results when tested on Cortex-M4 and Intel i7.
+   * When enabling MBEDTLS_SHA256_USE_A64_CRYPTO_* or
+     MBEDTLS_SHA512_USE_A64_CRYPTO_*, it is no longer necessary to specify
+     compiler target flags on the command line; the library now sets target
+     options within the appropriate modules.
+
 = Mbed TLS 3.3.0 branch released 2022-12-14
 
 Default behavior changes
diff --git a/ChangeLog.d/add-cache-remove-api.txt b/ChangeLog.d/add-cache-remove-api.txt
deleted file mode 100644
index 950ff97..0000000
--- a/ChangeLog.d/add-cache-remove-api.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Features
-   * Add new API mbedtls_ssl_cache_remove for cache entry removal by
-     its session id.
-Security
-   * Zeroize SSL cache entries when they are freed.
diff --git a/ChangeLog.d/add-uri-san.txt b/ChangeLog.d/add-uri-san.txt
deleted file mode 100644
index 5184e8f..0000000
--- a/ChangeLog.d/add-uri-san.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Features
-   * Add parsing of uniformResourceIdentifier subtype for subjectAltName
-     extension in x509 certificates.
diff --git a/ChangeLog.d/add_interruptible_sign_hash b/ChangeLog.d/add_interruptible_sign_hash
deleted file mode 100644
index 3d93303..0000000
--- a/ChangeLog.d/add_interruptible_sign_hash
+++ /dev/null
@@ -1,5 +0,0 @@
-Features
-   * Add an interruptible version of sign and verify hash to the PSA interface,
-     backed by internal library support for ECDSA signing and verification.
-
-
diff --git a/ChangeLog.d/alignment-perf.txt b/ChangeLog.d/alignment-perf.txt
deleted file mode 100644
index 7a8e6fb..0000000
--- a/ChangeLog.d/alignment-perf.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Features
-   * General performance improvements by accessing multiple bytes at a time.
-     Fixes #1666.
-   * Improvements to use of unaligned and byte-swapped memory, reducing code
-     size and improving performance (depending on compiler and target
-     architecture).
-Changes
-   * Mixed-endian systems are explicitly not supported any more.
diff --git a/ChangeLog.d/armv8-aes.txt b/ChangeLog.d/armv8-aes.txt
deleted file mode 100644
index 8a95d28..0000000
--- a/ChangeLog.d/armv8-aes.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Features
-   * Add support for the Armv8-A Cryptographic Extension in AES on
-     64-bit Arm. A new configuration option, MBEDTLS_AESCE_C, can
-     be used to enable this feature. Run-time detection is supported
-     under Linux only.
diff --git a/ChangeLog.d/c-build-helper-hostcc.txt b/ChangeLog.d/c-build-helper-hostcc.txt
deleted file mode 100644
index 86182c3..0000000
--- a/ChangeLog.d/c-build-helper-hostcc.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Features
-   * Use HOSTCC (if it is set) when compiling C code during generation of the
-     configuration-independent files. This allows them to be generated when
-     CC is set for cross compilation.
diff --git a/ChangeLog.d/changelog-6567-psa_key_derivation_abort-no-other_secret.txt b/ChangeLog.d/changelog-6567-psa_key_derivation_abort-no-other_secret.txt
deleted file mode 100644
index 8fcc18b..0000000
--- a/ChangeLog.d/changelog-6567-psa_key_derivation_abort-no-other_secret.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Fix a compilation error when PSA Crypto is built with support for
-     TLS12_PRF but not TLS12_PSK_TO_MS. Reported by joerchan in #7125.
diff --git a/ChangeLog.d/cmake-install.txt b/ChangeLog.d/cmake-install.txt
deleted file mode 100644
index d8eb72e..0000000
--- a/ChangeLog.d/cmake-install.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Changes
-  * Install the .cmake files into CMAKE_INSTALL_LIBDIR/cmake/MbedTLS,
-    typically /usr/lib/cmake/MbedTLS.
diff --git a/ChangeLog.d/coding-style.txt b/ChangeLog.d/coding-style.txt
deleted file mode 100644
index b2cff5c..0000000
--- a/ChangeLog.d/coding-style.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Changes
-   * The C code follows a new coding style. This is transparent for users but
-     affects contributors and maintainers of local patches. For more
-     information, see
-     https://mbed-tls.readthedocs.io/en/latest/kb/how-to/rewrite-branch-for-coding-style/
diff --git a/ChangeLog.d/conditionalize-mbedtls_mpi_sub_abs-memcpy.txt b/ChangeLog.d/conditionalize-mbedtls_mpi_sub_abs-memcpy.txt
deleted file mode 100644
index 0a90721..0000000
--- a/ChangeLog.d/conditionalize-mbedtls_mpi_sub_abs-memcpy.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * Fix potential undefined behavior in mbedtls_mpi_sub_abs().  Reported by
-     Pascal Cuoq using TrustInSoft Analyzer in #6701; observed independently by
-     Aaron Ucko under Valgrind.
diff --git a/ChangeLog.d/crypto_config_ccm_star.txt b/ChangeLog.d/crypto_config_ccm_star.txt
deleted file mode 100644
index 947014a..0000000
--- a/ChangeLog.d/crypto_config_ccm_star.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * List PSA_WANT_ALG_CCM_STAR_NO_TAG in psa/crypto_config.h so that it can
-     be toggled with config.py.
diff --git a/ChangeLog.d/csr_v3_extensions.txt b/ChangeLog.d/csr_v3_extensions.txt
deleted file mode 100644
index 9274017..0000000
--- a/ChangeLog.d/csr_v3_extensions.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Features
-   * Add parsing of V3 extensions (key usage, Netscape cert-type,
-     Subject Alternative Names) in x509 Certificate Sign Requests.
diff --git a/ChangeLog.d/driver-only-ecdsa.txt b/ChangeLog.d/driver-only-ecdsa.txt
deleted file mode 100644
index 645a723..0000000
--- a/ChangeLog.d/driver-only-ecdsa.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Features
-   * When a PSA driver for ECDSA is present, it is now possible to disable
-     MBEDTLS_ECDSA_C in the build in order to save code size. For PK, X.509
-     and TLS to fully work, this requires MBEDTLS_USE_PSA_CRYPTO to be enabled.
-     Restartable/interruptible ECDSA operations in PK, X.509 and TLS are not
-     supported in those builds yet, as driver support for interruptible ECDSA
-     operations is not present yet.
diff --git a/ChangeLog.d/driver-only-ecjpake.txt b/ChangeLog.d/driver-only-ecjpake.txt
deleted file mode 100644
index 706f304..0000000
--- a/ChangeLog.d/driver-only-ecjpake.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Features
-   * When a PSA driver for EC J-PAKE is present, it is now possible to disable
-     MBEDTLS_ECJPAKE_C in the build in order to save code size. For the
-     corresponding TLS 1.2 key exchange to work, MBEDTLS_USE_PSA_CRYPTO needs
-     to be enabled.
diff --git a/ChangeLog.d/driver-only-hashes.txt b/ChangeLog.d/driver-only-hashes.txt
new file mode 100644
index 0000000..4967bb1
--- /dev/null
+++ b/ChangeLog.d/driver-only-hashes.txt
@@ -0,0 +1,10 @@
+Features
+   * All modules that use hashes or HMAC can now take advantage of PSA Crypto
+     drivers when MBEDTLS_PSA_CRYPTO_C is enabled and psa_crypto_init() has
+     been called. Previously (in 3.3), this was restricted to a few modules,
+     and only in builds where MBEDTLS_MD_C was disabled; in particular the
+     entropy module was not covered which meant an external RNG had to be
+     provided - these limitations are lifted in this version. A new set of
+     feature macros, MBEDTLS_MD_CAN_xxx, has been introduced that can be used
+     to check for availability of hash algorithms, regardless of whether
+     they're provided by a built-in implementation, a driver or both.
diff --git a/ChangeLog.d/ec_jpake_driver_dispatch.txt b/ChangeLog.d/ec_jpake_driver_dispatch.txt
deleted file mode 100644
index 3439296..0000000
--- a/ChangeLog.d/ec_jpake_driver_dispatch.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Features
-   * Add a driver dispatch layer for EC J-PAKE, enabling alternative
-     implementations of EC J-PAKE through the driver entry points.
diff --git a/ChangeLog.d/empty-retval-description.txt b/ChangeLog.d/empty-retval-description.txt
deleted file mode 100644
index 491adf5..0000000
--- a/ChangeLog.d/empty-retval-description.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Silence warnings from clang -Wdocumentation about empty \retval
-     descriptions, which started appearing with Clang 15. Fixes #6960.
diff --git a/ChangeLog.d/fix-example-programs-no-args.txt b/ChangeLog.d/fix-example-programs-no-args.txt
deleted file mode 100644
index 57fe37a..0000000
--- a/ChangeLog.d/fix-example-programs-no-args.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * Fix behavior of certain sample programs which could, when run with no
-     arguments, access uninitialized memory in some cases. Fixes #6700 (which
-     was found by TrustInSoft Analyzer during REDOCS'22) and #1120.
diff --git a/ChangeLog.d/fix-gettimeofday-overflow.txt b/ChangeLog.d/fix-gettimeofday-overflow.txt
deleted file mode 100644
index b7e10d2..0000000
--- a/ChangeLog.d/fix-gettimeofday-overflow.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Fix possible integer overflow in mbedtls_timing_hardclock(), which
-     could cause a crash in programs/test/benchmark.
diff --git a/ChangeLog.d/fix-iar-warnings.txt b/ChangeLog.d/fix-iar-warnings.txt
deleted file mode 100644
index 8a30132..0000000
--- a/ChangeLog.d/fix-iar-warnings.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Bugfix
-   * Fix IAR compiler warnings. Fixes #6924.
diff --git a/ChangeLog.d/fix-jpake-user-peer.txt b/ChangeLog.d/fix-jpake-user-peer.txt
deleted file mode 100644
index e027fc3..0000000
--- a/ChangeLog.d/fix-jpake-user-peer.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * Allow setting user and peer identifiers for EC J-PAKE operation
-     instead of role in PAKE PSA Crypto API as described in the specification.
-     This is a partial fix that allows only "client" and "server" identifiers.
diff --git a/ChangeLog.d/fix-oid-to-string-bugs.txt b/ChangeLog.d/fix-oid-to-string-bugs.txt
deleted file mode 100644
index 3cf02c3..0000000
--- a/ChangeLog.d/fix-oid-to-string-bugs.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Bugfix
-   * Fix bug in conversion from OID to string in
-     mbedtls_oid_get_numeric_string(). OIDs such as 2.40.0.25 are now printed
-     correctly.
-   * Reject OIDs with overlong-encoded subidentifiers when converting
-     them to a string.
-   * Reject OIDs with subidentifier values exceeding UINT_MAX.  Such
-     subidentifiers can be valid, but Mbed TLS cannot currently handle them.
-   * Reject OIDs that have unterminated subidentifiers, or (equivalently)
-     have the most-significant bit set in their last byte.
diff --git a/ChangeLog.d/fix-rsaalt-test-guards.txt b/ChangeLog.d/fix-rsaalt-test-guards.txt
deleted file mode 100644
index f4f39c9..0000000
--- a/ChangeLog.d/fix-rsaalt-test-guards.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Fix compile error where MBEDTLS_RSA_C and MBEDTLS_X509_CRT_WRITE_C are
-     defined, but MBEDTLS_PK_RSA_ALT_SUPPORT is not defined. Fixes #3174.
diff --git a/ChangeLog.d/fix_build_for_directory_names_containing_spaces.txt b/ChangeLog.d/fix_build_for_directory_names_containing_spaces.txt
deleted file mode 100644
index e7643b7..0000000
--- a/ChangeLog.d/fix_build_for_directory_names_containing_spaces.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * Fix a bug in the build where directory names containing spaces were
-     causing generate_errors.pl to error out resulting in a build failure.
-     Fixes issue #6879.
diff --git a/ChangeLog.d/improve_x509_cert_writing_serial_number_management.txt b/ChangeLog.d/improve_x509_cert_writing_serial_number_management.txt
deleted file mode 100644
index 1764c2f..0000000
--- a/ChangeLog.d/improve_x509_cert_writing_serial_number_management.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-Bugfix
-   * mbedtls_x509write_crt_set_serial() now explicitly rejects serial numbers
-     whose binary representation is longer than 20 bytes. This was already
-     forbidden by the standard (RFC5280 - section 4.1.2.2) and now it's being
-     enforced also at code level.
-
-New deprecations
-   * mbedtls_x509write_crt_set_serial() is now being deprecated in favor of
-     mbedtls_x509write_crt_set_serial_raw(). The goal here is to remove any
-     direct dependency of X509 on BIGNUM_C.
-
-Changes
-   * programs/x509/cert_write:
-     - now it accepts the serial number in 2 different formats: decimal and
-       hex. They cannot be used simultaneously
-     - "serial" is used for the decimal format and it's limted in size to
-       unsigned long long int
-     - "serial_hex" is used for the hex format; max length here is
-       MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN*2
diff --git a/ChangeLog.d/make_sha224_sha384_independent_from_sha256_sha512.txt b/ChangeLog.d/make_sha224_sha384_independent_from_sha256_sha512.txt
deleted file mode 100644
index d2c9b35..0000000
--- a/ChangeLog.d/make_sha224_sha384_independent_from_sha256_sha512.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Features
-   * SHA224_C/SHA384_C are now independent from SHA384_C/SHA512_C respectively.
-     This helps in saving code size when some of the above hashes are not
-     required.
diff --git a/ChangeLog.d/mbedtls_ecp_point_read_binary-compressed-fmt.txt b/ChangeLog.d/mbedtls_ecp_point_read_binary-compressed-fmt.txt
deleted file mode 100644
index 44253dd..0000000
--- a/ChangeLog.d/mbedtls_ecp_point_read_binary-compressed-fmt.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Features
-   * Add support for reading points in compressed format
-     (MBEDTLS_ECP_PF_COMPRESSED) with mbedtls_ecp_point_read_binary()
-     (and callers) for Short Weierstrass curves with prime p where p = 3 mod 4
-     (all mbedtls MBEDTLS_ECP_DP_SECP* and MBEDTLS_ECP_DP_BP* curves
-      except MBEDTLS_ECP_DP_SECP224R1 and MBEDTLS_ECP_DP_SECP224K1)
diff --git a/ChangeLog.d/mbedtls_ssl_read_undefined_behavior.txt b/ChangeLog.d/mbedtls_ssl_read_undefined_behavior.txt
deleted file mode 100644
index 1f2c563..0000000
--- a/ChangeLog.d/mbedtls_ssl_read_undefined_behavior.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Bugfix
-   * Fix undefined behavior in mbedtls_ssl_read() and mbedtls_ssl_write() if
-     len argument is 0 and buffer is NULL.
diff --git a/ChangeLog.d/mpi-window-perf b/ChangeLog.d/mpi-window-perf
deleted file mode 100644
index 0f75d6a..0000000
--- a/ChangeLog.d/mpi-window-perf
+++ /dev/null
@@ -1,7 +0,0 @@
-Changes
-   * Changed the default MBEDTLS_ECP_WINDOW_SIZE from 6 to 2.
-     As tested in issue 6790, the correlation between this define and
-     RSA decryption performance has changed lately due to security fixes.
-     To fix the performance degradation when using default values the
-     window was reduced from 6 to 2, a value that gives the best or close
-     to best results when tested on Cortex-M4 and Intel i7.
diff --git a/ChangeLog.d/pk-sign-restartable.txt b/ChangeLog.d/pk-sign-restartable.txt
deleted file mode 100644
index 35da2be..0000000
--- a/ChangeLog.d/pk-sign-restartable.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Changes
-   * When MBEDTLS_USE_PSA_CRYPTO and MBEDTLS_ECDSA_DETERMINISTIC are both
-     defined, mbedtls_pk_sign() now use deterministic ECDSA for ECDSA
-     signatures. This aligns the behaviour with MBEDTLS_USE_PSA_CRYPTO to
-     the behaviour without it, where deterministic ECDSA was already used.
diff --git a/ChangeLog.d/pk_ext-pss_options-public.txt b/ChangeLog.d/pk_ext-pss_options-public.txt
deleted file mode 100644
index b11fa30..0000000
--- a/ChangeLog.d/pk_ext-pss_options-public.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * Make the fields of mbedtls_pk_rsassa_pss_options public. This makes it
-     possible to verify RSA PSS signatures with the pk module, which was
-     inadvertently broken since Mbed TLS 3.0.
diff --git a/ChangeLog.d/pkcs7-parser.txt b/ChangeLog.d/pkcs7-parser.txt
deleted file mode 100644
index b60d187..0000000
--- a/ChangeLog.d/pkcs7-parser.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Features
-   * Added partial support for parsing the PKCS #7 Cryptographic Message
-     Syntax, as defined in RFC 2315. Currently, support is limited to the
-     following:
-     - Only the signed-data content type, version 1 is supported.
-     - Only DER encoding is supported.
-     - Only a single digest algorithm per message is supported.
-     - Certificates must be in X.509 format. A message must have either 0
-       or 1 certificates.
-     - There is no support for certificate revocation lists.
-     - The authenticated and unauthenticated attribute fields of SignerInfo
-       must be empty.
-     Many thanks to Daniel Axtens, Nayna Jain, and Nick Child from IBM for
-     contributing this feature, and to Demi-Marie Obenour for contributing
-     various improvements, tests and bug fixes.
diff --git a/ChangeLog.d/platform-zeroization.txt b/ChangeLog.d/platform-zeroization.txt
deleted file mode 100644
index f17fbbb..0000000
--- a/ChangeLog.d/platform-zeroization.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Security
-  * Use platform-provided secure zeroization function where possible, such as
-    explicit_bzero().
diff --git a/ChangeLog.d/psa-alt-headers.txt b/ChangeLog.d/psa-alt-headers.txt
deleted file mode 100644
index 9555629..0000000
--- a/ChangeLog.d/psa-alt-headers.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Features
-   * The configuration macros MBEDTLS_PSA_CRYPTO_PLATFORM_FILE and
-     MBEDTLS_PSA_CRYPTO_STRUCT_FILE specify alternative locations for
-     the headers "psa/crypto_platform.h" and "psa/crypto_struct.h".
diff --git a/ChangeLog.d/psa_alg_tls12_ecjpake_to_pms-reject_ka.txt b/ChangeLog.d/psa_alg_tls12_ecjpake_to_pms-reject_ka.txt
deleted file mode 100644
index cfea661..0000000
--- a/ChangeLog.d/psa_alg_tls12_ecjpake_to_pms-reject_ka.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Bugfix
-   * The key derivation algorithm PSA_ALG_TLS12_ECJPAKE_TO_PMS cannot be
-     used on a shared secret from a key agreement since its input must be
-     an ECC public key. Reject this properly.
diff --git a/ChangeLog.d/rsa-padding-accessor.txt b/ChangeLog.d/rsa-padding-accessor.txt
deleted file mode 100644
index ad14686..0000000
--- a/ChangeLog.d/rsa-padding-accessor.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Features
-   * Add functions mbedtls_rsa_get_padding_mode() and mbedtls_rsa_get_md_alg()
-     to read non-public fields for padding mode and hash id from
-     an mbedtls_rsa_context, as requested in #6917.
diff --git a/ChangeLog.d/san_csr.txt b/ChangeLog.d/san_csr.txt
deleted file mode 100644
index b5c6cf3..0000000
--- a/ChangeLog.d/san_csr.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Features
-   * Add support to include the SubjectAltName extension to a CSR.
diff --git a/ChangeLog.d/san_rfc822Name.txt b/ChangeLog.d/san_rfc822Name.txt
deleted file mode 100644
index 9720e52..0000000
--- a/ChangeLog.d/san_rfc822Name.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Features
-   * Add parsing of rfc822Name subtype for subjectAltName
-     extension in x509 certificates.
diff --git a/ChangeLog.d/tls13-only-renegotiation.txt b/ChangeLog.d/tls13-only-renegotiation.txt
deleted file mode 100644
index f463de1..0000000
--- a/ChangeLog.d/tls13-only-renegotiation.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Bugfix
-   * Fix the handling of renegotiation attempts in TLS 1.3. They are now
-     systematically rejected.
-   * Fix an unused-variable warning in TLS 1.3-only builds if
-     MBEDTLS_SSL_RENEGOTIATION was enabled. Fixes #6200.
diff --git a/ChangeLog.d/vs2013.txt b/ChangeLog.d/vs2013.txt
deleted file mode 100644
index 6fe7a5e..0000000
--- a/ChangeLog.d/vs2013.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Changes
-  * Visual Studio: Rename the directory containing Visual Studio files from
-    visualc/VS2010 to visualc/VS2013 as we do not support building with versions
-    older than 2013. Update the solution file to specify VS2013 as a minimum.
diff --git a/ChangeLog.d/workaround_gnutls_anti_replay_fail.txt b/ChangeLog.d/workaround_gnutls_anti_replay_fail.txt
deleted file mode 100644
index cebc2b7..0000000
--- a/ChangeLog.d/workaround_gnutls_anti_replay_fail.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Bugfix
-    * In TLS 1.3, when using a ticket for session resumption, tweak its age
-      calculation on the client side. It prevents a server with more accurate
-      ticket timestamps (typically timestamps in milliseconds) compared to the
-      Mbed TLS ticket timestamps (in seconds) to compute a ticket age smaller
-      than the age computed and transmitted by the client and thus potentially
-      reject the ticket. Fix #6623.
diff --git a/ChangeLog.d/x509-subaltname-ext b/ChangeLog.d/x509-subaltname-ext
deleted file mode 100644
index 7845f18..0000000
--- a/ChangeLog.d/x509-subaltname-ext
+++ /dev/null
@@ -1,5 +0,0 @@
-Bugfix
-   * Fix parsing of X.509 SubjectAlternativeName extension. Previously,
-     malformed alternative name components were not caught during initial
-     certificate parsing, but only on subsequent calls to
-     mbedtls_x509_parse_subject_alt_name(). Fixes #2838.
diff --git a/SECURITY.md b/SECURITY.md
index 33bbc2f..61e3936 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -18,3 +18,120 @@
 Only the maintained branches, as listed in [`BRANCHES.md`](BRANCHES.md),
 get security fixes.
 Users are urged to always use the latest version of a maintained branch.
+
+## Threat model
+
+We classify attacks based on the capabilities of the attacker.
+
+### Remote attacks
+
+In this section, we consider an attacker who can observe and modify data sent
+over the network. This includes observing the content and timing of individual
+packets, as well as suppressing or delaying legitimate messages, and injecting
+messages.
+
+Mbed TLS aims to fully protect against remote attacks and to enable the user
+application in providing full protection against remote attacks. Said
+protection is limited to providing security guarantees offered by the protocol
+being implemented. (For example Mbed TLS alone won't guarantee that the
+messages will arrive without delay, as the TLS protocol doesn't guarantee that
+either.)
+
+**Warning!** Block ciphers do not yet achieve full protection against attackers
+who can measure the timing of packets with sufficient precision. For details
+and workarounds see the [Block Ciphers](#block-ciphers) section.
+
+### Local attacks
+
+In this section, we consider an attacker who can run software on the same
+machine. The attacker has insufficient privileges to directly access Mbed TLS
+assets such as memory and files.
+
+#### Timing attacks
+
+The attacker is able to observe the timing of instructions executed by Mbed TLS
+by leveraging shared hardware that both Mbed TLS and the attacker have access
+to. Typical attack vectors include cache timings, memory bus contention and
+branch prediction.
+
+Mbed TLS provides limited protection against timing attacks. The cost of
+protecting against timing attacks widely varies depending on the granularity of
+the measurements and the noise present. Therefore the protection in Mbed TLS is
+limited. We are only aiming to provide protection against **publicly
+documented attack techniques**.
+
+As attacks keep improving, so does Mbed TLS's protection. Mbed TLS is moving
+towards a model of fully timing-invariant code, but has not reached this point
+yet.
+
+**Remark:** Timing information can be observed over the network or through
+physical side channels as well. Remote and physical timing attacks are covered
+in the [Remote attacks](remote-attacks) and [Physical
+attacks](physical-attacks) sections respectively.
+
+**Warning!** Block ciphers do not yet achieve full protection. For
+details and workarounds see the [Block Ciphers](#block-ciphers) section.
+
+#### Local non-timing side channels
+
+The attacker code running on the platform has access to some sensor capable of
+picking up information on the physical state of the hardware while Mbed TLS is
+running. This could for example be an analogue-to-digital converter on the
+platform that is located unfortunately enough to pick up the CPU noise.
+
+Mbed TLS doesn't make any security guarantees against local non-timing-based
+side channel attacks. If local non-timing attacks are present in a use case or
+a user application's threat model, they need to be mitigated by the platform.
+
+#### Local fault injection attacks
+
+Software running on the same hardware can affect the physical state of the
+device and introduce faults.
+
+Mbed TLS doesn't make any security guarantees against local fault injection
+attacks. If local fault injection attacks are present in a use case or a user
+application's threat model, they need to be mitigated by the platform.
+
+### Physical attacks
+
+In this section, we consider an attacker who has access to physical information
+about the hardware Mbed TLS is running on and/or can alter the physical state
+of the hardware (e.g. power analysis, radio emissions or fault injection).
+
+Mbed TLS doesn't make any security guarantees against physical attacks. If
+physical attacks are present in a use case or a user application's threat
+model, they need to be mitigated by physical countermeasures.
+
+### Caveats
+
+#### Out-of-scope countermeasures
+
+Mbed TLS has evolved organically and a well defined threat model hasn't always
+been present. Therefore, Mbed TLS might have countermeasures against attacks
+outside the above defined threat model.
+
+The presence of such countermeasures don't mean that Mbed TLS provides
+protection against a class of attacks outside of the above described threat
+model. Neither does it mean that the failure of such a countermeasure is
+considered a vulnerability.
+
+#### Block ciphers
+
+Currently there are four block ciphers in Mbed TLS: AES, CAMELLIA, ARIA and
+DES. The pure software implementation in Mbed TLS implementation uses lookup
+tables, which are vulnerable to timing attacks.
+
+These timing attacks can be physical, local or depending on network latency
+even a remote. The attacks can result in key recovery.
+
+**Workarounds:**
+
+- Turn on hardware acceleration for AES. This is supported only on selected
+  architectures and currently only available for AES. See configuration options
+  `MBEDTLS_AESCE_C`, `MBEDTLS_AESNI_C` and `MBEDTLS_PADLOCK_C` for details.
+- Add a secure alternative implementation (typically hardware acceleration) for
+  the vulnerable cipher. See the [Alternative Implementations
+Guide](docs/architecture/alternative-implementations.md) for more information.
+- Use cryptographic mechanisms that are not based on block ciphers. In
+  particular, for authenticated encryption, use ChaCha20/Poly1305 instead of
+  block cipher modes. For random generation, use HMAC\_DRBG instead of CTR\_DRBG.
diff --git a/docs/.gitignore b/docs/.gitignore
index 23f832b..11f197b 100644
--- a/docs/.gitignore
+++ b/docs/.gitignore
@@ -1,2 +1,4 @@
 *.html
 *.pdf
+_build/
+api/
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 0000000..47510f9
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,40 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS    ?=
+SPHINXBUILD   ?= sphinx-build
+SOURCEDIR     = .
+BUILDDIR      = _build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help clean apidoc breathe_apidoc Makefile
+
+# Intercept the 'clean' target so we can do the right thing for apidoc as well
+clean:
+	@# Clean the apidoc
+	$(MAKE) -C .. apidoc_clean
+	@# Clean the breathe-apidoc generated files
+	rm -rf ./api
+	@# Clean the sphinx docs
+	@$(SPHINXBUILD) -M clean "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+apidoc:
+	@# Generate doxygen from source using the main Makefile
+	$(MAKE) -C .. apidoc
+
+breathe_apidoc: apidoc
+	@# Remove existing files - breathe-apidoc skips them if they're present
+	rm -rf ./api
+	@# Generate RST file structure with breathe-apidoc
+	breathe-apidoc -o ./api ../apidoc/xml
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile breathe_apidoc
+	@# Build the relevant target with sphinx
+	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/docs/architecture/psa-migration/psa-limitations.md b/docs/architecture/psa-migration/psa-limitations.md
index c368023..b81aeb4 100644
--- a/docs/architecture/psa-migration/psa-limitations.md
+++ b/docs/architecture/psa-migration/psa-limitations.md
@@ -11,11 +11,15 @@
 Limitations relevant for G1 (performing crypto operations)
 ==========================================================
 
-Restartable ECC operations
---------------------------
+Restartable (aka interruptible) ECC operations
+----------------------------------------------
 
-There is currently no support for that in PSA at all, but it will be added at
-some point, see <https://github.com/orgs/Mbed-TLS/projects/1#column-18816849>.
+Support for interruptible ECDSA sign/verify was added to PSA in Mbed TLS 3.4.
+However support for interruptible ECDH is not present yet. Also, PK, X.509 and
+TLS have not yet been adapted to take advantage of the new PSA APIs. See:
+- <https://github.com/Mbed-TLS/mbedtls/issues/7292>;
+- <https://github.com/Mbed-TLS/mbedtls/issues/7293>;
+- <https://github.com/Mbed-TLS/mbedtls/issues/7294>.
 
 Currently, when `MBEDTLS_USE_PSA_CRYPTO` and `MBEDTLS_ECP_RESTARTABLE` are
 both enabled, some operations that should be restartable are not (ECDH in TLS
@@ -78,6 +82,10 @@
 migration by implementing RFC 7919. (Implementing RFC 7919 could be done any
 time; making it mandatory can only be done in 4.0 or another major version.)
 
+As of early 2023, the plan is to go with option 2 in Mbed TLS 4.0, which has
+been announced on the mailing-list and got no push-back, see
+<https://github.com/Mbed-TLS/mbedtls/issues/5278>.
+
 RSA-PSS parameters
 ------------------
 
@@ -321,6 +329,8 @@
    in the meantime. Such an extension seems inconvenient and not motivated by
 strong security arguments, so it's unclear whether it would be accepted.
 
+Since Mbed TLS 3.4, option 1 is implemented.
+
 Limitations relevant for G2 (isolation of long-term secrets)
 ============================================================
 
diff --git a/docs/architecture/psa-migration/strategy.md b/docs/architecture/psa-migration/strategy.md
index 1542324..b985a77 100644
--- a/docs/architecture/psa-migration/strategy.md
+++ b/docs/architecture/psa-migration/strategy.md
@@ -18,13 +18,17 @@
 implemented, see `docs/use-psa-crypto.md`, where new APIs are about (G2), and
 internal changes implement (G1).
 
+As of early 2023, work towards G5 is in progress: Mbed TLS 3.3 and 3.4 saw
+some improvements in this area, and more will be coming in future releases.
+
 Generally speaking, the numbering above doesn't mean that each goal requires
 the preceding ones to be completed.
 
+
 Compile-time options
 ====================
 
-We currently have two compile-time options that are relevant to the migration:
+We currently have a few compile-time options that are relevant to the migration:
 
 - `MBEDTLS_PSA_CRYPTO_C` - enabled by default, controls the presence of the PSA
   Crypto APIs.
@@ -36,7 +40,9 @@
 
 The reasons why `MBEDTLS_USE_PSA_CRYPTO` is optional and disabled by default
 are:
-- it's incompatible with `MBEDTLS_ECP_RESTARTABLE`;
+- it's not fully compatible with `MBEDTLS_ECP_RESTARTABLE`: you can enable
+  both, but then you won't get the full effect of RESTARTBLE (see the
+documentation of this option in `mbedtls_config.h`);
 - to avoid a hard/default dependency of TLS, X.509 and PK on
   `MBEDTLS_PSA_CRYPTO_C`, for backward compatibility reasons:
   - When `MBEDTLS_PSA_CRYPTO_C` is enabled and used, applications need to call
@@ -71,10 +77,10 @@
 TLS and X.509 layers can't both use only PSA APIs and get restartable
 behaviour.
 
-Supporting this in PSA is on our roadmap and currently planned for end of
-2022, see <https://github.com/orgs/Mbed-TLS/projects/1#column-18883250>.
+Support for restartable (aka interruptible) ECDSA sign/verify operation was
+added to PSA in Mbed TLS 3.4, but support for ECDH is not present yet.
 
-It will then require follow-up work to make use of the new PSA API in
+It will then require follow-up work to make use of the new PSA APIs in
 PK/X.509/TLS in all places where we currently allow restartable operations.
 
 ### Backward compatibility issues with making `MBEDTLS_USE_PSA_CRYPTO` always on
@@ -137,8 +143,11 @@
 - Downside: tricky to implement if the PSA implementation is currently done on
   top of that layer (dependency loop).
 
-This strategy is currently (early 2022) used for all operations in the PK
-layer.
+This strategy is currently (early 2023) used for all operations in the PK
+layer; the MD layer uses a variant where it dispatches to PSA if a driver is
+available and the driver subsystem has been initialized, regardless of whether
+`USE_PSA_CRYPTO` is enabled; see `md-cipher-dispatch.md` in the same directory
+for details.
 
 This strategy is not very well suited to the Cipher layer, as the PSA
 implementation is currently done on top of that layer.
@@ -161,8 +170,9 @@
   code size.
 - Downside: TLS/X.509 code has to be done for each operation.
 
-This strategy is currently (early 2022) used for the MD layer and the Cipher
-layer.
+This strategy is currently (early 2023) used for the MD layer and the Cipher
+layer in X.509 and TLS. Crypto modules however always call to MD which may
+then dispatch to PSA, see `md-cipher-dispatch.md`.
 
 Opt-in use of PSA from the abstraction layer
 --------------------------------------------
@@ -210,7 +220,10 @@
 - PK (for G1): silently call PSA
 - PK (for G2): opt-in use of PSA (new key type)
 - Cipher (G1): replace calls at each call site
-- MD (G1): replace calls at each call site
+- MD (G1, X.509 and TLS): replace calls at each call site (depending on
+  `USE_PSA_CRYPTO`)
+- MD (G5): silently call PSA when a driver is available, see
+  `md-cipher-dispatch.md`.
 
 
 Supporting builds with drivers without the software implementation
@@ -219,10 +232,6 @@
 This section presents a plan towards G5: save code size by compiling out our
 software implementation when a driver is available.
 
-Additionally, we want to save code size by compiling out the
-abstractions layers that we are not using when `MBEDTLS_USE_PSA_CRYPTO` is
-enabled (see previous section): MD and Cipher.
-
 Let's expand a bit on the definition of the goal: in such a configuration
 (driver used, software implementation and abstraction layer compiled out),
 we want:
@@ -238,9 +247,10 @@
 We can roughly divide the work needed to get there in the following steps:
 
 0. Have a working driver interface for the algorithms we want to replace.
-1. Have users of these algorithms call to PSA, not the legacy API, for all
-   operations. (This is G1, and for PK, X.509 and TLS this is controlled by
-   `MBEDTLS_USE_PSA_CRYPTO`.) This needs to be done in the library and tests.
+1. Have users of these algorithms call to PSA or an abstraction layer than can
+   dispatch to PSA, but not the low-level legacy API, for all operations.
+(This is G1, and for PK, X.509 and TLS this is controlled by
+`MBEDTLS_USE_PSA_CRYPTO`.) This needs to be done in the library and tests.
 2. Have users of these algorithms not depend on the legacy API for information
    management (getting a size for a given algorithm, etc.)
 3. Adapt compile-time guards used to query availability of a given algorithm;
@@ -262,50 +272,32 @@
 is preferable to group with the next step(s) in the same PR until good test
 coverage can be reached.
 
-**Status as of Mbed TLS 3.2:**
+**Status as of end of March 2023 (shortly after 3.4):**
 
 - Step 0 is achieved for most algorithms, with only a few gaps remaining.
 - Step 1 is achieved for most of PK, X.509, and TLS when
   `MBEDTLS_USE_PSA_CRYPTO` is enabled with only a few gaps remaining (see
   docs/use-psa-crypto.md).
-- Step 1 is not achieved for a lot of the crypto library including the PSA
-  core. For example, `entropy.c` calls the legacy API
-  `mbedtls_sha256` (or `mbedtls_sha512` optionally); `hmac_drbg.c` calls the
-  legacy API `mbedtls_md` and `ctr_drbg.c` calls the legacy API `mbedtls_aes`;
-  the PSA core depends on the entropy module and at least one of the DRBG
-  modules (unless `MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG` is used). Further, several
-  crypto modules have similar issues, for example RSA PKCS#1 v2.1 calls
-  `mbedtls_md` directly.
+- Step 1 is achieved for the crypto library regarding hashes: everything uses
+  MD (not low-level hash APIs), which then dispatches to PSA if applicable.
+- Step 1 is not achieved for all of the crypto library when it come to
+  ciphers. For example,`ctr_drbg.c` calls the legacy API `mbedtls_aes`.
 - Step 2 is achieved for most of X.509 and TLS (same gaps as step 1) when
-  `MBEDTLS_USE_PSA_CRYPTO` is enabled - this was tasks like #5795, #5796,
-  #5797. It is being done in PK and RSA PKCS#1 v1.5 by PR #6065.
-- Step 3 was mostly not started at all before 3.2; it is being done for PK by
-  PR #6065.
+  `MBEDTLS_USE_PSA_CRYPTO` is enabled.
+- Step 3 is done for hashes and top-level ECC modules (ECDSA, ECDH, ECJPAKE).
 
 **Strategy for step 1:**
 
 Regarding PK, X.509, and TLS, this is mostly achieved with only a few gaps.
 (The strategy was outlined in the previous section.)
 
-Regarding libmbedcrypto, outside of the RNG subsystem, for modules that
-currently depend on other legacy crypto modules, this can be achieved without
-backwards compatibility issues, by using the software implementation if
-available, and "falling back" to PSA only if it's not. The compile-time
-dependency changes from the current one (say, `MD_C` or `AES_C`) to "the
-previous dependency OR PSA Crypto with needed algorithms". When building
-without software implementation, users need to call `psa_crypto_init()` before
-calling any function from these modules. This condition does not constitute a
-break of backwards compatibility, as it was previously impossible to build in
-those configurations, and in configurations were the build was possible,
-application code keeps working unchanged. An work-in-progress example of
-applying this strategy, for RSA PKCS#1 v2.1, is here:
-<https://github.com/Mbed-TLS/mbedtls/pull/6141>
-
-There is a problem with the modules used for the PSA RNG, as currently the RNG
-is initialized before drivers and the key store. This part will need further
-study, but in the meantime we can proceed with everything that's not the
-entropy module of one of the DRBG modules, and that does not depend on one of
-those modules.
+Regarding libmbedcrypto:
+- for hashes and ciphers, see `md-cipher-dispatch.md` in the same directory;
+- for ECC, we have no internal uses of the top-level algorithms (ECDSA, ECDH,
+  ECJPAKE), however they all depend on `ECP_C` which in turn depends on
+`BIGNUM_C`. So, direct calls from TLS, X.509 and PK to ECP and Bignum will
+need to be replaced; see <https://github.com/Mbed-TLS/mbedtls/issues/6839> and
+linked issues for a summary of intermediate steps and open points.
 
 **Strategy for step 2:**
 
@@ -315,14 +307,11 @@
 (such as `mbedtls_md_type_t`) in their API and can't assume PSA to be
 compiled in (such as `rsa.c`).
 
-It is suggested that, as a temporary solution until we clean this up
-later when removing the legacy API including its identifiers (G4), we may
-occasionally use ad-hoc internal functions, such as the ones introduced by PR
-6065 in `library/hash_info.[ch]`.
-
-An alternative would be to have two different code paths depending on whether
-`MBEDTLS_PSA_CRYPTO_C` is defined or not. However this is not great for
-readability or testability.
+When using an existing abstraction layer such as MD, it can provide
+information management functions. In other cases, information that was in a
+low-level module but logically belongs in a higher-level module can be moved
+to that module (for example, TLS identifiers of curves and there conversion
+to/from PSA or legacy identifiers belongs in TLS, not `ecp.c`).
 
 **Strategy for step 3:**
 
@@ -338,35 +327,15 @@
 if it is, the code want the algorithm available in PSA, otherwise, it wants it
 available via the legacy API(s) is it using (MD and/or low-level).
 
-The strategy for steps 1 and 2 above will introduce new situations: code that
-currently compute hashes using MD (resp. a low-level hash module) will gain
-the ability to "fall back" to using PSA if the legacy dependency isn't
-available. Data related to a certain hash (OID, sizes, translations) should
-only be included in the build if it is possible to use that hash in some way.
+As much as possible, we're trying to create for each algorithm a single new
+macro that can be used to express dependencies everywhere (except pure PSA
+code that should always use `PSA_WANT`). For example, for hashes this is the
+`MBEDTLS_MD_CAN_xxx` family. For ECC algorithms, we have similar
+`MBEDTLS_PK_CAN_xxx` macros.
 
-In order to cater to these new needs, new families of macros are introduced in
-`legacy_or_psa.h`, see its documentation for details.
-
-It should be noted that there are currently:
-- too many different ways of computing a hash (low-level, MD, PSA);
-- too many different ways to configure the library that influence which of
-  these ways is available and will be used (`MBEDTLS_USE_PSA_CRYPTO`,
-  `MBEDTLS_PSA_CRYPTO_CONFIG`, `mbedtls_config.h` + `psa/crypto_config.h`).
-
-As a result, we need more families of dependency macros than we'd like to.
-This is a temporary situation until we move to a place where everything is
-based on PSA Crypto. In the meantime, long and explicit names where chosen for
-the new macros in the hope of avoiding confusion.
-
-Note: the new macros supplement but do not replace the existing macros:
-- code that always uses PSA Crypto (for example, code specific to TLS 1.3)
-  should use `PSA_WANT_xxx`;
-- code that always uses the legacy API (for example, crypto modules that have
-  not undergone step 1 yet) should use `MBEDTLS_xxx_C`;
-- code that may use one of the two APIs, either based on
-  `MBEDTLS_USE_PSA_CRYPTO` (X.509, TLS 1.2, shared between TLS 1.2 and 1.3),
-  or based on availability (crypto modules after step 1), should use one of
-  the new macros from `legacy_or_psa.h`.
+Note that in order to achieve that goal, even for code that obeys
+`USE_PSA_CRYPTO`, it is useful to impose that all algorithms that are
+available via the legacy APIs are also available via PSA.
 
 Executing step 3 will mostly consist of using the right dependency macros in
 the right places (once the previous steps are done).
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000..41c50c7
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,34 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+import glob
+
+project = 'Mbed TLS Versioned'
+copyright = '2023, Mbed TLS Contributors'
+author = 'Mbed TLS Contributors'
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = ['breathe', 'sphinx.ext.graphviz']
+
+templates_path = ['_templates']
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+breathe_projects = {
+    'mbedtls-versioned': '../apidoc/xml'
+}
+breathe_default_project = 'mbedtls-versioned'
+
+primary_domain = 'c'
+highlight_language = 'c'
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = 'sphinx_rtd_theme'
+html_static_path = ['_static']
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 0000000..33a9722
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,20 @@
+.. Mbed TLS Versioned documentation master file, created by
+   sphinx-quickstart on Thu Feb 23 18:13:44 2023.
+   You can adapt this file completely to your liking, but it should at least
+   contain the root `toctree` directive.
+
+Mbed TLS API documentation
+==========================
+
+.. doxygenpage:: index
+   :project: mbedtls-versioned
+
+.. toctree::
+   :caption: Contents
+   :maxdepth: 1
+
+   Home <self>
+   api/grouplist.rst
+   api/filelist.rst
+   api/structlist.rst
+   api/unionlist.rst
diff --git a/docs/requirements.in b/docs/requirements.in
new file mode 100644
index 0000000..a523188
--- /dev/null
+++ b/docs/requirements.in
@@ -0,0 +1,2 @@
+sphinx-rtd-theme
+breathe
diff --git a/docs/requirements.txt b/docs/requirements.txt
new file mode 100644
index 0000000..4b9f3a6
--- /dev/null
+++ b/docs/requirements.txt
@@ -0,0 +1,66 @@
+#
+# This file is autogenerated by pip-compile with Python 3.9
+# by the following command:
+#
+#    pip-compile requirements.in
+#
+alabaster==0.7.13
+    # via sphinx
+babel==2.12.1
+    # via sphinx
+breathe==4.35.0
+    # via -r requirements.in
+certifi==2022.12.7
+    # via requests
+charset-normalizer==3.1.0
+    # via requests
+docutils==0.17.1
+    # via
+    #   breathe
+    #   sphinx
+    #   sphinx-rtd-theme
+idna==3.4
+    # via requests
+imagesize==1.4.1
+    # via sphinx
+importlib-metadata==6.0.0
+    # via sphinx
+jinja2==3.1.2
+    # via sphinx
+markupsafe==2.1.2
+    # via jinja2
+packaging==23.0
+    # via sphinx
+pygments==2.14.0
+    # via sphinx
+requests==2.28.2
+    # via sphinx
+snowballstemmer==2.2.0
+    # via sphinx
+sphinx==4.5.0
+    # via
+    #   breathe
+    #   sphinx-rtd-theme
+sphinx-rtd-theme==1.2.0
+    # via -r requirements.in
+sphinxcontrib-applehelp==1.0.4
+    # via sphinx
+sphinxcontrib-devhelp==1.0.2
+    # via sphinx
+sphinxcontrib-htmlhelp==2.0.1
+    # via sphinx
+sphinxcontrib-jquery==2.0.0
+    # via sphinx-rtd-theme
+sphinxcontrib-jsmath==1.0.1
+    # via sphinx
+sphinxcontrib-qthelp==1.0.3
+    # via sphinx
+sphinxcontrib-serializinghtml==1.1.5
+    # via sphinx
+urllib3==1.26.15
+    # via requests
+zipp==3.15.0
+    # via importlib-metadata
+
+# The following packages are considered to be unsafe in a requirements file:
+# setuptools
diff --git a/docs/use-psa-crypto.md b/docs/use-psa-crypto.md
index c63e65a..4d72f99 100644
--- a/docs/use-psa-crypto.md
+++ b/docs/use-psa-crypto.md
@@ -1,8 +1,12 @@
 This document describes the compile-time configuration option
 `MBEDTLS_USE_PSA_CRYPTO` from a user's perspective.
 
-This option makes the X.509 and TLS library use PSA for cryptographic
-operations, and enables new APIs for using keys handled by PSA Crypto.
+This option:
+- makes the X.509 and TLS libraries use PSA for cryptographic operations as
+  much as possible, see "Internal changes" below;
+- enables new APIs for using keys handled by PSA Crypto, such as
+  `mbedtls_pk_setup_opaque()` and `mbedtls_ssl_conf_psk_opaque()`, see
+"New APIs / API extensions" below.
 
 General considerations
 ----------------------
@@ -11,9 +15,25 @@
 `psa_crypto_init()` before calling any function from the SSL/TLS, X.509 or PK
 module.
 
-**Scope:** `MBEDTLS_USE_PSA_CRYPTO` has no effect on the most of the TLS 1.3
-code, which always uses PSA crypto. The parts of the TLS 1.3 code that will
-use PSA Crypto or not depending on the value of this option are:
+**Relationship with other options:** This option depends on
+`MBEDTLS_PSA_CRYPTO_C`. These two options differ in the following way:
+- `MBEDTLS_PSA_CRYPTO_C` enables the implementation of the PSA Crypto API.
+  When it is enabled, `psa_xxx()` APIs are available and you must call
+`psa_crypto_init()` before you call any other `psa_xxx()` function. Other
+modules in the library (non-PSA crypto APIs, X.509, TLS) may or may not use
+PSA Crypto but you're not required to call `psa_crypto_init()` before calling
+non-PSA functions, unless when explicitly documented (TLS 1.3).
+- `MBEDTLS_USE_PSA_CRYPTO` means that X.509 and TLS will use PSA Crypto as
+  much as possible (that is, everywhere except for features that are not
+supported by PSA Crypto, see "Internal Changes" below for a complete list of
+exceptions). When it is enabled, you need to call `psa_crypto_init()` before
+calling any function from PK, X.509 or TLS; however it doesn't change anything
+for the rest of the library.
+
+**Scope:** `MBEDTLS_USE_PSA_CRYPTO` has no effect on modules other than PK,
+X.509 and TLS. It also has no effect on most of the TLS 1.3 code, which always
+uses PSA crypto. The parts of the TLS 1.3 code that will use PSA Crypto or not
+depending on this option being set or not are:
 - record protection;
 - running handshake hash;
 - asymmetric signature verification & generation;
@@ -21,6 +41,21 @@
 You need to enable `MBEDTLS_USE_PSA_CRYPTO` if you want TLS 1.3 to use PSA
 everywhere.
 
+**Historical note:** This option was introduced at a time when PSA Crypto was
+still beta and not ready for production, so we made its use in X.509 and TLS
+opt-in: by default, these modules would keep using the stable,
+production-ready legacy (pre-PSA) crypto APIs. So, the scope of was X.509 and
+TLS, as well as some of PK for technical reasons. Nowadays PSA Crypto is no
+longer beta, and production quality, so there's no longer any reason to make
+its use in other modules opt-in. However, PSA Crypto functions require that
+`psa_crypto_init()` has been called before their use, and for backwards
+compatibility reasons we can't impose this requirement on non-PSA functions
+that didn't have such a requirement before. So, nowadays the main meaning of
+`MBEDTLS_USE_PSA_CRYPTO` is that the user promises to call `psa_crypto_init()`
+before calling any PK, X.509 or TLS functions. For the same compatibility
+reasons, we can't extend its scope. However, new modules in the library, such
+as TLS 1.3, can be introduced with a requirement to call `psa_crypto_init()`.
+
 New APIs / API extensions
 -------------------------
 
@@ -63,6 +98,19 @@
 **Use in TLS:** opt-in. The application needs to register the key using one of
 the new APIs to get the benefits.
 
+### PSA-held (opaque) keys for TLS 1.2 EC J-PAKE key exchange
+
+**New API function:** `mbedtls_ssl_set_hs_ecjpake_password_opaque()`.
+Call this function from an application to register a PSA key for use with the
+TLS 1.2 EC J-PAKE key exchange.
+
+**Benefits:** isolation of long-term secrets.
+
+**Limitations:** none.
+
+**Use in TLS:** opt-in. The application needs to register the key using one of
+the new APIs to get the benefits.
+
 ### PSA-based operations in the Cipher layer
 
 There is a new API function `mbedtls_cipher_setup_psa()` to set up a context
diff --git a/doxygen/input/doc_mainpage.h b/doxygen/input/doc_mainpage.h
index 7c6464f..c5bbf2c 100644
--- a/doxygen/input/doc_mainpage.h
+++ b/doxygen/input/doc_mainpage.h
@@ -22,7 +22,7 @@
  */
 
 /**
- * @mainpage mbed TLS v3.3.0 source code documentation
+ * @mainpage mbed TLS v3.4.0 source code documentation
  *
  * This documentation describes the internal structure of mbed TLS.  It was
  * automatically generated from specially formatted comment blocks in
diff --git a/doxygen/mbedtls.doxyfile b/doxygen/mbedtls.doxyfile
index c33c7e3..393fd41 100644
--- a/doxygen/mbedtls.doxyfile
+++ b/doxygen/mbedtls.doxyfile
@@ -1,4 +1,4 @@
-PROJECT_NAME           = "mbed TLS v3.3.0"
+PROJECT_NAME           = "mbed TLS v3.4.0"
 OUTPUT_DIRECTORY       = ../apidoc/
 FULL_PATH_NAMES        = NO
 OPTIMIZE_OUTPUT_FOR_C  = YES
@@ -18,6 +18,7 @@
 HTML_TIMESTAMP         = YES
 SEARCHENGINE           = YES
 GENERATE_LATEX         = NO
+GENERATE_XML           = YES
 MACRO_EXPANSION        = YES
 EXPAND_ONLY_PREDEF     = YES
 INCLUDE_PATH           = ../include
@@ -42,3 +43,12 @@
 #     \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 # This avoids writing redundant text and keeps Clang happy.
 ALIASES += emptydescription=""
+
+# Define away Mbed TLS macros that make parsing definitions difficult.
+# MBEDTLS_DEPRECATED is not included in this list as it's important to
+# display deprecated status in the documentation.
+PREDEFINED             = "MBEDTLS_CHECK_RETURN_CRITICAL="   \
+                         "MBEDTLS_CHECK_RETURN_TYPICAL="    \
+                         "MBEDTLS_CHECK_RETURN_OPTIONAL="   \
+                         "MBEDTLS_PRINTF_ATTRIBUTE(a,b)="   \
+
diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h
index b1d4b88..5c2c843 100644
--- a/include/mbedtls/bignum.h
+++ b/include/mbedtls/bignum.h
@@ -1005,7 +1005,7 @@
  *                 This must point to an initialized MPI.
  * \param rounds   The number of bases to perform the Miller-Rabin primality
  *                 test for. The probability of returning 0 on a composite is
- *                 at most 2<sup>-2*\p rounds</sup>.
+ *                 at most 2<sup>-2*\p rounds </sup>.
  * \param f_rng    The RNG function to use. This must not be \c NULL.
  * \param p_rng    The RNG parameter to be passed to \p f_rng.
  *                 This may be \c NULL if \p f_rng doesn't use
diff --git a/include/mbedtls/build_info.h b/include/mbedtls/build_info.h
index e66032d..8ffa51a 100644
--- a/include/mbedtls/build_info.h
+++ b/include/mbedtls/build_info.h
@@ -37,7 +37,7 @@
  * Major, Minor, Patchlevel
  */
 #define MBEDTLS_VERSION_MAJOR  3
-#define MBEDTLS_VERSION_MINOR  3
+#define MBEDTLS_VERSION_MINOR  4
 #define MBEDTLS_VERSION_PATCH  0
 
 /**
@@ -45,9 +45,9 @@
  *    MMNNPP00
  *    Major version | Minor version | Patch version
  */
-#define MBEDTLS_VERSION_NUMBER         0x03030000
-#define MBEDTLS_VERSION_STRING         "3.3.0"
-#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 3.3.0"
+#define MBEDTLS_VERSION_NUMBER         0x03040000
+#define MBEDTLS_VERSION_STRING         "3.4.0"
+#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 3.4.0"
 
 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
 #define _CRT_SECURE_NO_DEPRECATE 1
@@ -99,6 +99,7 @@
  */
 #if defined(MBEDTLS_ECJPAKE_C) || \
     defined(MBEDTLS_PEM_PARSE_C) || \
+    defined(MBEDTLS_ENTROPY_C) || \
     defined(MBEDTLS_PKCS12_C) || \
     defined(MBEDTLS_RSA_C)
 #define MBEDTLS_MD_LIGHT
@@ -120,7 +121,31 @@
 #define MBEDTLS_PK_PARSE_C
 #endif
 
+/* The following blocks make it easier to disable all of TLS,
+ * or of TLS 1.2 or 1.3 or DTLS, without having to manually disable all
+ * key exchanges, options and extensions related to them. */
+
+#if !defined(MBEDTLS_SSL_TLS_C)
+#undef MBEDTLS_SSL_CLI_C
+#undef MBEDTLS_SSL_SRV_C
+#undef MBEDTLS_SSL_PROTO_TLS1_3
+#undef MBEDTLS_SSL_PROTO_TLS1_2
+#undef MBEDTLS_SSL_PROTO_DTLS
+#endif
+
+#if !defined(MBEDTLS_SSL_PROTO_DTLS)
+#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY
+#undef MBEDTLS_SSL_DTLS_CONNECTION_ID
+#undef MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT
+#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY
+#undef MBEDTLS_SSL_DTLS_SRTP
+#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
+#endif
+
 #if !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#undef MBEDTLS_SSL_ENCRYPT_THEN_MAC
+#undef MBEDTLS_SSL_EXTENDED_MASTER_SECRET
+#undef MBEDTLS_SSL_RENEGOTIATION
 #undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 #undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 #undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
diff --git a/include/mbedtls/check_config.h b/include/mbedtls/check_config.h
index ff4eef7..5eadc0c 100644
--- a/include/mbedtls/check_config.h
+++ b/include/mbedtls/check_config.h
@@ -66,10 +66,6 @@
 #error "MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense"
 #endif
 
-#if defined(MBEDTLS_AESNI_C) && !defined(MBEDTLS_HAVE_ASM)
-#error "MBEDTLS_AESNI_C defined, but not all prerequisites"
-#endif
-
 #if defined(__aarch64__) && defined(__GNUC__)
 /* We don't do anything with MBEDTLS_AESCE_C on systems without ^ these two */
 #if defined(MBEDTLS_AESCE_C) && !defined(MBEDTLS_HAVE_ASM)
@@ -173,21 +169,36 @@
 #error "MBEDTLS_PKCS5_C defined, but not all prerequisites"
 #endif
 
-#if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) &&      \
-                                    !defined(MBEDTLS_SHA256_C))
+/* Helpers for hash dependencies, will be undefined at the end of the file */
+/* Do SHA-256, 384, 512 to cover Entropy and TLS. */
+#if defined(MBEDTLS_SHA256_C) || \
+    (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_256))
+#define MBEDTLS_MD_HAVE_SHA256
+#endif
+#if defined(MBEDTLS_SHA384_C) || \
+    (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_384))
+#define MBEDTLS_MD_HAVE_SHA384
+#endif
+#if defined(MBEDTLS_SHA512_C) || \
+    (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_512))
+#define MBEDTLS_MD_HAVE_SHA512
+#endif
+
+#if defined(MBEDTLS_ENTROPY_C) && \
+    !(defined(MBEDTLS_MD_HAVE_SHA512) || defined(MBEDTLS_MD_HAVE_SHA256))
 #error "MBEDTLS_ENTROPY_C defined, but not all prerequisites"
 #endif
-#if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_SHA512_C) &&         \
+#if defined(MBEDTLS_ENTROPY_C) && \
     defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64)
 #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high"
 #endif
 #if defined(MBEDTLS_ENTROPY_C) &&                                            \
-    ( !defined(MBEDTLS_SHA512_C) || defined(MBEDTLS_ENTROPY_FORCE_SHA256) ) \
+    (defined(MBEDTLS_ENTROPY_FORCE_SHA256) || !defined(MBEDTLS_MD_HAVE_SHA512)) \
     && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32)
 #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high"
 #endif
 #if defined(MBEDTLS_ENTROPY_C) && \
-    defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_SHA256_C)
+    defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_MD_HAVE_SHA256)
 #error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites"
 #endif
 
@@ -365,8 +376,7 @@
 
 /* Use of EC J-PAKE in TLS requires SHA-256. */
 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) &&                    \
-    !(defined(MBEDTLS_SHA256_C) || \
-      (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_256)))
+    !defined(MBEDTLS_MD_HAVE_SHA256)
 #error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites"
 #endif
 
@@ -773,34 +783,20 @@
 #error "MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY defined on non-Aarch64 system"
 #endif
 
-#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && !defined(MBEDTLS_USE_PSA_CRYPTO) && \
-    !( defined(MBEDTLS_SHA1_C) || defined(MBEDTLS_SHA256_C) || defined(MBEDTLS_SHA512_C) )
-#error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites"
-#endif
-
-/* TLS 1.3 requires separate HKDF parts from PSA */
+/* TLS 1.3 requires separate HKDF parts from PSA,
+ * and at least one ciphersuite, so at least SHA-256 or SHA-384
+ * from PSA to use with HKDF.
+ *
+ * Note: for dependencies common with TLS 1.2 (running handshake hash),
+ * see MBEDTLS_SSL_TLS_C. */
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
-        !( defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_HKDF_EXTRACT) && defined(PSA_WANT_ALG_HKDF_EXPAND) )
+    !(defined(MBEDTLS_PSA_CRYPTO_C) && \
+      defined(PSA_WANT_ALG_HKDF_EXTRACT) && \
+      defined(PSA_WANT_ALG_HKDF_EXPAND) && \
+      (defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384)))
 #error "MBEDTLS_SSL_PROTO_TLS1_3 defined, but not all prerequisites"
 #endif
 
-/* TLS 1.3 requires at least one ciphersuite, so at least SHA-256 or SHA-384 */
-#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
-/* We always need at least one of the hashes via PSA (for use with HKDF) */
-#if !( defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384) )
-#error "MBEDTLS_SSL_PROTO_TLS1_3 defined, but not all prerequisites"
-#endif /* !(PSA_WANT_ALG_SHA_256 || PSA_WANT_ALG_SHA_384) */
-#if !defined(MBEDTLS_USE_PSA_CRYPTO)
-/* When USE_PSA_CRYPTO is not defined, we also need SHA-256 or SHA-384 via the
- * legacy interface, including via the MD layer, for the parts of the code
- * that are shared with TLS 1.2 (running handshake hash). */
-#if !defined(MBEDTLS_MD_C) || \
-    !( defined(MBEDTLS_SHA256_C) || defined(MBEDTLS_SHA384_C) )
-#error "MBEDTLS_SSL_PROTO_TLS1_3 defined, but not all prerequisites"
-#endif /* !MBEDTLS_MD_C || !(MBEDTLS_SHA256_C || MBEDTLS_SHA384_C) */
-#endif /* !MBEDTLS_USE_PSA_CRYPTO */
-#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
-
 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
 #if !( defined(MBEDTLS_PK_HAVE_ECDH) && defined(MBEDTLS_X509_CRT_PARSE_C) && \
        ( defined(MBEDTLS_PK_HAVE_ECDSA) || defined(MBEDTLS_PKCS1_V21) ) )
@@ -864,11 +860,24 @@
 #error "MBEDTLS_SSL_ASYNC_PRIVATE defined, but not all prerequisites"
 #endif
 
-#if defined(MBEDTLS_SSL_TLS_C) && ( !defined(MBEDTLS_CIPHER_C) ||     \
-    ( !defined(MBEDTLS_MD_C) && !defined(MBEDTLS_USE_PSA_CRYPTO) ) )
+#if defined(MBEDTLS_SSL_TLS_C) && !defined(MBEDTLS_CIPHER_C)
 #error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
 #endif
 
+/* TLS 1.2 and 1.3 require SHA-256 or SHA-384 (running handshake hash) */
+#if defined(MBEDTLS_SSL_TLS_C)
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if !(defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384))
+#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
+#endif
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+#if !defined(MBEDTLS_MD_C) || \
+    !(defined(MBEDTLS_MD_HAVE_SHA256) || defined(MBEDTLS_MD_HAVE_SHA384))
+#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
+#endif
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+#endif /* MBEDTLS_SSL_TLS_C */
+
 #if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C)
 #error "MBEDTLS_SSL_SRV_C defined, but not all prerequisites"
 #endif
@@ -1107,6 +1116,9 @@
 #undef MBEDTLS_PK_HAVE_ECDSA
 #undef MBEDTLS_PK_HAVE_JPAKE
 #undef MBEDTLS_PK_HAVE_ECDH
+#undef MBEDTLS_MD_HAVE_SHA256
+#undef MBEDTLS_MD_HAVE_SHA384
+#undef MBEDTLS_MD_HAVE_SHA512
 
 /*
  * Avoid warning from -pedantic. This is a convenient place for this
diff --git a/include/mbedtls/ctr_drbg.h b/include/mbedtls/ctr_drbg.h
index 8d28150..0348281 100644
--- a/include/mbedtls/ctr_drbg.h
+++ b/include/mbedtls/ctr_drbg.h
@@ -45,6 +45,7 @@
 #include "mbedtls/build_info.h"
 
 #include "mbedtls/aes.h"
+#include "entropy.h"
 
 #if defined(MBEDTLS_THREADING_C)
 #include "mbedtls/threading.h"
@@ -94,17 +95,14 @@
  * \brief The amount of entropy used per seed by default, in bytes.
  */
 #if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
-#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
-/** This is 48 bytes because the entropy module uses SHA-512
- * (\c MBEDTLS_ENTROPY_FORCE_SHA256 is disabled).
+#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
+/** This is 48 bytes because the entropy module uses SHA-512.
  */
 #define MBEDTLS_CTR_DRBG_ENTROPY_LEN        48
 
-#else /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */
+#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 
-/** This is 32 bytes because the entropy module uses SHA-256
- * (the SHA512 module is disabled or
- * \c MBEDTLS_ENTROPY_FORCE_SHA256 is enabled).
+/** This is 32 bytes because the entropy module uses SHA-256.
  */
 #if !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
 /** \warning To achieve a 256-bit security strength, you must pass a nonce
@@ -112,7 +110,7 @@
  */
 #endif /* !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) */
 #define MBEDTLS_CTR_DRBG_ENTROPY_LEN        32
-#endif /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */
+#endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 #endif /* !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) */
 
 #if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
diff --git a/include/mbedtls/entropy.h b/include/mbedtls/entropy.h
index 2c8b750..e17245e 100644
--- a/include/mbedtls/entropy.h
+++ b/include/mbedtls/entropy.h
@@ -27,13 +27,17 @@
 
 #include <stddef.h>
 
-#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
-#include "mbedtls/sha512.h"
+#include "md.h"
+
+#if defined(MBEDTLS_MD_CAN_SHA512) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
 #define MBEDTLS_ENTROPY_SHA512_ACCUMULATOR
+#define MBEDTLS_ENTROPY_MD  MBEDTLS_MD_SHA512
+#define MBEDTLS_ENTROPY_BLOCK_SIZE      64      /**< Block size of entropy accumulator (SHA-512) */
 #else
-#if defined(MBEDTLS_SHA256_C)
+#if defined(MBEDTLS_MD_CAN_SHA256)
 #define MBEDTLS_ENTROPY_SHA256_ACCUMULATOR
-#include "mbedtls/sha256.h"
+#define MBEDTLS_ENTROPY_MD  MBEDTLS_MD_SHA256
+#define MBEDTLS_ENTROPY_BLOCK_SIZE      32      /**< Block size of entropy accumulator (SHA-256) */
 #endif
 #endif
 
@@ -71,12 +75,6 @@
 
 /** \} name SECTION: Module settings */
 
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-#define MBEDTLS_ENTROPY_BLOCK_SIZE      64      /**< Block size of entropy accumulator (SHA-512) */
-#else
-#define MBEDTLS_ENTROPY_BLOCK_SIZE      32      /**< Block size of entropy accumulator (SHA-256) */
-#endif
-
 #define MBEDTLS_ENTROPY_MAX_SEED_SIZE   1024    /**< Maximum size of seed we read from seed file */
 #define MBEDTLS_ENTROPY_SOURCE_MANUAL   MBEDTLS_ENTROPY_MAX_SOURCES
 
@@ -120,11 +118,7 @@
     int MBEDTLS_PRIVATE(accumulator_started); /* 0 after init.
                                                * 1 after the first update.
                                                * -1 after free. */
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_context  MBEDTLS_PRIVATE(accumulator);
-#elif defined(MBEDTLS_ENTROPY_SHA256_ACCUMULATOR)
-    mbedtls_sha256_context  MBEDTLS_PRIVATE(accumulator);
-#endif
+    mbedtls_md_context_t  MBEDTLS_PRIVATE(accumulator);
     int             MBEDTLS_PRIVATE(source_count); /* Number of entries used in source. */
     mbedtls_entropy_source_state    MBEDTLS_PRIVATE(source)[MBEDTLS_ENTROPY_MAX_SOURCES];
 #if defined(MBEDTLS_THREADING_C)
diff --git a/include/mbedtls/mbedtls_config.h b/include/mbedtls/mbedtls_config.h
index c8e215b..ef3cf24 100644
--- a/include/mbedtls/mbedtls_config.h
+++ b/include/mbedtls/mbedtls_config.h
@@ -56,7 +56,7 @@
  *
  * Required by:
  *      MBEDTLS_AESCE_C
- *      MBEDTLS_AESNI_C
+ *      MBEDTLS_AESNI_C (on some platforms)
  *      MBEDTLS_PADLOCK_C
  *
  * Comment to disable the use of assembly code.
@@ -1567,13 +1567,14 @@
  * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled).
  *
  * Requires: Without MBEDTLS_USE_PSA_CRYPTO: MBEDTLS_MD_C and
- *              (MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C)
+ *              (MBEDTLS_SHA256_C or MBEDTLS_SHA384_C or
+ *               SHA-256 or SHA-512 provided by a PSA driver)
  *           With MBEDTLS_USE_PSA_CRYPTO:
- *              PSA_WANT_ALG_SHA_1 or PSA_WANT_ALG_SHA_256 or
- *              PSA_WANT_ALG_SHA_512
+ *              PSA_WANT_ALG_SHA_256 or PSA_WANT_ALG_SHA_384
  *
- * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call
- * psa_crypto_init() before doing any TLS operations.
+ * \warning If building with MBEDTLS_USE_PSA_CRYPTO, or if the hash(es) used
+ * are only provided by PSA drivers, you must call psa_crypto_init() before
+ * doing any TLS operations.
  *
  * Comment this macro to disable support for TLS 1.2 / DTLS 1.2
  */
@@ -1921,20 +1922,23 @@
 /**
  * \def MBEDTLS_USE_PSA_CRYPTO
  *
- * Make the X.509 and TLS library use PSA for cryptographic operations, and
- * enable new APIs for using keys handled by PSA Crypto.
+ * Make the X.509 and TLS libraries use PSA for cryptographic operations as
+ * much as possible, and enable new APIs for using keys handled by PSA Crypto.
  *
  * \note Development of this option is currently in progress, and parts of Mbed
  * TLS's X.509 and TLS modules are not ported to PSA yet. However, these parts
  * will still continue to work as usual, so enabling this option should not
  * break backwards compatibility.
  *
- * \note See docs/use-psa-crypto.md for a complete description of what this
- * option currently does, and of parts that are not affected by it so far.
- *
  * \warning If you enable this option, you need to call `psa_crypto_init()`
  * before calling any function from the SSL/TLS, X.509 or PK modules.
  *
+ * \note Even with this option disabled, some code in PK, X.509, TLS or the
+ * crypto library might still use PSA drivers, if it can determine it's safe
+ * to do so.
+ *
+ * \note See docs/use-psa-crypto.md for a complete description this option.
+ *
  * Requires: MBEDTLS_PSA_CRYPTO_C.
  *
  * Uncomment this to enable internal use of PSA Crypto and new associated APIs.
@@ -2032,14 +2036,32 @@
 /**
  * \def MBEDTLS_AESNI_C
  *
- * Enable AES-NI support on x86-64.
+ * Enable AES-NI support on x86-64 or x86-32.
+ *
+ * \note AESNI is only supported with certain compilers and target options:
+ * - Visual Studio 2013: supported.
+ * - GCC, x86-64, target not explicitly supporting AESNI:
+ *   requires MBEDTLS_HAVE_ASM.
+ * - GCC, x86-32, target not explicitly supporting AESNI:
+ *   not supported.
+ * - GCC, x86-64 or x86-32, target supporting AESNI: supported.
+ *   For this assembly-less implementation, you must currently compile
+ *   `library/aesni.c` and `library/aes.c` with machine options to enable
+ *   SSE2 and AESNI instructions: `gcc -msse2 -maes -mpclmul` or
+ *   `clang -maes -mpclmul`.
+ * - Non-x86 targets: this option is silently ignored.
+ * - Other compilers: this option is silently ignored.
+ *
+ * \note
+ * Above, "GCC" includes compatible compilers such as Clang.
+ * The limitations on target support are likely to be relaxed in the future.
  *
  * Module:  library/aesni.c
  * Caller:  library/aes.c
  *
- * Requires: MBEDTLS_HAVE_ASM
+ * Requires: MBEDTLS_HAVE_ASM (on some platforms, see note)
  *
- * This module adds support for the AES-NI instructions on x86-64
+ * This modules adds support for the AES-NI instructions on x86.
  */
 #define MBEDTLS_AESNI_C
 
@@ -3781,7 +3803,7 @@
  */
 //#define MBEDTLS_SSL_DTLS_MAX_BUFFERING             32768
 
-//#define MBEDTLS_PSK_MAX_LEN               32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */
+//#define MBEDTLS_PSK_MAX_LEN               32 /**< Max size of TLS pre-shared keys, in bytes (default 256 or 384 bits) */
 //#define MBEDTLS_SSL_COOKIE_TIMEOUT        60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */
 
 /**
diff --git a/include/mbedtls/pk.h b/include/mbedtls/pk.h
index 3de7a8f..5d2cf34 100644
--- a/include/mbedtls/pk.h
+++ b/include/mbedtls/pk.h
@@ -197,6 +197,11 @@
 #define MBEDTLS_PK_CAN_ECDSA_SOME
 #endif
 
+#if (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_ECDH)) || \
+    (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C))
+#define MBEDTLS_PK_CAN_ECDH
+#endif
+
 /**
  * \brief           Types for interfacing with the debug module
  */
diff --git a/include/mbedtls/psa_util.h b/include/mbedtls/psa_util.h
index 6d5843d..b750716 100644
--- a/include/mbedtls/psa_util.h
+++ b/include/mbedtls/psa_util.h
@@ -388,8 +388,10 @@
 int psa_pk_status_to_mbedtls(psa_status_t status);
 
 /* Utility macro to shorten the defines of error translator in modules. */
-#define PSA_TO_MBEDTLS_ERR_LIST(status, error_list, fallback_f) \
-    psa_status_to_mbedtls(status, error_list, sizeof(error_list), fallback_f)
+#define PSA_TO_MBEDTLS_ERR_LIST(status, error_list, fallback_f)       \
+    psa_status_to_mbedtls(status, error_list,                         \
+                          sizeof(error_list)/sizeof(error_list[0]),   \
+                          fallback_f)
 
 #endif /* MBEDTLS_PSA_CRYPTO_C */
 #endif /* MBEDTLS_PSA_UTIL_H */
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
index efe0830..7d526a7 100644
--- a/include/mbedtls/ssl.h
+++ b/include/mbedtls/ssl.h
@@ -40,11 +40,7 @@
 #include "mbedtls/dhm.h"
 #endif
 
-/* Adding guard for MBEDTLS_ECDSA_C to ensure no compile errors due
- * to guards in TLS code. There is a gap in functionality that access to
- * ecdh_ctx structure is needed for MBEDTLS_ECDSA_C which does not seem correct.
- */
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
+#if defined(MBEDTLS_ECDH_C)
 #include "mbedtls/ecdh.h"
 #endif
 
@@ -601,8 +597,22 @@
  * Size defines
  */
 #if !defined(MBEDTLS_PSK_MAX_LEN)
-#define MBEDTLS_PSK_MAX_LEN            32 /* 256 bits */
+/*
+ * If the library supports TLS 1.3 tickets and the cipher suite
+ * TLS1-3-AES-256-GCM-SHA384, set the PSK maximum length to 48 instead of 32.
+ * That way, the TLS 1.3 client and server are able to resume sessions where
+ * the cipher suite is TLS1-3-AES-256-GCM-SHA384 (pre-shared keys are 48
+ * bytes long in that case).
+ */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
+    defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+    defined(MBEDTLS_AES_C) && defined(MBEDTLS_GCM_C) && \
+    defined(MBEDTLS_MD_CAN_SHA384)
+#define MBEDTLS_PSK_MAX_LEN 48 /* 384 bits */
+#else
+#define MBEDTLS_PSK_MAX_LEN 32 /* 256 bits */
 #endif
+#endif /* !MBEDTLS_PSK_MAX_LEN */
 
 /* Dummy type used only for its size */
 union mbedtls_ssl_premaster_secret {
@@ -1091,13 +1101,13 @@
 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) &&        \
     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN  48
-#if defined(MBEDTLS_SHA256_C)
+#if defined(MBEDTLS_MD_CAN_SHA256)
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA256
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN  32
-#elif defined(MBEDTLS_SHA384_C)
+#elif defined(MBEDTLS_MD_CAN_SHA384)
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA384
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN  48
-#elif defined(MBEDTLS_SHA1_C)
+#elif defined(MBEDTLS_MD_CAN_SHA1)
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA1
 #define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN  20
 #else
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index 06b0131..5359883 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -284,7 +284,7 @@
 if(USE_SHARED_MBEDTLS_LIBRARY)
     set(CMAKE_LIBRARY_PATH ${CMAKE_CURRENT_BINARY_DIR})
     add_library(${mbedcrypto_target} SHARED ${src_crypto})
-    set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 3.3.0 SOVERSION 13)
+    set_target_properties(${mbedcrypto_target} PROPERTIES VERSION 3.4.0 SOVERSION 14)
     target_link_libraries(${mbedcrypto_target} PUBLIC ${libs})
 
     if(TARGET everest)
@@ -292,11 +292,11 @@
     endif()
 
     add_library(${mbedx509_target} SHARED ${src_x509})
-    set_target_properties(${mbedx509_target} PROPERTIES VERSION 3.3.0 SOVERSION 4)
+    set_target_properties(${mbedx509_target} PROPERTIES VERSION 3.4.0 SOVERSION 5)
     target_link_libraries(${mbedx509_target} PUBLIC ${libs} ${mbedcrypto_target})
 
     add_library(${mbedtls_target} SHARED ${src_tls})
-    set_target_properties(${mbedtls_target} PROPERTIES VERSION 3.3.0 SOVERSION 19)
+    set_target_properties(${mbedtls_target} PROPERTIES VERSION 3.4.0 SOVERSION 19)
     target_link_libraries(${mbedtls_target} PUBLIC ${libs} ${mbedx509_target})
 endif(USE_SHARED_MBEDTLS_LIBRARY)
 
diff --git a/library/Makefile b/library/Makefile
index ceb9c0d..160aa6b 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -48,8 +48,8 @@
 endif
 
 SOEXT_TLS?=so.19
-SOEXT_X509?=so.4
-SOEXT_CRYPTO?=so.13
+SOEXT_X509?=so.5
+SOEXT_CRYPTO?=so.14
 
 # Set AR_DASH= (empty string) to use an ar implementation that does not accept
 # the - prefix for command line options (e.g. llvm-ar)
diff --git a/library/aes.c b/library/aes.c
index 64392fc..69da582 100644
--- a/library/aes.c
+++ b/library/aes.c
@@ -47,8 +47,7 @@
 
 #if !defined(MBEDTLS_AES_ALT)
 
-#if defined(MBEDTLS_PADLOCK_C) &&                      \
-    (defined(MBEDTLS_HAVE_X86) || defined(MBEDTLS_PADLOCK_ALIGN16))
+#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
 static int aes_padlock_ace = -1;
 #endif
 
@@ -505,6 +504,53 @@
 }
 #endif /* MBEDTLS_CIPHER_MODE_XTS */
 
+/* Some implementations need the round keys to be aligned.
+ * Return an offset to be added to buf, such that (buf + offset) is
+ * correctly aligned.
+ * Note that the offset is in units of elements of buf, i.e. 32-bit words,
+ * i.e. an offset of 1 means 4 bytes and so on.
+ */
+#if (defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)) ||        \
+    (defined(MBEDTLS_AESNI_C) && MBEDTLS_AESNI_HAVE_CODE == 2)
+#define MAY_NEED_TO_ALIGN
+#endif
+static unsigned mbedtls_aes_rk_offset(uint32_t *buf)
+{
+#if defined(MAY_NEED_TO_ALIGN)
+    int align_16_bytes = 0;
+
+#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
+    if (aes_padlock_ace == -1) {
+        aes_padlock_ace = mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE);
+    }
+    if (aes_padlock_ace) {
+        align_16_bytes = 1;
+    }
+#endif
+
+#if defined(MBEDTLS_AESNI_C) && MBEDTLS_AESNI_HAVE_CODE == 2
+    if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) {
+        align_16_bytes = 1;
+    }
+#endif
+
+    if (align_16_bytes) {
+        /* These implementations needs 16-byte alignment
+         * for the round key array. */
+        unsigned delta = ((uintptr_t) buf & 0x0000000fU) / 4;
+        if (delta == 0) {
+            return 0;
+        } else {
+            return 4 - delta; // 16 bytes = 4 uint32_t
+        }
+    }
+#else /* MAY_NEED_TO_ALIGN */
+    (void) buf;
+#endif /* MAY_NEED_TO_ALIGN */
+
+    return 0;
+}
+
 /*
  * AES key schedule (encryption)
  */
@@ -529,19 +575,10 @@
     }
 #endif
 
-    ctx->rk_offset = 0;
-#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)
-    if (aes_padlock_ace == -1) {
-        aes_padlock_ace = mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE);
-    }
-
-    if (aes_padlock_ace) {
-        ctx->rk_offset = MBEDTLS_PADLOCK_ALIGN16(ctx->buf) - ctx->buf;
-    }
-#endif
+    ctx->rk_offset = mbedtls_aes_rk_offset(ctx->buf);
     RK = ctx->buf + ctx->rk_offset;
 
-#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
     if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) {
         return mbedtls_aesni_setkey_enc((unsigned char *) RK, key, keybits);
     }
@@ -634,16 +671,7 @@
 
     mbedtls_aes_init(&cty);
 
-    ctx->rk_offset = 0;
-#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)
-    if (aes_padlock_ace == -1) {
-        aes_padlock_ace = mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE);
-    }
-
-    if (aes_padlock_ace) {
-        ctx->rk_offset = MBEDTLS_PADLOCK_ALIGN16(ctx->buf) - ctx->buf;
-    }
-#endif
+    ctx->rk_offset = mbedtls_aes_rk_offset(ctx->buf);
     RK = ctx->buf + ctx->rk_offset;
 
     /* Also checks keybits */
@@ -653,7 +681,7 @@
 
     ctx->nr = cty.nr;
 
-#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
     if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) {
         mbedtls_aesni_inverse_key((unsigned char *) RK,
                                   (const unsigned char *) (cty.buf + cty.rk_offset), ctx->nr);
@@ -945,6 +973,26 @@
 }
 #endif /* !MBEDTLS_AES_DECRYPT_ALT */
 
+#if defined(MAY_NEED_TO_ALIGN)
+/* VIA Padlock and our intrinsics-based implementation of AESNI require
+ * the round keys to be aligned on a 16-byte boundary. We take care of this
+ * before creating them, but the AES context may have moved (this can happen
+ * if the library is called from a language with managed memory), and in later
+ * calls it might have a different alignment with respect to 16-byte memory.
+ * So we may need to realign.
+ */
+static void aes_maybe_realign(mbedtls_aes_context *ctx)
+{
+    unsigned new_offset = mbedtls_aes_rk_offset(ctx->buf);
+    if (new_offset != ctx->rk_offset) {
+        memmove(ctx->buf + new_offset,     // new address
+                ctx->buf + ctx->rk_offset, // current address
+                (ctx->nr + 1) * 16);       // number of round keys * bytes per rk
+        ctx->rk_offset = new_offset;
+    }
+}
+#endif
+
 /*
  * AES-ECB block encryption/decryption
  */
@@ -957,7 +1005,11 @@
         return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
     }
 
-#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
+#if defined(MAY_NEED_TO_ALIGN)
+    aes_maybe_realign(ctx);
+#endif
+
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
     if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) {
         return mbedtls_aesni_crypt_ecb(ctx, mode, input, output);
     }
@@ -971,13 +1023,7 @@
 
 #if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
     if (aes_padlock_ace > 0) {
-        if (mbedtls_padlock_xcryptecb(ctx, mode, input, output) == 0) {
-            return 0;
-        }
-
-        // If padlock data misaligned, we just fall back to
-        // unaccelerated mode
-        //
+        return mbedtls_padlock_xcryptecb(ctx, mode, input, output);
     }
 #endif
 
@@ -1729,6 +1775,29 @@
     memset(key, 0, 32);
     mbedtls_aes_init(&ctx);
 
+    if (verbose != 0) {
+#if defined(MBEDTLS_AES_ALT)
+        mbedtls_printf("  AES note: alternative implementation.\n");
+#else /* MBEDTLS_AES_ALT */
+#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
+        if (mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE)) {
+            mbedtls_printf("  AES note: using VIA Padlock.\n");
+        } else
+#endif
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
+        if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) {
+            mbedtls_printf("  AES note: using AESNI.\n");
+        } else
+#endif
+#if defined(MBEDTLS_AESCE_C) && defined(MBEDTLS_HAVE_ARM64)
+        if (mbedtls_aesce_has_support()) {
+            mbedtls_printf("  AES note: using AESCE.\n");
+        } else
+#endif
+        mbedtls_printf("  AES note: built-in implementation.\n");
+#endif /* MBEDTLS_AES_ALT */
+    }
+
     /*
      * ECB mode
      */
diff --git a/library/aesni.c b/library/aesni.c
index f6b304d..a23c5b5 100644
--- a/library/aesni.c
+++ b/library/aesni.c
@@ -18,26 +18,26 @@
  */
 
 /*
- * [AES-WP] http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set
- * [CLMUL-WP] http://software.intel.com/en-us/articles/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode/
+ * [AES-WP] https://www.intel.com/content/www/us/en/developer/articles/tool/intel-advanced-encryption-standard-aes-instructions-set.html
+ * [CLMUL-WP] https://www.intel.com/content/www/us/en/develop/download/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode.html
  */
 
 #include "common.h"
 
 #if defined(MBEDTLS_AESNI_C)
 
-#if defined(__has_feature)
-#if __has_feature(memory_sanitizer)
-#warning \
-    "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code."
-#endif
-#endif
-
 #include "aesni.h"
 
 #include <string.h>
 
-#if defined(MBEDTLS_HAVE_X86_64)
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
+
+#if MBEDTLS_AESNI_HAVE_CODE == 2
+#if !defined(_WIN32)
+#include <cpuid.h>
+#endif
+#include <immintrin.h>
+#endif
 
 /*
  * AES-NI support detection routine
@@ -48,17 +48,355 @@
     static unsigned int c = 0;
 
     if (!done) {
+#if MBEDTLS_AESNI_HAVE_CODE == 2
+        static unsigned info[4] = { 0, 0, 0, 0 };
+#if defined(_MSC_VER)
+        __cpuid(info, 1);
+#else
+        __cpuid(1, info[0], info[1], info[2], info[3]);
+#endif
+        c = info[2];
+#else /* AESNI using asm */
         asm ("movl  $1, %%eax   \n\t"
              "cpuid             \n\t"
              : "=c" (c)
              :
              : "eax", "ebx", "edx");
+#endif /* MBEDTLS_AESNI_HAVE_CODE */
         done = 1;
     }
 
     return (c & what) != 0;
 }
 
+#if MBEDTLS_AESNI_HAVE_CODE == 2
+
+/*
+ * AES-NI AES-ECB block en(de)cryption
+ */
+int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx,
+                            int mode,
+                            const unsigned char input[16],
+                            unsigned char output[16])
+{
+    const __m128i *rk = (const __m128i *) (ctx->buf + ctx->rk_offset);
+    unsigned nr = ctx->nr; // Number of remaining rounds
+
+    // Load round key 0
+    __m128i state;
+    memcpy(&state, input, 16);
+    state = _mm_xor_si128(state, rk[0]);  // state ^= *rk;
+    ++rk;
+    --nr;
+
+    if (mode == 0) {
+        while (nr != 0) {
+            state = _mm_aesdec_si128(state, *rk);
+            ++rk;
+            --nr;
+        }
+        state = _mm_aesdeclast_si128(state, *rk);
+    } else {
+        while (nr != 0) {
+            state = _mm_aesenc_si128(state, *rk);
+            ++rk;
+            --nr;
+        }
+        state = _mm_aesenclast_si128(state, *rk);
+    }
+
+    memcpy(output, &state, 16);
+    return 0;
+}
+
+/*
+ * GCM multiplication: c = a times b in GF(2^128)
+ * Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5.
+ */
+
+static void gcm_clmul(const __m128i aa, const __m128i bb,
+                      __m128i *cc, __m128i *dd)
+{
+    /*
+     * Caryless multiplication dd:cc = aa * bb
+     * using [CLMUL-WP] algorithm 1 (p. 12).
+     */
+    *cc = _mm_clmulepi64_si128(aa, bb, 0x00); // a0*b0 = c1:c0
+    *dd = _mm_clmulepi64_si128(aa, bb, 0x11); // a1*b1 = d1:d0
+    __m128i ee = _mm_clmulepi64_si128(aa, bb, 0x10); // a0*b1 = e1:e0
+    __m128i ff = _mm_clmulepi64_si128(aa, bb, 0x01); // a1*b0 = f1:f0
+    ff = _mm_xor_si128(ff, ee);                      // e1+f1:e0+f0
+    ee = ff;                                         // e1+f1:e0+f0
+    ff = _mm_srli_si128(ff, 8);                      // 0:e1+f1
+    ee = _mm_slli_si128(ee, 8);                      // e0+f0:0
+    *dd = _mm_xor_si128(*dd, ff);                    // d1:d0+e1+f1
+    *cc = _mm_xor_si128(*cc, ee);                    // c1+e0+f0:c0
+}
+
+static void gcm_shift(__m128i *cc, __m128i *dd)
+{
+    /* [CMUCL-WP] Algorithm 5 Step 1: shift cc:dd one bit to the left,
+     * taking advantage of [CLMUL-WP] eq 27 (p. 18). */
+    //                                        // *cc = r1:r0
+    //                                        // *dd = r3:r2
+    __m128i cc_lo = _mm_slli_epi64(*cc, 1);   // r1<<1:r0<<1
+    __m128i dd_lo = _mm_slli_epi64(*dd, 1);   // r3<<1:r2<<1
+    __m128i cc_hi = _mm_srli_epi64(*cc, 63);  // r1>>63:r0>>63
+    __m128i dd_hi = _mm_srli_epi64(*dd, 63);  // r3>>63:r2>>63
+    __m128i xmm5 = _mm_srli_si128(cc_hi, 8);  // 0:r1>>63
+    cc_hi = _mm_slli_si128(cc_hi, 8);         // r0>>63:0
+    dd_hi = _mm_slli_si128(dd_hi, 8);         // 0:r1>>63
+
+    *cc = _mm_or_si128(cc_lo, cc_hi);         // r1<<1|r0>>63:r0<<1
+    *dd = _mm_or_si128(_mm_or_si128(dd_lo, dd_hi), xmm5); // r3<<1|r2>>62:r2<<1|r1>>63
+}
+
+static __m128i gcm_reduce(__m128i xx)
+{
+    //                                            // xx = x1:x0
+    /* [CLMUL-WP] Algorithm 5 Step 2 */
+    __m128i aa = _mm_slli_epi64(xx, 63);          // x1<<63:x0<<63 = stuff:a
+    __m128i bb = _mm_slli_epi64(xx, 62);          // x1<<62:x0<<62 = stuff:b
+    __m128i cc = _mm_slli_epi64(xx, 57);          // x1<<57:x0<<57 = stuff:c
+    __m128i dd = _mm_slli_si128(_mm_xor_si128(_mm_xor_si128(aa, bb), cc), 8); // a+b+c:0
+    return _mm_xor_si128(dd, xx);                 // x1+a+b+c:x0 = d:x0
+}
+
+static __m128i gcm_mix(__m128i dx)
+{
+    /* [CLMUL-WP] Algorithm 5 Steps 3 and 4 */
+    __m128i ee = _mm_srli_epi64(dx, 1);           // e1:x0>>1 = e1:e0'
+    __m128i ff = _mm_srli_epi64(dx, 2);           // f1:x0>>2 = f1:f0'
+    __m128i gg = _mm_srli_epi64(dx, 7);           // g1:x0>>7 = g1:g0'
+
+    // e0'+f0'+g0' is almost e0+f0+g0, except for some missing
+    // bits carried from d. Now get those bits back in.
+    __m128i eh = _mm_slli_epi64(dx, 63);          // d<<63:stuff
+    __m128i fh = _mm_slli_epi64(dx, 62);          // d<<62:stuff
+    __m128i gh = _mm_slli_epi64(dx, 57);          // d<<57:stuff
+    __m128i hh = _mm_srli_si128(_mm_xor_si128(_mm_xor_si128(eh, fh), gh), 8); // 0:missing bits of d
+
+    return _mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_xor_si128(ee, ff), gg), hh), dx);
+}
+
+void mbedtls_aesni_gcm_mult(unsigned char c[16],
+                            const unsigned char a[16],
+                            const unsigned char b[16])
+{
+    __m128i aa, bb, cc, dd;
+
+    /* The inputs are in big-endian order, so byte-reverse them */
+    for (size_t i = 0; i < 16; i++) {
+        ((uint8_t *) &aa)[i] = a[15 - i];
+        ((uint8_t *) &bb)[i] = b[15 - i];
+    }
+
+    gcm_clmul(aa, bb, &cc, &dd);
+    gcm_shift(&cc, &dd);
+    /*
+     * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1
+     * using [CLMUL-WP] algorithm 5 (p. 18).
+     * Currently dd:cc holds x3:x2:x1:x0 (already shifted).
+     */
+    __m128i dx = gcm_reduce(cc);
+    __m128i xh = gcm_mix(dx);
+    cc = _mm_xor_si128(xh, dd); // x3+h1:x2+h0
+
+    /* Now byte-reverse the outputs */
+    for (size_t i = 0; i < 16; i++) {
+        c[i] = ((uint8_t *) &cc)[15 - i];
+    }
+
+    return;
+}
+
+/*
+ * Compute decryption round keys from encryption round keys
+ */
+void mbedtls_aesni_inverse_key(unsigned char *invkey,
+                               const unsigned char *fwdkey, int nr)
+{
+    __m128i *ik = (__m128i *) invkey;
+    const __m128i *fk = (const __m128i *) fwdkey + nr;
+
+    *ik = *fk;
+    for (--fk, ++ik; fk > (const __m128i *) fwdkey; --fk, ++ik) {
+        *ik = _mm_aesimc_si128(*fk);
+    }
+    *ik = *fk;
+}
+
+/*
+ * Key expansion, 128-bit case
+ */
+static __m128i aesni_set_rk_128(__m128i state, __m128i xword)
+{
+    /*
+     * Finish generating the next round key.
+     *
+     * On entry state is r3:r2:r1:r0 and xword is X:stuff:stuff:stuff
+     * with X = rot( sub( r3 ) ) ^ RCON (obtained with AESKEYGENASSIST).
+     *
+     * On exit, xword is r7:r6:r5:r4
+     * with r4 = X + r0, r5 = r4 + r1, r6 = r5 + r2, r7 = r6 + r3
+     * and this is returned, to be written to the round key buffer.
+     */
+    xword = _mm_shuffle_epi32(xword, 0xff);   // X:X:X:X
+    xword = _mm_xor_si128(xword, state);      // X+r3:X+r2:X+r1:r4
+    state = _mm_slli_si128(state, 4);         // r2:r1:r0:0
+    xword = _mm_xor_si128(xword, state);      // X+r3+r2:X+r2+r1:r5:r4
+    state = _mm_slli_si128(state, 4);         // r1:r0:0:0
+    xword = _mm_xor_si128(xword, state);      // X+r3+r2+r1:r6:r5:r4
+    state = _mm_slli_si128(state, 4);         // r0:0:0:0
+    state = _mm_xor_si128(xword, state);      // r7:r6:r5:r4
+    return state;
+}
+
+static void aesni_setkey_enc_128(unsigned char *rk_bytes,
+                                 const unsigned char *key)
+{
+    __m128i *rk = (__m128i *) rk_bytes;
+
+    memcpy(&rk[0], key, 16);
+    rk[1] = aesni_set_rk_128(rk[0], _mm_aeskeygenassist_si128(rk[0], 0x01));
+    rk[2] = aesni_set_rk_128(rk[1], _mm_aeskeygenassist_si128(rk[1], 0x02));
+    rk[3] = aesni_set_rk_128(rk[2], _mm_aeskeygenassist_si128(rk[2], 0x04));
+    rk[4] = aesni_set_rk_128(rk[3], _mm_aeskeygenassist_si128(rk[3], 0x08));
+    rk[5] = aesni_set_rk_128(rk[4], _mm_aeskeygenassist_si128(rk[4], 0x10));
+    rk[6] = aesni_set_rk_128(rk[5], _mm_aeskeygenassist_si128(rk[5], 0x20));
+    rk[7] = aesni_set_rk_128(rk[6], _mm_aeskeygenassist_si128(rk[6], 0x40));
+    rk[8] = aesni_set_rk_128(rk[7], _mm_aeskeygenassist_si128(rk[7], 0x80));
+    rk[9] = aesni_set_rk_128(rk[8], _mm_aeskeygenassist_si128(rk[8], 0x1B));
+    rk[10] = aesni_set_rk_128(rk[9], _mm_aeskeygenassist_si128(rk[9], 0x36));
+}
+
+/*
+ * Key expansion, 192-bit case
+ */
+static void aesni_set_rk_192(__m128i *state0, __m128i *state1, __m128i xword,
+                             unsigned char *rk)
+{
+    /*
+     * Finish generating the next 6 quarter-keys.
+     *
+     * On entry state0 is r3:r2:r1:r0, state1 is stuff:stuff:r5:r4
+     * and xword is stuff:stuff:X:stuff with X = rot( sub( r3 ) ) ^ RCON
+     * (obtained with AESKEYGENASSIST).
+     *
+     * On exit, state0 is r9:r8:r7:r6 and state1 is stuff:stuff:r11:r10
+     * and those are written to the round key buffer.
+     */
+    xword = _mm_shuffle_epi32(xword, 0x55);   // X:X:X:X
+    xword = _mm_xor_si128(xword, *state0);    // X+r3:X+r2:X+r1:X+r0
+    *state0 = _mm_slli_si128(*state0, 4);     // r2:r1:r0:0
+    xword = _mm_xor_si128(xword, *state0);    // X+r3+r2:X+r2+r1:X+r1+r0:X+r0
+    *state0 = _mm_slli_si128(*state0, 4);     // r1:r0:0:0
+    xword = _mm_xor_si128(xword, *state0);    // X+r3+r2+r1:X+r2+r1+r0:X+r1+r0:X+r0
+    *state0 = _mm_slli_si128(*state0, 4);     // r0:0:0:0
+    xword = _mm_xor_si128(xword, *state0);    // X+r3+r2+r1+r0:X+r2+r1+r0:X+r1+r0:X+r0
+    *state0 = xword;                          // = r9:r8:r7:r6
+
+    xword = _mm_shuffle_epi32(xword, 0xff);   // r9:r9:r9:r9
+    xword = _mm_xor_si128(xword, *state1);    // stuff:stuff:r9+r5:r9+r4
+    *state1 = _mm_slli_si128(*state1, 4);     // stuff:stuff:r4:0
+    xword = _mm_xor_si128(xword, *state1);    // stuff:stuff:r9+r5+r4:r9+r4
+    *state1 = xword;                          // = stuff:stuff:r11:r10
+
+    /* Store state0 and the low half of state1 into rk, which is conceptually
+     * an array of 24-byte elements. Since 24 is not a multiple of 16,
+     * rk is not necessarily aligned so just `*rk = *state0` doesn't work. */
+    memcpy(rk, state0, 16);
+    memcpy(rk + 16, state1, 8);
+}
+
+static void aesni_setkey_enc_192(unsigned char *rk,
+                                 const unsigned char *key)
+{
+    /* First round: use original key */
+    memcpy(rk, key, 24);
+    /* aes.c guarantees that rk is aligned on a 16-byte boundary. */
+    __m128i state0 = ((__m128i *) rk)[0];
+    __m128i state1 = _mm_loadl_epi64(((__m128i *) rk) + 1);
+
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x01), rk + 24 * 1);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x02), rk + 24 * 2);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x04), rk + 24 * 3);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x08), rk + 24 * 4);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x10), rk + 24 * 5);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x20), rk + 24 * 6);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x40), rk + 24 * 7);
+    aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x80), rk + 24 * 8);
+}
+
+/*
+ * Key expansion, 256-bit case
+ */
+static void aesni_set_rk_256(__m128i state0, __m128i state1, __m128i xword,
+                             __m128i *rk0, __m128i *rk1)
+{
+    /*
+     * Finish generating the next two round keys.
+     *
+     * On entry state0 is r3:r2:r1:r0, state1 is r7:r6:r5:r4 and
+     * xword is X:stuff:stuff:stuff with X = rot( sub( r7 )) ^ RCON
+     * (obtained with AESKEYGENASSIST).
+     *
+     * On exit, *rk0 is r11:r10:r9:r8 and *rk1 is r15:r14:r13:r12
+     */
+    xword = _mm_shuffle_epi32(xword, 0xff);
+    xword = _mm_xor_si128(xword, state0);
+    state0 = _mm_slli_si128(state0, 4);
+    xword = _mm_xor_si128(xword, state0);
+    state0 = _mm_slli_si128(state0, 4);
+    xword = _mm_xor_si128(xword, state0);
+    state0 = _mm_slli_si128(state0, 4);
+    state0 = _mm_xor_si128(state0, xword);
+    *rk0 = state0;
+
+    /* Set xword to stuff:Y:stuff:stuff with Y = subword( r11 )
+     * and proceed to generate next round key from there */
+    xword = _mm_aeskeygenassist_si128(state0, 0x00);
+    xword = _mm_shuffle_epi32(xword, 0xaa);
+    xword = _mm_xor_si128(xword, state1);
+    state1 = _mm_slli_si128(state1, 4);
+    xword = _mm_xor_si128(xword, state1);
+    state1 = _mm_slli_si128(state1, 4);
+    xword = _mm_xor_si128(xword, state1);
+    state1 = _mm_slli_si128(state1, 4);
+    state1 = _mm_xor_si128(state1, xword);
+    *rk1 = state1;
+}
+
+static void aesni_setkey_enc_256(unsigned char *rk_bytes,
+                                 const unsigned char *key)
+{
+    __m128i *rk = (__m128i *) rk_bytes;
+
+    memcpy(&rk[0], key, 16);
+    memcpy(&rk[1], key + 16, 16);
+
+    /*
+     * Main "loop" - Generating one more key than necessary,
+     * see definition of mbedtls_aes_context.buf
+     */
+    aesni_set_rk_256(rk[0], rk[1], _mm_aeskeygenassist_si128(rk[1], 0x01), &rk[2], &rk[3]);
+    aesni_set_rk_256(rk[2], rk[3], _mm_aeskeygenassist_si128(rk[3], 0x02), &rk[4], &rk[5]);
+    aesni_set_rk_256(rk[4], rk[5], _mm_aeskeygenassist_si128(rk[5], 0x04), &rk[6], &rk[7]);
+    aesni_set_rk_256(rk[6], rk[7], _mm_aeskeygenassist_si128(rk[7], 0x08), &rk[8], &rk[9]);
+    aesni_set_rk_256(rk[8], rk[9], _mm_aeskeygenassist_si128(rk[9], 0x10), &rk[10], &rk[11]);
+    aesni_set_rk_256(rk[10], rk[11], _mm_aeskeygenassist_si128(rk[11], 0x20), &rk[12], &rk[13]);
+    aesni_set_rk_256(rk[12], rk[13], _mm_aeskeygenassist_si128(rk[13], 0x40), &rk[14], &rk[15]);
+}
+
+#else /* MBEDTLS_AESNI_HAVE_CODE == 1 */
+
+#if defined(__has_feature)
+#if __has_feature(memory_sanitizer)
+#warning \
+    "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code."
+#endif
+#endif
+
 /*
  * Binutils needs to be at least 2.19 to support AES-NI instructions.
  * Unfortunately, a lot of users have a lower version now (2014-04).
@@ -69,13 +407,13 @@
  * Operand macros are in gas order (src, dst) as opposed to Intel order
  * (dst, src) in order to blend better into the surrounding assembly code.
  */
-#define AESDEC      ".byte 0x66,0x0F,0x38,0xDE,"
-#define AESDECLAST  ".byte 0x66,0x0F,0x38,0xDF,"
-#define AESENC      ".byte 0x66,0x0F,0x38,0xDC,"
-#define AESENCLAST  ".byte 0x66,0x0F,0x38,0xDD,"
-#define AESIMC      ".byte 0x66,0x0F,0x38,0xDB,"
-#define AESKEYGENA  ".byte 0x66,0x0F,0x3A,0xDF,"
-#define PCLMULQDQ   ".byte 0x66,0x0F,0x3A,0x44,"
+#define AESDEC(regs)      ".byte 0x66,0x0F,0x38,0xDE," regs "\n\t"
+#define AESDECLAST(regs)  ".byte 0x66,0x0F,0x38,0xDF," regs "\n\t"
+#define AESENC(regs)      ".byte 0x66,0x0F,0x38,0xDC," regs "\n\t"
+#define AESENCLAST(regs)  ".byte 0x66,0x0F,0x38,0xDD," regs "\n\t"
+#define AESIMC(regs)      ".byte 0x66,0x0F,0x38,0xDB," regs "\n\t"
+#define AESKEYGENA(regs, imm)  ".byte 0x66,0x0F,0x3A,0xDF," regs "," imm "\n\t"
+#define PCLMULQDQ(regs, imm)   ".byte 0x66,0x0F,0x3A,0x44," regs "," imm "\n\t"
 
 #define xmm0_xmm0   "0xC0"
 #define xmm0_xmm1   "0xC8"
@@ -103,25 +441,25 @@
 
          "1:                        \n\t" // encryption loop
          "movdqu    (%1), %%xmm1    \n\t" // load round key
-         AESENC     xmm1_xmm0      "\n\t" // do round
-                                   "add       $16, %1         \n\t" // point to next round key
-                                   "subl      $1, %0          \n\t" // loop
-                                   "jnz       1b              \n\t"
-                                   "movdqu    (%1), %%xmm1    \n\t" // load round key
-         AESENCLAST xmm1_xmm0      "\n\t" // last round
-                                   "jmp       3f              \n\t"
+         AESENC(xmm1_xmm0)                // do round
+         "add       $16, %1         \n\t" // point to next round key
+         "subl      $1, %0          \n\t" // loop
+         "jnz       1b              \n\t"
+         "movdqu    (%1), %%xmm1    \n\t" // load round key
+         AESENCLAST(xmm1_xmm0)            // last round
+         "jmp       3f              \n\t"
 
-                                   "2:                        \n\t" // decryption loop
-                                   "movdqu    (%1), %%xmm1    \n\t"
-         AESDEC     xmm1_xmm0      "\n\t" // do round
-                                   "add       $16, %1         \n\t"
-                                   "subl      $1, %0          \n\t"
-                                   "jnz       2b              \n\t"
-                                   "movdqu    (%1), %%xmm1    \n\t" // load round key
-         AESDECLAST xmm1_xmm0      "\n\t" // last round
+         "2:                        \n\t" // decryption loop
+         "movdqu    (%1), %%xmm1    \n\t"
+         AESDEC(xmm1_xmm0)                // do round
+         "add       $16, %1         \n\t"
+         "subl      $1, %0          \n\t"
+         "jnz       2b              \n\t"
+         "movdqu    (%1), %%xmm1    \n\t" // load round key
+         AESDECLAST(xmm1_xmm0)            // last round
 
-                                   "3:                        \n\t"
-                                   "movdqu    %%xmm0, (%4)    \n\t" // export output
+         "3:                        \n\t"
+         "movdqu    %%xmm0, (%4)    \n\t" // export output
          :
          : "r" (ctx->nr), "r" (ctx->buf + ctx->rk_offset), "r" (mode), "r" (input), "r" (output)
          : "memory", "cc", "xmm0", "xmm1");
@@ -152,84 +490,84 @@
 
          /*
           * Caryless multiplication xmm2:xmm1 = xmm0 * xmm1
-          * using [CLMUL-WP] algorithm 1 (p. 13).
+          * using [CLMUL-WP] algorithm 1 (p. 12).
           */
          "movdqa %%xmm1, %%xmm2             \n\t" // copy of b1:b0
          "movdqa %%xmm1, %%xmm3             \n\t" // same
          "movdqa %%xmm1, %%xmm4             \n\t" // same
-         PCLMULQDQ xmm0_xmm1 ",0x00         \n\t" // a0*b0 = c1:c0
-         PCLMULQDQ xmm0_xmm2 ",0x11         \n\t" // a1*b1 = d1:d0
-         PCLMULQDQ xmm0_xmm3 ",0x10         \n\t" // a0*b1 = e1:e0
-         PCLMULQDQ xmm0_xmm4 ",0x01         \n\t" // a1*b0 = f1:f0
-                             "pxor %%xmm3, %%xmm4               \n\t" // e1+f1:e0+f0
-                             "movdqa %%xmm4, %%xmm3             \n\t" // same
-                             "psrldq $8, %%xmm4                 \n\t" // 0:e1+f1
-                             "pslldq $8, %%xmm3                 \n\t" // e0+f0:0
-                             "pxor %%xmm4, %%xmm2               \n\t" // d1:d0+e1+f1
-                             "pxor %%xmm3, %%xmm1               \n\t" // c1+e0+f1:c0
+         PCLMULQDQ(xmm0_xmm1, "0x00")             // a0*b0 = c1:c0
+         PCLMULQDQ(xmm0_xmm2, "0x11")             // a1*b1 = d1:d0
+         PCLMULQDQ(xmm0_xmm3, "0x10")             // a0*b1 = e1:e0
+         PCLMULQDQ(xmm0_xmm4, "0x01")             // a1*b0 = f1:f0
+         "pxor %%xmm3, %%xmm4               \n\t" // e1+f1:e0+f0
+         "movdqa %%xmm4, %%xmm3             \n\t" // same
+         "psrldq $8, %%xmm4                 \n\t" // 0:e1+f1
+         "pslldq $8, %%xmm3                 \n\t" // e0+f0:0
+         "pxor %%xmm4, %%xmm2               \n\t" // d1:d0+e1+f1
+         "pxor %%xmm3, %%xmm1               \n\t" // c1+e0+f1:c0
 
          /*
           * Now shift the result one bit to the left,
-          * taking advantage of [CLMUL-WP] eq 27 (p. 20)
+          * taking advantage of [CLMUL-WP] eq 27 (p. 18)
           */
-                             "movdqa %%xmm1, %%xmm3             \n\t" // r1:r0
-                             "movdqa %%xmm2, %%xmm4             \n\t" // r3:r2
-                             "psllq $1, %%xmm1                  \n\t" // r1<<1:r0<<1
-                             "psllq $1, %%xmm2                  \n\t" // r3<<1:r2<<1
-                             "psrlq $63, %%xmm3                 \n\t" // r1>>63:r0>>63
-                             "psrlq $63, %%xmm4                 \n\t" // r3>>63:r2>>63
-                             "movdqa %%xmm3, %%xmm5             \n\t" // r1>>63:r0>>63
-                             "pslldq $8, %%xmm3                 \n\t" // r0>>63:0
-                             "pslldq $8, %%xmm4                 \n\t" // r2>>63:0
-                             "psrldq $8, %%xmm5                 \n\t" // 0:r1>>63
-                             "por %%xmm3, %%xmm1                \n\t" // r1<<1|r0>>63:r0<<1
-                             "por %%xmm4, %%xmm2                \n\t" // r3<<1|r2>>62:r2<<1
-                             "por %%xmm5, %%xmm2                \n\t" // r3<<1|r2>>62:r2<<1|r1>>63
+         "movdqa %%xmm1, %%xmm3             \n\t" // r1:r0
+         "movdqa %%xmm2, %%xmm4             \n\t" // r3:r2
+         "psllq $1, %%xmm1                  \n\t" // r1<<1:r0<<1
+         "psllq $1, %%xmm2                  \n\t" // r3<<1:r2<<1
+         "psrlq $63, %%xmm3                 \n\t" // r1>>63:r0>>63
+         "psrlq $63, %%xmm4                 \n\t" // r3>>63:r2>>63
+         "movdqa %%xmm3, %%xmm5             \n\t" // r1>>63:r0>>63
+         "pslldq $8, %%xmm3                 \n\t" // r0>>63:0
+         "pslldq $8, %%xmm4                 \n\t" // r2>>63:0
+         "psrldq $8, %%xmm5                 \n\t" // 0:r1>>63
+         "por %%xmm3, %%xmm1                \n\t" // r1<<1|r0>>63:r0<<1
+         "por %%xmm4, %%xmm2                \n\t" // r3<<1|r2>>62:r2<<1
+         "por %%xmm5, %%xmm2                \n\t" // r3<<1|r2>>62:r2<<1|r1>>63
 
          /*
           * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1
-          * using [CLMUL-WP] algorithm 5 (p. 20).
+          * using [CLMUL-WP] algorithm 5 (p. 18).
           * Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted).
           */
          /* Step 2 (1) */
-                             "movdqa %%xmm1, %%xmm3             \n\t" // x1:x0
-                             "movdqa %%xmm1, %%xmm4             \n\t" // same
-                             "movdqa %%xmm1, %%xmm5             \n\t" // same
-                             "psllq $63, %%xmm3                 \n\t" // x1<<63:x0<<63 = stuff:a
-                             "psllq $62, %%xmm4                 \n\t" // x1<<62:x0<<62 = stuff:b
-                             "psllq $57, %%xmm5                 \n\t" // x1<<57:x0<<57 = stuff:c
+         "movdqa %%xmm1, %%xmm3             \n\t" // x1:x0
+         "movdqa %%xmm1, %%xmm4             \n\t" // same
+         "movdqa %%xmm1, %%xmm5             \n\t" // same
+         "psllq $63, %%xmm3                 \n\t" // x1<<63:x0<<63 = stuff:a
+         "psllq $62, %%xmm4                 \n\t" // x1<<62:x0<<62 = stuff:b
+         "psllq $57, %%xmm5                 \n\t" // x1<<57:x0<<57 = stuff:c
 
          /* Step 2 (2) */
-                             "pxor %%xmm4, %%xmm3               \n\t" // stuff:a+b
-                             "pxor %%xmm5, %%xmm3               \n\t" // stuff:a+b+c
-                             "pslldq $8, %%xmm3                 \n\t" // a+b+c:0
-                             "pxor %%xmm3, %%xmm1               \n\t" // x1+a+b+c:x0 = d:x0
+         "pxor %%xmm4, %%xmm3               \n\t" // stuff:a+b
+         "pxor %%xmm5, %%xmm3               \n\t" // stuff:a+b+c
+         "pslldq $8, %%xmm3                 \n\t" // a+b+c:0
+         "pxor %%xmm3, %%xmm1               \n\t" // x1+a+b+c:x0 = d:x0
 
          /* Steps 3 and 4 */
-                             "movdqa %%xmm1,%%xmm0              \n\t" // d:x0
-                             "movdqa %%xmm1,%%xmm4              \n\t" // same
-                             "movdqa %%xmm1,%%xmm5              \n\t" // same
-                             "psrlq $1, %%xmm0                  \n\t" // e1:x0>>1 = e1:e0'
-                             "psrlq $2, %%xmm4                  \n\t" // f1:x0>>2 = f1:f0'
-                             "psrlq $7, %%xmm5                  \n\t" // g1:x0>>7 = g1:g0'
-                             "pxor %%xmm4, %%xmm0               \n\t" // e1+f1:e0'+f0'
-                             "pxor %%xmm5, %%xmm0               \n\t" // e1+f1+g1:e0'+f0'+g0'
+         "movdqa %%xmm1,%%xmm0              \n\t" // d:x0
+         "movdqa %%xmm1,%%xmm4              \n\t" // same
+         "movdqa %%xmm1,%%xmm5              \n\t" // same
+         "psrlq $1, %%xmm0                  \n\t" // e1:x0>>1 = e1:e0'
+         "psrlq $2, %%xmm4                  \n\t" // f1:x0>>2 = f1:f0'
+         "psrlq $7, %%xmm5                  \n\t" // g1:x0>>7 = g1:g0'
+         "pxor %%xmm4, %%xmm0               \n\t" // e1+f1:e0'+f0'
+         "pxor %%xmm5, %%xmm0               \n\t" // e1+f1+g1:e0'+f0'+g0'
          // e0'+f0'+g0' is almost e0+f0+g0, ex\tcept for some missing
          // bits carried from d. Now get those\t bits back in.
-                             "movdqa %%xmm1,%%xmm3              \n\t" // d:x0
-                             "movdqa %%xmm1,%%xmm4              \n\t" // same
-                             "movdqa %%xmm1,%%xmm5              \n\t" // same
-                             "psllq $63, %%xmm3                 \n\t" // d<<63:stuff
-                             "psllq $62, %%xmm4                 \n\t" // d<<62:stuff
-                             "psllq $57, %%xmm5                 \n\t" // d<<57:stuff
-                             "pxor %%xmm4, %%xmm3               \n\t" // d<<63+d<<62:stuff
-                             "pxor %%xmm5, %%xmm3               \n\t" // missing bits of d:stuff
-                             "psrldq $8, %%xmm3                 \n\t" // 0:missing bits of d
-                             "pxor %%xmm3, %%xmm0               \n\t" // e1+f1+g1:e0+f0+g0
-                             "pxor %%xmm1, %%xmm0               \n\t" // h1:h0
-                             "pxor %%xmm2, %%xmm0               \n\t" // x3+h1:x2+h0
+         "movdqa %%xmm1,%%xmm3              \n\t" // d:x0
+         "movdqa %%xmm1,%%xmm4              \n\t" // same
+         "movdqa %%xmm1,%%xmm5              \n\t" // same
+         "psllq $63, %%xmm3                 \n\t" // d<<63:stuff
+         "psllq $62, %%xmm4                 \n\t" // d<<62:stuff
+         "psllq $57, %%xmm5                 \n\t" // d<<57:stuff
+         "pxor %%xmm4, %%xmm3               \n\t" // d<<63+d<<62:stuff
+         "pxor %%xmm5, %%xmm3               \n\t" // missing bits of d:stuff
+         "psrldq $8, %%xmm3                 \n\t" // 0:missing bits of d
+         "pxor %%xmm3, %%xmm0               \n\t" // e1+f1+g1:e0+f0+g0
+         "pxor %%xmm1, %%xmm0               \n\t" // h1:h0
+         "pxor %%xmm2, %%xmm0               \n\t" // x3+h1:x2+h0
 
-                             "movdqu %%xmm0, (%2)               \n\t" // done
+         "movdqu %%xmm0, (%2)               \n\t" // done
          :
          : "r" (aa), "r" (bb), "r" (cc)
          : "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5");
@@ -255,8 +593,8 @@
 
     for (fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16) {
         asm ("movdqu (%0), %%xmm0       \n\t"
-             AESIMC  xmm0_xmm0         "\n\t"
-                                       "movdqu %%xmm0, (%1)       \n\t"
+             AESIMC(xmm0_xmm0)
+             "movdqu %%xmm0, (%1)       \n\t"
              :
              : "r" (fk), "r" (ik)
              : "memory", "xmm0");
@@ -300,16 +638,16 @@
 
          /* Main "loop" */
          "2:                                \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x01        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x02        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x04        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x08        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x10        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x20        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x40        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x80        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x1B        \n\tcall 1b \n\t"
-         AESKEYGENA xmm0_xmm1 ",0x36        \n\tcall 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x01")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x02")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x04")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x08")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x10")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x20")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x40")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x80")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x1B")      "call 1b \n\t"
+         AESKEYGENA(xmm0_xmm1, "0x36")      "call 1b \n\t"
          :
          : "r" (rk), "r" (key)
          : "memory", "cc", "0");
@@ -358,14 +696,14 @@
          "ret                           \n\t"
 
          "2:                            \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x01    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x02    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x04    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x08    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x10    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x20    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x40    \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x80    \n\tcall 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x01")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x02")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x04")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x08")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x10")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x20")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x40")  "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x80")  "call 1b \n\t"
 
          :
          : "r" (rk), "r" (key)
@@ -408,36 +746,38 @@
 
          /* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 )
           * and proceed to generate next round key from there */
-         AESKEYGENA xmm0_xmm2 ",0x00        \n\t"
-                              "pshufd $0xaa, %%xmm2, %%xmm2      \n\t"
-                              "pxor %%xmm1, %%xmm2               \n\t"
-                              "pslldq $4, %%xmm1                 \n\t"
-                              "pxor %%xmm1, %%xmm2               \n\t"
-                              "pslldq $4, %%xmm1                 \n\t"
-                              "pxor %%xmm1, %%xmm2               \n\t"
-                              "pslldq $4, %%xmm1                 \n\t"
-                              "pxor %%xmm2, %%xmm1               \n\t"
-                              "add $16, %0                       \n\t"
-                              "movdqu %%xmm1, (%0)               \n\t"
-                              "ret                               \n\t"
+         AESKEYGENA(xmm0_xmm2, "0x00")
+         "pshufd $0xaa, %%xmm2, %%xmm2      \n\t"
+         "pxor %%xmm1, %%xmm2               \n\t"
+         "pslldq $4, %%xmm1                 \n\t"
+         "pxor %%xmm1, %%xmm2               \n\t"
+         "pslldq $4, %%xmm1                 \n\t"
+         "pxor %%xmm1, %%xmm2               \n\t"
+         "pslldq $4, %%xmm1                 \n\t"
+         "pxor %%xmm2, %%xmm1               \n\t"
+         "add $16, %0                       \n\t"
+         "movdqu %%xmm1, (%0)               \n\t"
+         "ret                               \n\t"
 
          /*
           * Main "loop" - Generating one more key than necessary,
           * see definition of mbedtls_aes_context.buf
           */
-                              "2:                                \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x01        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x02        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x04        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x08        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x10        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x20        \n\tcall 1b \n\t"
-         AESKEYGENA xmm1_xmm2 ",0x40        \n\tcall 1b \n\t"
+         "2:                                \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x01")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x02")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x04")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x08")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x10")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x20")      "call 1b \n\t"
+         AESKEYGENA(xmm1_xmm2, "0x40")      "call 1b \n\t"
          :
          : "r" (rk), "r" (key)
          : "memory", "cc", "0");
 }
 
+#endif  /* MBEDTLS_AESNI_HAVE_CODE */
+
 /*
  * Key expansion, wrapper
  */
@@ -455,6 +795,6 @@
     return 0;
 }
 
-#endif /* MBEDTLS_HAVE_X86_64 */
+#endif /* MBEDTLS_AESNI_HAVE_CODE */
 
 #endif /* MBEDTLS_AESNI_C */
diff --git a/library/aesni.h b/library/aesni.h
index a842fb7..51b770f 100644
--- a/library/aesni.h
+++ b/library/aesni.h
@@ -32,13 +32,46 @@
 #define MBEDTLS_AESNI_AES      0x02000000u
 #define MBEDTLS_AESNI_CLMUL    0x00000002u
 
-#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) &&  \
+/* Can we do AESNI with inline assembly?
+ * (Only implemented with gas syntax, only for 64-bit.)
+ */
+#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && \
     (defined(__amd64__) || defined(__x86_64__))   &&  \
     !defined(MBEDTLS_HAVE_X86_64)
 #define MBEDTLS_HAVE_X86_64
 #endif
 
+#if defined(MBEDTLS_AESNI_C)
+
+/* Can we do AESNI with intrinsics?
+ * (Only implemented with certain compilers, only for certain targets.)
+ */
+#undef MBEDTLS_AESNI_HAVE_INTRINSICS
+#if defined(_MSC_VER)
+/* Visual Studio supports AESNI intrinsics since VS 2008 SP1. We only support
+ * VS 2013 and up for other reasons anyway, so no need to check the version. */
+#define MBEDTLS_AESNI_HAVE_INTRINSICS
+#endif
+/* GCC-like compilers: currently, we only support intrinsics if the requisite
+ * target flag is enabled when building the library (e.g. `gcc -mpclmul -msse2`
+ * or `clang -maes -mpclmul`). */
+#if defined(__GNUC__) && defined(__AES__) && defined(__PCLMUL__)
+#define MBEDTLS_AESNI_HAVE_INTRINSICS
+#endif
+
+/* Choose the implementation of AESNI, if one is available. */
+#undef MBEDTLS_AESNI_HAVE_CODE
+/* To minimize disruption when releasing the intrinsics-based implementation,
+ * favor the assembly-based implementation if it's available. We intend to
+ * revise this in a later release of Mbed TLS 3.x. In the long run, we will
+ * likely remove the assembly implementation. */
 #if defined(MBEDTLS_HAVE_X86_64)
+#define MBEDTLS_AESNI_HAVE_CODE 1 // via assembly
+#elif defined(MBEDTLS_AESNI_HAVE_INTRINSICS)
+#define MBEDTLS_AESNI_HAVE_CODE 2 // via intrinsics
+#endif
+
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
 
 #ifdef __cplusplus
 extern "C" {
@@ -127,6 +160,7 @@
 }
 #endif
 
-#endif /* MBEDTLS_HAVE_X86_64 */
+#endif /* MBEDTLS_AESNI_HAVE_CODE */
+#endif  /* MBEDTLS_AESNI_C */
 
 #endif /* MBEDTLS_AESNI_H */
diff --git a/library/ecp_curves.c b/library/ecp_curves.c
index db21d7d..6ee3d6c 100644
--- a/library/ecp_curves.c
+++ b/library/ecp_curves.c
@@ -4585,6 +4585,8 @@
 #endif
 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
 static int ecp_mod_p384(mbedtls_mpi *);
+MBEDTLS_STATIC_TESTABLE
+int mbedtls_ecp_mod_p384_raw(mbedtls_mpi_uint *X, size_t X_limbs);
 #endif
 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
 static int ecp_mod_p521(mbedtls_mpi *);
@@ -5181,6 +5183,102 @@
 
 #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
 
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+/*
+ * Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)
+ */
+static int ecp_mod_p384(mbedtls_mpi *N)
+{
+    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+    size_t expected_width = 2 * ((384 + biL - 1) / biL);
+    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(N, expected_width));
+    ret = mbedtls_ecp_mod_p384_raw(N->p, expected_width);
+cleanup:
+    return ret;
+}
+
+MBEDTLS_STATIC_TESTABLE
+int mbedtls_ecp_mod_p384_raw(mbedtls_mpi_uint *X, size_t X_limbs)
+{
+    if (X_limbs != 2*((384 + biL - 1)/biL)) {
+        return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
+    }
+
+    INIT(384);
+
+    ADD(12); ADD(21); ADD(20);
+    SUB(23);                                                NEXT; // A0
+
+    ADD(13); ADD(22); ADD(23);
+    SUB(12); SUB(20);                                       NEXT; // A1
+
+    ADD(14); ADD(23);
+    SUB(13); SUB(21);                                       NEXT; // A2
+
+    ADD(15); ADD(12); ADD(20); ADD(21);
+    SUB(14); SUB(22); SUB(23);                              NEXT; // A3
+
+    ADD(21); ADD(21); ADD(16); ADD(13); ADD(12); ADD(20); ADD(22);
+    SUB(15); SUB(23); SUB(23);                              NEXT; // A4
+
+    ADD(22); ADD(22); ADD(17); ADD(14); ADD(13); ADD(21); ADD(23);
+    SUB(16);                                                NEXT; // A5
+
+    ADD(23); ADD(23); ADD(18); ADD(15); ADD(14); ADD(22);
+    SUB(17);                                                NEXT; // A6
+
+    ADD(19); ADD(16); ADD(15); ADD(23);
+    SUB(18);                                                NEXT; // A7
+
+    ADD(20); ADD(17); ADD(16);
+    SUB(19);                                                NEXT; // A8
+
+    ADD(21); ADD(18); ADD(17);
+    SUB(20);                                                NEXT; // A9
+
+    ADD(22); ADD(19); ADD(18);
+    SUB(21);                                                NEXT; // A10
+
+    ADD(23); ADD(20); ADD(19);
+    SUB(22);                                                      // A11
+
+    RESET;
+
+    /* Use 2^384 = P + 2^128 + 2^96 - 2^32 + 1 to modulo reduce the final carry */
+    ADD_LAST; NEXT;                                               // A0
+    SUB_LAST; NEXT;                                               // A1
+    ;         NEXT;                                               // A2
+    ADD_LAST; NEXT;                                               // A3
+    ADD_LAST; NEXT;                                               // A4
+    ;         NEXT;                                               // A5
+    ;         NEXT;                                               // A6
+    ;         NEXT;                                               // A7
+    ;         NEXT;                                               // A8
+    ;         NEXT;                                               // A9
+    ;         NEXT;                                               // A10
+                                                                  // A11
+
+    RESET;
+
+    ADD_LAST; NEXT;                                               // A0
+    SUB_LAST; NEXT;                                               // A1
+    ;         NEXT;                                               // A2
+    ADD_LAST; NEXT;                                               // A3
+    ADD_LAST; NEXT;                                               // A4
+    ;         NEXT;                                               // A5
+    ;         NEXT;                                               // A6
+    ;         NEXT;                                               // A7
+    ;         NEXT;                                               // A8
+    ;         NEXT;                                               // A9
+    ;         NEXT;                                               // A10
+                                                                  // A11
+
+    LAST;
+
+    return 0;
+}
+#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
+
 #undef LOAD32
 #undef MAX32
 #undef A
@@ -5201,96 +5299,7 @@
           MBEDTLS_ECP_DP_SECP256R1_ENABLED ||
           MBEDTLS_ECP_DP_SECP384R1_ENABLED */
 
-#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
-/*
- * The reader is advised to first understand ecp_mod_p192() since the same
- * general structure is used here, but with additional complications:
- * (1) chunks of 32 bits, and (2) subtractions.
- */
-
-/*
- * For these primes, we need to handle data in chunks of 32 bits.
- * This makes it more complicated if we use 64 bits limbs in MPI,
- * which prevents us from using a uniform access method as for p192.
- *
- * So, we define a mini abstraction layer to access 32 bit chunks,
- * load them in 'cur' for work, and store them back from 'cur' when done.
- *
- * While at it, also define the size of N in terms of 32-bit chunks.
- */
-#define LOAD32      cur = A(i);
-
-#if defined(MBEDTLS_HAVE_INT32)  /* 32 bit */
-
-#define MAX32       N->n
-#define A(j)      N->p[j]
-#define STORE32     N->p[i] = cur;
-
-#else                               /* 64-bit */
-
-#define MAX32       N->n * 2
-#define A(j) (j) % 2 ? (uint32_t) (N->p[(j)/2] >> 32) : \
-    (uint32_t) (N->p[(j)/2])
-#define STORE32                                   \
-    if (i % 2) {                                 \
-        N->p[i/2] &= 0x00000000FFFFFFFF;          \
-        N->p[i/2] |= ((mbedtls_mpi_uint) cur) << 32;        \
-    } else {                                      \
-        N->p[i/2] &= 0xFFFFFFFF00000000;          \
-        N->p[i/2] |= (mbedtls_mpi_uint) cur;                \
-    }
-
-#endif /* sizeof( mbedtls_mpi_uint ) */
-
-/*
- * Helpers for addition and subtraction of chunks, with signed carry.
- */
-static inline void add32(uint32_t *dst, uint32_t src, signed char *carry)
-{
-    *dst += src;
-    *carry += (*dst < src);
-}
-
-static inline void sub32(uint32_t *dst, uint32_t src, signed char *carry)
-{
-    *carry -= (*dst < src);
-    *dst -= src;
-}
-
-#define ADD(j)    add32(&cur, A(j), &c);
-#define SUB(j)    sub32(&cur, A(j), &c);
-
-/*
- * Helpers for the main 'loop'
- */
-#define INIT(b)                                                       \
-    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;                    \
-    signed char c = 0, cc;                                              \
-    uint32_t cur;                                                       \
-    size_t i = 0, bits = (b);                                           \
-    /* N is the size of the product of two b-bit numbers, plus one */   \
-    /* limb for fix_negative */                                         \
-    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(N, (b) * 2 / biL + 1));      \
-    LOAD32;
-
-#define NEXT                    \
-    STORE32; i++; LOAD32;       \
-    cc = c; c = 0;              \
-    if (cc < 0)                \
-    sub32(&cur, -cc, &c); \
-    else                        \
-    add32(&cur, cc, &c);  \
-
-#define LAST                                    \
-    STORE32; i++;                               \
-    cur = c > 0 ? c : 0; STORE32;               \
-    cur = 0; while (++i < MAX32) { STORE32; }  \
-    if (c < 0) mbedtls_ecp_fix_negative(N, c, bits);
-
-/*
- * If the result is negative, we get it in the form
- * c * 2^bits + N, with c negative and N positive shorter than 'bits'
- */
+#if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_ECP_C)
 MBEDTLS_STATIC_TESTABLE
 void mbedtls_ecp_fix_negative(mbedtls_mpi *N, signed char c, size_t bits)
 {
@@ -5321,66 +5330,7 @@
 #endif
     N->p[bits / 8 / sizeof(mbedtls_mpi_uint)] += msw;
 }
-
-#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
-/*
- * Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)
- */
-static int ecp_mod_p384(mbedtls_mpi *N)
-{
-    INIT(384);
-
-    ADD(12); ADD(21); ADD(20);
-    SUB(23);                                              NEXT;   // A0
-
-    ADD(13); ADD(22); ADD(23);
-    SUB(12); SUB(20);                                   NEXT;     // A2
-
-    ADD(14); ADD(23);
-    SUB(13); SUB(21);                                   NEXT;     // A2
-
-    ADD(15); ADD(12); ADD(20); ADD(21);
-    SUB(14); SUB(22); SUB(23);                        NEXT;       // A3
-
-    ADD(21); ADD(21); ADD(16); ADD(13); ADD(12); ADD(20); ADD(22);
-    SUB(15); SUB(23); SUB(23);                        NEXT;       // A4
-
-    ADD(22); ADD(22); ADD(17); ADD(14); ADD(13); ADD(21); ADD(23);
-    SUB(16);                                              NEXT;   // A5
-
-    ADD(23); ADD(23); ADD(18); ADD(15); ADD(14); ADD(22);
-    SUB(17);                                              NEXT;   // A6
-
-    ADD(19); ADD(16); ADD(15); ADD(23);
-    SUB(18);                                              NEXT;   // A7
-
-    ADD(20); ADD(17); ADD(16);
-    SUB(19);                                              NEXT;   // A8
-
-    ADD(21); ADD(18); ADD(17);
-    SUB(20);                                              NEXT;   // A9
-
-    ADD(22); ADD(19); ADD(18);
-    SUB(21);                                              NEXT;   // A10
-
-    ADD(23); ADD(20); ADD(19);
-    SUB(22);                                              LAST;   // A11
-
-cleanup:
-    return ret;
-}
-#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
-
-#undef A
-#undef LOAD32
-#undef STORE32
-#undef MAX32
-#undef INIT
-#undef NEXT
-#undef LAST
-
-#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED ||
-          MBEDTLS_ECP_DP_SECP384R1_ENABLED */
+#endif /* MBEDTLS_TEST_HOOKS & MBEDTLS_ECP_C */
 
 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
 /* Size of p521 in terms of mbedtls_mpi_uint */
diff --git a/library/ecp_invasive.h b/library/ecp_invasive.h
index cb16d23..05522b6 100644
--- a/library/ecp_invasive.h
+++ b/library/ecp_invasive.h
@@ -160,6 +160,28 @@
 
 #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
 
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+
+/** Fast quasi-reduction modulo p384 (FIPS 186-3 D.2.4)
+ *
+ * \param[in,out]   X       The address of the MPI to be converted.
+ *                          Must have exact limb size that stores a 768-bit MPI
+ *                          (double the bitlength of the modulus).
+ *                          Upon return holds the reduced value which is
+ *                          in range `0 <= X < 2 * N` (where N is the modulus).
+ *                          The bitlength of the reduced value is the same as
+ *                          that of the modulus (384 bits).
+ * \param[in]       X_limbs The length of \p N in limbs.
+ *
+ * \return          \c 0 on success.
+ * \return          #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if \p N_n does not have
+ *                  twice as many limbs as the modulus.
+ */
+MBEDTLS_STATIC_TESTABLE
+int  mbedtls_ecp_mod_p384_raw(mbedtls_mpi_uint *X, size_t X_limbs);
+
+#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
+
 /** Initialise a modulus with hard-coded const curve data.
  *
  * \note            The caller is responsible for the \p N modulus' memory.
diff --git a/library/entropy.c b/library/entropy.c
index e55410c..0007917 100644
--- a/library/entropy.c
+++ b/library/entropy.c
@@ -34,9 +34,6 @@
 
 #include "mbedtls/platform.h"
 
-#include "mbedtls/platform.h"
-
-
 #define ENTROPY_MAX_LOOP    256     /**< Maximum amount to loop before error */
 
 void mbedtls_entropy_init(mbedtls_entropy_context *ctx)
@@ -49,11 +46,7 @@
 #endif
 
     ctx->accumulator_started = 0;
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_init(&ctx->accumulator);
-#else
-    mbedtls_sha256_init(&ctx->accumulator);
-#endif
+    mbedtls_md_init(&ctx->accumulator);
 
     /* Reminder: Update ENTROPY_HAVE_STRONG in the test files
      *           when adding more strong entropy sources here. */
@@ -89,11 +82,7 @@
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_mutex_free(&ctx->mutex);
 #endif
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_free(&ctx->accumulator);
-#else
-    mbedtls_sha256_free(&ctx->accumulator);
-#endif
+    mbedtls_md_free(&ctx->accumulator);
 #if defined(MBEDTLS_ENTROPY_NV_SEED)
     ctx->initial_entropy_run = 0;
 #endif
@@ -150,15 +139,10 @@
     int ret = 0;
 
     if (use_len > MBEDTLS_ENTROPY_BLOCK_SIZE) {
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-        if ((ret = mbedtls_sha512(data, len, tmp, 0)) != 0) {
+        if ((ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_ENTROPY_MD),
+                              data, len, tmp)) != 0) {
             goto cleanup;
         }
-#else
-        if ((ret = mbedtls_sha256(data, len, tmp, 0)) != 0) {
-            goto cleanup;
-        }
-#endif
         p = tmp;
         use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
     }
@@ -171,29 +155,22 @@
      * it is sufficient to start the accumulator here only because all calls to
      * gather entropy eventually execute this code.
      */
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    if (ctx->accumulator_started == 0 &&
-        (ret = mbedtls_sha512_starts(&ctx->accumulator, 0)) != 0) {
-        goto cleanup;
-    } else {
+    if (ctx->accumulator_started == 0) {
+        ret = mbedtls_md_setup(&ctx->accumulator,
+                               mbedtls_md_info_from_type(MBEDTLS_ENTROPY_MD), 0);
+        if (ret != 0) {
+            goto cleanup;
+        }
+        ret = mbedtls_md_starts(&ctx->accumulator);
+        if (ret != 0) {
+            goto cleanup;
+        }
         ctx->accumulator_started = 1;
     }
-    if ((ret = mbedtls_sha512_update(&ctx->accumulator, header, 2)) != 0) {
+    if ((ret = mbedtls_md_update(&ctx->accumulator, header, 2)) != 0) {
         goto cleanup;
     }
-    ret = mbedtls_sha512_update(&ctx->accumulator, p, use_len);
-#else
-    if (ctx->accumulator_started == 0 &&
-        (ret = mbedtls_sha256_starts(&ctx->accumulator, 0)) != 0) {
-        goto cleanup;
-    } else {
-        ctx->accumulator_started = 1;
-    }
-    if ((ret = mbedtls_sha256_update(&ctx->accumulator, header, 2)) != 0) {
-        goto cleanup;
-    }
-    ret = mbedtls_sha256_update(&ctx->accumulator, p, use_len);
-#endif
+    ret = mbedtls_md_update(&ctx->accumulator, p, use_len);
 
 cleanup:
     mbedtls_platform_zeroize(tmp, sizeof(tmp));
@@ -354,62 +331,41 @@
 
     memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
 
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
     /*
      * Note that at this stage it is assumed that the accumulator was started
      * in a previous call to entropy_update(). If this is not guaranteed, the
      * code below will fail.
      */
-    if ((ret = mbedtls_sha512_finish(&ctx->accumulator, buf)) != 0) {
+    if ((ret = mbedtls_md_finish(&ctx->accumulator, buf)) != 0) {
         goto exit;
     }
 
     /*
      * Reset accumulator and counters and recycle existing entropy
      */
-    mbedtls_sha512_free(&ctx->accumulator);
-    mbedtls_sha512_init(&ctx->accumulator);
-    if ((ret = mbedtls_sha512_starts(&ctx->accumulator, 0)) != 0) {
+    mbedtls_md_free(&ctx->accumulator);
+    mbedtls_md_init(&ctx->accumulator);
+    ret = mbedtls_md_setup(&ctx->accumulator,
+                           mbedtls_md_info_from_type(MBEDTLS_ENTROPY_MD), 0);
+    if (ret != 0) {
         goto exit;
     }
-    if ((ret = mbedtls_sha512_update(&ctx->accumulator, buf,
-                                     MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
+    ret = mbedtls_md_starts(&ctx->accumulator);
+    if (ret != 0) {
+        goto exit;
+    }
+    if ((ret = mbedtls_md_update(&ctx->accumulator, buf,
+                                 MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
         goto exit;
     }
 
     /*
-     * Perform second SHA-512 on entropy
+     * Perform second hashing on entropy
      */
-    if ((ret = mbedtls_sha512(buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
-                              buf, 0)) != 0) {
+    if ((ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_ENTROPY_MD),
+                          buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf)) != 0) {
         goto exit;
     }
-#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
-    if ((ret = mbedtls_sha256_finish(&ctx->accumulator, buf)) != 0) {
-        goto exit;
-    }
-
-    /*
-     * Reset accumulator and counters and recycle existing entropy
-     */
-    mbedtls_sha256_free(&ctx->accumulator);
-    mbedtls_sha256_init(&ctx->accumulator);
-    if ((ret = mbedtls_sha256_starts(&ctx->accumulator, 0)) != 0) {
-        goto exit;
-    }
-    if ((ret = mbedtls_sha256_update(&ctx->accumulator, buf,
-                                     MBEDTLS_ENTROPY_BLOCK_SIZE)) != 0) {
-        goto exit;
-    }
-
-    /*
-     * Perform second SHA-256 on entropy
-     */
-    if ((ret = mbedtls_sha256(buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
-                              buf, 0)) != 0) {
-        goto exit;
-    }
-#endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 
     for (i = 0; i < ctx->source_count; i++) {
         ctx->source[i].size = 0;
diff --git a/library/gcm.c b/library/gcm.c
index 14886bd..71fcc35 100644
--- a/library/gcm.c
+++ b/library/gcm.c
@@ -90,7 +90,7 @@
     ctx->HL[8] = vl;
     ctx->HH[8] = vh;
 
-#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
     /* With CLMUL support, we need only h, not the rest of the table */
     if (mbedtls_aesni_has_support(MBEDTLS_AESNI_CLMUL)) {
         return 0;
@@ -193,7 +193,7 @@
     unsigned char lo, hi, rem;
     uint64_t zh, zl;
 
-#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
     if (mbedtls_aesni_has_support(MBEDTLS_AESNI_CLMUL)) {
         unsigned char h[16];
 
@@ -206,7 +206,7 @@
         mbedtls_aesni_gcm_mult(output, x, h);
         return;
     }
-#endif /* MBEDTLS_AESNI_C && MBEDTLS_HAVE_X86_64 */
+#endif /* MBEDTLS_AESNI_HAVE_CODE */
 
 #if defined(MBEDTLS_AESCE_C) && defined(MBEDTLS_HAVE_ARM64)
     if (mbedtls_aesce_has_support()) {
@@ -871,6 +871,19 @@
     mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
     size_t olen;
 
+    if (verbose != 0) {
+#if defined(MBEDTLS_GCM_ALT)
+        mbedtls_printf("  GCM note: alternative implementation.\n");
+#else /* MBEDTLS_GCM_ALT */
+#if defined(MBEDTLS_AESNI_HAVE_CODE)
+        if (mbedtls_aesni_has_support(MBEDTLS_AESNI_CLMUL)) {
+            mbedtls_printf("  GCM note: using AESNI.\n");
+        } else
+#endif
+        mbedtls_printf("  GCM note: built-in implementation.\n");
+#endif /* MBEDTLS_GCM_ALT */
+    }
+
     for (j = 0; j < 3; j++) {
         int key_len = 128 + 64 * j;
 
diff --git a/library/hmac_drbg.c b/library/hmac_drbg.c
index b157302..af205aa 100644
--- a/library/hmac_drbg.c
+++ b/library/hmac_drbg.c
@@ -510,7 +510,7 @@
 
 #if defined(MBEDTLS_SELF_TEST)
 
-#if !defined(MBEDTLS_SHA1_C)
+#if !defined(MBEDTLS_MD_CAN_SHA1)
 /* Dummy checkup routine */
 int mbedtls_hmac_drbg_self_test(int verbose)
 {
@@ -639,7 +639,7 @@
 
     return 0;
 }
-#endif /* MBEDTLS_SHA1_C */
+#endif /* MBEDTLS_MD_CAN_SHA1 */
 #endif /* MBEDTLS_SELF_TEST */
 
 #endif /* MBEDTLS_HMAC_DRBG_C */
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index bc19ed0..1609c74 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -377,11 +377,7 @@
 /* Key management */
 /****************************************************************/
 
-#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) || \
-    defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) || \
-    defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
-    defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) || \
-    defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
+#if defined(MBEDTLS_ECP_C)
 mbedtls_ecp_group_id mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,
                                               size_t bits,
                                               int bits_is_sloppy)
@@ -473,11 +469,7 @@
     (void) bits_is_sloppy;
     return MBEDTLS_ECP_DP_NONE;
 }
-#endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) ||
-          defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) ||
-          defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
-          defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) ||
-          defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH) */
+#endif /* defined(MBEDTLS_ECP_C) */
 
 psa_status_t psa_validate_unstructured_key_bit_size(psa_key_type_t type,
                                                     size_t bits)
diff --git a/library/psa_crypto_random_impl.h b/library/psa_crypto_random_impl.h
index f1a2af1..4197b4b 100644
--- a/library/psa_crypto_random_impl.h
+++ b/library/psa_crypto_random_impl.h
@@ -62,7 +62,7 @@
 #elif defined(MBEDTLS_HMAC_DRBG_C)
 
 #include "mbedtls/hmac_drbg.h"
-#if defined(MBEDTLS_SHA512_C) && defined(MBEDTLS_SHA256_C)
+#if defined(MBEDTLS_MD_CAN_SHA512) && defined(MBEDTLS_MD_CAN_SHA256)
 #include <limits.h>
 #if SIZE_MAX > 0xffffffff
 /* Looks like a 64-bit system, so prefer SHA-512. */
@@ -71,9 +71,9 @@
 /* Looks like a 32-bit system, so prefer SHA-256. */
 #define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA256
 #endif
-#elif defined(MBEDTLS_SHA512_C)
+#elif defined(MBEDTLS_MD_CAN_SHA512)
 #define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA512
-#elif defined(MBEDTLS_SHA256_C)
+#elif defined(MBEDTLS_MD_CAN_SHA256)
 #define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA256
 #else
 #error "No hash algorithm available for HMAC_DBRG."
diff --git a/library/psa_util.c b/library/psa_util.c
index fefeea5..43a10a3 100644
--- a/library/psa_util.c
+++ b/library/psa_util.c
@@ -112,10 +112,9 @@
 
 int psa_status_to_mbedtls(psa_status_t status,
                           const mbedtls_error_pair_t *local_translations,
-                          size_t local_errors_size,
+                          size_t local_errors_num,
                           int (*fallback_f)(psa_status_t))
 {
-    size_t local_errors_num = (size_t) local_errors_size / 2;
     for (size_t i = 0; i < local_errors_num; i++) {
         if (status == local_translations[i].psa_status) {
             return local_translations[i].mbedtls_error;
diff --git a/library/ssl_ciphersuites.c b/library/ssl_ciphersuites.c
index 6fbbe21..9cef3fe 100644
--- a/library/ssl_ciphersuites.c
+++ b/library/ssl_ciphersuites.c
@@ -50,9 +50,9 @@
 #else
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
     /* TLS 1.3 ciphersuites */
-    MBEDTLS_TLS1_3_AES_128_GCM_SHA256,
-    MBEDTLS_TLS1_3_AES_256_GCM_SHA384,
     MBEDTLS_TLS1_3_CHACHA20_POLY1305_SHA256,
+    MBEDTLS_TLS1_3_AES_256_GCM_SHA384,
+    MBEDTLS_TLS1_3_AES_128_GCM_SHA256,
     MBEDTLS_TLS1_3_AES_128_CCM_SHA256,
     MBEDTLS_TLS1_3_AES_128_CCM_8_SHA256,
 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
diff --git a/library/ssl_misc.h b/library/ssl_misc.h
index 9dc4021..14a3c7e 100644
--- a/library/ssl_misc.h
+++ b/library/ssl_misc.h
@@ -751,16 +751,9 @@
     mbedtls_dhm_context dhm_ctx;                /*!<  DHM key exchange        */
 #endif
 
-/* Adding guard for MBEDTLS_ECDSA_C to ensure no compile errors due
- * to guards in client and server code. There is a gap in functionality that
- * access to ecdh_ctx structure is needed for MBEDTLS_ECDSA_C which does not
- * seem correct.
- */
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
-#if !defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_USE_PSA_CRYPTO)
     mbedtls_ecdh_context ecdh_ctx;              /*!<  ECDH key exchange       */
-#endif /* !MBEDTLS_USE_PSA_CRYPTO */
-#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
+#endif /* MBEDTLS_ECDH_C && !MBEDTLS_USE_PSA_CRYPTO */
 
 #if defined(PSA_WANT_ALG_ECDH) && \
     (defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_SSL_PROTO_TLS1_3))
@@ -787,7 +780,7 @@
 #endif
 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
 
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ||      \
+#if defined(MBEDTLS_PK_CAN_ECDH) || defined(MBEDTLS_PK_CAN_ECDSA_SOME) ||      \
     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
     uint16_t *curves_tls_id;      /*!<  List of TLS IDs of supported elliptic curves */
 #endif
diff --git a/library/ssl_tls12_client.c b/library/ssl_tls12_client.c
index 890e9a9..d94d829 100644
--- a/library/ssl_tls12_client.c
+++ b/library/ssl_tls12_client.c
@@ -831,11 +831,9 @@
     while (list_size > 0) {
         if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
             p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
-#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
-            (defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C))
+#if !defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C)
             ssl->handshake->ecdh_ctx.point_format = p[0];
-#endif /* !MBEDTLS_USE_PSA_CRYPTO &&
-          ( MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ) */
+#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_ECDH_C */
 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
             defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
             mbedtls_ecjpake_set_point_format(&ssl->handshake->ecjpake_ctx,
diff --git a/library/ssl_tls12_server.c b/library/ssl_tls12_server.c
index 631331d..656c40d 100644
--- a/library/ssl_tls12_server.c
+++ b/library/ssl_tls12_server.c
@@ -140,7 +140,7 @@
     return 0;
 }
 
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
+#if defined(MBEDTLS_PK_CAN_ECDH) || defined(MBEDTLS_PK_CAN_ECDSA_SOME) || \
     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
 /*
  * Function for parsing a supported groups (TLS 1.3) or supported elliptic
@@ -266,11 +266,9 @@
     while (list_size > 0) {
         if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
             p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
-#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
-            (defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C))
+#if !defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C)
             ssl->handshake->ecdh_ctx.point_format = p[0];
-#endif /* !MBEDTLS_USE_PSA_CRYPTO &&
-          ( MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ) */
+#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_ECDH_C */
 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
             defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
             mbedtls_ecjpake_set_point_format(&ssl->handshake->ecjpake_ctx,
@@ -286,7 +284,7 @@
 
     return 0;
 }
-#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
+#endif /* MBEDTLS_PK_CAN_ECDH || MBEDTLS_PK_CAN_ECDSA_SOME ||
           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
 
 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
@@ -662,7 +660,7 @@
 /*
  * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
  */
-#if defined(MBEDTLS_ECDSA_C)
+#if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_check_key_curve(mbedtls_pk_context *pk,
                                uint16_t *curves_tls_id)
@@ -681,7 +679,7 @@
 
     return -1;
 }
-#endif /* MBEDTLS_ECDSA_C */
+#endif /* MBEDTLS_PK_CAN_ECDSA_SOME */
 
 /*
  * Try picking a certificate for this ciphersuite,
@@ -766,7 +764,7 @@
             continue;
         }
 
-#if defined(MBEDTLS_ECDSA_C)
+#if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
         if (pk_alg == MBEDTLS_PK_ECDSA &&
             ssl_check_key_curve(&cur->cert->pk,
                                 ssl->handshake->curves_tls_id) != 0) {
@@ -830,7 +828,7 @@
 #endif
 
 
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
+#if defined(MBEDTLS_PK_CAN_ECDH) || defined(MBEDTLS_PK_CAN_ECDSA_SOME)
     if (mbedtls_ssl_ciphersuite_uses_ec(suite_info) &&
         (ssl->handshake->curves_tls_id == NULL ||
          ssl->handshake->curves_tls_id[0] == 0)) {
@@ -1369,7 +1367,7 @@
                 break;
 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
 
-#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
+#if defined(MBEDTLS_PK_CAN_ECDH) || defined(MBEDTLS_PK_CAN_ECDSA_SOME) || \
                 defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
             case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
                 MBEDTLS_SSL_DEBUG_MSG(3, ("found supported elliptic curves extension"));
@@ -1389,7 +1387,7 @@
                     return ret;
                 }
                 break;
-#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
+#endif /* MBEDTLS_PK_CAN_ECDH || MBEDTLS_PK_CAN_ECDSA_SOME ||
           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
 
 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
@@ -1499,7 +1497,7 @@
     if (!sig_hash_alg_ext_present) {
         uint16_t *received_sig_algs = ssl->handshake->received_sig_algs;
         const uint16_t default_sig_algs[] = {
-#if defined(MBEDTLS_ECDSA_C)
+#if defined(MBEDTLS_PK_CAN_ECDSA_SOME)
             MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_ECDSA,
                                                MBEDTLS_SSL_HASH_SHA1),
 #endif
diff --git a/library/ssl_tls13_server.c b/library/ssl_tls13_server.c
index 4cfb20b..bd27eaf 100644
--- a/library/ssl_tls13_server.c
+++ b/library/ssl_tls13_server.c
@@ -258,6 +258,8 @@
     int *psk_type,
     mbedtls_ssl_session *session)
 {
+    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+
     ((void) session);
     ((void) obfuscated_ticket_age);
     *psk_type = MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL;
@@ -271,9 +273,13 @@
             session) == SSL_TLS1_3_OFFERED_PSK_MATCH) {
         ssl->handshake->resume = 1;
         *psk_type = MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION;
-        mbedtls_ssl_set_hs_psk(ssl,
-                               session->resumption_key,
-                               session->resumption_key_len);
+        ret = mbedtls_ssl_set_hs_psk(ssl,
+                                     session->resumption_key,
+                                     session->resumption_key_len);
+        if (ret != 0) {
+            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
+            return ret;
+        }
 
         MBEDTLS_SSL_DEBUG_BUF(4, "Ticket-resumed PSK:",
                               session->resumption_key,
@@ -299,7 +305,11 @@
         identity_len == ssl->conf->psk_identity_len &&
         mbedtls_ct_memcmp(ssl->conf->psk_identity,
                           identity, identity_len) == 0) {
-        mbedtls_ssl_set_hs_psk(ssl, ssl->conf->psk, ssl->conf->psk_len);
+        ret = mbedtls_ssl_set_hs_psk(ssl, ssl->conf->psk, ssl->conf->psk_len);
+        if (ret != 0) {
+            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
+            return ret;
+        }
         return SSL_TLS1_3_OFFERED_PSK_MATCH;
     }
 
@@ -1331,6 +1341,15 @@
     cipher_suites_len = MBEDTLS_GET_UINT16_BE(p, 0);
     p += 2;
 
+    /*
+     * The length of the ciphersuite list has to be even.
+     */
+    if (cipher_suites_len & 1) {
+        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
+                                     MBEDTLS_ERR_SSL_DECODE_ERROR);
+        return MBEDTLS_ERR_SSL_DECODE_ERROR;
+    }
+
     /* Check we have enough data for the ciphersuite list, the legacy
      * compression methods and the length of the extensions.
      *
@@ -1360,8 +1379,11 @@
         uint16_t cipher_suite;
         const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
 
-        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, cipher_suites_end, 2);
-
+        /*
+         * "cipher_suite_end - p is even" is an invariant of the loop. As
+         * cipher_suites_end - p > 0, we have cipher_suites_end - p >= 2 and
+         * it is thus safe to read two bytes.
+         */
         cipher_suite = MBEDTLS_GET_UINT16_BE(p, 0);
         ciphersuite_info = ssl_tls13_validate_peer_ciphersuite(
             ssl, cipher_suite);
@@ -1374,6 +1396,7 @@
         MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %04x - %s",
                                   cipher_suite,
                                   ciphersuite_info->name));
+        break;
     }
 
     if (handshake->ciphersuite_info == NULL) {
@@ -1381,6 +1404,7 @@
                                      MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
         return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
     }
+    p = cipher_suites_end;
 
     /* ...
      * opaque legacy_compression_methods<1..2^8-1>;
diff --git a/programs/pkey/dh_client.c b/programs/pkey/dh_client.c
index bc58a15..1fbf045 100644
--- a/programs/pkey/dh_client.c
+++ b/programs/pkey/dh_client.c
@@ -23,9 +23,9 @@
 
 #if defined(MBEDTLS_AES_C) && defined(MBEDTLS_DHM_C) && \
     defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_NET_C) && \
-    defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C) && \
+    defined(MBEDTLS_RSA_C) && defined(MBEDTLS_MD_CAN_SHA256) && \
     defined(MBEDTLS_FS_IO) && defined(MBEDTLS_CTR_DRBG_C) && \
-    defined(MBEDTLS_SHA1_C)
+    defined(MBEDTLS_MD_CAN_SHA1)
 #include "mbedtls/net_sockets.h"
 #include "mbedtls/aes.h"
 #include "mbedtls/dhm.h"
@@ -43,14 +43,14 @@
 
 #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_DHM_C) ||     \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NET_C) ||  \
-    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_SHA256_C) ||    \
+    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_MD_CAN_SHA256) ||    \
     !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_CTR_DRBG_C) || \
-    !defined(MBEDTLS_SHA1_C)
+    !defined(MBEDTLS_MD_CAN_SHA1)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_DHM_C and/or MBEDTLS_ENTROPY_C "
                    "and/or MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_FS_IO and/or "
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_FS_IO and/or "
                    "MBEDTLS_CTR_DRBG_C not defined.\n");
     mbedtls_exit(0);
 }
@@ -280,5 +280,5 @@
     mbedtls_exit(exit_code);
 }
 #endif /* MBEDTLS_AES_C && MBEDTLS_DHM_C && MBEDTLS_ENTROPY_C &&
-          MBEDTLS_NET_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C &&
+          MBEDTLS_NET_C && MBEDTLS_RSA_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_FS_IO && MBEDTLS_CTR_DRBG_C */
diff --git a/programs/pkey/dh_server.c b/programs/pkey/dh_server.c
index 2514fc0..66f7d6f 100644
--- a/programs/pkey/dh_server.c
+++ b/programs/pkey/dh_server.c
@@ -23,9 +23,9 @@
 
 #if defined(MBEDTLS_AES_C) && defined(MBEDTLS_DHM_C) && \
     defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_NET_C) && \
-    defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C) && \
+    defined(MBEDTLS_RSA_C) && defined(MBEDTLS_MD_CAN_SHA256) && \
     defined(MBEDTLS_FS_IO) && defined(MBEDTLS_CTR_DRBG_C) && \
-    defined(MBEDTLS_SHA1_C)
+    defined(MBEDTLS_MD_CAN_SHA1)
 #include "mbedtls/net_sockets.h"
 #include "mbedtls/aes.h"
 #include "mbedtls/dhm.h"
@@ -43,14 +43,14 @@
 
 #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_DHM_C) ||     \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NET_C) ||  \
-    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_SHA256_C) ||    \
+    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_MD_CAN_SHA256) ||    \
     !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_CTR_DRBG_C) || \
-    !defined(MBEDTLS_SHA1_C)
+    !defined(MBEDTLS_MD_CAN_SHA1)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_DHM_C and/or MBEDTLS_ENTROPY_C "
                    "and/or MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_FS_IO and/or "
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_FS_IO and/or "
                    "MBEDTLS_CTR_DRBG_C not defined.\n");
     mbedtls_exit(0);
 }
@@ -302,5 +302,5 @@
     mbedtls_exit(exit_code);
 }
 #endif /* MBEDTLS_AES_C && MBEDTLS_DHM_C && MBEDTLS_ENTROPY_C &&
-          MBEDTLS_NET_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C &&
+          MBEDTLS_NET_C && MBEDTLS_RSA_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_FS_IO && MBEDTLS_CTR_DRBG_C */
diff --git a/programs/pkey/pk_sign.c b/programs/pkey/pk_sign.c
index 21a75e9..f3bcdb2 100644
--- a/programs/pkey/pk_sign.c
+++ b/programs/pkey/pk_sign.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_ENTROPY_C) ||  \
-    !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
+    !defined(MBEDTLS_MD_CAN_SHA256) || !defined(MBEDTLS_MD_C) || \
     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_FS_IO) ||    \
     !defined(MBEDTLS_CTR_DRBG_C)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_ENTROPY_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_MD_C and/or "
                    "MBEDTLS_PK_PARSE_C and/or MBEDTLS_FS_IO and/or "
                    "MBEDTLS_CTR_DRBG_C not defined.\n");
     mbedtls_exit(0);
@@ -150,5 +150,5 @@
     mbedtls_exit(exit_code);
 }
 #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C &&
-          MBEDTLS_SHA256_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
+          MBEDTLS_MD_CAN_SHA256 && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
           MBEDTLS_CTR_DRBG_C */
diff --git a/programs/pkey/pk_verify.c b/programs/pkey/pk_verify.c
index b1fd1b6..e24f27f 100644
--- a/programs/pkey/pk_verify.c
+++ b/programs/pkey/pk_verify.c
@@ -22,12 +22,12 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_MD_C) || \
-    !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_PK_PARSE_C) ||   \
+    !defined(MBEDTLS_MD_CAN_SHA256) || !defined(MBEDTLS_PK_PARSE_C) ||   \
     !defined(MBEDTLS_FS_IO)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_MD_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_PK_PARSE_C and/or "
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_PK_PARSE_C and/or "
                    "MBEDTLS_FS_IO not defined.\n");
     mbedtls_exit(0);
 }
@@ -123,5 +123,5 @@
 
     mbedtls_exit(exit_code);
 }
-#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_SHA256_C &&
+#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO */
diff --git a/programs/pkey/rsa_sign.c b/programs/pkey/rsa_sign.c
index a8418d1..051db07 100644
--- a/programs/pkey/rsa_sign.c
+++ b/programs/pkey/rsa_sign.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_RSA_C) ||  \
-    !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
+    !defined(MBEDTLS_MD_CAN_SHA256) || !defined(MBEDTLS_MD_C) || \
     !defined(MBEDTLS_FS_IO)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_RSA_C and/or "
                    "MBEDTLS_MD_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_FS_IO not defined.\n");
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_FS_IO not defined.\n");
     mbedtls_exit(0);
 }
 #else
@@ -162,5 +162,5 @@
 
     mbedtls_exit(exit_code);
 }
-#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C &&
+#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_FS_IO */
diff --git a/programs/pkey/rsa_sign_pss.c b/programs/pkey/rsa_sign_pss.c
index 19ab962..4fa3582 100644
--- a/programs/pkey/rsa_sign_pss.c
+++ b/programs/pkey/rsa_sign_pss.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_MD_C) || !defined(MBEDTLS_ENTROPY_C) ||  \
-    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_SHA256_C) ||        \
+    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_MD_CAN_SHA256) ||        \
     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_FS_IO) ||    \
     !defined(MBEDTLS_CTR_DRBG_C)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_MD_C and/or MBEDTLS_ENTROPY_C and/or "
-                   "MBEDTLS_RSA_C and/or MBEDTLS_SHA256_C and/or "
+                   "MBEDTLS_RSA_C and/or MBEDTLS_MD_CAN_SHA256 and/or "
                    "MBEDTLS_PK_PARSE_C and/or MBEDTLS_FS_IO and/or "
                    "MBEDTLS_CTR_DRBG_C not defined.\n");
     mbedtls_exit(0);
@@ -156,5 +156,5 @@
     mbedtls_exit(exit_code);
 }
 #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C && MBEDTLS_RSA_C &&
-          MBEDTLS_SHA256_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
+          MBEDTLS_MD_CAN_SHA256 && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
           MBEDTLS_CTR_DRBG_C */
diff --git a/programs/pkey/rsa_verify.c b/programs/pkey/rsa_verify.c
index 9c08435..e17d776 100644
--- a/programs/pkey/rsa_verify.c
+++ b/programs/pkey/rsa_verify.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_RSA_C) ||  \
-    !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
+    !defined(MBEDTLS_MD_CAN_SHA256) || !defined(MBEDTLS_MD_C) || \
     !defined(MBEDTLS_FS_IO)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_RSA_C and/or "
                    "MBEDTLS_MD_C and/or "
-                   "MBEDTLS_SHA256_C and/or MBEDTLS_FS_IO not defined.\n");
+                   "MBEDTLS_MD_CAN_SHA256 and/or MBEDTLS_FS_IO not defined.\n");
     mbedtls_exit(0);
 }
 #else
@@ -138,5 +138,5 @@
 
     mbedtls_exit(exit_code);
 }
-#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C &&
+#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_FS_IO */
diff --git a/programs/pkey/rsa_verify_pss.c b/programs/pkey/rsa_verify_pss.c
index df61e47..bbd8c17 100644
--- a/programs/pkey/rsa_verify_pss.c
+++ b/programs/pkey/rsa_verify_pss.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_MD_C) || !defined(MBEDTLS_ENTROPY_C) ||  \
-    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_SHA256_C) ||        \
+    !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_MD_CAN_SHA256) ||        \
     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_FS_IO) ||    \
     !defined(MBEDTLS_CTR_DRBG_C)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_MD_C and/or MBEDTLS_ENTROPY_C and/or "
-                   "MBEDTLS_RSA_C and/or MBEDTLS_SHA256_C and/or "
+                   "MBEDTLS_RSA_C and/or MBEDTLS_MD_CAN_SHA256 and/or "
                    "MBEDTLS_PK_PARSE_C and/or MBEDTLS_FS_IO and/or "
                    "MBEDTLS_CTR_DRBG_C not defined.\n");
     mbedtls_exit(0);
@@ -131,5 +131,5 @@
 
     mbedtls_exit(exit_code);
 }
-#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C &&
+#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_MD_CAN_SHA256 &&
           MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO */
diff --git a/programs/psa/key_ladder_demo.c b/programs/psa/key_ladder_demo.c
index f5c31de..a79fac6 100644
--- a/programs/psa/key_ladder_demo.c
+++ b/programs/psa/key_ladder_demo.c
@@ -62,13 +62,13 @@
 #include <psa/crypto.h>
 
 /* If the build options we need are not enabled, compile a placeholder. */
-#if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) ||      \
+#if !defined(PSA_WANT_ALG_SHA_256) || !defined(MBEDTLS_MD_C) ||      \
     !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) ||        \
     !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
     defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
 int main(void)
 {
-    printf("MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
+    printf("PSA_WANT_ALG_SHA_256 and/or MBEDTLS_MD_C and/or "
            "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
            "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
            "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
@@ -698,6 +698,6 @@
     usage();
     return EXIT_FAILURE;
 }
-#endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C &&
+#endif /* PSA_WANT_ALG_SHA_256 && MBEDTLS_MD_C &&
           MBEDTLS_AES_C && MBEDTLS_CCM_C &&
           MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */
diff --git a/programs/x509/cert_req.c b/programs/x509/cert_req.c
index 5241438..01d09bc 100644
--- a/programs/x509/cert_req.c
+++ b/programs/x509/cert_req.c
@@ -22,13 +22,13 @@
 #include "mbedtls/platform.h"
 
 #if !defined(MBEDTLS_X509_CSR_WRITE_C) || !defined(MBEDTLS_FS_IO) ||  \
-    !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_SHA256_C) || \
+    !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_MD_CAN_SHA256) || \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
     !defined(MBEDTLS_PEM_WRITE_C)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_X509_CSR_WRITE_C and/or MBEDTLS_FS_IO and/or "
-                   "MBEDTLS_PK_PARSE_C and/or MBEDTLS_SHA256_C and/or "
+                   "MBEDTLS_PK_PARSE_C and/or MBEDTLS_MD_CAN_SHA256 and/or "
                    "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C "
                    "not defined.\n");
     mbedtls_exit(0);
diff --git a/programs/x509/cert_write.c b/programs/x509/cert_write.c
index 0daee56..99ede78 100644
--- a/programs/x509/cert_write.c
+++ b/programs/x509/cert_write.c
@@ -24,12 +24,12 @@
 #if !defined(MBEDTLS_X509_CRT_WRITE_C) || \
     !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_FS_IO) || \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
-    !defined(MBEDTLS_ERROR_C) || !defined(MBEDTLS_SHA256_C) || \
+    !defined(MBEDTLS_ERROR_C) || !defined(MBEDTLS_MD_CAN_SHA256) || \
     !defined(MBEDTLS_PEM_WRITE_C)
 int main(void)
 {
     mbedtls_printf("MBEDTLS_X509_CRT_WRITE_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
-                   "MBEDTLS_FS_IO and/or MBEDTLS_SHA256_C and/or "
+                   "MBEDTLS_FS_IO and/or MBEDTLS_MD_CAN_SHA256 and/or "
                    "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
                    "MBEDTLS_ERROR_C not defined.\n");
     mbedtls_exit(0);
@@ -771,7 +771,7 @@
         mbedtls_printf(" ok\n");
     }
 
-#if defined(MBEDTLS_SHA1_C)
+#if defined(MBEDTLS_MD_CAN_SHA1)
     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
         opt.subject_identifier != 0) {
         mbedtls_printf("  . Adding the Subject Key Identifier ...");
@@ -805,7 +805,7 @@
 
         mbedtls_printf(" ok\n");
     }
-#endif /* MBEDTLS_SHA1_C */
+#endif /* MBEDTLS_MD_CAN_SHA1 */
 
     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
         opt.key_usage != 0) {
diff --git a/scripts/mbedtls_dev/ecp.py b/scripts/mbedtls_dev/ecp.py
index ffe48fc..aee8718 100644
--- a/scripts/mbedtls_dev/ecp.py
+++ b/scripts/mbedtls_dev/ecp.py
@@ -145,6 +145,100 @@
         return True
 
 
+class EcpP384R1Raw(bignum_common.ModOperationCommon,
+                   EcpTarget):
+    """Test cases for ecp quasi_reduction modulo p384."""
+    test_function = "ecp_mod_p384_raw"
+    test_name = "ecp_mod_p384_raw"
+    input_style = "fixed"
+    arity = 1
+
+    moduli = [("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
+               "fffffeffffffff0000000000000000ffffffff")
+             ] # type: List[str]
+
+    input_values = [
+        "0", "1",
+
+        # Modulus - 1
+        ("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef"
+         "fffffff0000000000000000fffffffe"),
+
+        # Maximum canonical P384 multiplication result
+        ("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
+         "fdfffffffe0000000000000001fffffffc0000000000000000000000000000000"
+         "10000000200000000fffffffe000000020000000400000000fffffffc00000004"),
+
+        # Testing with overflow in A(12) + A(21) + A(20);
+        ("497811378624857a2c2af60d70583376545484cfae5c812fe2999fc1abb51d18b"
+         "559e8ca3b50aaf263fdf8f24bdfb98fffffffff20e65bf9099e4e73a5e8b517cf"
+         "4fbeb8fd1750fdae6d43f2e53f82d5ffffffffffffffffcc6f1e06111c62e0"),
+
+        # Testing with underflow in A(13) + A(22) + A(23) - A(12) - A(20);
+        ("dfdd25e96777406b3c04b8c7b406f5fcf287e1e576003a092852a6fbe517f2712"
+         "b68abef41dbd35183a0614fb7222606ffffffff84396eee542f18a9189d94396c"
+         "784059c17a9f18f807214ef32f2f10ffffffff8a77fac20000000000000000"),
+
+        # Testing with overflow in A(23) + A(20) + A(19) - A(22);
+        ("783753f8a5afba6c1862eead1deb2fcdd907272be3ffd18542b24a71ee8b26ca"
+         "b0aa33513610ff973042bbe1637cc9fc99ad36c7f703514572cf4f5c3044469a"
+         "8f5be6312c19e5d3f8fc1ac6ffffffffffffffff8c86252400000000ffffffff"),
+
+        # Testing with underflow in A(23) + A(20) + A(19) - A(22);
+        ("65e1d2362fce922663b7fd517586e88842a9b4bd092e93e6251c9c69f278cbf8"
+         "285d99ae3b53da5ba36e56701e2b17c225f1239556c5f00117fa140218b46ebd8"
+         "e34f50d0018701fa8a0a5cc00000000000000004410bcb4ffffffff00000000"),
+
+        # Testing the second round of carry reduction
+        ("000000000000000000000000ffffffffffffffffffffffffffffffffffffffff"
+         "ffffffffffffffff00000000000000000000000000000000ffffffff00000000"
+         "000000000000000100000000000000000000000000000000ffffffff00000001"),
+
+        # First 8 number generated by random.getrandbits(768) - seed(2,2)
+        ("ffed9235288bc781ae66267594c9c9500925e4749b575bd13653f8dd9b1f282e"
+         "4067c3584ee207f8da94e3e8ab73738fcf1822ffbc6887782b491044d5e34124"
+         "5c6e433715ba2bdd177219d30e7a269fd95bafc8f2a4d27bdcf4bb99f4bea973"),
+        ("e8624fab5186ee32ee8d7ee9770348a05d300cb90706a045defc044a09325626"
+         "e6b58de744ab6cce80877b6f71e1f6d2ef8acd128b4f2fc15f3f57ebf30b94fa"
+         "82523e86feac7eb7dc38f519b91751dacdbd47d364be8049a372db8f6e405d93"),
+        ("fec3f6b32e8d4b8a8f54f8ceacaab39e83844b40ffa9b9f15c14bc4a829e07b0"
+         "829a48d422fe99a22c70501e533c91352d3d854e061b90303b08c6e33c729578"
+         "2d6c797f8f7d9b782a1be9cd8697bbd0e2520e33e44c50556c71c4a66148a86f"),
+        ("bd143fa9b714210c665d7435c1066932f4767f26294365b2721dea3bf63f23d0"
+         "dbe53fcafb2147df5ca495fa5a91c89b97eeab64ca2ce6bc5d3fd983c34c769f"
+         "e89204e2e8168561867e5e15bc01bfce6a27e0dfcbf8754472154e76e4c11ab2"),
+        ("8ebdbfe3eb9ac688b9d39cca91551e8259cc60b17604e4b4e73695c3e652c71a"
+         "74667bffe202849da9643a295a9ac6decbd4d3e2d4dec9ef83f0be4e80371eb9"
+         "7f81375eecc1cb6347733e847d718d733ff98ff387c56473a7a83ee0761ebfd2"),
+        ("d4c0dca8b4c9e755cc9c3adcf515a8234da4daeb4f3f87777ad1f45ae9500ec9"
+         "c5e2486c44a4a8f69dc8db48e86ec9c6e06f291b2a838af8d5c44a4eb3172062"
+         "d08f1bb2531d6460f0caeef038c89b38a8acb5137c9260dc74e088a9b9492f25"),
+        ("227eeb7b9d7d01f5769da05d205bbfcc8c69069134bccd3e1cf4f589f8e4ce0a"
+         "f29d115ef24bd625dd961e6830b54fa7d28f93435339774bb1e386c4fd5079e6"
+         "81b8f5896838b769da59b74a6c3181c81e220df848b1df78feb994a81167346"),
+        ("d322a7353ead4efe440e2b4fda9c025a22f1a83185b98f5fc11e60de1b343f52"
+         "ea748db9e020307aaeb6db2c3a038a709779ac1f45e9dd320c855fdfa7251af0"
+         "930cdbd30f0ad2a81b2d19a2beaa14a7ff3fe32a30ffc4eed0a7bd04e85bfcdd"),
+
+        # Next 2 number generated by random.getrandbits(384)
+        ("5c3747465cc36c270e8a35b10828d569c268a20eb78ac332e5e138e26c4454b9"
+         "0f756132e16dce72f18e859835e1f291"),
+        ("eb2b5693babb7fbb0a76c196067cfdcb11457d9cf45e2fa01d7f427515392480"
+         "0600571fac3a5b263fdf57cd2c006497")
+    ]
+
+    @property
+    def arg_a(self) -> str:
+        return super().format_arg('{:x}'.format(self.int_a)).zfill(2 * self.hex_digits)
+
+    def result(self) -> List[str]:
+        result = self.int_a % self.int_n
+        return [self.format_result(result)]
+
+    @property
+    def is_valid(self) -> bool:
+        return True
+
 class EcpP256R1Raw(bignum_common.ModOperationCommon,
                    EcpTarget):
     """Test cases for ECP P256 fast reduction."""
diff --git a/tests/include/test/drivers/config_test_driver.h b/tests/include/test/drivers/config_test_driver.h
index 22518bf..2585fd9 100644
--- a/tests/include/test/drivers/config_test_driver.h
+++ b/tests/include/test/drivers/config_test_driver.h
@@ -39,6 +39,7 @@
 #define MBEDTLS_PSA_BUILTIN_ALG_SHA_256 1
 #define MBEDTLS_CTR_DRBG_C
 #define MBEDTLS_ENTROPY_C
+#define MBEDTLS_ENTROPY_FORCE_SHA256
 
 /*
  * Configuration options that may need to be additionally enabled for the
diff --git a/tests/include/test/psa_exercise_key.h b/tests/include/test/psa_exercise_key.h
index eb69fc6..b5e3d35 100644
--- a/tests/include/test/psa_exercise_key.h
+++ b/tests/include/test/psa_exercise_key.h
@@ -34,7 +34,7 @@
  */
 #if defined(PSA_WANT_ALG_MD5)
 #define KNOWN_SUPPORTED_HASH_ALG PSA_ALG_MD5
-/* MBEDTLS_RIPEMD160_C omitted. This is necessary for the sake of
+/* PSA_WANT_ALG_RIPEMD160 omitted. This is necessary for the sake of
  * exercise_signature_key() because Mbed TLS doesn't support RIPEMD160
  * in RSA PKCS#1v1.5 signatures. A RIPEMD160-only configuration would be
  * implausible anyway. */
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index c97f666..23ad16e 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -2103,94 +2103,6 @@
     make test
 }
 
-# Auxiliary function to build config for ECDSA with and without drivers
-config_psa_crypto_config_ecdsa_use_psa () {
-    DRIVER_ONLY="$1"
-    # start with config full for maximum coverage (also enables USE_PSA)
-    scripts/config.py full
-    # enable support for drivers and configuring PSA-only algorithms
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
-    if [ "$DRIVER_ONLY" -eq 1 ]; then
-        # Disable the module that's accelerated
-        scripts/config.py unset MBEDTLS_ECDSA_C
-    fi
-    # Restartable feature is not yet supported by PSA. Once it will in
-    # the future, the following line could be removed (see issues
-    # 6061, 6332 and following ones)
-    scripts/config.py unset MBEDTLS_ECP_RESTARTABLE
-    # Dynamic secure element support is a deprecated feature and needs to be disabled here.
-    # This is done to have the same form of psa_key_attributes_s for libdriver and library.
-    scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
-}
-
-# Keep in sync with component_test_psa_crypto_config_reference_ecdsa_use_psa
-component_test_psa_crypto_config_accel_ecdsa_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDSA + USE_PSA"
-
-    # Algorithms and key types to accelerate
-    loc_accel_list="ALG_ECDSA ALG_DETERMINISTIC_ECDSA KEY_TYPE_ECC_KEY_PAIR KEY_TYPE_ECC_PUBLIC_KEY"
-
-    # Configure and build the test driver library
-    # -------------------------------------------
-
-    # Disable ALG_STREAM_CIPHER and ALG_ECB_NO_PADDING to avoid having
-    # partial support for cipher operations in the driver test library.
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
-    # SHA-1 and all variants of SHA-2 are needed for ECDSA and X.509 tests
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_1"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_224"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_256"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_384"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_512"
-    make -C tests libtestdriver1.a CFLAGS="$ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
-
-    # Configure and build the main libraries with drivers enabled
-    # -----------------------------------------------------------
-
-    # Use the same config as reference, only without built-in ECDSA
-    config_psa_crypto_config_ecdsa_use_psa 1
-
-    # Build the library
-    loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
-    make CFLAGS="$ASAN_CFLAGS -O -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
-
-    # Make sure ECDSA was not re-enabled by accident (additive config)
-    not grep mbedtls_ecdsa_ library/ecdsa.o
-
-    # Run the tests
-    # -------------
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDSA + USE_PSA"
-    make test
-
-    msg "test: ssl-opt.sh"
-    tests/ssl-opt.sh
-}
-
-# Keep in sync with component_test_psa_crypto_config_accel_ecdsa_use_psa.
-# Used by tests/scripts/analyze_outcomes.py for comparison purposes.
-component_test_psa_crypto_config_reference_ecdsa_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDSA + USE_PSA"
-
-    # To be aligned with the accel component that needs this
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    config_psa_crypto_config_ecdsa_use_psa 0
-
-    make
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDSA + USE_PSA"
-    make test
-
-    msg "test: ssl-opt.sh"
-    tests/ssl-opt.sh
-}
-
 component_test_psa_crypto_config_accel_ecdh () {
     msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDH"
 
@@ -2239,14 +2151,50 @@
     make test
 }
 
-# Auxiliary function to build config for ECDH with and without drivers.
+component_test_psa_crypto_config_accel_pake() {
+    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated PAKE"
+
+    # Start with full
+    scripts/config.py full
+
+    # Disable ALG_STREAM_CIPHER and ALG_ECB_NO_PADDING to avoid having
+    # partial support for cipher operations in the driver test library.
+    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
+    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
+
+    loc_accel_list="ALG_JPAKE"
+    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
+    make -C tests libtestdriver1.a CFLAGS="$ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
+
+    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
+    scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
+
+    # Make build-in fallback not available
+    scripts/config.py unset MBEDTLS_ECJPAKE_C
+    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
+
+    # Dynamic secure element support is a deprecated feature and needs to be disabled here.
+    # This is done to have the same form of psa_key_attributes_s for libdriver and library.
+    scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
+
+    loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
+    make CFLAGS="$ASAN_CFLAGS -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
+
+    not grep mbedtls_ecjpake_init library/ecjpake.o
+
+    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated PAKE"
+    make test
+}
+
+# Auxiliary function to build config for all EC based algorithms (EC-JPAKE,
+# ECDH, ECDSA) with and without drivers.
 #
 # This is used by the two following components to ensure they always use the
-# same config, except for the use of driver or built-in ECDH:
-# - component_test_psa_crypto_config_accel_ecdh_use_psa;
-# - component_test_psa_crypto_config_reference_ecdh_use_psa.
-# This support comparing their test coverage with analyze_outcomes.py.
-config_psa_crypto_config_ecdh_use_psa () {
+# same config, except for the use of driver or built-in EC algorithms:
+# - component_test_psa_crypto_config_accel_all_ec_algs_use_psa;
+# - component_test_psa_crypto_config_reference_all_ec_algs_use_psa.
+# This supports comparing their test coverage with analyze_outcomes.py.
+config_psa_crypto_config_all_ec_algs_use_psa () {
     DRIVER_ONLY="$1"
     # start with config full for maximum coverage (also enables USE_PSA)
     scripts/config.py full
@@ -2254,107 +2202,30 @@
     scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
     scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
     if [ "$DRIVER_ONLY" -eq 1 ]; then
-        # Disable the module that's accelerated
+        # Disable modules that are accelerated
+        scripts/config.py unset MBEDTLS_ECDSA_C
         scripts/config.py unset MBEDTLS_ECDH_C
+        scripts/config.py unset MBEDTLS_ECJPAKE_C
     fi
 
     # Restartable feature is not yet supported by PSA. Once it will in
     # the future, the following line could be removed (see issues
     # 6061, 6332 and following ones)
     scripts/config.py unset MBEDTLS_ECP_RESTARTABLE
-}
-
-# Keep in sync with component_test_psa_crypto_config_reference_ecdh_use_psa
-component_test_psa_crypto_config_accel_ecdh_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDH + USE_PSA"
-
-    # Algorithms and key types to accelerate
-    loc_accel_list="ALG_ECDH KEY_TYPE_ECC_KEY_PAIR KEY_TYPE_ECC_PUBLIC_KEY"
-
-    # Configure and build the test driver library
-    # -------------------------------------------
-
-    # Disable ALG_STREAM_CIPHER and ALG_ECB_NO_PADDING to avoid having
-    # partial support for cipher operations in the driver test library.
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
-    make -C tests libtestdriver1.a CFLAGS=" $ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
-
-    # Configure and build the main libraries
-    # --------------------------------------
-
-    # Use the same config as reference, only without built-in ECDH
-    config_psa_crypto_config_ecdh_use_psa 1
-
-    # Build the main library
-    loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
-    make CFLAGS="$ASAN_CFLAGS -O -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
-
-    # Make sure this was not re-enabled by accident (additive config)
-    not grep mbedtls_ecdh_ library/ecdh.o
-
-    # Run the tests
-    # -------------
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECDH + USE_PSA"
-    make test
-
-    msg "test: ssl-opt.sh"
-    tests/ssl-opt.sh
-}
-
-# Keep in sync with component_test_psa_crypto_config_accel_ecdh_use_psa.
-# Used by tests/scripts/analyze_outcomes.py for comparison purposes.
-component_test_psa_crypto_config_reference_ecdh_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with reference ECDH + USE_PSA"
-
-    # To be aligned with the accel component that needs this
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    config_psa_crypto_config_ecdh_use_psa 0
-
-    make
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with reference ECDH + USE_PSA"
-    make test
-
-    msg "test: ssl-opt.sh"
-    tests/ssl-opt.sh
-}
-
-# Auxiliary function to build config for EC JPAKE with and without drivers.
-#
-# This is used by the two following components to ensure they always use the
-# same config, except for the use of driver or built-in ECJPAKE:
-# - component_test_psa_crypto_config_accel_ecjpake_use_psa;
-# - component_test_psa_crypto_config_reference_ecjpake_use_psa.
-# This support comparing their test coverage with analyze_outcomes.py.
-config_psa_crypto_config_ecjpake_use_psa () {
-    DRIVER_ONLY="$1"
-    # start with config full for maximum coverage (also enables USE_PSA)
-    scripts/config.py full
-    # enable support for drivers and configuring PSA-only algorithms
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
-    if [ "$DRIVER_ONLY" -eq 1 ]; then
-        # Disable the module that's accelerated
-        scripts/config.py unset MBEDTLS_ECJPAKE_C
-    fi
-
     # Dynamic secure element support is a deprecated feature and needs to be disabled here.
     # This is done to have the same form of psa_key_attributes_s for libdriver and library.
     scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
 }
 
-# Keep in sync with component_test_psa_crypto_config_reference_ecjpake_use_psa
-component_test_psa_crypto_config_accel_ecjpake_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECJPAKE + USE_PSA"
+# Keep in sync with component_test_psa_crypto_config_reference_all_ec_algs_use_psa
+component_test_psa_crypto_config_accel_all_ec_algs_use_psa () {
+    msg "build: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated EC algs + USE_PSA"
 
     # Algorithms and key types to accelerate
-    loc_accel_list="ALG_JPAKE KEY_TYPE_ECC_KEY_PAIR KEY_TYPE_ECC_PUBLIC_KEY"
+    loc_accel_list="ALG_ECDSA ALG_DETERMINISTIC_ECDSA \
+                    ALG_ECDH \
+                    ALG_JPAKE \
+                    KEY_TYPE_ECC_KEY_PAIR KEY_TYPE_ECC_PUBLIC_KEY"
 
     # Configure and build the test driver library
     # -------------------------------------------
@@ -2364,110 +2235,56 @@
     scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
     scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
 
-    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
-    make -C tests libtestdriver1.a CFLAGS=" $ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
+    # Things we wanted supported in libtestdriver1, but not accelerated in the main library:
+    # SHA-1 and all SHA-2 variants, as they are used by ECDSA deterministic.
+    loc_extra_list="ALG_SHA_1 ALG_SHA_224 ALG_SHA_256 ALG_SHA_384 ALG_SHA_512"
+    loc_accel_flags=$( echo "$loc_accel_list $loc_extra_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
+    make -C tests libtestdriver1.a CFLAGS="$ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
 
-    # Configure and build the main libraries
-    # --------------------------------------
+    # Configure and build the main libraries with drivers enabled
+    # -----------------------------------------------------------
 
-    # Use the same config as reference, only without built-in JPAKE
-    config_psa_crypto_config_ecjpake_use_psa 1
+    # Use the same config as reference, only without built-in EC algs
+    config_psa_crypto_config_all_ec_algs_use_psa 1
 
-    # Build the main library
+    # Build the library
     loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
-    make CFLAGS="$ASAN_CFLAGS -O -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
+    make CFLAGS="$ASAN_CFLAGS -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
 
-    # Make sure this was not re-enabled by accident (additive config)
+    # Make sure any built-in EC alg was not re-enabled by accident (additive config)
+    not grep mbedtls_ecdsa_ library/ecdsa.o
+    not grep mbedtls_ecdh_ library/ecdh.o
     not grep mbedtls_ecjpake_ library/ecjpake.o
 
     # Run the tests
     # -------------
 
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated JPAKE + USE_PSA"
+    msg "test suites: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated EC algs + USE_PSA"
     make test
 
-    msg "test: ssl-opt.sh"
+    msg "ssl-opt: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated EC algs + USE_PSA"
     tests/ssl-opt.sh
 }
 
-# Keep in sync with component_test_psa_crypto_config_accel_ecjpake_use_psa.
-# Used by tests/scripts/analyze_outcomes.py for comparison purposes.
-component_test_psa_crypto_config_reference_ecjpake_use_psa () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with reference ECJPAKE + USE_PSA"
+# Keep in sync with component_test_psa_crypto_config_accel_all_ec_algs_use_psa
+component_test_psa_crypto_config_reference_all_ec_algs_use_psa () {
+    msg "build: MBEDTLS_PSA_CRYPTO_CONFIG with non-accelerated EC algs + USE_PSA"
 
-    # To be aligned with the accel component that needs this
+    # To be aligned with component_test_psa_crypto_config_accel_all_ec_algs_use_psa()
     scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
     scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
 
-    config_psa_crypto_config_ecjpake_use_psa 0
+    config_psa_crypto_config_all_ec_algs_use_psa 0
 
     make
 
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with reference ECJPAKE + USE_PSA"
+    msg "test suites: MBEDTLS_PSA_CRYPTO_CONFIG with non-accelerated EC algs + USE_PSA"
     make test
 
-    msg "test: ssl-opt.sh"
+    msg "ssl-opt: MBEDTLS_PSA_CRYPTO_CONFIG with non-accelerated EC algs + USE_PSA"
     tests/ssl-opt.sh
 }
 
-component_test_psa_crypto_config_accel_ecc () {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECC"
-
-    # Algorithms and key types to accelerate
-    loc_accel_list="ALG_ECDH ALG_ECDSA ALG_DETERMINISTIC_ECDSA ALG_JPAKE KEY_TYPE_ECC_KEY_PAIR KEY_TYPE_ECC_PUBLIC_KEY"
-
-    # Configure and build the test driver library
-    # --------------------------------------------
-
-    # Disable ALG_STREAM_CIPHER and ALG_ECB_NO_PADDING to avoid having
-    # partial support for cipher operations in the driver test library.
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
-    # These hashes are needed for some ECDSA signature tests.
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_224"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_256"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_384"
-    loc_accel_flags="$loc_accel_flags -DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_ALG_SHA_512"
-    make -C tests libtestdriver1.a CFLAGS="$ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
-
-    # Configure and build the main libraries
-    # ---------------------------------------
-
-    # start with default + driver support
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
-
-    # disable modules for which we have drivers
-    scripts/config.py unset MBEDTLS_ECDSA_C
-    scripts/config.py unset MBEDTLS_ECDH_C
-    scripts/config.py unset MBEDTLS_ECJPAKE_C
-
-    # dependencies
-    #scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3 # not in default anyway
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-
-    # build and link with test drivers
-    loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
-    make CFLAGS="$ASAN_CFLAGS -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
-
-    # make sure these were not auto-re-enabled by accident
-    not grep mbedtls_ecdh_ library/ecdh.o
-    not grep mbedtls_ecdsa_ library/ecdsa.o
-    not grep mbedtls_ecjpake_ library/ecjpake.o
-
-    # Run the tests
-    # -------------
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated ECC"
-    make test
-}
-
 component_test_psa_crypto_config_accel_rsa_signature () {
     msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated RSA signature"
 
@@ -2563,14 +2380,20 @@
     scripts/config.py unset MBEDTLS_MD5_C
     scripts/config.py unset MBEDTLS_RIPEMD160_C
     scripts/config.py unset MBEDTLS_SHA1_C
-    # Don't unset MBEDTLS_SHA256_C as it is needed by PSA crypto core.
+    scripts/config.py unset MBEDTLS_SHA224_C
+    scripts/config.py unset MBEDTLS_SHA256_C
     scripts/config.py unset MBEDTLS_SHA384_C
     scripts/config.py unset MBEDTLS_SHA512_C
     loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
     make CFLAGS="$ASAN_CFLAGS -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
 
-    not grep mbedtls_sha512_init library/sha512.o
-    not grep mbedtls_sha1_init library/sha1.o
+    # There's a risk of something getting re-enabled via config_psa.h;
+    # make sure it did not happen. Note: it's OK for MD_C to be enabled.
+    not grep mbedtls_md5 library/md5.o
+    not grep mbedtls_sha1 library/sha1.o
+    not grep mbedtls_sha256 library/sha256.o
+    not grep mbedtls_sha512 library/sha512.o
+    not grep mbedtls_ripemd160 library/ripemd160.o
 
     msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated hash"
     make test
@@ -2619,13 +2442,6 @@
         scripts/config.py unset MBEDTLS_SHA512_C
         scripts/config.py unset MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
     fi
-    # Use an external RNG as currently internal RNGs depend on entropy.c
-    # which in turn hard-depends on SHA256_C (or SHA512_C).
-    # See component_test_psa_external_rng_no_drbg_use_psa.
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG
-    scripts/config.py unset MBEDTLS_ENTROPY_C
-    scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED # depends on ENTROPY_C
-    scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT # depends on former
 
     # Dynamic secure element support is a deprecated feature and needs to be disabled here.
     # This is done to have the same form of psa_key_attributes_s for libdriver and library.
@@ -2767,41 +2583,6 @@
     make test
 }
 
-component_test_psa_crypto_config_accel_pake() {
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated PAKE"
-
-    # Start with full
-    scripts/config.py full
-
-    # Disable ALG_STREAM_CIPHER and ALG_ECB_NO_PADDING to avoid having
-    # partial support for cipher operations in the driver test library.
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER
-    scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING
-
-    loc_accel_list="ALG_JPAKE"
-    loc_accel_flags=$( echo "$loc_accel_list" | sed 's/[^ ]* */-DLIBTESTDRIVER1_MBEDTLS_PSA_ACCEL_&/g' )
-    make -C tests libtestdriver1.a CFLAGS="$ASAN_CFLAGS $loc_accel_flags" LDFLAGS="$ASAN_CFLAGS"
-
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
-    scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
-
-    # Make build-in fallback not available
-    scripts/config.py unset MBEDTLS_ECJPAKE_C
-    scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
-
-    # Dynamic secure element support is a deprecated feature and needs to be disabled here.
-    # This is done to have the same form of psa_key_attributes_s for libdriver and library.
-    scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
-
-    loc_accel_flags="$loc_accel_flags $( echo "$loc_accel_list" | sed 's/[^ ]* */-DMBEDTLS_PSA_ACCEL_&/g' )"
-    make CFLAGS="$ASAN_CFLAGS -Werror -I../tests/include -I../tests -I../../tests -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_TEST_LIBTESTDRIVER1 $loc_accel_flags" LDFLAGS="-ltestdriver1 $ASAN_CFLAGS"
-
-    not grep mbedtls_ecjpake_init library/ecjpake.o
-
-    msg "test: MBEDTLS_PSA_CRYPTO_CONFIG with accelerated PAKE"
-    make test
-}
-
 component_test_psa_crypto_config_no_driver() {
     # full plus MBEDTLS_PSA_CRYPTO_CONFIG
     msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG minus MBEDTLS_PSA_CRYPTO_DRIVERS"
diff --git a/tests/scripts/analyze_outcomes.py b/tests/scripts/analyze_outcomes.py
index 800b744..60cf654 100755
--- a/tests/scripts/analyze_outcomes.py
+++ b/tests/scripts/analyze_outcomes.py
@@ -10,6 +10,8 @@
 import sys
 import traceback
 import re
+import subprocess
+import os
 
 import check_test_cases
 
@@ -51,6 +53,26 @@
         """
         return len(self.successes) + len(self.failures)
 
+def execute_reference_driver_tests(ref_component, driver_component, outcome_file):
+    """Run the tests specified in ref_component and driver_component. Results
+    are stored in the output_file and they will be used for the following
+    coverage analysis"""
+    # If the outcome file already exists, we assume that the user wants to
+    # perform the comparison analysis again without repeating the tests.
+    if os.path.exists(outcome_file):
+        Results.log("Outcome file (" + outcome_file + ") already exists. " + \
+                    "Tests will be skipped.")
+        return
+
+    shell_command = "tests/scripts/all.sh --outcome-file " + outcome_file + \
+                    " " + ref_component + " " + driver_component
+    Results.log("Running: " + shell_command)
+    ret_val = subprocess.run(shell_command.split(), check=False).returncode
+
+    if ret_val != 0:
+        Results.log("Error: failed to run reference/driver components")
+        sys.exit(ret_val)
+
 def analyze_coverage(results, outcomes):
     """Check that all available test cases are executed at least once."""
     available = check_test_cases.collect_available_test_cases()
@@ -137,6 +159,9 @@
 
 def do_analyze_driver_vs_reference(outcome_file, args):
     """Perform driver vs reference analyze."""
+    execute_reference_driver_tests(args['component_ref'], \
+                                    args['component_driver'], outcome_file)
+
     ignored_suites = ['test_suite_' + x for x in args['ignored_suites']]
 
     outcomes = read_outcome_file(outcome_file)
@@ -152,9 +177,12 @@
         'test_function': do_analyze_coverage,
         'args': {}
         },
-    # How to use analyze_driver_vs_reference_xxx locally:
-    # 1. tests/scripts/all.sh --outcome-file "$PWD/out.csv" <component_ref> <component_driver>
-    # 2. tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
+    # There are 2 options to use analyze_driver_vs_reference_xxx locally:
+    # 1. Run tests and then analysis:
+    #   - tests/scripts/all.sh --outcome-file "$PWD/out.csv" <component_ref> <component_driver>
+    #   - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
+    # 2. Let this script run both automatically:
+    #   - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
     'analyze_driver_vs_reference_hash': {
         'test_function': do_analyze_driver_vs_reference,
         'args': {
@@ -168,13 +196,16 @@
             }
         }
     },
-    'analyze_driver_vs_reference_ecdsa': {
+    'analyze_driver_vs_reference_all_ec_algs': {
         'test_function': do_analyze_driver_vs_reference,
         'args': {
-            'component_ref': 'test_psa_crypto_config_reference_ecdsa_use_psa',
-            'component_driver': 'test_psa_crypto_config_accel_ecdsa_use_psa',
+            'component_ref': 'test_psa_crypto_config_reference_all_ec_algs_use_psa',
+            'component_driver': 'test_psa_crypto_config_accel_all_ec_algs_use_psa',
+            # ignore the suites of the accelerated components
             'ignored_suites': [
-                'ecdsa', # the software implementation that's excluded
+                'ecdsa',
+                'ecdh',
+                'ecjpake',
             ],
             'ignored_tests': {
                 'test_suite_random': [
@@ -183,30 +214,6 @@
             }
         }
     },
-    'analyze_driver_vs_reference_ecdh': {
-        'test_function': do_analyze_driver_vs_reference,
-        'args': {
-            'component_ref': 'test_psa_crypto_config_reference_ecdh_use_psa',
-            'component_driver': 'test_psa_crypto_config_accel_ecdh_use_psa',
-            'ignored_suites': [
-                'ecdh', # the software implementation that's excluded
-            ],
-            'ignored_tests': {
-            }
-        }
-    },
-    'analyze_driver_vs_reference_ecjpake': {
-        'test_function': do_analyze_driver_vs_reference,
-        'args': {
-            'component_ref': 'test_psa_crypto_config_reference_ecjpake_use_psa',
-            'component_driver': 'test_psa_crypto_config_accel_ecjpake_use_psa',
-            'ignored_suites': [
-                'ecjpake', # the software implementation that's excluded
-            ],
-            'ignored_tests': {
-            }
-        }
-    },
 }
 
 def main():
diff --git a/tests/scripts/depends.py b/tests/scripts/depends.py
index 581baad..b29ea0a 100755
--- a/tests/scripts/depends.py
+++ b/tests/scripts/depends.py
@@ -277,7 +277,7 @@
 # if a given define is the only one enabled from an exclusive group.
 EXCLUSIVE_GROUPS = {
     'MBEDTLS_SHA512_C': ['-MBEDTLS_SSL_COOKIE_C',
-                         '-MBEDTLS_SSL_PROTO_TLS1_3'],
+                         '-MBEDTLS_SSL_TLS_C'],
     'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['-MBEDTLS_ECDSA_C',
                                         '-MBEDTLS_ECDSA_DETERMINISTIC',
                                         '-MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
diff --git a/tests/scripts/generate_pkcs7_tests.py b/tests/scripts/generate_pkcs7_tests.py
index 187debc..0e73850 100755
--- a/tests/scripts/generate_pkcs7_tests.py
+++ b/tests/scripts/generate_pkcs7_tests.py
@@ -49,7 +49,7 @@
     Take in test_suite_pkcs7.data file.
     Allow for new tests to be added.
     """
-    mandatory_dep = "MBEDTLS_SHA256_C"
+    mandatory_dep = "MBEDTLS_MD_CAN_SHA256"
     test_name = "PKCS7 Parse Failure Invalid ASN1"
     test_function = "pkcs7_asn1_fail:"
     def __init__(self, file_name):
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 566860d..6017f78 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -11527,6 +11527,20 @@
             -c "Version: TLS1.3"
 
 # TLS1.3 test cases
+requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
+requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+requires_ciphersuite_enabled TLS1-3-CHACHA20-POLY1305-SHA256
+requires_config_enabled MBEDTLS_ECP_DP_CURVE25519_ENABLED
+requires_config_enabled MBEDTLS_ECP_DP_SECP256R1_ENABLED
+run_test    "TLS 1.3: Default" \
+            "$P_SRV allow_sha1=0 debug_level=3 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13" \
+            "$P_CLI allow_sha1=0" \
+            0 \
+            -s "Protocol is TLSv1.3" \
+            -s "Ciphersuite is TLS1-3-CHACHA20-POLY1305-SHA256" \
+            -s "ECDH group: x25519" \
+            -s "selected signature algorithm ecdsa_secp256r1_sha256"
+
 requires_openssl_tls1_3
 requires_config_enabled MBEDTLS_DEBUG_C
 requires_config_enabled MBEDTLS_SSL_CLI_C
@@ -11547,7 +11561,7 @@
             -c "client state: MBEDTLS_SSL_FLUSH_BUFFERS" \
             -c "client state: MBEDTLS_SSL_HANDSHAKE_WRAPUP" \
             -c "<= ssl_tls13_process_server_hello" \
-            -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
+            -c "server hello, chosen ciphersuite: ( 1303 ) - TLS1-3-CHACHA20-POLY1305-SHA256" \
             -c "ECDH curve: x25519" \
             -c "=> ssl_tls13_process_server_hello" \
             -c "<= parse encrypted extensions" \
@@ -11581,7 +11595,7 @@
             -c "client state: MBEDTLS_SSL_FLUSH_BUFFERS" \
             -c "client state: MBEDTLS_SSL_HANDSHAKE_WRAPUP" \
             -c "<= ssl_tls13_process_server_hello" \
-            -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
+            -c "server hello, chosen ciphersuite: ( 1303 ) - TLS1-3-CHACHA20-POLY1305-SHA256" \
             -c "ECDH curve: x25519" \
             -c "=> ssl_tls13_process_server_hello" \
             -c "<= parse encrypted extensions" \
@@ -11614,7 +11628,7 @@
             -c "client state: MBEDTLS_SSL_FLUSH_BUFFERS" \
             -c "client state: MBEDTLS_SSL_HANDSHAKE_WRAPUP" \
             -c "<= ssl_tls13_process_server_hello" \
-            -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
+            -c "server hello, chosen ciphersuite: ( 1303 ) - TLS1-3-CHACHA20-POLY1305-SHA256" \
             -c "ECDH curve: x25519" \
             -c "=> ssl_tls13_process_server_hello" \
             -c "<= parse encrypted extensions" \
@@ -11650,7 +11664,7 @@
             -c "client state: MBEDTLS_SSL_FLUSH_BUFFERS" \
             -c "client state: MBEDTLS_SSL_HANDSHAKE_WRAPUP" \
             -c "<= ssl_tls13_process_server_hello" \
-            -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
+            -c "server hello, chosen ciphersuite: ( 1303 ) - TLS1-3-CHACHA20-POLY1305-SHA256" \
             -c "ECDH curve: x25519" \
             -c "=> ssl_tls13_process_server_hello" \
             -c "<= parse encrypted extensions" \
@@ -13294,6 +13308,31 @@
             -s "key exchange mode: psk_ephemeral" \
             -s "found pre_shared_key extension"
 
+requires_gnutls_tls1_3
+requires_config_enabled MBEDTLS_SSL_SESSION_TICKETS
+requires_config_enabled MBEDTLS_SSL_SRV_C
+requires_config_enabled MBEDTLS_DEBUG_C
+requires_all_configs_enabled MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE \
+                             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED \
+                             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+# Test the session resumption when the cipher suite for the original session is
+# TLS1-3-AES-256-GCM-SHA384. In that case, the PSK is 384 bits long and not
+# 256 bits long as with all the other TLS 1.3 cipher suites.
+requires_ciphersuite_enabled TLS1-3-AES-256-GCM-SHA384
+run_test    "TLS 1.3: NewSessionTicket: Basic check with AES-256-GCM only, G->m" \
+            "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=4" \
+            "$G_NEXT_CLI localhost -d 4 --priority=NORMAL:-VERS-ALL:+VERS-TLS1.3:-CIPHER-ALL:+AES-256-GCM -V -r" \
+            0 \
+            -c "Connecting again- trying to resume previous session" \
+            -c "NEW SESSION TICKET (4) was received" \
+            -s "Ciphersuite is TLS1-3-AES-256-GCM-SHA384" \
+            -s "=> write NewSessionTicket msg" \
+            -s "server state: MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET" \
+            -s "server state: MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH" \
+            -s "key exchange mode: ephemeral" \
+            -s "key exchange mode: psk_ephemeral" \
+            -s "found pre_shared_key extension"
+
 requires_config_enabled MBEDTLS_SSL_SESSION_TICKETS
 requires_config_enabled MBEDTLS_SSL_SRV_C
 requires_config_enabled MBEDTLS_SSL_CLI_C
diff --git a/tests/suites/test_suite_aes.ecb.data b/tests/suites/test_suite_aes.ecb.data
index b468ac3..9385865 100644
--- a/tests/suites/test_suite_aes.ecb.data
+++ b/tests/suites/test_suite_aes.ecb.data
@@ -229,5 +229,11 @@
 AES-256-ECB Decrypt NIST KAT #12
 aes_decrypt_ecb:"0000000000000000000000000000000000000000000000000000000000000000":"9b80eefb7ebe2d2b16247aa0efc72f5d":"e0000000000000000000000000000000":0
 
-AES-256-ECB Copy Context NIST KAT #1
-aes_ecb_copy_context:"c1cc358b449909a19436cfbb3f852ef8bcb5ed12ac7058325f56e6099aab1a1c":"00000000000000000000000000000000"
+AES-128-ECB Copy context
+aes_ecb_copy_context:"000102030405060708090a0b0c0d0e0f"
+
+AES-192-ECB Copy context
+aes_ecb_copy_context:"000102030405060708090a0b0c0d0e0f1011121314151617"
+
+AES-256-ECB Copy context
+aes_ecb_copy_context:"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
diff --git a/tests/suites/test_suite_aes.function b/tests/suites/test_suite_aes.function
index d95503a..363a5fd 100644
--- a/tests/suites/test_suite_aes.function
+++ b/tests/suites/test_suite_aes.function
@@ -1,5 +1,61 @@
 /* BEGIN_HEADER */
 #include "mbedtls/aes.h"
+
+/* Test AES with a copied context.
+ *
+ * master, enc and dec must be AES context objects. They don't need to
+ * be initialized, and are left freed.
+ */
+static int test_copy(const data_t *key,
+                     mbedtls_aes_context *master,
+                     mbedtls_aes_context *enc,
+                     mbedtls_aes_context *dec)
+{
+    unsigned char plaintext[16] = {
+        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+    };
+    unsigned char ciphertext[16];
+    unsigned char output[16];
+
+    // Set key and encrypt with original context
+    mbedtls_aes_init(master);
+    TEST_ASSERT(mbedtls_aes_setkey_enc(master, key->x,
+                                       key->len * 8) == 0);
+    TEST_ASSERT(mbedtls_aes_crypt_ecb(master, MBEDTLS_AES_ENCRYPT,
+                                      plaintext, ciphertext) == 0);
+    *enc = *master;
+
+    // Set key for decryption with original context
+    mbedtls_aes_init(master);
+    TEST_ASSERT(mbedtls_aes_setkey_dec(master, key->x,
+                                       key->len * 8) == 0);
+    *dec = *master;
+
+    // Wipe the original context to make sure nothing from it is used
+    memset(master, 0, sizeof(*master));
+
+    // Encrypt with copied context
+    TEST_ASSERT(mbedtls_aes_crypt_ecb(enc, MBEDTLS_AES_ENCRYPT,
+                                      plaintext, output) == 0);
+    ASSERT_COMPARE(ciphertext, 16, output, 16);
+    mbedtls_aes_free(enc);
+
+    // Decrypt with copied context
+    TEST_ASSERT(mbedtls_aes_crypt_ecb(dec, MBEDTLS_AES_DECRYPT,
+                                      ciphertext, output) == 0);
+    ASSERT_COMPARE(plaintext, 16, output, 16);
+    mbedtls_aes_free(dec);
+
+    return 1;
+
+exit:
+    /* Bug: we may be leaving something unfreed. This is harmless
+     * in our built-in implementations, but might cause a memory leak
+     * with alternative implementations. */
+    return 0;
+}
+
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -468,32 +524,89 @@
 /* END_CASE */
 
 /* BEGIN_CASE */
-void aes_ecb_copy_context(data_t *key_str, data_t *src_str)
+void aes_ecb_copy_context(data_t *key)
 {
-    unsigned char output1[16], output2[16], plain[16];
-    mbedtls_aes_context ctx1, ctx2, ctx3;
+    /* We test context copying multiple times, with different alignments
+     * of the original and of the copies. */
 
-    // Set key and encrypt with original context
-    mbedtls_aes_init(&ctx1);
-    TEST_ASSERT(mbedtls_aes_setkey_enc(&ctx1, key_str->x,
-                                       key_str->len * 8) == 0);
-    TEST_ASSERT(mbedtls_aes_crypt_ecb(&ctx1, MBEDTLS_AES_ENCRYPT,
-                                      src_str->x, output1) == 0);
+    struct align0 {
+        mbedtls_aes_context ctx;
+    };
+    struct align0 *src0 = NULL;
+    struct align0 *enc0 = NULL;
+    struct align0 *dec0 = NULL;
 
-    ctx2 = ctx1;
-    TEST_ASSERT(mbedtls_aes_setkey_dec(&ctx1, key_str->x,
-                                       key_str->len * 8) == 0);
-    ctx3 = ctx1;
-    memset(&ctx1, 0, sizeof(ctx1));
+    struct align1 {
+        char bump;
+        mbedtls_aes_context ctx;
+    };
+    struct align1 *src1 = NULL;
+    struct align1 *enc1 = NULL;
+    struct align1 *dec1 = NULL;
 
-    // Encrypt and decrypt with copied context
-    TEST_ASSERT(mbedtls_aes_crypt_ecb(&ctx2, MBEDTLS_AES_ENCRYPT,
-                                      src_str->x, output2) == 0);
-    TEST_ASSERT(mbedtls_aes_crypt_ecb(&ctx3, MBEDTLS_AES_DECRYPT,
-                                      output1, plain) == 0);
+    /* All peak alignment */
+    ASSERT_ALLOC(src0, 1);
+    ASSERT_ALLOC(enc0, 1);
+    ASSERT_ALLOC(dec0, 1);
+    if (!test_copy(key, &src0->ctx, &enc0->ctx, &dec0->ctx)) {
+        goto exit;
+    }
+    mbedtls_free(src0);
+    src0 = NULL;
+    mbedtls_free(enc0);
+    enc0 = NULL;
+    mbedtls_free(dec0);
+    dec0 = NULL;
 
-    TEST_ASSERT(mbedtls_test_hexcmp(output1, output2, 16, 16) == 0);
-    TEST_ASSERT(mbedtls_test_hexcmp(src_str->x, plain, src_str->len, 16) == 0);
+    /* Original shifted */
+    ASSERT_ALLOC(src1, 1);
+    ASSERT_ALLOC(enc0, 1);
+    ASSERT_ALLOC(dec0, 1);
+    if (!test_copy(key, &src1->ctx, &enc0->ctx, &dec0->ctx)) {
+        goto exit;
+    }
+    mbedtls_free(src1);
+    src1 = NULL;
+    mbedtls_free(enc0);
+    enc0 = NULL;
+    mbedtls_free(dec0);
+    dec0 = NULL;
+
+    /* Copies shifted */
+    ASSERT_ALLOC(src0, 1);
+    ASSERT_ALLOC(enc1, 1);
+    ASSERT_ALLOC(dec1, 1);
+    if (!test_copy(key, &src0->ctx, &enc1->ctx, &dec1->ctx)) {
+        goto exit;
+    }
+    mbedtls_free(src0);
+    src0 = NULL;
+    mbedtls_free(enc1);
+    enc1 = NULL;
+    mbedtls_free(dec1);
+    dec1 = NULL;
+
+    /* Source and copies shifted */
+    ASSERT_ALLOC(src1, 1);
+    ASSERT_ALLOC(enc1, 1);
+    ASSERT_ALLOC(dec1, 1);
+    if (!test_copy(key, &src1->ctx, &enc1->ctx, &dec1->ctx)) {
+        goto exit;
+    }
+    mbedtls_free(src1);
+    src1 = NULL;
+    mbedtls_free(enc1);
+    enc1 = NULL;
+    mbedtls_free(dec1);
+    dec1 = NULL;
+
+exit:
+    mbedtls_free(src0);
+    mbedtls_free(enc0);
+    mbedtls_free(dec0);
+    mbedtls_free(src1);
+    mbedtls_free(enc1);
+    mbedtls_free(dec1);
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_ecp.function b/tests/suites/test_suite_ecp.function
index ecb3546..71fd4e1 100644
--- a/tests/suites/test_suite_ecp.function
+++ b/tests/suites/test_suite_ecp.function
@@ -1430,6 +1430,49 @@
 }
 /* END_CASE */
 
+/* BEGIN_CASE depends_on:MBEDTLS_TEST_HOOKS:MBEDTLS_ECP_DP_SECP384R1_ENABLED */
+void ecp_mod_p384_raw(char *input_N,
+                      char *input_X,
+                      char *result)
+{
+    mbedtls_mpi_uint *X = NULL;
+    mbedtls_mpi_uint *N = NULL;
+    mbedtls_mpi_uint *res = NULL;
+    size_t limbs_X;
+    size_t limbs_N;
+    size_t limbs_res;
+
+    mbedtls_mpi_mod_modulus m;
+    mbedtls_mpi_mod_modulus_init(&m);
+
+    TEST_EQUAL(mbedtls_test_read_mpi_core(&X,   &limbs_X,   input_X), 0);
+    TEST_EQUAL(mbedtls_test_read_mpi_core(&N,   &limbs_N,   input_N), 0);
+    TEST_EQUAL(mbedtls_test_read_mpi_core(&res, &limbs_res, result),  0);
+
+    size_t limbs = limbs_N;
+    size_t bytes = limbs * sizeof(mbedtls_mpi_uint);
+
+    TEST_EQUAL(limbs_X, 2 * limbs);
+    TEST_EQUAL(limbs_res, limbs);
+
+    TEST_EQUAL(mbedtls_mpi_mod_modulus_setup(
+                   &m, N, limbs,
+                   MBEDTLS_MPI_MOD_REP_MONTGOMERY), 0);
+
+    TEST_EQUAL(mbedtls_ecp_mod_p384_raw(X, limbs_X), 0);
+    TEST_LE_U(mbedtls_mpi_core_bitlen(X, limbs_X), 384);
+    mbedtls_mpi_mod_raw_fix_quasi_reduction(X, &m);
+    ASSERT_COMPARE(X, bytes, res, bytes);
+
+exit:
+    mbedtls_free(X);
+    mbedtls_free(res);
+
+    mbedtls_mpi_mod_modulus_free(&m);
+    mbedtls_free(N);
+}
+/* END_CASE */
+
 /* BEGIN_CASE depends_on:MBEDTLS_TEST_HOOKS */
 void ecp_mod_p521_raw(char *input_N,
                       char *input_X,
diff --git a/tests/suites/test_suite_entropy.function b/tests/suites/test_suite_entropy.function
index c36d2c8..724542c 100644
--- a/tests/suites/test_suite_entropy.function
+++ b/tests/suites/test_suite_entropy.function
@@ -167,6 +167,8 @@
 {
     mbedtls_entropy_context ctx;
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
 
     TEST_ASSERT(mbedtls_entropy_write_seed_file(&ctx, path) == ret);
@@ -174,6 +176,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -182,6 +185,8 @@
 {
     mbedtls_entropy_context ctx;
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
 
     TEST_ASSERT(mbedtls_entropy_write_seed_file(&ctx, MBEDTLS_PLATFORM_STD_NV_SEED_FILE) == ret);
@@ -189,6 +194,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -243,6 +249,8 @@
     unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE + 10] = { 0 };
     size_t i, j;
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
 
     /*
@@ -267,6 +275,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -277,6 +286,8 @@
     unsigned char buf[16];
     entropy_dummy_context dummy = { DUMMY_FAIL, 0, 0 };
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
 
     TEST_ASSERT(mbedtls_entropy_add_source(&ctx, entropy_dummy_source,
@@ -299,6 +310,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -312,6 +324,8 @@
     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
     int ret;
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
     entropy_clear_sources(&ctx);
 
@@ -340,6 +354,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -359,6 +374,8 @@
     unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
     int ret;
 
+    MD_PSA_INIT();
+
     mbedtls_entropy_init(&ctx);
     entropy_clear_sources(&ctx);
 
@@ -385,6 +402,7 @@
 
 exit:
     mbedtls_entropy_free(&ctx);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -455,6 +473,8 @@
     unsigned char check_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
     unsigned char check_entropy[MBEDTLS_ENTROPY_BLOCK_SIZE];
 
+    MD_PSA_INIT();
+
     memset(entropy, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
     memset(buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
     memset(empty, 0, MBEDTLS_ENTROPY_BLOCK_SIZE);
@@ -523,12 +543,18 @@
     mbedtls_entropy_free(&ctx);
     mbedtls_nv_seed_read = original_mbedtls_nv_seed_read;
     mbedtls_nv_seed_write = original_mbedtls_nv_seed_write;
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
 /* BEGIN_CASE depends_on:ENTROPY_HAVE_STRONG:MBEDTLS_SELF_TEST */
 void entropy_selftest(int result)
 {
+    MD_PSA_INIT();
+
     TEST_ASSERT(mbedtls_entropy_self_test(1) == result);
+
+exit:
+    MD_PSA_DONE();
 }
 /* END_CASE */
diff --git a/tests/suites/test_suite_pk.function b/tests/suites/test_suite_pk.function
index 2caa65f..20f61fc 100644
--- a/tests/suites/test_suite_pk.function
+++ b/tests/suites/test_suite_pk.function
@@ -760,7 +760,7 @@
 #endif
 
     mbedtls_pk_init(&pk);
-    USE_PSA_INIT();
+    MD_OR_USE_PSA_INIT();
 
     memset(hash, 0x2a, sizeof(hash));
     memset(sig, 0, sizeof(sig));
@@ -824,7 +824,7 @@
     mbedtls_pk_restart_free(rs_ctx);
 #endif
     mbedtls_pk_free(&pk);
-    USE_PSA_DONE();
+    MD_OR_USE_PSA_DONE();
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_psa_crypto_driver_wrappers.function b/tests/suites/test_suite_psa_crypto_driver_wrappers.function
index 56f4d1d..5105ef5 100644
--- a/tests/suites/test_suite_psa_crypto_driver_wrappers.function
+++ b/tests/suites/test_suite_psa_crypto_driver_wrappers.function
@@ -2241,12 +2241,14 @@
     unsigned char *output = NULL;
     size_t output_length;
 
-    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
-    mbedtls_test_driver_hash_hooks.forced_status = forced_status;
 
     PSA_ASSERT(psa_crypto_init());
     ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
+    /* Do this after psa_crypto_init() which may call hash drivers */
+    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
+    mbedtls_test_driver_hash_hooks.forced_status = forced_status;
+
     TEST_EQUAL(psa_hash_compute(alg, input->x, input->len,
                                 output, PSA_HASH_LENGTH(alg),
                                 &output_length), expected_status);
@@ -2277,12 +2279,14 @@
     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
     size_t output_length;
 
-    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
-    ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
     PSA_ASSERT(psa_crypto_init());
+    ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
+    /* Do this after psa_crypto_init() which may call hash drivers */
+    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
     mbedtls_test_driver_hash_hooks.forced_status = forced_status;
+
     TEST_EQUAL(psa_hash_setup(&operation, alg), expected_status);
     TEST_EQUAL(mbedtls_test_driver_hash_hooks.hits, 1);
     TEST_EQUAL(mbedtls_test_driver_hash_hooks.driver_status, forced_status);
@@ -2322,10 +2326,12 @@
     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
     size_t output_length;
 
-    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
-    ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
     PSA_ASSERT(psa_crypto_init());
+    ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
+
+    /* Do this after psa_crypto_init() which may call hash drivers */
+    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
 
     /*
      * Update inactive operation, the driver shouldn't be called.
@@ -2377,10 +2383,11 @@
     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
     size_t output_length;
 
-    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
+    PSA_ASSERT(psa_crypto_init());
     ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
-    PSA_ASSERT(psa_crypto_init());
+    /* Do this after psa_crypto_init() which may call hash drivers */
+    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
 
     /*
      * Finish inactive operation, the driver shouldn't be called.
@@ -2431,10 +2438,11 @@
     psa_hash_operation_t target_operation = PSA_HASH_OPERATION_INIT;
     size_t output_length;
 
-    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
+    PSA_ASSERT(psa_crypto_init());
     ASSERT_ALLOC(output, PSA_HASH_LENGTH(alg));
 
-    PSA_ASSERT(psa_crypto_init());
+    /* Do this after psa_crypto_init() which may call hash drivers */
+    mbedtls_test_driver_hash_hooks = mbedtls_test_driver_hash_hooks_init();
 
     /*
      * Clone inactive operation, the driver shouldn't be called.
diff --git a/tests/suites/test_suite_psa_crypto_init.function b/tests/suites/test_suite_psa_crypto_init.function
index f0b98e7..6e1305e 100644
--- a/tests/suites/test_suite_psa_crypto_init.function
+++ b/tests/suites/test_suite_psa_crypto_init.function
@@ -74,11 +74,7 @@
 #endif
 
     ctx->accumulator_started = 0;
-#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_init(&ctx->accumulator);
-#else
-    mbedtls_sha256_init(&ctx->accumulator);
-#endif
+    mbedtls_md_init(&ctx->accumulator);
 
 #if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
     if (custom_entropy_sources_mask & ENTROPY_SOURCE_PLATFORM) {
diff --git a/tests/suites/test_suite_psa_crypto_se_driver_hal.function b/tests/suites/test_suite_psa_crypto_se_driver_hal.function
index 5c94371..bb6b0e4 100644
--- a/tests/suites/test_suite_psa_crypto_se_driver_hal.function
+++ b/tests/suites/test_suite_psa_crypto_se_driver_hal.function
@@ -720,7 +720,7 @@
                                         buffer, sizeof(buffer), NULL, 0,
                                         buffer, sizeof(buffer), &length));
 
-#if defined(MBEDTLS_SHA256_C)
+#if defined(PSA_WANT_ALG_SHA_256)
     /* Try the key in a plain key derivation. */
     PSA_ASSERT(psa_key_derivation_setup(&derivation_operation,
                                         PSA_ALG_HKDF(PSA_ALG_SHA_256)));
@@ -753,7 +753,7 @@
                          alg, key, buffer, length,
                          buffer, sizeof(buffer), &length));
     }
-#endif /* MBEDTLS_SHA256_C */
+#endif /* PSA_WANT_ALG_SHA_256 */
 
     ok = 1;
 
diff --git a/tests/suites/test_suite_random.data b/tests/suites/test_suite_random.data
index c23d922..9211591 100644
--- a/tests/suites/test_suite_random.data
+++ b/tests/suites/test_suite_random.data
@@ -2,15 +2,15 @@
 random_twice_with_ctr_drbg:
 
 Generate random twice with HMAC_DRBG(SHA-1)
-depends_on:MBEDTLS_SHA1_C
+depends_on:MBEDTLS_MD_CAN_SHA1
 random_twice_with_hmac_drbg:MBEDTLS_MD_SHA1
 
 Generate random twice with HMAC_DRBG(SHA-256)
-depends_on:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_MD_CAN_SHA256
 random_twice_with_hmac_drbg:MBEDTLS_MD_SHA256
 
 Generate random twice with HMAC_DRBG(SHA-512)
-depends_on:MBEDTLS_SHA512_C
+depends_on:MBEDTLS_MD_CAN_SHA512
 random_twice_with_hmac_drbg:MBEDTLS_MD_SHA512
 
 Generate random twice with PSA classic wrapper
diff --git a/tests/suites/test_suite_random.function b/tests/suites/test_suite_random.function
index 3026bae..0df92b0 100644
--- a/tests/suites/test_suite_random.function
+++ b/tests/suites/test_suite_random.function
@@ -26,6 +26,8 @@
     unsigned char output1[OUTPUT_SIZE];
     unsigned char output2[OUTPUT_SIZE];
 
+    MD_PSA_INIT();
+
     /* First round */
     mbedtls_entropy_init(&entropy);
     mbedtls_ctr_drbg_init(&drbg);
@@ -54,6 +56,7 @@
 exit:
     mbedtls_ctr_drbg_free(&drbg);
     mbedtls_entropy_free(&entropy);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
@@ -66,6 +69,8 @@
     unsigned char output2[OUTPUT_SIZE];
     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
 
+    MD_PSA_INIT();
+
     /* First round */
     mbedtls_entropy_init(&entropy);
     mbedtls_hmac_drbg_init(&drbg);
@@ -94,6 +99,7 @@
 exit:
     mbedtls_hmac_drbg_free(&drbg);
     mbedtls_entropy_free(&entropy);
+    MD_PSA_DONE();
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_version.data b/tests/suites/test_suite_version.data
index ea6fc62..548e760 100644
--- a/tests/suites/test_suite_version.data
+++ b/tests/suites/test_suite_version.data
@@ -1,8 +1,8 @@
 Check compile time library version
-check_compiletime_version:"3.3.0"
+check_compiletime_version:"3.4.0"
 
 Check runtime library version
-check_runtime_version:"3.3.0"
+check_runtime_version:"3.4.0"
 
 Check for MBEDTLS_VERSION_C
 check_feature:"MBEDTLS_VERSION_C":0