Merge pull request #6919 from valeriosetti/issue6843-backport

Backport: Improve X.509 cert writing serial number management
diff --git a/ChangeLog.d/fix-rsaalt-test-guards.txt b/ChangeLog.d/fix-rsaalt-test-guards.txt
new file mode 100644
index 0000000..f4f39c9
--- /dev/null
+++ b/ChangeLog.d/fix-rsaalt-test-guards.txt
@@ -0,0 +1,3 @@
+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_timing_alt.txt b/ChangeLog.d/fix_timing_alt.txt
new file mode 100644
index 0000000..86ec16d
--- /dev/null
+++ b/ChangeLog.d/fix_timing_alt.txt
@@ -0,0 +1,5 @@
+Bugfix
+   * Fix a build issue when defining MBEDTLS_TIMING_ALT and MBEDTLS_SELF_TEST.
+     The library would not link if the user didn't provide an external self-test
+     function. The self-test is now provided regardless of the choice of
+     internal/alternative timing implementation. Fixes #6923.
diff --git a/docs/getting_started.md b/docs/getting_started.md
index fdbf0e9..507afa1 100644
--- a/docs/getting_started.md
+++ b/docs/getting_started.md
@@ -1,8 +1,9 @@
-## Getting started with Mbed Crypto
+## Getting started with Mbed TLS
 
-### What is Mbed Crypto?
+### What is Mbed TLS?
 
-Mbed Crypto is an open source cryptographic library that supports a wide range of cryptographic operations, including:
+Mbed TLS is an open source cryptographic library that supports a wide range of
+cryptographic operations, including:
 * Key management
 * Hashing
 * Symmetric cryptography
@@ -11,20 +12,25 @@
 * Key generation and derivation
 * Authenticated encryption with associated data (AEAD)
 
-The Mbed Crypto library is a reference implementation of the cryptography interface of the Arm Platform Security Architecture (PSA). It is written in portable C.
+Mbed TLS provides a reference implementation of the cryptography interface of
+the Arm Platform Security Architecture (PSA). It is written in portable C.
 
-The Mbed Crypto library is distributed under the Apache License, version 2.0.
+Mbed TLS is distributed under the Apache License, version 2.0.
 
 #### Platform Security Architecture (PSA)
 
 Arm's Platform Security Architecture (PSA) is a holistic set of threat models,
-security analyses, hardware and firmware architecture specifications, and an open source firmware reference implementation. PSA provides a recipe, based on industry best practice, that enables you to design security into both hardware and firmware consistently. Part of the API provided by PSA is the cryptography interface, which provides access to a set of primitives.
+security analyses, hardware and firmware architecture specifications, and an
+open source firmware reference implementation. PSA provides a recipe, based on
+industry best practice, that enables you to design security into both hardware
+and firmware consistently. Part of the API provided by PSA is the cryptography
+interface, which provides access to a set of primitives.
 
-### Using Mbed Crypto
+### Using Mbed TLS
 
-* [Getting the Mbed Crypto library](#getting-the-mbed-crypto-library)
-* [Building the Mbed Crypto library](#building-the-mbed-crypto-library)
-* [Using the Mbed Crypto library](#using-the-mbed-crypto-library)
+* [Getting the Mbed TLS library](#getting-the-mbed-tls-library)
+* [Building the Mbed TLS library](#building-the-mbed-tls-library)
+* [Using the PSA Crypto API](#using-the-psa-crypto-api)
 * [Importing a key](#importing-a-key)
 * [Signing a message using RSA](#signing-a-message-using-RSA)
 * [Encrypting or decrypting using symmetric ciphers](#encrypting-or-decrypting-using-symmetric-ciphers)
@@ -33,37 +39,45 @@
 * [Generating a random value](#generating-a-random-value)
 * [Authenticating and encrypting or decrypting a message](#authenticating-and-encrypting-or-decrypting-a-message)
 * [Generating and exporting keys](#generating-and-exporting-keys)
-* [More about the Mbed Crypto library](#more-about-the-mbed-crypto-library)
+* [More about the PSA Crypto API](#more-about-the-psa-crypto-api)
 
-### Getting the Mbed Crypto library
+### Getting the Mbed TLS library
 
-Mbed Crypto releases are available in the [public GitHub repository](https://github.com/ARMmbed/mbed-crypto).
+Mbed TLS releases are available in the [public GitHub repository](https://github.com/Mbed-TLS/mbedtls).
 
-### Building the Mbed Crypto library
+### Building the Mbed TLS library
 
 **Prerequisites to building the library with the provided makefiles:**
 * GNU Make.
-* A C toolchain (compiler, linker, archiver).
-* Python 2 or Python 3 (either works) to generate the test code.
+* A C toolchain (compiler, linker, archiver) that supports C99.
+* Python 3.6 to generate the test code.
 * Perl to run the tests.
 
-If you have a C compiler such as GCC or Clang, just run `make` in the top-level directory to build the library, a set of unit tests and some sample programs.
+If you have a C compiler such as GCC or Clang, just run `make` in the top-level
+directory to build the library, a set of unit tests and some sample programs.
 
-To select a different compiler, set the `CC` variable to the name or path of the compiler and linker (default: `cc`) and set `AR` to a compatible archiver (default: `ar`); for example:
+To select a different compiler, set the `CC` variable to the name or path of the
+compiler and linker (default: `cc`) and set `AR` to a compatible archiver
+(default: `ar`); for example:
 ```
 make CC=arm-linux-gnueabi-gcc AR=arm-linux-gnueabi-ar
 ```
-The provided makefiles pass options to the compiler that assume a GCC-like command line syntax. To use a different compiler, you may need to pass different values for `CFLAGS`, `WARNINGS_CFLAGS` and `LDFLAGS`.
+The provided makefiles pass options to the compiler that assume a GCC-like
+command line syntax. To use a different compiler, you may need to pass different
+values for `CFLAGS`, `WARNINGS_CFLAGS` and `LDFLAGS`.
 
-To run the unit tests on the host machine, run `make test` from the top-level directory. If you are cross-compiling, copy the test executable from the `tests` directory to the target machine.
+To run the unit tests on the host machine, run `make test` from the top-level
+directory. If you are cross-compiling, copy the test executable from the `tests`
+directory to the target machine.
 
-### Using the Mbed Crypto library
+### Using the PSA Crypto API
 
-To use the Mbed Crypto APIs, call `psa_crypto_init()` before calling any other API. This initializes the library.
+If using PSA Crypto, you must initialize the library by calling
+`psa_crypto_init()` before any other PSA API.
 
 ### Importing a key
 
-To use a key for cryptography operations in Mbed Crypto, you need to first
+To use a key for cryptography operations in PSA, you need to first
 import it. The import operation returns the identifier of the key for use
 with other function calls.
 
@@ -114,7 +128,8 @@
 
 ### Signing a message using RSA
 
-Mbed Crypto supports encrypting, decrypting, signing and verifying messages using public key signature algorithms, such as RSA or ECDSA.
+The PSA Crypto API supports encrypting, decrypting, signing and verifying
+messages using public key signature algorithms, such as RSA or ECDSA.
 
 **Prerequisites to performing asymmetric signature operations:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
@@ -184,21 +199,33 @@
 
 ### Using symmetric ciphers
 
-Mbed Crypto supports encrypting and decrypting messages using various symmetric cipher algorithms (both block and stream ciphers).
+The PSA Crypto API supports encrypting and decrypting messages using various
+symmetric cipher algorithms (both block and stream ciphers).
 
 **Prerequisites to working with the symmetric cipher API:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
-* Have a symmetric key. This key's usage flags must include `PSA_KEY_USAGE_ENCRYPT` to allow encryption or `PSA_KEY_USAGE_DECRYPT` to allow decryption.
+* Have a symmetric key. This key's usage flags must include
+  `PSA_KEY_USAGE_ENCRYPT` to allow encryption or `PSA_KEY_USAGE_DECRYPT` to
+  allow decryption.
 
 **To encrypt a message with a symmetric cipher:**
-1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the cipher functions.
+1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the
+   cipher functions.
 1. Initialize the operation structure to zero or to `PSA_CIPHER_OPERATION_INIT`.
-1. Call `psa_cipher_encrypt_setup()` to specify the algorithm and the key to be used.
-1. Call either `psa_cipher_generate_iv()` or `psa_cipher_set_iv()` to generate or set the initialization vector (IV). We recommend calling `psa_cipher_generate_iv()`, unless you require a specific IV value.
-1. Call `psa_cipher_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
-1. Call `psa_cipher_finish()` to end the operation and output the encrypted message.
+1. Call `psa_cipher_encrypt_setup()` to specify the algorithm and the key to be
+   used.
+1. Call either `psa_cipher_generate_iv()` or `psa_cipher_set_iv()` to generate
+   or set the initialization vector (IV). We recommend calling
+   `psa_cipher_generate_iv()`, unless you require a specific IV value.
+1. Call `psa_cipher_update()` with the message to encrypt. You may call this
+   function multiple times, passing successive fragments of the message on
+   successive calls.
+1. Call `psa_cipher_finish()` to end the operation and output the encrypted
+   message.
 
-This example shows how to encrypt data using an AES (Advanced Encryption Standard) key in CBC (Cipher Block Chaining) mode with no padding (assuming all prerequisites have been fulfilled):
+This example shows how to encrypt data using an AES (Advanced Encryption
+Standard) key in CBC (Cipher Block Chaining) mode with no padding (assuming all
+prerequisites have been fulfilled):
 ```c
 void encrypt_with_symmetric_ciphers(const uint8_t *key, size_t key_len)
 {
@@ -275,15 +302,20 @@
 ```
 
 **To decrypt a message with a symmetric cipher:**
-1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the cipher functions.
+1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the
+   cipher functions.
 1. Initialize the operation structure to zero or to `PSA_CIPHER_OPERATION_INIT`.
-1. Call `psa_cipher_decrypt_setup()` to specify the algorithm and the key to be used.
+1. Call `psa_cipher_decrypt_setup()` to specify the algorithm and the key to be
+   used.
 1. Call `psa_cipher_set_iv()` with the IV for the decryption.
-1. Call `psa_cipher_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
-1. Call `psa_cipher_finish()` to end the operation and output the decrypted message.
+1. Call `psa_cipher_update()` with the message to encrypt. You may call this
+   function multiple times, passing successive fragments of the message on
+   successive calls.
+1. Call `psa_cipher_finish()` to end the operation and output the decrypted
+   message.
 
-This example shows how to decrypt encrypted data using an AES key in CBC mode with no padding
-(assuming all prerequisites have been fulfilled):
+This example shows how to decrypt encrypted data using an AES key in CBC mode
+with no padding (assuming all prerequisites have been fulfilled):
 ```c
 void decrypt_with_symmetric_ciphers(const uint8_t *key, size_t key_len)
 {
@@ -360,34 +392,49 @@
 
 #### Handling cipher operation contexts
 
-After you've initialized the operation structure with a successful call to `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()`, you can terminate the operation at any time by calling `psa_cipher_abort()`.
+After you've initialized the operation structure with a successful call to
+`psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()`, you can terminate
+the operation at any time by calling `psa_cipher_abort()`.
 
-The call to `psa_cipher_abort()` frees any resources associated with the operation, except for the operation structure itself.
+The call to `psa_cipher_abort()` frees any resources associated with the
+operation, except for the operation structure itself.
 
-Mbed Crypto implicitly calls `psa_cipher_abort()` when:
-* A call to `psa_cipher_generate_iv()`, `psa_cipher_set_iv()` or `psa_cipher_update()` fails (returning any status other than `PSA_SUCCESS`).
+The PSA Crypto API implicitly calls `psa_cipher_abort()` when:
+* A call to `psa_cipher_generate_iv()`, `psa_cipher_set_iv()` or
+  `psa_cipher_update()` fails (returning any status other than `PSA_SUCCESS`).
 * A call to `psa_cipher_finish()` succeeds or fails.
 
-After an implicit or explicit call to `psa_cipher_abort()`, the operation structure is invalidated; in other words, you cannot reuse the operation structure for the same operation. You can, however, reuse the operation structure for a different operation by calling either `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()` again.
+After an implicit or explicit call to `psa_cipher_abort()`, the operation
+structure is invalidated; in other words, you cannot reuse the operation
+structure for the same operation. You can, however, reuse the operation
+structure for a different operation by calling either
+`psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()` again.
 
-You must call `psa_cipher_abort()` at some point for any operation that is initialized successfully (by a successful call to `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()`).
+You must call `psa_cipher_abort()` at some point for any operation that is
+initialized successfully (by a successful call to `psa_cipher_encrypt_setup()`
+or `psa_cipher_decrypt_setup()`).
 
-Making multiple sequential calls to `psa_cipher_abort()` on an operation that is terminated (either implicitly or explicitly) is safe and has no effect.
+Making multiple sequential calls to `psa_cipher_abort()` on an operation that
+is terminated (either implicitly or explicitly) is safe and has no effect.
 
 ### Hashing a message
 
-Mbed Crypto lets you compute and verify hashes using various hashing
+The PSA Crypto API lets you compute and verify hashes using various hashing
 algorithms.
 
 **Prerequisites to working with the hash APIs:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
 
 **To calculate a hash:**
-1. Allocate an operation structure (`psa_hash_operation_t`) to pass to the hash functions.
+1. Allocate an operation structure (`psa_hash_operation_t`) to pass to the hash
+   functions.
 1. Initialize the operation structure to zero or to `PSA_HASH_OPERATION_INIT`.
 1. Call `psa_hash_setup()` to specify the hash algorithm.
-1. Call `psa_hash_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
-1. Call `psa_hash_finish()` to calculate the hash, or `psa_hash_verify()` to compare the computed hash with an expected hash value.
+1. Call `psa_hash_update()` with the message to encrypt. You may call this
+   function multiple times, passing successive fragments of the message on
+   successive calls.
+1. Call `psa_hash_finish()` to calculate the hash, or `psa_hash_verify()` to
+   compare the computed hash with an expected hash value.
 
 This example shows how to calculate the SHA-256 hash of a message:
 ```c
@@ -482,33 +529,46 @@
     mbedtls_psa_crypto_free();
 ```
 
-The API provides the macro `PSA_HASH_LENGTH`, which returns the expected hash length (in bytes) for the specified algorithm.
+The API provides the macro `PSA_HASH_LENGTH`, which returns the expected hash
+length (in bytes) for the specified algorithm.
 
 #### Handling hash operation contexts
 
-After a successful call to `psa_hash_setup()`, you can terminate the operation at any time by calling `psa_hash_abort()`. The call to `psa_hash_abort()` frees any resources associated with the operation, except for the operation structure itself.
+After a successful call to `psa_hash_setup()`, you can terminate the operation
+at any time by calling `psa_hash_abort()`. The call to `psa_hash_abort()` frees
+any resources associated with the operation, except for the operation structure
+itself.
 
-Mbed Crypto implicitly calls `psa_hash_abort()` when:
-1. A call to `psa_hash_update()` fails (returning any status other than `PSA_SUCCESS`).
+The PSA Crypto API implicitly calls `psa_hash_abort()` when:
+1. A call to `psa_hash_update()` fails (returning any status other than
+   `PSA_SUCCESS`).
 1. A call to `psa_hash_finish()` succeeds or fails.
 1. A call to `psa_hash_verify()` succeeds or fails.
 
-After an implicit or explicit call to `psa_hash_abort()`, the operation structure is invalidated; in other words, you cannot reuse the operation structure for the same operation. You can, however, reuse the operation structure for a different operation by calling `psa_hash_setup()` again.
+After an implicit or explicit call to `psa_hash_abort()`, the operation
+structure is invalidated; in other words, you cannot reuse the operation
+structure for the same operation. You can, however, reuse the operation
+structure for a different operation by calling `psa_hash_setup()` again.
 
-You must call `psa_hash_abort()` at some point for any operation that is initialized successfully (by a successful call to `psa_hash_setup()`) .
+You must call `psa_hash_abort()` at some point for any operation that is
+initialized successfully (by a successful call to `psa_hash_setup()`) .
 
-Making multiple sequential calls to `psa_hash_abort()` on an operation that has already been terminated (either implicitly or explicitly) is safe and has no effect.
+Making multiple sequential calls to `psa_hash_abort()` on an operation that has
+already been terminated (either implicitly or explicitly) is safe and has no
+effect.
 
 ### Generating a random value
 
-Mbed Crypto can generate random data.
+The PSA Crypto API can generate random data.
 
 **Prerequisites to generating random data:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
 
-<span class="notes">**Note:** To generate a random key, use `psa_generate_key()` instead of `psa_generate_random()`.</span>
+<span class="notes">**Note:** To generate a random key, use `psa_generate_key()`
+instead of `psa_generate_random()`.</span>
 
-This example shows how to generate ten bytes of random data by calling `psa_generate_random()`:
+This example shows how to generate ten bytes of random data by calling
+`psa_generate_random()`:
 ```C
     psa_status_t status;
     uint8_t random[10] = { 0 };
@@ -537,16 +597,19 @@
 
 ### Deriving a new key from an existing key
 
-Mbed Crypto provides a key derivation API that lets you derive new keys from
-existing ones. The key derivation API has functions to take inputs, including
-other keys and data, and functions to generate outputs, such as new keys or
-other data.
+The PSA Crypto API provides a key derivation API that lets you derive new keys
+from existing ones. The key derivation API has functions to take inputs,
+including other keys and data, and functions to generate outputs, such as
+new keys or other data.
 
 You must first initialize and set up a key derivation context,
-provided with a key and, optionally, other data. Then, use the key derivation context to either read derived data to a buffer or send derived data directly to a key slot.
+provided with a key and, optionally, other data. Then, use the key derivation
+context to either read derived data to a buffer or send derived data directly
+to a key slot.
 
-See the documentation for the particular algorithm (such as HKDF or the TLS1.2 PRF) for
-information about which inputs to pass when, and when you can obtain which outputs.
+See the documentation for the particular algorithm (such as HKDF or the
+TLS 1.2 PRF) for information about which inputs to pass when, and when you can
+obtain which outputs.
 
 **Prerequisites to working with the key derivation APIs:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
@@ -563,11 +626,11 @@
 function, specifying the derivation algorithm `PSA_ALG_HKDF(PSA_ALG_SHA_256)`.
 1. Provide an optional salt with `psa_key_derivation_input_bytes()`.
 1. Provide info with `psa_key_derivation_input_bytes()`.
-1. Provide a secret with `psa_key_derivation_input_key()`, referencing a key that
-   can be used for key derivation.
+1. Provide a secret with `psa_key_derivation_input_key()`, referencing a key
+   that can be used for key derivation.
 1. Set the key attributes desired for the new derived key. We'll set
-   the `PSA_KEY_USAGE_ENCRYPT` usage flag and the `PSA_ALG_CTR` algorithm for this
-   example.
+   the `PSA_KEY_USAGE_ENCRYPT` usage flag and the `PSA_ALG_CTR` algorithm for
+   this example.
 1. Derive the key by calling `psa_key_derivation_output_key()`.
 1. Clean up the key derivation context.
 
@@ -675,11 +738,13 @@
 
 ### Authenticating and encrypting or decrypting a message
 
-Mbed Crypto provides a simple way to authenticate and encrypt with associated data (AEAD), supporting the `PSA_ALG_CCM` algorithm.
+The PSA Crypto API provides a simple way to authenticate and encrypt with
+associated data (AEAD), supporting the `PSA_ALG_CCM` algorithm.
 
 **Prerequisites to working with the AEAD cipher APIs:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
-* The key attributes for the key used for derivation must have the `PSA_KEY_USAGE_ENCRYPT` or `PSA_KEY_USAGE_DECRYPT` usage flags.
+* The key attributes for the key used for derivation must have the
+  `PSA_KEY_USAGE_ENCRYPT` or `PSA_KEY_USAGE_DECRYPT` usage flags.
 
 This example shows how to authenticate and encrypt a message:
 ```C
@@ -829,7 +894,7 @@
 
 ### Generating and exporting keys
 
-Mbed Crypto provides a simple way to generate a key or key pair.
+The PSA Crypto API provides a simple way to generate a key or key pair.
 
 **Prerequisites to using key generation and export APIs:**
 * Initialize the library with a successful call to `psa_crypto_init()`.
@@ -837,7 +902,9 @@
 **To generate an ECDSA key:**
 1. Set the desired key attributes for key generation by calling
    `psa_set_key_algorithm()` with the chosen ECDSA algorithm (such as
-   `PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256)`). You only want to export the public key, not the key pair (or private key); therefore, do not set `PSA_KEY_USAGE_EXPORT`.
+   `PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256)`). You only want to export the
+   public key, not the key pair (or private key); therefore, do not
+   set `PSA_KEY_USAGE_EXPORT`.
 1. Generate a key by calling `psa_generate_key()`.
 1. Export the generated public key by calling `psa_export_public_key()`:
 ```C
@@ -891,4 +958,5 @@
 
 ### More about the PSA Crypto API
 
-For more information about the PSA Crypto API, please see the [PSA Cryptography API Specification](https://armmbed.github.io/mbed-crypto/html/index.html).
+For more information about the PSA Crypto API, please see the
+[PSA Cryptography API Specification](https://arm-software.github.io/psa-api/crypto/).
diff --git a/library/Makefile b/library/Makefile
index 3b91e25..b011e88 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -186,6 +186,13 @@
 all: shared static
 endif
 
+ifdef TEST_TIMING_ALT_IMPL
+OBJS_CRYPTO += external_timing_for_test.o
+external_timing_for_test.o: ../tests/src/external_timing/external_timing_for_test.c
+	echo "  CC    $<"
+	$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
+endif
+
 static: libmbedcrypto.a libmbedx509.a libmbedtls.a
 	cd ../tests && echo "This is a seedfile that contains 64 bytes (65 on Windows)......" > seedfile
 
diff --git a/library/timing.c b/library/timing.c
index d4f9554..47e34f9 100644
--- a/library/timing.c
+++ b/library/timing.c
@@ -352,9 +352,9 @@
     return 0;
 }
 
+#endif /* !MBEDTLS_TIMING_ALT */
 
 #if defined(MBEDTLS_SELF_TEST)
-
 /*
  * Busy-waits for the given number of milliseconds.
  * Used for testing mbedtls_timing_hardclock.
@@ -383,9 +383,8 @@
             mbedtls_printf(" cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \
                            cycles, ratio, millisecs, secs, hardfail,   \
                            (unsigned long) a, (unsigned long) b);     \
-            mbedtls_printf(" elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \
+            mbedtls_printf(" elapsed(hires)=%lu status(ctx)=%d\n", \
                            mbedtls_timing_get_timer(&hires, 0),      \
-                           mbedtls_timing_get_timer(&ctx.timer, 0),  \
                            mbedtls_timing_get_delay(&ctx));         \
         }                                                               \
         return 1;                                                    \
@@ -526,5 +525,4 @@
 }
 
 #endif /* MBEDTLS_SELF_TEST */
-#endif /* !MBEDTLS_TIMING_ALT */
 #endif /* MBEDTLS_TIMING_C */
diff --git a/scripts/code_style.py b/scripts/code_style.py
index aae3e24..3958e87 100755
--- a/scripts/code_style.py
+++ b/scripts/code_style.py
@@ -171,18 +171,32 @@
     """
     uncrustify_version = get_uncrustify_version().strip()
     if UNCRUSTIFY_SUPPORTED_VERSION not in uncrustify_version:
-        print("Warning: Using unsupported Uncrustify version '" \
-                + uncrustify_version + "' (Note: The only supported version" \
-                "is " + UNCRUSTIFY_SUPPORTED_VERSION + ")", file=STDOUT_UTF8)
-
-    src_files = get_src_files()
+        print("Warning: Using unsupported Uncrustify version '" +
+              uncrustify_version + "'", file=STDOUT_UTF8)
+        print("Note: The only supported version is " +
+              UNCRUSTIFY_SUPPORTED_VERSION, file=STDOUT_UTF8)
 
     parser = argparse.ArgumentParser()
-    parser.add_argument('-f', '--fix', action='store_true', \
-            help='modify source files to fix the code style')
+    parser.add_argument('-f', '--fix', action='store_true',
+                        help=('modify source files to fix the code style '
+                              '(default: print diff, do not modify files)'))
+    # --files is almost useless: it only matters if there are no files
+    # ('code_style.py' without arguments checks all files known to Git,
+    # 'code_style.py --files' does nothing). In particular,
+    # 'code_style.py --fix --files ...' is intended as a stable ("porcelain")
+    # way to restyle a possibly empty set of files.
+    parser.add_argument('--files', action='store_true',
+                        help='only check the specified files (default with non-option arguments)')
+    parser.add_argument('operands', nargs='*', metavar='FILE',
+                        help='files to check (if none: check files that are known to git)')
 
     args = parser.parse_args()
 
+    if args.files or args.operands:
+        src_files = args.operands
+    else:
+        src_files = get_src_files()
+
     if args.fix:
         # Fix mode
         return fix_style(src_files)
diff --git a/scripts/mbedtls_dev/crypto_knowledge.py b/scripts/mbedtls_dev/crypto_knowledge.py
index f227a41..4e9503e 100644
--- a/scripts/mbedtls_dev/crypto_knowledge.py
+++ b/scripts/mbedtls_dev/crypto_knowledge.py
@@ -20,7 +20,7 @@
 
 import enum
 import re
-from typing import FrozenSet, Iterable, List, Optional, Tuple
+from typing import FrozenSet, Iterable, List, Optional, Tuple, Dict
 
 from .asymmetric_key_data import ASYMMETRIC_KEY_DATA
 
@@ -148,7 +148,7 @@
         'PSA_ECC_FAMILY_BRAINPOOL_P_R1': (160, 192, 224, 256, 320, 384, 512),
         'PSA_ECC_FAMILY_MONTGOMERY': (255, 448),
         'PSA_ECC_FAMILY_TWISTED_EDWARDS': (255, 448),
-    }
+    } # type: Dict[str, Tuple[int, ...]]
     KEY_TYPE_SIZES = {
         'PSA_KEY_TYPE_AES': (128, 192, 256), # exhaustive
         'PSA_KEY_TYPE_ARC4': (8, 128, 2048), # extremes + sensible
@@ -160,7 +160,7 @@
         'PSA_KEY_TYPE_HMAC': (128, 160, 224, 256, 384, 512), # standard size for each supported hash
         'PSA_KEY_TYPE_RAW_DATA': (8, 40, 128), # sample
         'PSA_KEY_TYPE_RSA_KEY_PAIR': (1024, 1536), # small sample
-    }
+    } # type: Dict[str, Tuple[int, ...]]
     def sizes_to_test(self) -> Tuple[int, ...]:
         """Return a tuple of key sizes to test.
 
@@ -212,9 +212,7 @@
         This function does not currently handle key derivation or PAKE.
         """
         #pylint: disable=too-many-branches,too-many-return-statements
-        if alg.is_wildcard:
-            return False
-        if alg.is_invalid_truncation():
+        if not alg.is_valid_for_operation():
             return False
         if self.head == 'HMAC' and alg.head == 'HMAC':
             return True
@@ -495,6 +493,19 @@
                 return True
         return False
 
+    def is_valid_for_operation(self) -> bool:
+        """Whether this algorithm construction is valid for an operation.
+
+        This function assumes that the algorithm is constructed in a
+        "grammatically" correct way, and only rejects semantically invalid
+        combinations.
+        """
+        if self.is_wildcard:
+            return False
+        if self.is_invalid_truncation():
+            return False
+        return True
+
     def can_do(self, category: AlgorithmCategory) -> bool:
         """Whether this algorithm can perform operations in the given category.
         """
diff --git a/tests/compat.sh b/tests/compat.sh
index c06694e..02ffed2 100755
--- a/tests/compat.sh
+++ b/tests/compat.sh
@@ -1092,15 +1092,17 @@
     echo "$SERVER_CMD" > $SRV_OUT
     # for servers without -www or equivalent
     while :; do echo bla; sleep 1; done | $SERVER_CMD >> $SRV_OUT 2>&1 &
-    PROCESS_ID=$!
+    SRV_PID=$!
 
-    wait_server_start "$PORT" "$PROCESS_ID"
+    wait_server_start "$PORT" "$SRV_PID"
 }
 
 # terminate the running server
 stop_server() {
-    kill $PROCESS_ID 2>/dev/null
-    wait $PROCESS_ID 2>/dev/null
+    # For Ubuntu 22.04, `Terminated` message is outputed by wait command.
+    # To remove it from stdout, redirect stdout/stderr to SRV_OUT
+    kill $SRV_PID >/dev/null 2>&1
+    wait $SRV_PID >> $SRV_OUT 2>&1
 
     if [ "$MEMCHECK" -gt 0 ]; then
         if is_mbedtls "$SERVER_CMD" && has_mem_err $SRV_OUT; then
@@ -1116,7 +1118,7 @@
 # kill the running server (used when killed by signal)
 cleanup() {
     rm -f $SRV_OUT $CLI_OUT
-    kill $PROCESS_ID >/dev/null 2>&1
+    kill $SRV_PID >/dev/null 2>&1
     kill $WATCHDOG_PID >/dev/null 2>&1
     exit 1
 }
@@ -1129,11 +1131,13 @@
     ( sleep "$DOG_DELAY"; echo "TIMEOUT" >> $CLI_OUT; kill $CLI_PID ) &
     WATCHDOG_PID=$!
 
-    wait $CLI_PID
+    # For Ubuntu 22.04, `Terminated` message is outputed by wait command.
+    # To remove it from stdout, redirect stdout/stderr to CLI_OUT
+    wait $CLI_PID >> $CLI_OUT 2>&1
     EXIT=$?
 
-    kill $WATCHDOG_PID
-    wait $WATCHDOG_PID
+    kill $WATCHDOG_PID >/dev/null 2>&1
+    wait $WATCHDOG_PID >> $CLI_OUT 2>&1
 
     echo "EXIT: $EXIT" >> $CLI_OUT
 }
@@ -1445,8 +1449,7 @@
 
 echo "------------------------------------------------------------------------"
 
-if [ $FAILED -ne 0 -o $SRVMEM -ne 0 ];
-then
+if [ $FAILED -ne 0 -o $SRVMEM -ne 0 ]; then
     printf "FAILED"
 else
     printf "PASSED"
@@ -1462,4 +1465,9 @@
 echo " ($PASSED / $TESTS tests ($SKIPPED skipped$MEMREPORT))"
 
 FAILED=$(( $FAILED + $SRVMEM ))
+if [ $FAILED -gt 255 ]; then
+    # Clamp at 255 as caller gets exit code & 0xFF
+    # (so 256 would be 0, or success, etc)
+    FAILED=255
+fi
 exit $FAILED
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index d0bd1eb..97d4296 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -1806,6 +1806,18 @@
     tests/scripts/depends.py pkalgs
 }
 
+component_build_no_pk_rsa_alt_support () {
+    msg "build: !MBEDTLS_PK_RSA_ALT_SUPPORT" # ~30s
+
+    scripts/config.py full
+    scripts/config.py unset MBEDTLS_PK_RSA_ALT_SUPPORT
+    scripts/config.py set MBEDTLS_RSA_C
+    scripts/config.py set MBEDTLS_X509_CRT_WRITE_C
+
+    # Only compile - this is primarily to test for compile issues
+    make CC=gcc CFLAGS='-Werror -Wall -Wextra -I../tests/include/alt-dummy'
+}
+
 component_test_no_use_psa_crypto_full_cmake_asan() {
     # full minus MBEDTLS_USE_PSA_CRYPTO: run the same set of tests as basic-build-test.sh
     msg "build: cmake, full config minus MBEDTLS_USE_PSA_CRYPTO, ASan"
@@ -2716,6 +2728,19 @@
     make test
 }
 
+component_test_alt_timing() {
+    msg "build: alternate timing implementation"
+    scripts/config.py set MBEDTLS_TIMING_ALT
+    make lib TEST_TIMING_ALT_IMPL=1 CFLAGS="-I../tests/src/external_timing"
+
+    msg "test: MBEDTLS_TIMING_ALT - test suites"
+    make test TEST_TIMING_ALT_IMPL=1 CFLAGS="-I../tests/src/external_timing"
+
+    msg "selftest - MBEDTLS-TIMING_ALT"
+    make programs TEST_TIMING_ALT_IMPL=1 CFLAGS="-I../../tests/src/external_timing -I../tests/src/external_timing"
+    programs/test/selftest
+}
+
 component_test_platform_calloc_macro () {
     msg "build: MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO enabled (ASan build)"
     scripts/config.py set MBEDTLS_PLATFORM_MEMORY
diff --git a/tests/scripts/check_names.py b/tests/scripts/check_names.py
index f71a978..8c08e5c 100755
--- a/tests/scripts/check_names.py
+++ b/tests/scripts/check_names.py
@@ -264,7 +264,7 @@
             "3rdparty/everest/include/everest/everest.h",
             "3rdparty/everest/include/everest/x25519.h"
         ])
-        identifiers = self.parse_identifiers([
+        identifiers, excluded_identifiers = self.parse_identifiers([
             "include/mbedtls/*.h",
             "include/psa/*.h",
             "library/*.h",
@@ -302,6 +302,7 @@
             "private_macros": private_macros,
             "enum_consts": enum_consts,
             "identifiers": identifiers,
+            "excluded_identifiers": excluded_identifiers,
             "symbols": symbols,
             "mbed_psa_words": mbed_psa_words
         }
@@ -315,12 +316,42 @@
                 return True
         return False
 
-    def get_files(self, include_wildcards, exclude_wildcards):
+    def get_all_files(self, include_wildcards, exclude_wildcards):
         """
-        Get all files that match any of the UNIX-style wildcards. While the
-        check_names script is designed only for use on UNIX/macOS (due to nm),
-        this function alone would work fine on Windows even with forward slashes
-        in the wildcard.
+        Get all files that match any of the included UNIX-style wildcards
+        and filter them into included and excluded lists.
+        While the check_names script is designed only for use on UNIX/macOS
+        (due to nm), this function alone will work fine on Windows even with
+        forward slashes in the wildcard.
+
+        Args:
+        * include_wildcards: a List of shell-style wildcards to match filepaths.
+        * exclude_wildcards: a List of shell-style wildcards to exclude.
+
+        Returns:
+        * inc_files: A List of relative filepaths for included files.
+        * exc_files: A List of relative filepaths for excluded files.
+        """
+        accumulator = set()
+        all_wildcards = include_wildcards + (exclude_wildcards or [])
+        for wildcard in all_wildcards:
+            accumulator = accumulator.union(glob.iglob(wildcard))
+
+        inc_files = []
+        exc_files = []
+        for path in accumulator:
+            if self.is_file_excluded(path, exclude_wildcards):
+                exc_files.append(path)
+            else:
+                inc_files.append(path)
+        return (inc_files, exc_files)
+
+    def get_included_files(self, include_wildcards, exclude_wildcards):
+        """
+        Get all files that match any of the included UNIX-style wildcards.
+        While the check_names script is designed only for use on UNIX/macOS
+        (due to nm), this function alone will work fine on Windows even with
+        forward slashes in the wildcard.
 
         Args:
         * include_wildcards: a List of shell-style wildcards to match filepaths.
@@ -351,7 +382,7 @@
             "asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
         )
 
-        files = self.get_files(include, exclude)
+        files = self.get_included_files(include, exclude)
         self.log.debug("Looking for macros in {} files".format(len(files)))
 
         macros = []
@@ -386,7 +417,7 @@
         mbed_regex = re.compile(r"\b(MBED.+?|PSA)_[A-Z0-9_]*")
         exclusions = re.compile(r"// *no-check-names|#error")
 
-        files = self.get_files(include, exclude)
+        files = self.get_included_files(include, exclude)
         self.log.debug(
             "Looking for MBED|PSA words in {} files"
             .format(len(files))
@@ -419,7 +450,7 @@
 
         Returns a List of Match objects for the findings.
         """
-        files = self.get_files(include, exclude)
+        files = self.get_included_files(include, exclude)
         self.log.debug("Looking for enum consts in {} files".format(len(files)))
 
         # Emulate a finite state machine to parse enum declarations.
@@ -602,23 +633,34 @@
         """
         Parse all lines of a header where a function/enum/struct/union/typedef
         identifier is declared, based on some regex and heuristics. Highly
-        dependent on formatting style.
+        dependent on formatting style. Identifiers in excluded files are still
+        parsed
 
         Args:
         * include: A List of glob expressions to look for files through.
         * exclude: A List of glob expressions for excluding files.
 
-        Returns a List of Match objects with identifiers.
+        Returns: a Tuple of two Lists of Match objects with identifiers.
+        * included_identifiers: A List of Match objects with identifiers from
+          included files.
+        * excluded_identifiers: A List of Match objects with identifiers from
+          excluded files.
         """
 
-        files = self.get_files(include, exclude)
-        self.log.debug("Looking for identifiers in {} files".format(len(files)))
+        included_files, excluded_files = \
+            self.get_all_files(include, exclude)
 
-        identifiers = []
-        for header_file in files:
-            self.parse_identifiers_in_file(header_file, identifiers)
+        self.log.debug("Looking for included identifiers in {} files".format \
+            (len(included_files)))
 
-        return identifiers
+        included_identifiers = []
+        excluded_identifiers = []
+        for header_file in included_files:
+            self.parse_identifiers_in_file(header_file, included_identifiers)
+        for header_file in excluded_files:
+            self.parse_identifiers_in_file(header_file, excluded_identifiers)
+
+        return (included_identifiers, excluded_identifiers)
 
     def parse_symbols(self):
         """
@@ -779,10 +821,12 @@
         Returns the number of problems that need fixing.
         """
         problems = []
+        all_identifiers = self.parse_result["identifiers"] +  \
+            self.parse_result["excluded_identifiers"]
 
         for symbol in self.parse_result["symbols"]:
             found_symbol_declared = False
-            for identifier_match in self.parse_result["identifiers"]:
+            for identifier_match in all_identifiers:
                 if symbol == identifier_match.name:
                     found_symbol_declared = True
                     break
diff --git a/tests/scripts/depends.py b/tests/scripts/depends.py
index ed9caa4..b8bcfd2 100755
--- a/tests/scripts/depends.py
+++ b/tests/scripts/depends.py
@@ -433,11 +433,8 @@
             'hashes': DualDomain(hash_symbols, build_and_test,
                                  exclude=r'MBEDTLS_(MD|RIPEMD|SHA1_)'\
                                           '|!MBEDTLS_*_NO_SHA'),
-            # Key exchange types. Only build the library and the sample
-            # programs.
-            'kex': ExclusiveDomain(key_exchange_symbols,
-                                   [build_command + ['lib'],
-                                    build_command + ['-C', 'programs']]),
+            # Key exchange types.
+            'kex': ExclusiveDomain(key_exchange_symbols, build_and_test),
             'pkalgs': ComplementaryDomain(['MBEDTLS_ECDSA_C',
                                            'MBEDTLS_ECP_C',
                                            'MBEDTLS_PKCS1_V21',
diff --git a/tests/scripts/doxygen.sh b/tests/scripts/doxygen.sh
index 2c523ba..e355073 100755
--- a/tests/scripts/doxygen.sh
+++ b/tests/scripts/doxygen.sh
@@ -35,7 +35,7 @@
     grep -v "warning: ignoring unsupported tag" \
     > doc.filtered
 
-if egrep "(warning|error):" doc.filtered; then
+if grep -E "(warning|error):" doc.filtered; then
     echo "FAIL" >&2
     exit 1;
 fi
diff --git a/tests/scripts/generate_psa_tests.py b/tests/scripts/generate_psa_tests.py
index a11dade..f5b921e 100755
--- a/tests/scripts/generate_psa_tests.py
+++ b/tests/scripts/generate_psa_tests.py
@@ -151,8 +151,8 @@
     tc.set_arguments([key_type] + list(args))
     return tc
 
-class NotSupported:
-    """Generate test cases for when something is not supported."""
+class KeyTypeNotSupported:
+    """Generate test cases for when a key type is not supported."""
 
     def __init__(self, info: Information) -> None:
         self.constructors = info.constructors
@@ -354,7 +354,7 @@
                 dependencies[i] = '!' + dep
         tc.set_dependencies(dependencies)
         tc.set_function(category.name.lower() + '_fail')
-        arguments = []
+        arguments = [] # type: List[str]
         if kt:
             key_material = kt.key_material(kt.sizes_to_test()[0])
             arguments += [key_type, test_case.hex_string(key_material)]
@@ -521,7 +521,7 @@
             key_type: psa_storage.Expr, bits: int,
             alg: psa_storage.Expr
     ) -> bool:
-        """Whether to the given key with the given algorithm.
+        """Whether to exercise the given key with the given algorithm.
 
         Normally only the type and algorithm matter for compatibility, and
         this is handled in crypto_knowledge.KeyType.can_do(). This function
@@ -902,7 +902,7 @@
         'test_suite_psa_crypto_generate_key.generated':
         lambda info: KeyGenerate(info).test_cases_for_key_generation(),
         'test_suite_psa_crypto_not_supported.generated':
-        lambda info: NotSupported(info).test_cases_for_not_supported(),
+        lambda info: KeyTypeNotSupported(info).test_cases_for_not_supported(),
         'test_suite_psa_crypto_op_fail.generated':
         lambda info: OpFail(info).all_test_cases(),
         'test_suite_psa_crypto_storage_format.current':
diff --git a/tests/scripts/list_internal_identifiers.py b/tests/scripts/list_internal_identifiers.py
index 779a16f..6b41607 100755
--- a/tests/scripts/list_internal_identifiers.py
+++ b/tests/scripts/list_internal_identifiers.py
@@ -46,7 +46,7 @@
     result = name_check.parse_identifiers([
         "include/mbedtls/*_internal.h",
         "library/*.h"
-    ])
+    ])[0]
     result.sort(key=lambda x: x.name)
 
     identifiers = ["{}\n".format(match.name) for match in result]
diff --git a/tests/src/external_timing/external_timing_for_test.c b/tests/src/external_timing/external_timing_for_test.c
new file mode 100644
index 0000000..454ebbe
--- /dev/null
+++ b/tests/src/external_timing/external_timing_for_test.c
@@ -0,0 +1,351 @@
+/** \file external_timing_for_test.c
+ *
+ * \brief Helper functions to test an alternate timing implementation.
+ */
+
+/*
+ *  Copyright The Mbed TLS Contributors
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include <timing_alt.h>
+#if defined(MBEDTLS_TIMING_ALT)
+
+#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
+    !defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
+    !defined(__HAIKU__) && !defined(__midipix__)
+#error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h"
+#endif
+
+/* *INDENT-OFF* */
+#ifndef asm
+#define asm __asm
+#endif
+/* *INDENT-ON* */
+
+#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
+
+#include <windows.h>
+#include <process.h>
+
+struct _hr_time {
+    LARGE_INTEGER start;
+};
+
+#else
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <signal.h>
+/* time.h should be included independently of MBEDTLS_HAVE_TIME. If the
+ * platform matches the ifdefs above, it will be used. */
+#include <time.h>
+#include <sys/time.h>
+struct _hr_time {
+    struct timeval start;
+};
+#endif /* _WIN32 && !EFIX64 && !EFI32 */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long tsc;
+    __asm   rdtsc
+    __asm   mov[tsc], eax
+    return tsc;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          ( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
+
+/* some versions of mingw-64 have 32-bit longs even on x84_64 */
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    defined(__GNUC__) && (defined(__i386__) || (                       \
+    (defined(__amd64__) || defined(__x86_64__)) && __SIZEOF_LONG__ == 4))
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long lo, hi;
+    asm volatile ("rdtsc" : "=a" (lo), "=d" (hi));
+    return lo;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && __i386__ */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    defined(__GNUC__) && (defined(__amd64__) || defined(__x86_64__))
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long lo, hi;
+    asm volatile ("rdtsc" : "=a" (lo), "=d" (hi));
+    return lo | (hi << 32);
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && ( __amd64__ || __x86_64__ ) */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__))
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long tbl, tbu0, tbu1;
+
+    do {
+        asm volatile ("mftbu %0" : "=r" (tbu0));
+        asm volatile ("mftb  %0" : "=r" (tbl));
+        asm volatile ("mftbu %0" : "=r" (tbu1));
+    } while (tbu0 != tbu1);
+
+    return tbl;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && ( __powerpc__ || __ppc__ ) */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    defined(__GNUC__) && defined(__sparc64__)
+
+#if defined(__OpenBSD__)
+#warning OpenBSD does not allow access to tick register using software version instead
+#else
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long tick;
+    asm volatile ("rdpr %%tick, %0;" : "=&r" (tick));
+    return tick;
+}
+#endif /* __OpenBSD__ */
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && __sparc64__ */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&  \
+    defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long tick;
+    asm volatile (".byte 0x83, 0x41, 0x00, 0x00");
+    asm volatile ("mov   %%g1, %0" : "=r" (tick));
+    return tick;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && __sparc__ && !__sparc64__ */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&      \
+    defined(__GNUC__) && defined(__alpha__)
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long cc;
+    asm volatile ("rpcc %0" : "=r" (cc));
+    return cc & 0xFFFFFFFF;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && __alpha__ */
+
+#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) &&      \
+    defined(__GNUC__) && defined(__ia64__)
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    unsigned long itc;
+    asm volatile ("mov %0 = ar.itc" : "=r" (itc));
+    return itc;
+}
+#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
+          __GNUC__ && __ia64__ */
+
+#if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \
+    !defined(EFIX64) && !defined(EFI32)
+
+#define HAVE_HARDCLOCK
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    LARGE_INTEGER offset;
+
+    QueryPerformanceCounter(&offset);
+
+    return (unsigned long) (offset.QuadPart);
+}
+#endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */
+
+#if !defined(HAVE_HARDCLOCK)
+
+#define HAVE_HARDCLOCK
+
+static int hardclock_init = 0;
+static struct timeval tv_init;
+
+unsigned long mbedtls_timing_hardclock(void)
+{
+    struct timeval tv_cur;
+
+    if (hardclock_init == 0) {
+        gettimeofday(&tv_init, NULL);
+        hardclock_init = 1;
+    }
+
+    gettimeofday(&tv_cur, NULL);
+    return (tv_cur.tv_sec  - tv_init.tv_sec) * 1000000U
+           + (tv_cur.tv_usec - tv_init.tv_usec);
+}
+#endif /* !HAVE_HARDCLOCK */
+
+volatile int mbedtls_timing_alarmed = 0;
+
+#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
+
+unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset)
+{
+    struct _hr_time *t = (struct _hr_time *) val;
+
+    if (reset) {
+        QueryPerformanceCounter(&t->start);
+        return 0;
+    } else {
+        unsigned long delta;
+        LARGE_INTEGER now, hfreq;
+        QueryPerformanceCounter(&now);
+        QueryPerformanceFrequency(&hfreq);
+        delta = (unsigned long) ((now.QuadPart - t->start.QuadPart) * 1000ul
+                                 / hfreq.QuadPart);
+        return delta;
+    }
+}
+
+/* It's OK to use a global because alarm() is supposed to be global anyway */
+static DWORD alarmMs;
+
+static void TimerProc(void *TimerContext)
+{
+    (void) TimerContext;
+    Sleep(alarmMs);
+    mbedtls_timing_alarmed = 1;
+    /* _endthread will be called implicitly on return
+     * That ensures execution of thread function's epilogue */
+}
+
+void mbedtls_set_alarm(int seconds)
+{
+    if (seconds == 0) {
+        /* No need to create a thread for this simple case.
+         * Also, this shorcut is more reliable at least on MinGW32 */
+        mbedtls_timing_alarmed = 1;
+        return;
+    }
+
+    mbedtls_timing_alarmed = 0;
+    alarmMs = seconds * 1000;
+    (void) _beginthread(TimerProc, 0, NULL);
+}
+
+#else /* _WIN32 && !EFIX64 && !EFI32 */
+
+unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset)
+{
+    struct _hr_time *t = (struct _hr_time *) val;
+
+    if (reset) {
+        gettimeofday(&t->start, NULL);
+        return 0;
+    } else {
+        unsigned long delta;
+        struct timeval now;
+        gettimeofday(&now, NULL);
+        delta = (now.tv_sec  - t->start.tv_sec) * 1000ul
+                + (now.tv_usec - t->start.tv_usec) / 1000;
+        return delta;
+    }
+}
+
+static void sighandler(int signum)
+{
+    mbedtls_timing_alarmed = 1;
+    signal(signum, sighandler);
+}
+
+void mbedtls_set_alarm(int seconds)
+{
+    mbedtls_timing_alarmed = 0;
+    signal(SIGALRM, sighandler);
+    alarm(seconds);
+    if (seconds == 0) {
+        /* alarm(0) cancelled any previous pending alarm, but the
+           handler won't fire, so raise the flag straight away. */
+        mbedtls_timing_alarmed = 1;
+    }
+}
+
+#endif /* _WIN32 && !EFIX64 && !EFI32 */
+
+/*
+ * Set delays to watch
+ */
+void mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms)
+{
+    mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
+
+    ctx->int_ms = int_ms;
+    ctx->fin_ms = fin_ms;
+
+    if (fin_ms != 0) {
+        (void) mbedtls_timing_get_timer(&ctx->timer, 1);
+    }
+}
+
+/*
+ * Get number of delays expired
+ */
+int mbedtls_timing_get_delay(void *data)
+{
+    mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
+    unsigned long elapsed_ms;
+
+    if (ctx->fin_ms == 0) {
+        return -1;
+    }
+
+    elapsed_ms = mbedtls_timing_get_timer(&ctx->timer, 0);
+
+    if (elapsed_ms >= ctx->fin_ms) {
+        return 2;
+    }
+
+    if (elapsed_ms >= ctx->int_ms) {
+        return 1;
+    }
+
+    return 0;
+}
+
+#endif /* MBEDTLS_TIMING_ALT */
diff --git a/tests/src/external_timing/timing_alt.h b/tests/src/external_timing/timing_alt.h
new file mode 100644
index 0000000..82e8c8b
--- /dev/null
+++ b/tests/src/external_timing/timing_alt.h
@@ -0,0 +1,130 @@
+/*
+ * Copy of the internal MbedTLS timing implementation, to be used in tests.
+ */
+/*
+ *  Copyright The Mbed TLS Contributors
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#ifndef EXTERNAL_TIMING_FOR_TEST_H
+#define EXTERNAL_TIMING_FOR_TEST_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "mbedtls/config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include <stdint.h>
+
+/**
+ * \brief          timer structure
+ */
+struct mbedtls_timing_hr_time {
+    unsigned char opaque[32];
+};
+
+/**
+ * \brief          Context for mbedtls_timing_set/get_delay()
+ */
+typedef struct mbedtls_timing_delay_context {
+    struct mbedtls_timing_hr_time   timer;
+    uint32_t                        int_ms;
+    uint32_t                        fin_ms;
+} mbedtls_timing_delay_context;
+
+#else  /* MBEDTLS_TIMING_ALT */
+#include "timing_alt.h"
+#endif /* MBEDTLS_TIMING_ALT */
+
+extern volatile int mbedtls_timing_alarmed;
+
+/**
+ * \brief          Return the CPU cycle counter value
+ *
+ * \warning        This is only a best effort! Do not rely on this!
+ *                 In particular, it is known to be unreliable on virtual
+ *                 machines.
+ *
+ * \note           This value starts at an unspecified origin and
+ *                 may wrap around.
+ */
+unsigned long mbedtls_timing_hardclock(void);
+
+/**
+ * \brief          Return the elapsed time in milliseconds
+ *
+ * \param val      points to a timer structure
+ * \param reset    If 0, query the elapsed time. Otherwise (re)start the timer.
+ *
+ * \return         Elapsed time since the previous reset in ms. When
+ *                 restarting, this is always 0.
+ *
+ * \note           To initialize a timer, call this function with reset=1.
+ *
+ *                 Determining the elapsed time and resetting the timer is not
+ *                 atomic on all platforms, so after the sequence
+ *                 `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =
+ *                 get_timer(0) }` the value time1+time2 is only approximately
+ *                 the delay since the first reset.
+ */
+unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset);
+
+/**
+ * \brief          Setup an alarm clock
+ *
+ * \param seconds  delay before the "mbedtls_timing_alarmed" flag is set
+ *                 (must be >=0)
+ *
+ * \warning        Only one alarm at a time  is supported. In a threaded
+ *                 context, this means one for the whole process, not one per
+ *                 thread.
+ */
+void mbedtls_set_alarm(int seconds);
+
+/**
+ * \brief          Set a pair of delays to watch
+ *                 (See \c mbedtls_timing_get_delay().)
+ *
+ * \param data     Pointer to timing data.
+ *                 Must point to a valid \c mbedtls_timing_delay_context struct.
+ * \param int_ms   First (intermediate) delay in milliseconds.
+ *                 The effect if int_ms > fin_ms is unspecified.
+ * \param fin_ms   Second (final) delay in milliseconds.
+ *                 Pass 0 to cancel the current delay.
+ *
+ * \note           To set a single delay, either use \c mbedtls_timing_set_timer
+ *                 directly or use this function with int_ms == fin_ms.
+ */
+void mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms);
+
+/**
+ * \brief          Get the status of delays
+ *                 (Memory helper: number of delays passed.)
+ *
+ * \param data     Pointer to timing data
+ *                 Must point to a valid \c mbedtls_timing_delay_context struct.
+ *
+ * \return         -1 if cancelled (fin_ms = 0),
+ *                  0 if none of the delays are passed,
+ *                  1 if only the intermediate delay is passed,
+ *                  2 if the final delay is passed.
+ */
+int mbedtls_timing_get_delay(void *data);
+
+#ifdef __cplusplus
+}
+
+#endif /* EXTERNAL_TIMING_FOR_TEST_H */
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 94c339e..5a563ab 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -10576,4 +10576,9 @@
 PASSES=$(( $TESTS - $FAILS ))
 echo " ($PASSES / $TESTS tests ($SKIPS skipped))"
 
+if [ $FAILS -gt 255 ]; then
+    # Clamp at 255 as caller gets exit code & 0xFF
+    # (so 256 would be 0, or success, etc)
+    FAILS=255
+fi
 exit $FAILS
diff --git a/tests/suites/test_suite_ssl.data b/tests/suites/test_suite_ssl.data
index c0b76c9..e8ac888 100644
--- a/tests/suites/test_suite_ssl.data
+++ b/tests/suites/test_suite_ssl.data
@@ -101,58 +101,59 @@
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_HELLO:1
 
 Test moving clients handshake to state: SERVER_CERTIFICATE
+depends_on:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_CERTIFICATE:1
 
 Test moving clients handshake to state: SERVER_KEY_EXCHANGE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_KEY_EXCHANGE:1
 
 Test moving clients handshake to state: CERTIFICATE_REQUEST
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CERTIFICATE_REQUEST:1
 
 Test moving clients handshake to state: SERVER_HELLO_DONE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_HELLO_DONE:1
 
 Test moving clients handshake to state: CLIENT_CERTIFICATE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CLIENT_CERTIFICATE:1
 
 Test moving clients handshake to state: CLIENT_KEY_EXCHANGE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:1
 
 Test moving clients handshake to state: CERTIFICATE_VERIFY
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CERTIFICATE_VERIFY:1
 
 Test moving clients handshake to state: CLIENT_CHANGE_CIPHER_SPEC
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:1
 
 Test moving clients handshake to state: CLIENT_FINISHED
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_CLIENT_FINISHED:1
 
 Test moving clients handshake to state: SERVER_CHANGE_CIPHER_SPEC
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:1
 
 Test moving clients handshake to state: SERVER_FINISHED
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_SERVER_FINISHED:1
 
 Test moving clients handshake to state: FLUSH_BUFFERS
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_FLUSH_BUFFERS:1
 
 Test moving clients handshake to state: HANDSHAKE_WRAPUP
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_HANDSHAKE_WRAPUP:1
 
 Test moving clients handshake to state: HANDSHAKE_OVER
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_CLIENT:MBEDTLS_SSL_HANDSHAKE_OVER:1
 
 Test moving servers handshake to state: HELLO_REQUEST
@@ -162,61 +163,63 @@
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CLIENT_HELLO:1
 
 Test moving servers handshake to state: SERVER_HELLO
+depends_on:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_HELLO:1
 
 Test moving servers handshake to state: SERVER_CERTIFICATE
+depends_on:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_CERTIFICATE:1
 
 Test moving servers handshake to state: SERVER_KEY_EXCHANGE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_KEY_EXCHANGE:1
 
 Test moving servers handshake to state: CERTIFICATE_REQUEST
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CERTIFICATE_REQUEST:1
 
 Test moving servers handshake to state: SERVER_HELLO_DONE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_HELLO_DONE:1
 
 Test moving servers handshake to state: CLIENT_CERTIFICATE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CLIENT_CERTIFICATE:1
 
 Test moving servers handshake to state: CLIENT_KEY_EXCHANGE
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:1
 
 Test moving servers handshake to state: CERTIFICATE_VERIFY
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CERTIFICATE_VERIFY:1
 
 Test moving servers handshake to state: CLIENT_CHANGE_CIPHER_SPEC
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:1
 
 Test moving servers handshake to state: CLIENT_FINISHED
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_CLIENT_FINISHED:1
 
 Test moving servers handshake to state: SERVER_CHANGE_CIPHER_SPEC
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:1
 
 Test moving servers handshake to state: SERVER_FINISHED
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_FINISHED:1
 
 Test moving servers handshake to state: FLUSH_BUFFERS
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_FLUSH_BUFFERS:1
 
 Test moving servers handshake to state: HANDSHAKE_WRAPUP
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_HANDSHAKE_WRAPUP:1
 
 Test moving servers handshake to state: HANDSHAKE_OVER
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_HANDSHAKE_OVER:1
 
 Negative test moving clients ssl to state: VERIFY_REQUEST_SENT
@@ -226,19 +229,19 @@
 move_handshake_to_state:MBEDTLS_SSL_IS_SERVER:MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:0
 
 Handshake, SSL3
-depends_on:MBEDTLS_SSL_PROTO_SSL3:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_CIPHER_MODE_CBC
+depends_on:MBEDTLS_SSL_PROTO_SSL3:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
 handshake_version:0:MBEDTLS_SSL_MINOR_VERSION_0:MBEDTLS_SSL_MINOR_VERSION_0:MBEDTLS_SSL_MINOR_VERSION_0:MBEDTLS_SSL_MINOR_VERSION_0:MBEDTLS_SSL_MINOR_VERSION_0
 
 Handshake, tls1
-depends_on:MBEDTLS_SSL_PROTO_TLS1:MBEDTLS_CIPHER_MODE_CBC
+depends_on:MBEDTLS_SSL_PROTO_TLS1:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:0:MBEDTLS_SSL_MINOR_VERSION_1:MBEDTLS_SSL_MINOR_VERSION_1:MBEDTLS_SSL_MINOR_VERSION_1:MBEDTLS_SSL_MINOR_VERSION_1:MBEDTLS_SSL_MINOR_VERSION_1
 
 Handshake, tls1_1
-depends_on:MBEDTLS_SSL_PROTO_TLS1_1:MBEDTLS_CIPHER_MODE_CBC
+depends_on:MBEDTLS_SSL_PROTO_TLS1_1:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:0:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2
 
 Handshake, tls1_2
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:0:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3
 
 Handshake, ECDHE-RSA-WITH-AES-256-GCM-SHA384
@@ -266,11 +269,11 @@
 handshake_psk_cipher:"TLS-PSK-WITH-AES-128-CBC-SHA":MBEDTLS_PK_RSA:"abc123":0
 
 DTLS Handshake, tls1_1
-depends_on:MBEDTLS_SSL_PROTO_TLS1_1:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_SSL_PROTO_DTLS
+depends_on:MBEDTLS_SSL_PROTO_TLS1_1:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:1:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2:MBEDTLS_SSL_MINOR_VERSION_2
 
 DTLS Handshake, tls1_2
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_PROTO_DTLS
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:1:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3:MBEDTLS_SSL_MINOR_VERSION_3
 
 DTLS Handshake, ECDHE-RSA-WITH-AES-256-GCM-SHA384
@@ -308,7 +311,7 @@
 handshake_fragmentation:MBEDTLS_SSL_MAX_FRAG_LEN_1024:0:1
 
 Handshake min/max version check, all -> 1.2
-depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CIPHER_MODE_CBC
+depends_on:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
 handshake_version:0:TEST_SSL_MINOR_VERSION_NONE:TEST_SSL_MINOR_VERSION_NONE:TEST_SSL_MINOR_VERSION_NONE:TEST_SSL_MINOR_VERSION_NONE:MBEDTLS_SSL_MINOR_VERSION_3
 
 Handshake min/max version check, cli max 1.1 -> 1.1
@@ -521,99 +524,99 @@
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-ECDHE-RSA-WITH-AES-256-GCM-SHA384"
 
 DTLS no legacy renegotiation with MFL=512, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS no legacy renegotiation with MFL=1024, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS no legacy renegotiation with MFL=2048, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS no legacy renegotiation with MFL=4096, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy allow renegotiation with MFL=512, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy allow renegotiation with MFL=1024, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy allow renegotiation with MFL=2048, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy allow renegotiation with MFL=4096, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy break handshake renegotiation with MFL=512, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy break handshake renegotiation with MFL=1024, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy break handshake renegotiation with MFL=2048, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS legacy break handshake renegotiation with MFL=4096, RSA-WITH-AES-128-CCM
-depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C
+depends_on:MBEDTLS_CCM_C:MBEDTLS_AES_C:MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-RSA-WITH-AES-128-CCM"
 
 DTLS no legacy renegotiation with MFL=512, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS no legacy renegotiation with MFL=1024, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS no legacy renegotiation with MFL=2048, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS no legacy renegotiation with MFL=4096, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy allow renegotiation with MFL=512, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy allow renegotiation with MFL=1024, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy allow renegotiation with MFL=2048, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy allow renegotiation with MFL=4096, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy break handshake renegotiation with MFL=512, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_512:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy break handshake renegotiation with MFL=1024, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_1024:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy break handshake renegotiation with MFL=2048, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_2048:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 DTLS legacy break handshake renegotiation with MFL=4096, DHE-RSA-WITH-AES-256-CBC-SHA256
-depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_AES_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 resize_buffers_renegotiate_mfl:MBEDTLS_SSL_MAX_FRAG_LEN_4096:MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE:"TLS-DHE-RSA-WITH-AES-256-CBC-SHA256"
 
 SSL DTLS replay: initial state, seqnum 0
@@ -10003,11 +10006,11 @@
 ssl_serialize_session_load_buf_size:1023:"data_files/server5.crt"
 
 Raw key agreement: nominal
-depends_on:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
 raw_key_agreement_fail:0
 
 Raw key agreement: bad server key
-depends_on:MBEDTLS_SHA256_C
+depends_on:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
 raw_key_agreement_fail:1
 
 Cookie parsing: nominal run
diff --git a/tests/suites/test_suite_ssl.function b/tests/suites/test_suite_ssl.function
index 5a92820..6004098 100644
--- a/tests/suites/test_suite_ssl.function
+++ b/tests/suites/test_suite_ssl.function
@@ -12,6 +12,12 @@
 
 #include <test/constant_flow.h>
 
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+    defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
+#define MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
+#endif
+
 enum {
 #define MBEDTLS_SSL_TLS1_3_LABEL(name, string)   \
     tls1_3_label_ ## name,
@@ -4072,7 +4078,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_ECP_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_ECP_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void handshake_version(int dtls, int client_min_version, int client_max_version,
                        int server_min_version, int server_max_version,
                        int expected_negotiated_version)
@@ -4151,7 +4157,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_ECP_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_ECP_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void app_data_tls(int mfl, int cli_msg_len, int srv_msg_len,
                   int expected_cli_fragments,
                   int expected_srv_fragments)
@@ -4163,7 +4169,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void app_data_dtls(int mfl, int cli_msg_len, int srv_msg_len,
                    int expected_cli_fragments,
                    int expected_srv_fragments)
@@ -4175,7 +4181,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void handshake_serialization()
 {
     handshake_test_options options;
@@ -4189,7 +4195,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_DEBUG_C:MBEDTLS_SSL_MAX_FRAGMENT_LENGTH:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_DEBUG_C:MBEDTLS_SSL_MAX_FRAGMENT_LENGTH:MBEDTLS_CIPHER_MODE_CBC:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED*/
 void handshake_fragmentation(int mfl,
                              int expected_srv_hs_fragmentation,
                              int expected_cli_hs_fragmentation)
@@ -4225,7 +4231,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void renegotiation(int legacy_renegotiation)
 {
     handshake_test_options options;
@@ -4262,7 +4268,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_CONTEXT_SERIALIZATION:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_SSL_PROTO_DTLS:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void resize_buffers_serialize_mfl(int mfl)
 {
     test_resize_buffers(mfl, 0, MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION, 1, 1,
@@ -4273,7 +4279,7 @@
 }
 /* END_CASE */
 
-/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C */
+/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED:!MBEDTLS_USE_PSA_CRYPTO:MBEDTLS_PKCS1_V15:MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH:MBEDTLS_SSL_PROTO_TLS1_2:MBEDTLS_RSA_C:MBEDTLS_ECP_DP_SECP384R1_ENABLED:MBEDTLS_ENTROPY_C:MBEDTLS_CTR_DRBG_C:MBEDTLS_SHA256_C:MBEDTLS_SSL_RENEGOTIATION:MBEDTLS_CAN_HANDLE_RSA_TEST_KEY */
 void resize_buffers_renegotiate_mfl(int mfl, int legacy_renegotiation,
                                     char *cipher)
 {
diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function
index 6fd7347..cb3f6a5 100644
--- a/tests/suites/test_suite_x509write.function
+++ b/tests/suites/test_suite_x509write.function
@@ -294,7 +294,7 @@
     TEST_ASSERT(mbedtls_pk_parse_keyfile(&issuer_key, issuer_key_file,
                                          issuer_pwd) == 0);
 
-#if defined(MBEDTLS_RSA_C)
+#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
     /* For RSA PK contexts, create a copy as an alternative RSA context. */
     if (rsa_alt == 1 && mbedtls_pk_get_type(&issuer_key) == MBEDTLS_PK_RSA) {
         TEST_ASSERT(mbedtls_pk_setup_rsa_alt(&issuer_key_alt,