Merge pull request #6559 from ihsinme/patch-1

dh_genprime: Fix issue where the error code returned by mbedtls_mpi_write_file() is incorrectly reported on failure
diff --git a/ChangeLog.d/fix_x509_info_hwmodulename.txt b/ChangeLog.d/fix_x509_info_hwmodulename.txt
new file mode 100644
index 0000000..8b227ce
--- /dev/null
+++ b/ChangeLog.d/fix_x509_info_hwmodulename.txt
@@ -0,0 +1,5 @@
+Bugfix
+   * Fix a bug in which mbedtls_x509_crt_info() would produce non-printable
+     bytes when parsing certificates containing a binary RFC 4108
+     HardwareModuleName as a Subject Alternative Name extension. Hardware
+     serial numbers are now rendered in hex format. Fixes #6262.
diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h
index ee37430..9d15955 100644
--- a/include/mbedtls/bignum.h
+++ b/include/mbedtls/bignum.h
@@ -758,11 +758,11 @@
  *
  * \param Q        The destination MPI for the quotient.
  *                 This may be \c NULL if the value of the
- *                 quotient is not needed.
+ *                 quotient is not needed. This must not alias A or B.
  * \param R        The destination MPI for the remainder value.
  *                 This may be \c NULL if the value of the
- *                 remainder is not needed.
- * \param A        The dividend. This must point to an initialized MPi.
+ *                 remainder is not needed. This must not alias A or B.
+ * \param A        The dividend. This must point to an initialized MPI.
  * \param B        The divisor. This must point to an initialized MPI.
  *
  * \return         \c 0 if successful.
@@ -779,10 +779,10 @@
  *
  * \param Q        The destination MPI for the quotient.
  *                 This may be \c NULL if the value of the
- *                 quotient is not needed.
+ *                 quotient is not needed.  This must not alias A.
  * \param R        The destination MPI for the remainder value.
  *                 This may be \c NULL if the value of the
- *                 remainder is not needed.
+ *                 remainder is not needed.  This must not alias A.
  * \param A        The dividend. This must point to an initialized MPi.
  * \param b        The divisor.
  *
@@ -837,6 +837,7 @@
  * \brief          Perform a sliding-window exponentiation: X = A^E mod N
  *
  * \param X        The destination MPI. This must point to an initialized MPI.
+ *                 This must not alias E or N.
  * \param A        The base of the exponentiation.
  *                 This must point to an initialized MPI.
  * \param E        The exponent MPI. This must point to an initialized MPI.
diff --git a/include/mbedtls/lms.h b/include/mbedtls/lms.h
index 5e03d9b..fe87d40 100644
--- a/include/mbedtls/lms.h
+++ b/include/mbedtls/lms.h
@@ -30,6 +30,7 @@
 #include <stdint.h>
 #include <stddef.h>
 
+#include "mbedtls/private_access.h"
 #include "mbedtls/build_info.h"
 
 #define MBEDTLS_ERR_LMS_BAD_INPUT_DATA   -0x0011 /**< Bad data has been input to an LMS function */
diff --git a/library/bignum_mod_raw.c b/library/bignum_mod_raw.c
index a329e86..b43add7 100644
--- a/library/bignum_mod_raw.c
+++ b/library/bignum_mod_raw.c
@@ -127,7 +127,40 @@
 /* END MERGE SLOT 6 */
 
 /* BEGIN MERGE SLOT 7 */
+int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X,
+                                     const mbedtls_mpi_mod_modulus *m )
+{
+    mbedtls_mpi_uint *T;
+    const size_t t_limbs = m->limbs * 2 + 1;
 
+    if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL )
+        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
+
+    mbedtls_mpi_core_montmul( X, X, m->rep.mont.rr, m->limbs, m->p, m->limbs,
+                              m->rep.mont.mm, T );
+
+    mbedtls_platform_zeroize( T, t_limbs * ciL );
+    mbedtls_free( T );
+    return( 0 );
+}
+
+int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X,
+                                       const mbedtls_mpi_mod_modulus *m )
+{
+    const mbedtls_mpi_uint one = 1;
+    const size_t t_limbs = m->limbs * 2 + 1;
+    mbedtls_mpi_uint *T;
+
+    if( ( T = (mbedtls_mpi_uint *) mbedtls_calloc( t_limbs, ciL ) ) == NULL )
+        return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
+
+    mbedtls_mpi_core_montmul( X, X, &one, 1, m->p, m->limbs,
+                              m->rep.mont.mm, T );
+
+    mbedtls_platform_zeroize( T, t_limbs * ciL );
+    mbedtls_free( T );
+    return( 0 );
+}
 /* END MERGE SLOT 7 */
 
 /* BEGIN MERGE SLOT 8 */
diff --git a/library/bignum_mod_raw.h b/library/bignum_mod_raw.h
index 30648d3..f738e91 100644
--- a/library/bignum_mod_raw.h
+++ b/library/bignum_mod_raw.h
@@ -163,7 +163,29 @@
 /* END MERGE SLOT 6 */
 
 /* BEGIN MERGE SLOT 7 */
+/** Convert an MPI into Montgomery form.
+ *
+ * \param X      The address of the MPI.
+ *               Must have the same number of limbs as \p m.
+ * \param m      The address of the modulus, which gives the size of
+ *               the base `R` = 2^(biL*m->limbs).
+ *
+ * \return       \c 0 if successful.
+ */
+int mbedtls_mpi_mod_raw_to_mont_rep( mbedtls_mpi_uint *X,
+                                     const mbedtls_mpi_mod_modulus *m );
 
+/** Convert an MPI back from Montgomery representation.
+ *
+ * \param X      The address of the MPI.
+ *               Must have the same number of limbs as \p m.
+ * \param m      The address of the modulus, which gives the size of
+ *               the base `R`= 2^(biL*m->limbs).
+ *
+ * \return       \c 0 if successful.
+ */
+int mbedtls_mpi_mod_raw_from_mont_rep( mbedtls_mpi_uint *X,
+                                       const mbedtls_mpi_mod_modulus *m );
 /* END MERGE SLOT 7 */
 
 /* BEGIN MERGE SLOT 8 */
diff --git a/library/constant_time_internal.h b/library/constant_time_internal.h
index 9cc63c2..1e4a3ab 100644
--- a/library/constant_time_internal.h
+++ b/library/constant_time_internal.h
@@ -138,6 +138,7 @@
  * \param B        The right-hand MPI. This must point to an array of limbs
  *                 with the same allocated length as \p A.
  * \param limbs    The number of limbs in \p A and \p B.
+ *                 This must not be 0.
  *
  * \return         The result of the comparison:
  *                 \c 1 if \p A is less than \p B.
diff --git a/library/ssl_client.c b/library/ssl_client.c
index d9c6781..0f0ea1d 100644
--- a/library/ssl_client.c
+++ b/library/ssl_client.c
@@ -106,6 +106,9 @@
 
     *olen = hostname_len + 9;
 
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_SERVERNAME );
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
     return( 0 );
 }
 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
@@ -177,6 +180,9 @@
     /* Extension length = *out_len - 2 (ext_type) - 2 (ext_len) */
     MBEDTLS_PUT_UINT16_BE( *out_len - 4, buf, 2 );
 
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_ALPN );
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
     return( 0 );
 }
 #endif /* MBEDTLS_SSL_ALPN */
@@ -296,7 +302,8 @@
     *out_len = p - buf;
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SUPPORTED_GROUPS;
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+        ssl, MBEDTLS_TLS_EXT_SUPPORTED_GROUPS );
 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
 
     return( 0 );
@@ -557,7 +564,7 @@
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
     /* Keeping track of the included extensions */
-    handshake->extensions_present = MBEDTLS_SSL_EXT_NONE;
+    handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
 #endif
 
     /* First write extensions, then the total length */
@@ -667,6 +674,11 @@
                                   p_extensions_len, extensions_len );
     }
 
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, MBEDTLS_SSL_HS_CLIENT_HELLO, handshake->sent_extensions );
+#endif
+
     *out_len = p - buf;
     return( 0 );
 }
diff --git a/library/ssl_debug_helpers.h b/library/ssl_debug_helpers.h
index 9f1df73..4412f8e 100644
--- a/library/ssl_debug_helpers.h
+++ b/library/ssl_debug_helpers.h
@@ -43,6 +43,32 @@
 
 const char *mbedtls_ssl_named_group_to_str( uint16_t in );
 
+const char *mbedtls_ssl_get_extension_name( unsigned int extension_type );
+
+void mbedtls_ssl_print_extensions( const mbedtls_ssl_context *ssl,
+                                   int level, const char *file, int line,
+                                   int hs_msg_type, uint32_t extensions_mask,
+                                   const char *extra );
+
+void mbedtls_ssl_print_extension( const mbedtls_ssl_context *ssl,
+                                  int level, const char *file, int line,
+                                  int hs_msg_type, unsigned int extension_type,
+                                  const char *extra_msg0, const char *extra_msg1 );
+
+#define MBEDTLS_SSL_PRINT_EXTS( level, hs_msg_type, extensions_mask )            \
+            mbedtls_ssl_print_extensions( ssl, level, __FILE__, __LINE__,       \
+                                          hs_msg_type, extensions_mask, NULL )
+
+#define MBEDTLS_SSL_PRINT_EXT( level, hs_msg_type, extension_type, extra )      \
+            mbedtls_ssl_print_extension( ssl, level, __FILE__, __LINE__,        \
+                                         hs_msg_type, extension_type,           \
+                                         extra, NULL )
+#else
+
+#define MBEDTLS_SSL_PRINT_EXTS( level, hs_msg_type, extension_mask )
+
+#define MBEDTLS_SSL_PRINT_EXT( level, hs_msg_type, extension_type, extra )
+
 #endif /* MBEDTLS_DEBUG_C */
 
-#endif /* SSL_DEBUG_HELPERS_H */
+#endif /* MBEDTLS_SSL_DEBUG_HELPERS_H */
diff --git a/library/ssl_misc.h b/library/ssl_misc.h
index 41bb9c5..ad8754c 100644
--- a/library/ssl_misc.h
+++ b/library/ssl_misc.h
@@ -74,34 +74,147 @@
 #define MBEDTLS_SSL_RENEGOTIATION_DONE          2   /* Done or aborted */
 #define MBEDTLS_SSL_RENEGOTIATION_PENDING       3   /* Requested (server only) */
 
-/*
- * Mask of TLS 1.3 handshake extensions used in extensions_present
- * of mbedtls_ssl_handshake_params.
- */
-#define MBEDTLS_SSL_EXT_NONE                        0
+/* Faked handshake message identity for HelloRetryRequest. */
+#define MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST ( -MBEDTLS_SSL_HS_SERVER_HELLO )
 
-#define MBEDTLS_SSL_EXT_SERVERNAME                  ( 1 <<  0 )
-#define MBEDTLS_SSL_EXT_MAX_FRAGMENT_LENGTH         ( 1 <<  1 )
-#define MBEDTLS_SSL_EXT_STATUS_REQUEST              ( 1 <<  2 )
-#define MBEDTLS_SSL_EXT_SUPPORTED_GROUPS            ( 1 <<  3 )
-#define MBEDTLS_SSL_EXT_SIG_ALG                     ( 1 <<  4 )
-#define MBEDTLS_SSL_EXT_USE_SRTP                    ( 1 <<  5 )
-#define MBEDTLS_SSL_EXT_HEARTBEAT                   ( 1 <<  6 )
-#define MBEDTLS_SSL_EXT_ALPN                        ( 1 <<  7 )
-#define MBEDTLS_SSL_EXT_SCT                         ( 1 <<  8 )
-#define MBEDTLS_SSL_EXT_CLI_CERT_TYPE               ( 1 <<  9 )
-#define MBEDTLS_SSL_EXT_SERV_CERT_TYPE              ( 1 << 10 )
-#define MBEDTLS_SSL_EXT_PADDING                     ( 1 << 11 )
-#define MBEDTLS_SSL_EXT_PRE_SHARED_KEY              ( 1 << 12 )
-#define MBEDTLS_SSL_EXT_EARLY_DATA                  ( 1 << 13 )
-#define MBEDTLS_SSL_EXT_SUPPORTED_VERSIONS          ( 1 << 14 )
-#define MBEDTLS_SSL_EXT_COOKIE                      ( 1 << 15 )
-#define MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES      ( 1 << 16 )
-#define MBEDTLS_SSL_EXT_CERT_AUTH                   ( 1 << 17 )
-#define MBEDTLS_SSL_EXT_OID_FILTERS                 ( 1 << 18 )
-#define MBEDTLS_SSL_EXT_POST_HANDSHAKE_AUTH         ( 1 << 19 )
-#define MBEDTLS_SSL_EXT_SIG_ALG_CERT                ( 1 << 20 )
-#define MBEDTLS_SSL_EXT_KEY_SHARE                   ( 1 << 21 )
+/*
+ * Internal identity of handshake extensions
+ */
+#define MBEDTLS_SSL_EXT_ID_UNRECOGNIZED                0
+#define MBEDTLS_SSL_EXT_ID_SERVERNAME                  1
+#define MBEDTLS_SSL_EXT_ID_SERVERNAME_HOSTNAME         1
+#define MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH         2
+#define MBEDTLS_SSL_EXT_ID_STATUS_REQUEST              3
+#define MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS            4
+#define MBEDTLS_SSL_EXT_ID_SUPPORTED_ELLIPTIC_CURVES   4
+#define MBEDTLS_SSL_EXT_ID_SIG_ALG                     5
+#define MBEDTLS_SSL_EXT_ID_USE_SRTP                    6
+#define MBEDTLS_SSL_EXT_ID_HEARTBEAT                   7
+#define MBEDTLS_SSL_EXT_ID_ALPN                        8
+#define MBEDTLS_SSL_EXT_ID_SCT                         9
+#define MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE              10
+#define MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE             11
+#define MBEDTLS_SSL_EXT_ID_PADDING                    12
+#define MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY             13
+#define MBEDTLS_SSL_EXT_ID_EARLY_DATA                 14
+#define MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS         15
+#define MBEDTLS_SSL_EXT_ID_COOKIE                     16
+#define MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES     17
+#define MBEDTLS_SSL_EXT_ID_CERT_AUTH                  18
+#define MBEDTLS_SSL_EXT_ID_OID_FILTERS                19
+#define MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH        20
+#define MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT               21
+#define MBEDTLS_SSL_EXT_ID_KEY_SHARE                  22
+#define MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC             23
+#define MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS    24
+#define MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC           25
+#define MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET     26
+#define MBEDTLS_SSL_EXT_ID_SESSION_TICKET             27
+
+/* Utility for translating IANA extension type. */
+uint32_t mbedtls_ssl_get_extension_id( unsigned int extension_type );
+uint32_t mbedtls_ssl_get_extension_mask( unsigned int extension_type );
+/* Macros used to define mask constants */
+#define MBEDTLS_SSL_EXT_MASK( id )       ( 1ULL << ( MBEDTLS_SSL_EXT_ID_##id ) )
+/* Reset value of extension mask */
+#define MBEDTLS_SSL_EXT_MASK_NONE                                              0
+
+/* In messages containing extension requests, we should ignore unrecognized
+ * extensions. In messages containing extension responses, unrecognized
+ * extensions should result in handshake abortion. Messages containing
+ * extension requests include ClientHello, CertificateRequest and
+ * NewSessionTicket. Messages containing extension responses include
+ * ServerHello, HelloRetryRequest, EncryptedExtensions and Certificate.
+ *
+ * RFC 8446 section 4.1.3
+ *
+ * The ServerHello MUST only include extensions which are required to establish
+ * the cryptographic context and negotiate the protocol version.
+ *
+ * RFC 8446 section 4.2
+ *
+ * If an implementation receives an extension which it recognizes and which is
+ * not specified for the message in which it appears, it MUST abort the handshake
+ * with an "illegal_parameter" alert.
+ */
+
+/* Extensions that are not recognized by TLS 1.3 */
+#define MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED                               \
+            ( MBEDTLS_SSL_EXT_MASK( SUPPORTED_POINT_FORMATS )                | \
+              MBEDTLS_SSL_EXT_MASK( ENCRYPT_THEN_MAC )                       | \
+              MBEDTLS_SSL_EXT_MASK( EXTENDED_MASTER_SECRET )                 | \
+              MBEDTLS_SSL_EXT_MASK( SESSION_TICKET )                         | \
+              MBEDTLS_SSL_EXT_MASK( TRUNCATED_HMAC )                         | \
+              MBEDTLS_SSL_EXT_MASK( UNRECOGNIZED ) )
+
+/* RFC 8446 section 4.2. Allowed extensions for ClienHello */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH                                  \
+            ( MBEDTLS_SSL_EXT_MASK( SERVERNAME )                             | \
+              MBEDTLS_SSL_EXT_MASK( MAX_FRAGMENT_LENGTH )                    | \
+              MBEDTLS_SSL_EXT_MASK( STATUS_REQUEST )                         | \
+              MBEDTLS_SSL_EXT_MASK( SUPPORTED_GROUPS )                       | \
+              MBEDTLS_SSL_EXT_MASK( SIG_ALG )                                | \
+              MBEDTLS_SSL_EXT_MASK( USE_SRTP )                               | \
+              MBEDTLS_SSL_EXT_MASK( HEARTBEAT )                              | \
+              MBEDTLS_SSL_EXT_MASK( ALPN )                                   | \
+              MBEDTLS_SSL_EXT_MASK( SCT )                                    | \
+              MBEDTLS_SSL_EXT_MASK( CLI_CERT_TYPE )                          | \
+              MBEDTLS_SSL_EXT_MASK( SERV_CERT_TYPE )                         | \
+              MBEDTLS_SSL_EXT_MASK( PADDING )                                | \
+              MBEDTLS_SSL_EXT_MASK( KEY_SHARE )                              | \
+              MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY )                         | \
+              MBEDTLS_SSL_EXT_MASK( PSK_KEY_EXCHANGE_MODES )                 | \
+              MBEDTLS_SSL_EXT_MASK( EARLY_DATA )                             | \
+              MBEDTLS_SSL_EXT_MASK( COOKIE )                                 | \
+              MBEDTLS_SSL_EXT_MASK( SUPPORTED_VERSIONS )                     | \
+              MBEDTLS_SSL_EXT_MASK( CERT_AUTH )                              | \
+              MBEDTLS_SSL_EXT_MASK( POST_HANDSHAKE_AUTH )                    | \
+              MBEDTLS_SSL_EXT_MASK( SIG_ALG_CERT )                           | \
+              MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED )
+
+/* RFC 8446 section 4.2. Allowed extensions for EncryptedExtensions */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_EE                                  \
+            ( MBEDTLS_SSL_EXT_MASK( SERVERNAME )                             | \
+              MBEDTLS_SSL_EXT_MASK( MAX_FRAGMENT_LENGTH )                    | \
+              MBEDTLS_SSL_EXT_MASK( SUPPORTED_GROUPS )                       | \
+              MBEDTLS_SSL_EXT_MASK( USE_SRTP )                               | \
+              MBEDTLS_SSL_EXT_MASK( HEARTBEAT )                              | \
+              MBEDTLS_SSL_EXT_MASK( ALPN )                                   | \
+              MBEDTLS_SSL_EXT_MASK( CLI_CERT_TYPE )                          | \
+              MBEDTLS_SSL_EXT_MASK( SERV_CERT_TYPE )                         | \
+              MBEDTLS_SSL_EXT_MASK( EARLY_DATA ) )
+
+/* RFC 8446 section 4.2. Allowed extensions for CertificateRequest */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CR                                  \
+            ( MBEDTLS_SSL_EXT_MASK( STATUS_REQUEST )                         | \
+              MBEDTLS_SSL_EXT_MASK( SIG_ALG )                                | \
+              MBEDTLS_SSL_EXT_MASK( SCT )                                    | \
+              MBEDTLS_SSL_EXT_MASK( CERT_AUTH )                              | \
+              MBEDTLS_SSL_EXT_MASK( OID_FILTERS )                            | \
+              MBEDTLS_SSL_EXT_MASK( SIG_ALG_CERT )                           | \
+              MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED )
+
+/* RFC 8446 section 4.2. Allowed extensions for Certificate */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CT                                  \
+            ( MBEDTLS_SSL_EXT_MASK( STATUS_REQUEST )                         | \
+              MBEDTLS_SSL_EXT_MASK( SCT ) )
+
+/* RFC 8446 section 4.2. Allowed extensions for ServerHello */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_SH                                  \
+            ( MBEDTLS_SSL_EXT_MASK( KEY_SHARE )                              | \
+              MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY )                         | \
+              MBEDTLS_SSL_EXT_MASK( SUPPORTED_VERSIONS ) )
+
+/* RFC 8446 section 4.2. Allowed extensions for HelloRetryRequest */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_HRR                                 \
+            ( MBEDTLS_SSL_EXT_MASK( KEY_SHARE )                              | \
+              MBEDTLS_SSL_EXT_MASK( COOKIE )                                 | \
+              MBEDTLS_SSL_EXT_MASK( SUPPORTED_VERSIONS ) )
+
+/* RFC 8446 section 4.2. Allowed extensions for NewSessionTicket */
+#define MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_NST                                 \
+            ( MBEDTLS_SSL_EXT_MASK( EARLY_DATA )                             | \
+              MBEDTLS_SSL_TLS1_3_EXT_MASK_UNRECOGNIZED )
 
 /*
  * Helper macros for function call with return check.
@@ -858,9 +971,8 @@
 #endif
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
-    int extensions_present;             /*!< extension presence; Each bitfield
-                                             represents an extension and defined
-                                             as \c MBEDTLS_SSL_EXT_XXX */
+    uint32_t sent_extensions;       /*!< extensions sent by endpoint */
+    uint32_t received_extensions;   /*!< extensions received by endpoint */
 
 #if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
     unsigned char certificate_request_context_len;
@@ -1839,6 +1951,24 @@
           MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
 
 /*
+ * Helper functions for extensions checking.
+ */
+
+MBEDTLS_CHECK_RETURN_CRITICAL
+int mbedtls_ssl_tls13_check_received_extension(
+        mbedtls_ssl_context *ssl,
+        int hs_msg_type,
+        unsigned int received_extension_type,
+        uint32_t hs_msg_allowed_extensions_mask );
+
+static inline void mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+                       mbedtls_ssl_context *ssl, unsigned int extension_type )
+{
+    ssl->handshake->sent_extensions |=
+        mbedtls_ssl_get_extension_mask( extension_type );
+}
+
+/*
  * Helper functions to check the selected key exchange mode.
  */
 static inline int mbedtls_ssl_tls13_key_exchange_mode_check(
diff --git a/library/ssl_msg.c b/library/ssl_msg.c
index 4cd4107..dbc6391 100644
--- a/library/ssl_msg.c
+++ b/library/ssl_msg.c
@@ -1797,8 +1797,7 @@
 
     if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
     {
-        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
-                            "or mbedtls_ssl_set_bio()" ) );
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " ) );
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
     }
 
@@ -2013,8 +2012,7 @@
 
     if( ssl->f_send == NULL )
     {
-        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
-                            "or mbedtls_ssl_set_bio()" ) );
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " ) );
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
     }
 
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index dbbd6f2..da90b23 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -521,6 +521,245 @@
 }
 #endif /* MBEDTLS_X509_CRT_PARSE_C */
 
+uint32_t mbedtls_ssl_get_extension_id( unsigned int extension_type )
+{
+    switch( extension_type )
+    {
+        case MBEDTLS_TLS_EXT_SERVERNAME:
+            return( MBEDTLS_SSL_EXT_ID_SERVERNAME );
+
+        case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
+            return( MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH );
+
+        case MBEDTLS_TLS_EXT_STATUS_REQUEST:
+            return( MBEDTLS_SSL_EXT_ID_STATUS_REQUEST );
+
+        case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
+            return( MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS );
+
+        case MBEDTLS_TLS_EXT_SIG_ALG:
+            return( MBEDTLS_SSL_EXT_ID_SIG_ALG );
+
+        case MBEDTLS_TLS_EXT_USE_SRTP:
+            return( MBEDTLS_SSL_EXT_ID_USE_SRTP );
+
+        case MBEDTLS_TLS_EXT_HEARTBEAT:
+            return( MBEDTLS_SSL_EXT_ID_HEARTBEAT );
+
+        case MBEDTLS_TLS_EXT_ALPN:
+            return( MBEDTLS_SSL_EXT_ID_ALPN );
+
+        case MBEDTLS_TLS_EXT_SCT:
+            return( MBEDTLS_SSL_EXT_ID_SCT );
+
+        case MBEDTLS_TLS_EXT_CLI_CERT_TYPE:
+            return( MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE );
+
+        case MBEDTLS_TLS_EXT_SERV_CERT_TYPE:
+            return( MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE );
+
+        case MBEDTLS_TLS_EXT_PADDING:
+            return( MBEDTLS_SSL_EXT_ID_PADDING );
+
+        case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
+            return( MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY );
+
+        case MBEDTLS_TLS_EXT_EARLY_DATA:
+            return( MBEDTLS_SSL_EXT_ID_EARLY_DATA );
+
+        case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS:
+            return( MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS );
+
+        case MBEDTLS_TLS_EXT_COOKIE:
+            return( MBEDTLS_SSL_EXT_ID_COOKIE );
+
+        case MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES:
+            return( MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES );
+
+        case MBEDTLS_TLS_EXT_CERT_AUTH:
+            return( MBEDTLS_SSL_EXT_ID_CERT_AUTH );
+
+        case MBEDTLS_TLS_EXT_OID_FILTERS:
+            return( MBEDTLS_SSL_EXT_ID_OID_FILTERS );
+
+        case MBEDTLS_TLS_EXT_POST_HANDSHAKE_AUTH:
+            return( MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH );
+
+        case MBEDTLS_TLS_EXT_SIG_ALG_CERT:
+            return( MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT );
+
+        case MBEDTLS_TLS_EXT_KEY_SHARE:
+            return( MBEDTLS_SSL_EXT_ID_KEY_SHARE );
+
+        case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
+            return( MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC );
+
+        case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
+            return( MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS );
+
+        case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
+            return( MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC );
+
+        case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
+            return( MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET );
+
+        case MBEDTLS_TLS_EXT_SESSION_TICKET:
+            return( MBEDTLS_SSL_EXT_ID_SESSION_TICKET );
+
+    }
+
+    return( MBEDTLS_SSL_EXT_ID_UNRECOGNIZED );
+}
+
+uint32_t mbedtls_ssl_get_extension_mask( unsigned int extension_type )
+{
+    return( 1 << mbedtls_ssl_get_extension_id( extension_type ) );
+}
+
+#if defined(MBEDTLS_DEBUG_C)
+static const char *extension_name_table[] = {
+    [MBEDTLS_SSL_EXT_ID_UNRECOGNIZED] = "unrecognized",
+    [MBEDTLS_SSL_EXT_ID_SERVERNAME] = "server_name",
+    [MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH] = "max_fragment_length",
+    [MBEDTLS_SSL_EXT_ID_STATUS_REQUEST] = "status_request",
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS] = "supported_groups",
+    [MBEDTLS_SSL_EXT_ID_SIG_ALG] = "signature_algorithms",
+    [MBEDTLS_SSL_EXT_ID_USE_SRTP] = "use_srtp",
+    [MBEDTLS_SSL_EXT_ID_HEARTBEAT] = "heartbeat",
+    [MBEDTLS_SSL_EXT_ID_ALPN] = "application_layer_protocol_negotiation",
+    [MBEDTLS_SSL_EXT_ID_SCT] = "signed_certificate_timestamp",
+    [MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE] = "client_certificate_type",
+    [MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE] = "server_certificate_type",
+    [MBEDTLS_SSL_EXT_ID_PADDING] = "padding",
+    [MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY] = "pre_shared_key",
+    [MBEDTLS_SSL_EXT_ID_EARLY_DATA] = "early_data",
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS] = "supported_versions",
+    [MBEDTLS_SSL_EXT_ID_COOKIE] = "cookie",
+    [MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES] = "psk_key_exchange_modes",
+    [MBEDTLS_SSL_EXT_ID_CERT_AUTH] = "certificate_authorities",
+    [MBEDTLS_SSL_EXT_ID_OID_FILTERS] = "oid_filters",
+    [MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH] = "post_handshake_auth",
+    [MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT] = "signature_algorithms_cert",
+    [MBEDTLS_SSL_EXT_ID_KEY_SHARE] = "key_share",
+    [MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC] = "truncated_hmac",
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS] = "supported_point_formats",
+    [MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC] = "encrypt_then_mac",
+    [MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET] = "extended_master_secret",
+    [MBEDTLS_SSL_EXT_ID_SESSION_TICKET] = "session_ticket"
+};
+
+static unsigned int extension_type_table[]={
+    [MBEDTLS_SSL_EXT_ID_UNRECOGNIZED] = 0xff,
+    [MBEDTLS_SSL_EXT_ID_SERVERNAME] = MBEDTLS_TLS_EXT_SERVERNAME,
+    [MBEDTLS_SSL_EXT_ID_MAX_FRAGMENT_LENGTH] = MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH,
+    [MBEDTLS_SSL_EXT_ID_STATUS_REQUEST] = MBEDTLS_TLS_EXT_STATUS_REQUEST,
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_GROUPS] = MBEDTLS_TLS_EXT_SUPPORTED_GROUPS,
+    [MBEDTLS_SSL_EXT_ID_SIG_ALG] = MBEDTLS_TLS_EXT_SIG_ALG,
+    [MBEDTLS_SSL_EXT_ID_USE_SRTP] = MBEDTLS_TLS_EXT_USE_SRTP,
+    [MBEDTLS_SSL_EXT_ID_HEARTBEAT] = MBEDTLS_TLS_EXT_HEARTBEAT,
+    [MBEDTLS_SSL_EXT_ID_ALPN] = MBEDTLS_TLS_EXT_ALPN,
+    [MBEDTLS_SSL_EXT_ID_SCT] = MBEDTLS_TLS_EXT_SCT,
+    [MBEDTLS_SSL_EXT_ID_CLI_CERT_TYPE] = MBEDTLS_TLS_EXT_CLI_CERT_TYPE,
+    [MBEDTLS_SSL_EXT_ID_SERV_CERT_TYPE] = MBEDTLS_TLS_EXT_SERV_CERT_TYPE,
+    [MBEDTLS_SSL_EXT_ID_PADDING] = MBEDTLS_TLS_EXT_PADDING,
+    [MBEDTLS_SSL_EXT_ID_PRE_SHARED_KEY] = MBEDTLS_TLS_EXT_PRE_SHARED_KEY,
+    [MBEDTLS_SSL_EXT_ID_EARLY_DATA] = MBEDTLS_TLS_EXT_EARLY_DATA,
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_VERSIONS] = MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS,
+    [MBEDTLS_SSL_EXT_ID_COOKIE] = MBEDTLS_TLS_EXT_COOKIE,
+    [MBEDTLS_SSL_EXT_ID_PSK_KEY_EXCHANGE_MODES] = MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES,
+    [MBEDTLS_SSL_EXT_ID_CERT_AUTH] = MBEDTLS_TLS_EXT_CERT_AUTH,
+    [MBEDTLS_SSL_EXT_ID_OID_FILTERS] = MBEDTLS_TLS_EXT_OID_FILTERS,
+    [MBEDTLS_SSL_EXT_ID_POST_HANDSHAKE_AUTH] = MBEDTLS_TLS_EXT_POST_HANDSHAKE_AUTH,
+    [MBEDTLS_SSL_EXT_ID_SIG_ALG_CERT] = MBEDTLS_TLS_EXT_SIG_ALG_CERT,
+    [MBEDTLS_SSL_EXT_ID_KEY_SHARE] = MBEDTLS_TLS_EXT_KEY_SHARE,
+    [MBEDTLS_SSL_EXT_ID_TRUNCATED_HMAC] = MBEDTLS_TLS_EXT_TRUNCATED_HMAC,
+    [MBEDTLS_SSL_EXT_ID_SUPPORTED_POINT_FORMATS] = MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS,
+    [MBEDTLS_SSL_EXT_ID_ENCRYPT_THEN_MAC] = MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC,
+    [MBEDTLS_SSL_EXT_ID_EXTENDED_MASTER_SECRET] = MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET,
+    [MBEDTLS_SSL_EXT_ID_SESSION_TICKET] = MBEDTLS_TLS_EXT_SESSION_TICKET
+};
+
+const char *mbedtls_ssl_get_extension_name( unsigned int extension_type )
+{
+    return( extension_name_table[
+                mbedtls_ssl_get_extension_id( extension_type ) ] );
+}
+
+static const char *ssl_tls13_get_hs_msg_name( int hs_msg_type )
+{
+    switch( hs_msg_type )
+    {
+        case MBEDTLS_SSL_HS_CLIENT_HELLO:
+            return( "ClientHello" );
+        case MBEDTLS_SSL_HS_SERVER_HELLO:
+            return( "ServerHello" );
+        case MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST:
+            return( "HelloRetryRequest" );
+        case MBEDTLS_SSL_HS_NEW_SESSION_TICKET:
+            return( "NewSessionTicket" );
+        case MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS:
+            return( "EncryptedExtensions" );
+        case MBEDTLS_SSL_HS_CERTIFICATE:
+            return( "Certificate" );
+        case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST:
+            return( "CertificateRequest" );
+    }
+    return( "Unknown" );
+}
+
+void mbedtls_ssl_print_extension( const mbedtls_ssl_context *ssl,
+                                  int level, const char *file, int line,
+                                  int hs_msg_type, unsigned int extension_type,
+                                  const char *extra_msg0, const char *extra_msg1 )
+{
+    const char *extra_msg;
+    if( extra_msg0 && extra_msg1 )
+    {
+        mbedtls_debug_print_msg(
+            ssl, level, file, line,
+            "%s: %s(%u) extension %s %s.",
+            ssl_tls13_get_hs_msg_name( hs_msg_type ),
+            mbedtls_ssl_get_extension_name( extension_type ),
+            extension_type,
+            extra_msg0, extra_msg1 );
+        return;
+    }
+
+    extra_msg = extra_msg0 ? extra_msg0 : extra_msg1;
+    if( extra_msg )
+    {
+        mbedtls_debug_print_msg(
+            ssl, level, file, line,
+            "%s: %s(%u) extension %s.", ssl_tls13_get_hs_msg_name( hs_msg_type ),
+            mbedtls_ssl_get_extension_name( extension_type ), extension_type,
+            extra_msg );
+        return;
+    }
+
+    mbedtls_debug_print_msg(
+        ssl, level, file, line,
+        "%s: %s(%u) extension.", ssl_tls13_get_hs_msg_name( hs_msg_type ),
+        mbedtls_ssl_get_extension_name( extension_type ), extension_type );
+}
+
+void mbedtls_ssl_print_extensions( const mbedtls_ssl_context *ssl,
+                                   int level, const char *file, int line,
+                                   int hs_msg_type, uint32_t extensions_mask,
+                                   const char *extra )
+{
+
+    for( unsigned i = 0;
+         i < sizeof( extension_name_table ) / sizeof( extension_name_table[0] );
+         i++ )
+    {
+        mbedtls_ssl_print_extension(
+            ssl, level, file, line, hs_msg_type, extension_type_table[i],
+            extensions_mask & ( 1 << i ) ? "exists" : "does not exist", extra );
+    }
+}
+
+#endif /* MBEDTLS_DEBUG_C */
+
 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
 {
@@ -8744,8 +8983,9 @@
     *out_len = p - buf;
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SIG_ALG;
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_SIG_ALG );
 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+
     return( 0 );
 }
 #endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
@@ -8944,6 +9184,11 @@
     p[6] = MBEDTLS_BYTE_0( protocol_name_len );
 
     memcpy( p + 7, ssl->alpn_chosen, protocol_name_len );
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_ALPN );
+#endif
+
     return ( 0 );
 }
 #endif /* MBEDTLS_SSL_ALPN */
diff --git a/library/ssl_tls13_client.c b/library/ssl_tls13_client.c
index ac19f63..9940a0e 100644
--- a/library/ssl_tls13_client.c
+++ b/library/ssl_tls13_client.c
@@ -32,6 +32,7 @@
 #include "ssl_misc.h"
 #include "ssl_client.h"
 #include "ssl_tls13_keys.h"
+#include "ssl_debug_helpers.h"
 
 /* Write extensions */
 
@@ -89,6 +90,9 @@
 
     *out_len = 5 + versions_len;
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+        ssl, MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS );
+
     return( 0 );
 }
 
@@ -359,7 +363,7 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, key_share extension", buf, *out_len );
 
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_KEY_SHARE;
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_KEY_SHARE );
 
 cleanup:
 
@@ -512,7 +516,6 @@
     else
         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
 
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_KEY_SHARE;
     return( ret );
 }
 
@@ -600,6 +603,8 @@
 
     *out_len = handshake->hrr_cookie_len + 6;
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_COOKIE );
+
     return( 0 );
 }
 
@@ -669,7 +674,10 @@
     buf[4] = ke_modes_len;
 
     *out_len = p - buf;
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES;
+
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+        ssl, MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES );
+
     return ( 0 );
 }
 
@@ -981,8 +989,6 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "pre_shared_key identities", buf, p - buf );
 
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_PRE_SHARED_KEY;
-
     return( 0 );
 }
 
@@ -1037,6 +1043,9 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "pre_shared_key binders", buf, p - buf );
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+        ssl, MBEDTLS_TLS_EXT_PRE_SHARED_KEY );
+
     return( 0 );
 }
 
@@ -1109,8 +1118,6 @@
         return( ret );
     }
 
-    ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_PRE_SHARED_KEY;
-
     return( 0 );
 }
 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
@@ -1388,7 +1395,7 @@
     ssl->session_negotiate->tls_version = ssl->tls_version;
 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
 
-    handshake->extensions_present = MBEDTLS_SSL_EXT_NONE;
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
 
     ret = ssl_server_hello_is_hrr( ssl, buf, end );
     switch( ret )
@@ -1498,6 +1505,9 @@
     uint16_t cipher_suite;
     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
     int fatal_alert = 0;
+    uint32_t allowed_extensions_mask;
+    int hs_msg_type = is_hrr ? MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST :
+                               MBEDTLS_SSL_HS_SERVER_HELLO;
 
     /*
      * Check there is space for minimal fields
@@ -1640,6 +1650,11 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello extensions", p, extensions_len );
 
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+    allowed_extensions_mask = is_hrr ?
+                                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_HRR :
+                                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_SH;
+
     while( p < extensions_end )
     {
         unsigned int extension_type;
@@ -1654,16 +1669,15 @@
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, extension_data_len );
         extension_data_end = p + extension_data_len;
 
+        ret = mbedtls_ssl_tls13_check_received_extension(
+                  ssl, hs_msg_type, extension_type, allowed_extensions_mask );
+        if( ret != 0 )
+            return( ret );
+
         switch( extension_type )
         {
             case MBEDTLS_TLS_EXT_COOKIE:
 
-                if( !is_hrr )
-                {
-                    fatal_alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT;
-                    goto cleanup;
-                }
-
                 ret = ssl_tls13_parse_cookie_ext( ssl,
                                                   p, extension_data_end );
                 if( ret != 0 )
@@ -1686,11 +1700,6 @@
 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
             case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found pre_shared_key extension" ) );
-                if( is_hrr )
-                {
-                    fatal_alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT;
-                    goto cleanup;
-                }
 
                 if( ( ret = ssl_tls13_parse_server_pre_shared_key_ext(
                                 ssl, p, extension_data_end ) ) != 0 )
@@ -1726,18 +1735,15 @@
                 break;
 
             default:
-                MBEDTLS_SSL_DEBUG_MSG(
-                    3,
-                    ( "unknown extension found: %u ( ignoring )",
-                      extension_type ) );
-
-                fatal_alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT;
+                ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
                 goto cleanup;
         }
 
         p += extension_data_len;
     }
 
+    MBEDTLS_SSL_PRINT_EXTS( 3, hs_msg_type, handshake->received_extensions );
+
 cleanup:
 
     if( fatal_alert == MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT )
@@ -1786,21 +1792,21 @@
      * 3) If only the key_share extension was received then the key
      *    exchange mode is EPHEMERAL-only.
      */
-    switch( handshake->extensions_present &
-            ( MBEDTLS_SSL_EXT_PRE_SHARED_KEY | MBEDTLS_SSL_EXT_KEY_SHARE ) )
+    switch( handshake->received_extensions &
+            ( MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY ) | MBEDTLS_SSL_EXT_MASK( KEY_SHARE ) ) )
     {
         /* Only the pre_shared_key extension was received */
-        case MBEDTLS_SSL_EXT_PRE_SHARED_KEY:
+        case MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY ):
             handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
             break;
 
         /* Only the key_share extension was received */
-        case MBEDTLS_SSL_EXT_KEY_SHARE:
+        case MBEDTLS_SSL_EXT_MASK( KEY_SHARE ):
             handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
             break;
 
         /* Both the pre_shared_key and key_share extensions were received */
-        case ( MBEDTLS_SSL_EXT_PRE_SHARED_KEY | MBEDTLS_SSL_EXT_KEY_SHARE ):
+        case ( MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY ) | MBEDTLS_SSL_EXT_MASK( KEY_SHARE ) ):
             handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
             break;
 
@@ -1969,6 +1975,7 @@
     size_t extensions_len;
     const unsigned char *p = buf;
     const unsigned char *extensions_end;
+    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
 
     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
     extensions_len = MBEDTLS_GET_UINT16_BE( p, 0 );
@@ -1978,6 +1985,8 @@
     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, extensions_len );
     extensions_end = p + extensions_len;
 
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+
     while( p < extensions_end )
     {
         unsigned int extension_type;
@@ -1996,22 +2005,14 @@
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, extension_data_len );
 
-        /* The client MUST check EncryptedExtensions for the
-         * presence of any forbidden extensions and if any are found MUST abort
-         * the handshake with an "unsupported_extension" alert.
-         */
+        ret = mbedtls_ssl_tls13_check_received_extension(
+                  ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS, extension_type,
+                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_EE );
+        if( ret != 0 )
+            return( ret );
+
         switch( extension_type )
         {
-            case MBEDTLS_TLS_EXT_SERVERNAME:
-                MBEDTLS_SSL_DEBUG_MSG( 3, ( "found server_name extension" ) );
-
-                /* The server_name extension should be an empty extension */
-
-                break;
-            case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
-                MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extensions supported groups" ) );
-                break;
-
 #if defined(MBEDTLS_SSL_ALPN)
             case MBEDTLS_TLS_EXT_ALPN:
                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
@@ -2024,17 +2025,18 @@
                 break;
 #endif /* MBEDTLS_SSL_ALPN */
             default:
-                MBEDTLS_SSL_DEBUG_MSG(
-                    3, ( "unsupported extension found: %u ", extension_type) );
-                MBEDTLS_SSL_PEND_FATAL_ALERT(
-                    MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT,
-                    MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
-                return ( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
+                MBEDTLS_SSL_PRINT_EXT(
+                    3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
+                    extension_type, "( ignored )" );
+                break;
         }
 
         p += extension_data_len;
     }
 
+    MBEDTLS_SSL_PRINT_EXTS( 3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
+                            handshake->received_extensions );
+
     /* Check that we consumed all the message. */
     if( p != end )
     {
@@ -2140,7 +2142,7 @@
     size_t certificate_request_context_len = 0;
     size_t extensions_len = 0;
     const unsigned char *extensions_end;
-    unsigned char sig_alg_ext_found = 0;
+    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
 
     /* ...
      * opaque certificate_request_context<0..2^8-1>
@@ -2156,7 +2158,6 @@
         MBEDTLS_SSL_DEBUG_BUF( 3, "Certificate Request Context",
                                p, certificate_request_context_len );
 
-        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
         handshake->certificate_request_context =
                 mbedtls_calloc( 1, certificate_request_context_len );
         if( handshake->certificate_request_context == NULL )
@@ -2180,6 +2181,8 @@
     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, extensions_len );
     extensions_end = p + extensions_len;
 
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+
     while( p < extensions_end )
     {
         unsigned int extension_type;
@@ -2192,6 +2195,12 @@
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, extension_data_len );
 
+        ret = mbedtls_ssl_tls13_check_received_extension(
+                  ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST, extension_type,
+                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CR );
+        if( ret != 0 )
+            return( ret );
+
         switch( extension_type )
         {
             case MBEDTLS_TLS_EXT_SIG_ALG:
@@ -2201,25 +2210,22 @@
                                                      p + extension_data_len );
                 if( ret != 0 )
                     return( ret );
-                if( ! sig_alg_ext_found )
-                    sig_alg_ext_found = 1;
-                else
-                {
-                    MBEDTLS_SSL_DEBUG_MSG( 3,
-                        ( "Duplicate signature algorithms extensions found" ) );
-                    goto decode_error;
-                }
+
                 break;
 
             default:
-                MBEDTLS_SSL_DEBUG_MSG(
-                    3,
-                    ( "unknown extension found: %u ( ignoring )",
-                    extension_type ) );
+                MBEDTLS_SSL_PRINT_EXT(
+                    3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
+                    extension_type, "( ignored )" );
                 break;
         }
+
         p += extension_data_len;
     }
+
+    MBEDTLS_SSL_PRINT_EXTS( 3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
+                            handshake->received_extensions );
+
     /* Check that we consumed all the message. */
     if( p != end )
     {
@@ -2227,8 +2233,12 @@
             ( "CertificateRequest misaligned" ) );
         goto decode_error;
     }
-    /* Check that we found signature algorithms extension */
-    if( ! sig_alg_ext_found )
+
+    /* RFC 8446 section 4.3.2
+     *
+     * The "signature_algorithms" extension MUST be specified
+     */
+    if( ( handshake->received_extensions & MBEDTLS_SSL_EXT_MASK( SIG_ALG ) ) == 0 )
     {
         MBEDTLS_SSL_DEBUG_MSG( 3,
             ( "no signature algorithms extension found" ) );
@@ -2468,14 +2478,17 @@
                                                     const unsigned char *buf,
                                                     const unsigned char *end )
 {
+    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
     const unsigned char *p = buf;
 
-    ((void) ssl);
+
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
 
     while( p < end )
     {
         unsigned int extension_type;
         size_t extension_data_len;
+        int ret;
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 4 );
         extension_type = MBEDTLS_GET_UINT16_BE( p, 0 );
@@ -2484,18 +2497,27 @@
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, extension_data_len );
 
+        ret = mbedtls_ssl_tls13_check_received_extension(
+                  ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET, extension_type,
+                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_NST );
+        if( ret != 0 )
+            return( ret );
+
         switch( extension_type )
         {
-            case MBEDTLS_TLS_EXT_EARLY_DATA:
-                MBEDTLS_SSL_DEBUG_MSG( 4, ( "early_data extension received" ) );
-                break;
-
             default:
+                MBEDTLS_SSL_PRINT_EXT(
+                    3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
+                    extension_type, "( ignored )" );
                 break;
         }
+
         p +=  extension_data_len;
     }
 
+    MBEDTLS_SSL_PRINT_EXTS( 3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
+                            handshake->received_extensions );
+
     return( 0 );
 }
 
diff --git a/library/ssl_tls13_generic.c b/library/ssl_tls13_generic.c
index 48e3675..f854998 100644
--- a/library/ssl_tls13_generic.c
+++ b/library/ssl_tls13_generic.c
@@ -398,6 +398,7 @@
     size_t certificate_list_len = 0;
     const unsigned char *p = buf;
     const unsigned char *certificate_list_end;
+    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
 
     MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 4 );
     certificate_request_context_len = p[0];
@@ -447,6 +448,7 @@
     while( p < certificate_list_end )
     {
         size_t cert_data_len, extensions_len;
+        const unsigned char *extensions_end;
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, 3 );
         cert_data_len = MBEDTLS_GET_UINT24_BE( p, 0 );
@@ -504,7 +506,48 @@
         extensions_len = MBEDTLS_GET_UINT16_BE( p, 0 );
         p += 2;
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, certificate_list_end, extensions_len );
-        p += extensions_len;
+
+        extensions_end = p + extensions_len;
+        handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+
+        while( p < extensions_end )
+        {
+            unsigned int extension_type;
+            size_t extension_data_len;
+
+            /*
+            * struct {
+            *     ExtensionType extension_type; (2 bytes)
+            *     opaque extension_data<0..2^16-1>;
+            * } Extension;
+            */
+            MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, 4 );
+            extension_type = MBEDTLS_GET_UINT16_BE( p, 0 );
+            extension_data_len = MBEDTLS_GET_UINT16_BE( p, 2 );
+            p += 4;
+
+            MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, extension_data_len );
+
+            ret = mbedtls_ssl_tls13_check_received_extension(
+                      ssl, MBEDTLS_SSL_HS_CERTIFICATE, extension_type,
+                      MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CT );
+            if( ret != 0 )
+                return( ret );
+
+            switch( extension_type )
+            {
+                default:
+                    MBEDTLS_SSL_PRINT_EXT(
+                        3, MBEDTLS_SSL_HS_CERTIFICATE,
+                        extension_type, "( ignored )" );
+                    break;
+            }
+
+            p += extension_data_len;
+        }
+
+        MBEDTLS_SSL_PRINT_EXTS( 3, MBEDTLS_SSL_HS_CERTIFICATE,
+                                handshake->received_extensions );
     }
 
 exit:
@@ -512,7 +555,7 @@
     if( p != end )
     {
         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad Certificate message" ) );
-        MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR, \
+        MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
                                       MBEDTLS_ERR_SSL_DECODE_ERROR );
         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
     }
@@ -843,6 +886,9 @@
 
     *out_len = p - buf;
 
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, MBEDTLS_SSL_HS_CERTIFICATE, ssl->handshake->sent_extensions );
+
     return( 0 );
 }
 
@@ -1485,4 +1531,61 @@
 }
 #endif /* MBEDTLS_ECDH_C */
 
+/* RFC 8446 section 4.2
+ *
+ * If an implementation receives an extension which it recognizes and which is
+ * not specified for the message in which it appears, it MUST abort the handshake
+ * with an "illegal_parameter" alert.
+ *
+ */
+int mbedtls_ssl_tls13_check_received_extension(
+        mbedtls_ssl_context *ssl,
+        int hs_msg_type,
+        unsigned int received_extension_type,
+        uint32_t hs_msg_allowed_extensions_mask )
+{
+    uint32_t extension_mask = mbedtls_ssl_get_extension_mask(
+                                  received_extension_type );
+
+    MBEDTLS_SSL_PRINT_EXT(
+        3, hs_msg_type, received_extension_type, "received" );
+
+    if( ( extension_mask & hs_msg_allowed_extensions_mask ) == 0 )
+    {
+        MBEDTLS_SSL_PRINT_EXT(
+            3, hs_msg_type, received_extension_type, "is illegal" );
+        MBEDTLS_SSL_PEND_FATAL_ALERT(
+            MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
+            MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
+        return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
+    }
+
+    ssl->handshake->received_extensions |= extension_mask;
+    /*
+     * If it is a message containing extension responses, check that we
+     * previously sent the extension.
+     */
+    switch( hs_msg_type )
+    {
+        case MBEDTLS_SSL_HS_SERVER_HELLO:
+        case MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST:
+        case MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS:
+        case MBEDTLS_SSL_HS_CERTIFICATE:
+            /* Check if the received extension is sent by peer message.*/
+            if( ( ssl->handshake->sent_extensions & extension_mask ) != 0 )
+                return( 0 );
+            break;
+        default:
+            return( 0 );
+    }
+
+    MBEDTLS_SSL_PRINT_EXT(
+            3, hs_msg_type, received_extension_type, "is unsupported" );
+    MBEDTLS_SSL_PEND_FATAL_ALERT(
+        MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT,
+        MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
+    return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
+}
+
 #endif /* MBEDTLS_SSL_TLS_C && MBEDTLS_SSL_PROTO_TLS1_3 */
+
diff --git a/library/ssl_tls13_server.c b/library/ssl_tls13_server.c
index 3762393..3cd0310 100644
--- a/library/ssl_tls13_server.c
+++ b/library/ssl_tls13_server.c
@@ -700,6 +700,8 @@
     MBEDTLS_SSL_DEBUG_MSG( 4, ( "sent selected_identity: %u",
                                 ssl->handshake->selected_identity ) );
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_PRE_SHARED_KEY );
+
     return( 0 );
 }
 
@@ -926,110 +928,69 @@
 }
 #endif /* MBEDTLS_ECDH_C */
 
-#if defined(MBEDTLS_DEBUG_C)
-static void ssl_tls13_debug_print_client_hello_exts( mbedtls_ssl_context *ssl )
-{
-    ((void) ssl);
-
-    MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Extensions:" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- KEY_SHARE_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_KEY_SHARE ) > 0 ) ? "TRUE" : "FALSE" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- PSK_KEY_EXCHANGE_MODES_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES ) > 0 ) ?
-                "TRUE" : "FALSE" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- PRE_SHARED_KEY_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_PRE_SHARED_KEY ) > 0 ) ? "TRUE" : "FALSE" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- SIGNATURE_ALGORITHM_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_SIG_ALG ) > 0 ) ? "TRUE" : "FALSE" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- SUPPORTED_GROUPS_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_SUPPORTED_GROUPS ) >0 ) ?
-                "TRUE" : "FALSE" ) );
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- SUPPORTED_VERSION_EXTENSION ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_SUPPORTED_VERSIONS ) > 0 ) ?
-                "TRUE" : "FALSE" ) );
-#if defined ( MBEDTLS_SSL_SERVER_NAME_INDICATION )
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- SERVERNAME_EXTENSION    ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_SERVERNAME ) > 0 ) ?
-                "TRUE" : "FALSE" ) );
-#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
-#if defined ( MBEDTLS_SSL_ALPN )
-    MBEDTLS_SSL_DEBUG_MSG( 3,
-            ( "- ALPN_EXTENSION   ( %s )",
-            ( ( ssl->handshake->extensions_present
-                & MBEDTLS_SSL_EXT_ALPN ) > 0 ) ?
-                "TRUE" : "FALSE" ) );
-#endif /* MBEDTLS_SSL_ALPN */
-}
-#endif /* MBEDTLS_DEBUG_C */
-
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_client_hello_has_exts( mbedtls_ssl_context *ssl,
                                             int exts_mask )
 {
-    int masked = ssl->handshake->extensions_present & exts_mask;
+    int masked = ssl->handshake->received_extensions & exts_mask;
     return( masked == exts_mask );
 }
 
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(
         mbedtls_ssl_context *ssl )
 {
     return( ssl_tls13_client_hello_has_exts(
                 ssl,
-                MBEDTLS_SSL_EXT_SUPPORTED_GROUPS |
-                MBEDTLS_SSL_EXT_KEY_SHARE        |
-                MBEDTLS_SSL_EXT_SIG_ALG ) );
+                MBEDTLS_SSL_EXT_MASK( SUPPORTED_GROUPS ) |
+                MBEDTLS_SSL_EXT_MASK( KEY_SHARE )        |
+                MBEDTLS_SSL_EXT_MASK( SIG_ALG ) ) );
 }
+#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
 
-#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_client_hello_has_exts_for_psk_key_exchange(
                mbedtls_ssl_context *ssl )
 {
     return( ssl_tls13_client_hello_has_exts(
                 ssl,
-                MBEDTLS_SSL_EXT_PRE_SHARED_KEY          |
-                MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES ) );
+                MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY )          |
+                MBEDTLS_SSL_EXT_MASK( PSK_KEY_EXCHANGE_MODES ) ) );
 }
+#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED */
 
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(
                mbedtls_ssl_context *ssl )
 {
     return( ssl_tls13_client_hello_has_exts(
                 ssl,
-                MBEDTLS_SSL_EXT_SUPPORTED_GROUPS        |
-                MBEDTLS_SSL_EXT_KEY_SHARE               |
-                MBEDTLS_SSL_EXT_PRE_SHARED_KEY          |
-                MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES ) );
+                MBEDTLS_SSL_EXT_MASK( SUPPORTED_GROUPS )        |
+                MBEDTLS_SSL_EXT_MASK( KEY_SHARE )               |
+                MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY )          |
+                MBEDTLS_SSL_EXT_MASK( PSK_KEY_EXCHANGE_MODES ) ) );
 }
-#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
+#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED */
 
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_check_ephemeral_key_exchange( mbedtls_ssl_context *ssl )
 {
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
     return( mbedtls_ssl_conf_tls13_ephemeral_enabled( ssl ) &&
             ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange( ssl ) );
+#else
+    ((void) ssl);
+    return( 0 );
+#endif
 }
 
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_check_psk_key_exchange( mbedtls_ssl_context *ssl )
 {
-#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
     return( mbedtls_ssl_conf_tls13_psk_enabled( ssl ) &&
             mbedtls_ssl_tls13_psk_enabled( ssl ) &&
             ssl_tls13_client_hello_has_exts_for_psk_key_exchange( ssl ) );
@@ -1042,7 +1003,7 @@
 MBEDTLS_CHECK_RETURN_CRITICAL
 static int ssl_tls13_check_psk_ephemeral_key_exchange( mbedtls_ssl_context *ssl )
 {
-#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
     return( mbedtls_ssl_conf_tls13_psk_ephemeral_enabled( ssl ) &&
             mbedtls_ssl_tls13_psk_ephemeral_enabled( ssl ) &&
             ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange( ssl ) );
@@ -1289,6 +1250,7 @@
     const unsigned char *cipher_suites_end;
     size_t extensions_len;
     const unsigned char *extensions_end;
+    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
     int hrr_required = 0;
 
 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
@@ -1297,8 +1259,6 @@
     const unsigned char *pre_shared_key_ext_end = NULL;
 #endif
 
-    ssl->handshake->extensions_present = MBEDTLS_SSL_EXT_NONE;
-
     /*
      * ClientHello layout:
      *     0  .   1   protocol version
@@ -1356,7 +1316,7 @@
     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes",
                            p, MBEDTLS_CLIENT_HELLO_RANDOM_LEN );
 
-    memcpy( &ssl->handshake->randbytes[0], p, MBEDTLS_CLIENT_HELLO_RANDOM_LEN );
+    memcpy( &handshake->randbytes[0], p, MBEDTLS_CLIENT_HELLO_RANDOM_LEN );
     p += MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
 
     /* ...
@@ -1426,13 +1386,13 @@
             continue;
 
         ssl->session_negotiate->ciphersuite = cipher_suite;
-        ssl->handshake->ciphersuite_info = ciphersuite_info;
+        handshake->ciphersuite_info = ciphersuite_info;
         MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %04x - %s",
                                     cipher_suite,
                                     ciphersuite_info->name ) );
     }
 
-    if( ssl->handshake->ciphersuite_info == NULL )
+    if( handshake->ciphersuite_info == NULL )
     {
         MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
                                       MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
@@ -1468,27 +1428,29 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", p, extensions_len );
 
+    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+
     while( p < extensions_end )
     {
         unsigned int extension_type;
         size_t extension_data_len;
         const unsigned char *extension_data_end;
 
-        /* RFC 8446, page 57
+        /* RFC 8446, section 4.2.11
          *
          * The "pre_shared_key" extension MUST be the last extension in the
          * ClientHello (this facilitates implementation as described below).
          * Servers MUST check that it is the last extension and otherwise fail
          * the handshake with an "illegal_parameter" alert.
          */
-        if( ssl->handshake->extensions_present & MBEDTLS_SSL_EXT_PRE_SHARED_KEY )
+        if( handshake->received_extensions & MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY ) )
         {
             MBEDTLS_SSL_DEBUG_MSG(
                 3, ( "pre_shared_key is not last extension." ) );
             MBEDTLS_SSL_PEND_FATAL_ALERT(
                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
-                MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
-            return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+                MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
+            return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
         }
 
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, 4 );
@@ -1499,6 +1461,12 @@
         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, extensions_end, extension_data_len );
         extension_data_end = p + extension_data_len;
 
+        ret = mbedtls_ssl_tls13_check_received_extension(
+                  ssl, MBEDTLS_SSL_HS_CLIENT_HELLO, extension_type,
+                  MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH );
+        if( ret != 0 )
+            return( ret );
+
         switch( extension_type )
         {
 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
@@ -1512,7 +1480,6 @@
                             1, "mbedtls_ssl_parse_servername_ext", ret );
                     return( ret );
                 }
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SERVERNAME;
                 break;
 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
 
@@ -1535,7 +1502,6 @@
                     return( ret );
                 }
 
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SUPPORTED_GROUPS;
                 break;
 #endif /* MBEDTLS_ECDH_C */
 
@@ -1565,7 +1531,6 @@
                     return( ret );
                 }
 
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_KEY_SHARE;
                 break;
 #endif /* MBEDTLS_ECDH_C */
 
@@ -1580,7 +1545,6 @@
                                 ( "ssl_tls13_parse_supported_versions_ext" ), ret );
                     return( ret );
                 }
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SUPPORTED_VERSIONS;
                 break;
 
 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
@@ -1596,19 +1560,18 @@
                     return( ret );
                 }
 
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES;
                 break;
 #endif
 
             case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found pre_shared_key extension" ) );
-                if( ( ssl->handshake->extensions_present &
-                      MBEDTLS_SSL_EXT_PSK_KEY_EXCHANGE_MODES ) == 0 )
+                if( ( handshake->received_extensions &
+                      MBEDTLS_SSL_EXT_MASK( PSK_KEY_EXCHANGE_MODES ) ) == 0 )
                 {
                     MBEDTLS_SSL_PEND_FATAL_ALERT(
                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
-                        MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
-                    return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+                        MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
+                    return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
                 }
 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
                 /* Delay processing of the PSK identity once we have
@@ -1617,8 +1580,7 @@
                  */
                 pre_shared_key_ext = p;
                 pre_shared_key_ext_end = extension_data_end;
-#endif
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_PRE_SHARED_KEY;
+#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
                 break;
 
 #if defined(MBEDTLS_SSL_ALPN)
@@ -1632,7 +1594,6 @@
                             1, ( "mbedtls_ssl_parse_alpn_ext" ), ret );
                     return( ret );
                 }
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_ALPN;
                 break;
 #endif /* MBEDTLS_SSL_ALPN */
 
@@ -1649,23 +1610,21 @@
                       ret ) );
                     return( ret );
                 }
-                ssl->handshake->extensions_present |= MBEDTLS_SSL_EXT_SIG_ALG;
                 break;
 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
 
             default:
-                MBEDTLS_SSL_DEBUG_MSG( 3,
-                        ( "unknown extension found: %ud ( ignoring )",
-                          extension_type ) );
+                MBEDTLS_SSL_PRINT_EXT(
+                    3, MBEDTLS_SSL_HS_CLIENT_HELLO,
+                    extension_type, "( ignored )" );
+                break;
         }
 
         p += extension_data_len;
     }
 
-#if defined(MBEDTLS_DEBUG_C)
-    /* List all the extensions we have received */
-    ssl_tls13_debug_print_client_hello_exts( ssl );
-#endif /* MBEDTLS_DEBUG_C */
+    MBEDTLS_SSL_PRINT_EXTS( 3, MBEDTLS_SSL_HS_CLIENT_HELLO,
+                            handshake->received_extensions );
 
     mbedtls_ssl_add_hs_hdr_to_checksum( ssl,
                                         MBEDTLS_SSL_HS_CLIENT_HELLO,
@@ -1679,9 +1638,9 @@
     /* If we've settled on a PSK-based exchange, parse PSK identity ext */
     if( mbedtls_ssl_tls13_some_psk_enabled( ssl ) &&
         mbedtls_ssl_conf_tls13_some_psk_enabled( ssl ) &&
-        ( ssl->handshake->extensions_present & MBEDTLS_SSL_EXT_PRE_SHARED_KEY ) )
+        ( handshake->received_extensions & MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY ) ) )
     {
-        ssl->handshake->update_checksum( ssl, buf,
+        handshake->update_checksum( ssl, buf,
                                          pre_shared_key_ext - buf );
         ret = ssl_tls13_parse_pre_shared_key_ext( ssl,
                                                   pre_shared_key_ext,
@@ -1690,26 +1649,26 @@
                                                   cipher_suites_end );
         if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
         {
-            ssl->handshake->extensions_present &= ~MBEDTLS_SSL_EXT_PRE_SHARED_KEY;
+            handshake->received_extensions &= ~MBEDTLS_SSL_EXT_MASK( PRE_SHARED_KEY );
         }
         else if( ret != 0 )
         {
-            MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_tls13_parse_pre_shared_key_ext" ),
-                                   ret );
+            MBEDTLS_SSL_DEBUG_RET(
+                1, "ssl_tls13_parse_pre_shared_key_ext" , ret );
             return( ret );
         }
     }
     else
 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
     {
-        ssl->handshake->update_checksum( ssl, buf, p - buf );
+        handshake->update_checksum( ssl, buf, p - buf );
     }
 
     ret = ssl_tls13_determine_key_exchange_mode( ssl );
     if( ret < 0 )
         return( ret );
 
-    mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info );
+    mbedtls_ssl_optimize_checksum( ssl, handshake->ciphersuite_info );
 
     return( hrr_required ? SSL_CLIENT_HELLO_HRR_REQUIRED : SSL_CLIENT_HELLO_OK );
 }
@@ -1856,6 +1815,9 @@
 
     *out_len = 6;
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
+        ssl, MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS );
+
     return( 0 );
 }
 
@@ -1962,6 +1924,8 @@
 
     *out_len = p - buf;
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_KEY_SHARE );
+
     return( 0 );
 }
 
@@ -2026,6 +1990,8 @@
 
     *out_len = 6;
 
+    mbedtls_ssl_tls13_set_hs_sent_ext_mask( ssl, MBEDTLS_TLS_EXT_KEY_SHARE );
+
     return( 0 );
 }
 
@@ -2054,6 +2020,7 @@
     size_t output_len;
 
     *out_len = 0;
+    ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
 
     /* ...
      * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
@@ -2179,6 +2146,11 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello", buf, *out_len );
 
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, is_hrr ? MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST :
+                    MBEDTLS_SSL_HS_SERVER_HELLO,
+        ssl->handshake->sent_extensions );
+
     return( ret );
 }
 
@@ -2363,6 +2335,9 @@
 
     MBEDTLS_SSL_DEBUG_BUF( 4, "encrypted extensions", buf, *out_len );
 
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS, ssl->handshake->sent_extensions );
+
     return( 0 );
 }
 
@@ -2492,6 +2467,9 @@
 
     *out_len = p - buf;
 
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST, ssl->handshake->sent_extensions );
+
     return( 0 );
 }
 
@@ -2877,6 +2855,8 @@
      * Note: We currently don't have any extensions.
      * Set length to zero.
      */
+    ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
+
     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
     MBEDTLS_PUT_UINT16_BE( 0, p, 0 );
     p += 2;
@@ -2885,6 +2865,9 @@
     MBEDTLS_SSL_DEBUG_BUF( 4, "ticket", buf, *out_len );
     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) );
 
+    MBEDTLS_SSL_PRINT_EXTS(
+        3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET, ssl->handshake->sent_extensions );
+
     return( 0 );
 }
 
diff --git a/library/x509_crt.c b/library/x509_crt.c
index 81186fa..0eee97c 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -1837,6 +1837,7 @@
                                        const char *prefix )
 {
     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+    size_t i;
     size_t n = *size;
     char *p = *buf;
     const mbedtls_x509_sequence *cur = subject_alt_name;
@@ -1889,18 +1890,11 @@
                     ret = mbedtls_snprintf( p, n, "\n%s            hardware serial number : ", prefix );
                     MBEDTLS_X509_SAFE_SNPRINTF;
 
-                    if( other_name->value.hardware_module_name.val.len >= n )
+                    for( i = 0; i < other_name->value.hardware_module_name.val.len; i++ )
                     {
-                        *p = '\0';
-                        return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
+                        ret = mbedtls_snprintf( p, n, "%02X", other_name->value.hardware_module_name.val.p[i] );
+                        MBEDTLS_X509_SAFE_SNPRINTF;
                     }
-
-                    memcpy( p, other_name->value.hardware_module_name.val.p,
-                            other_name->value.hardware_module_name.val.len );
-                    p += other_name->value.hardware_module_name.val.len;
-
-                    n -= other_name->value.hardware_module_name.val.len;
-
                 }/* MBEDTLS_OID_ON_HW_MODULE_NAME */
             }
             break;
diff --git a/programs/ssl/ssl_client2.c b/programs/ssl/ssl_client2.c
index 86a9c1e..56efb3c 100644
--- a/programs/ssl/ssl_client2.c
+++ b/programs/ssl/ssl_client2.c
@@ -376,6 +376,8 @@
     "                        a second non-empty message before attempting\n" \
     "                        to read a response from the server\n"           \
     "    debug_level=%%d      default: 0 (disabled)\n"             \
+    "    build_version=%%d    default: none (disabled)\n"                     \
+    "                        option: 1 (print build version only and stop)\n" \
     "    nbio=%%d             default: 0 (blocking I/O)\n"         \
     "                        options: 1 (non-blocking), 2 (added delays)\n"   \
     "    event=%%d            default: 0 (loop)\n"                            \
@@ -981,6 +983,16 @@
             if( opt.debug_level < 0 || opt.debug_level > 65535 )
                 goto usage;
         }
+        else if( strcmp( p, "build_version" ) == 0 )
+        {
+            if( strcmp( q, "1" ) == 0 )
+            {
+                mbedtls_printf( "build version: %s (build %d)\n",
+                                MBEDTLS_VERSION_STRING_FULL,
+                                MBEDTLS_VERSION_NUMBER );
+                goto exit;
+            }
+        }
         else if( strcmp( p, "context_crt_cb" ) == 0 )
         {
             opt.context_crt_cb = atoi( q );
@@ -1691,6 +1703,9 @@
     }
 #endif /* MBEDTLS_SSL_ALPN */
 
+    mbedtls_printf( "build version: %s (build %d)\n",
+                    MBEDTLS_VERSION_STRING_FULL, MBEDTLS_VERSION_NUMBER );
+
     /*
      * 0. Initialize the RNG and the session data
      */
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index 9ec2f87..1b4a94a 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -488,6 +488,8 @@
     "    server_addr=%%s      default: (all interfaces)\n"  \
     "    server_port=%%d      default: 4433\n"              \
     "    debug_level=%%d      default: 0 (disabled)\n"      \
+    "    build_version=%%d    default: none (disabled)\n"                     \
+    "                        option: 1 (print build version only and stop)\n" \
     "    buffer_size=%%d      default: 200 \n" \
     "                         (minimum: 1)\n" \
     "    response_size=%%d    default: about 152 (basic response)\n" \
@@ -1743,6 +1745,16 @@
             if( opt.debug_level < 0 || opt.debug_level > 65535 )
                 goto usage;
         }
+        else if( strcmp( p, "build_version" ) == 0 )
+        {
+            if( strcmp( q, "1" ) == 0 )
+            {
+                mbedtls_printf( "build version: %s (build %d)\n",
+                                MBEDTLS_VERSION_STRING_FULL,
+                                MBEDTLS_VERSION_NUMBER );
+                goto exit;
+            }
+        }
         else if( strcmp( p, "nbio" ) == 0 )
         {
             opt.nbio = atoi( q );
@@ -2572,6 +2584,9 @@
     }
 #endif /* MBEDTLS_SSL_ALPN */
 
+    mbedtls_printf( "build version: %s (build %d)\n",
+                    MBEDTLS_VERSION_STRING_FULL, MBEDTLS_VERSION_NUMBER );
+
     /*
      * 0. Initialize the RNG and the session data
      */
diff --git a/scripts/mbedtls_dev/bignum_mod_raw.py b/scripts/mbedtls_dev/bignum_mod_raw.py
index 2e059b2..bd694a6 100644
--- a/scripts/mbedtls_dev/bignum_mod_raw.py
+++ b/scripts/mbedtls_dev/bignum_mod_raw.py
@@ -15,14 +15,88 @@
 # limitations under the License.
 
 from abc import ABCMeta
+from typing import Dict, Iterator, List
 
+from . import test_case
 from . import test_data_generation
+from . import bignum_common
 
 class BignumModRawTarget(test_data_generation.BaseTarget, metaclass=ABCMeta):
     #pylint: disable=abstract-method
     """Target for bignum mod_raw test case generation."""
     target_basename = 'test_suite_bignum_mod_raw.generated'
 
+class BignumModRawOperation(bignum_common.OperationCommon, BignumModRawTarget, metaclass=ABCMeta):
+    #pylint: disable=abstract-method
+    """Target for bignum mod_raw test case generation."""
+
+    def __init__(self, val_n: str, val_a: str, val_b: str = "0", bits_in_limb: int = 64) -> None:
+        super().__init__(val_a=val_a, val_b=val_b)
+        self.val_n = val_n
+        self.bits_in_limb = bits_in_limb
+
+    @property
+    def int_n(self) -> int:
+        return bignum_common.hex_to_int(self.val_n)
+
+    @property
+    def boundary(self) -> int:
+        data_in = [self.int_a, self.int_b, self.int_n]
+        return max([n for n in data_in if n is not None])
+
+    @property
+    def limbs(self) -> int:
+        return bignum_common.limbs_mpi(self.boundary, self.bits_in_limb)
+
+    @property
+    def hex_digits(self) -> int:
+        return 2 * (self.limbs * self.bits_in_limb // 8)
+
+    @property
+    def hex_n(self) -> str:
+        return "{:x}".format(self.int_n).zfill(self.hex_digits)
+
+    @property
+    def hex_a(self) -> str:
+        return "{:x}".format(self.int_a).zfill(self.hex_digits)
+
+    @property
+    def hex_b(self) -> str:
+        return "{:x}".format(self.int_b).zfill(self.hex_digits)
+
+    @property
+    def r(self) -> int: # pylint: disable=invalid-name
+        l = bignum_common.limbs_mpi(self.int_n, self.bits_in_limb)
+        return bignum_common.bound_mpi_limbs(l, self.bits_in_limb)
+
+    @property
+    def r_inv(self) -> int:
+        return bignum_common.invmod(self.r, self.int_n)
+
+    @property
+    def r2(self) -> int: # pylint: disable=invalid-name
+        return pow(self.r, 2)
+
+class BignumModRawOperationArchSplit(BignumModRawOperation):
+    #pylint: disable=abstract-method
+    """Common features for bignum mod raw operations where the result depends on
+    the limb size."""
+
+    limb_sizes = [32, 64] # type: List[int]
+
+    def __init__(self, val_n: str, val_a: str, val_b: str = "0", bits_in_limb: int = 64) -> None:
+        super().__init__(val_n=val_n, val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
+
+        if bits_in_limb not in self.limb_sizes:
+            raise ValueError("Invalid number of bits in limb!")
+
+        self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
+
+    @classmethod
+    def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
+        for a_value, b_value in cls.get_value_pairs():
+            for bil in cls.limb_sizes:
+                yield cls(a_value, b_value, bits_in_limb=bil).create_test_case()
 # BEGIN MERGE SLOT 1
 
 # END MERGE SLOT 1
@@ -48,7 +122,126 @@
 # END MERGE SLOT 6
 
 # BEGIN MERGE SLOT 7
+class BignumModRawConvertToMont(BignumModRawOperationArchSplit):
+    """ Test cases for mpi_mod_raw_to_mont_rep(). """
 
+    test_function = "mpi_mod_raw_to_mont_rep"
+    test_name = "Convert into Mont: "
+
+    test_data_moduli = ["b",
+                        "fd",
+                        "eeff99aa37",
+                        "eeff99aa11",
+                        "800000000005",
+                        "7fffffffffffffff",
+                        "80fe000a10000001",
+                        "25a55a46e5da99c71c7",
+                        "1058ad82120c3a10196bb36229c1",
+                        "7e35b84cb19ea5bc57ec37f5e431462fa962d98c1e63738d4657f"
+                        "18ad6532e6adc3eafe67f1e5fa262af94cee8d3e7268593942a2a"
+                        "98df75154f8c914a282f8b",
+                        "8335616aed761f1f7f44e6bd49e807b82e3bf2bf11bfa63",
+                        "ffcece570f2f991013f26dd5b03c4c5b65f97be5905f36cb4664f"
+                        "2c78ff80aa8135a4aaf57ccb8a0aca2f394909a74cef1ef6758a6"
+                        "4d11e2c149c393659d124bfc94196f0ce88f7d7d567efa5a649e2"
+                        "deefaa6e10fdc3deac60d606bf63fc540ac95294347031aefd73d"
+                        "6a9ee10188aaeb7a90d920894553cb196881691cadc51808715a0"
+                        "7e8b24fcb1a63df047c7cdf084dd177ba368c806f3d51ddb5d389"
+                        "8c863e687ecaf7d649a57a46264a582f94d3c8f2edaf59f77a7f6"
+                        "bdaf83c991e8f06abe220ec8507386fce8c3da84c6c3903ab8f3a"
+                        "d4630a204196a7dbcbd9bcca4e40ec5cc5c09938d49f5e1e6181d"
+                        "b8896f33bb12e6ef73f12ec5c5ea7a8a337"
+                        ]
+
+    test_input_numbers = ["0",
+                          "1",
+                          "97",
+                          "f5",
+                          "6f5c3",
+                          "745bfe50f7",
+                          "ffa1f9924123",
+                          "334a8b983c79bd",
+                          "5b84f632b58f3461",
+                          "19acd15bc38008e1",
+                          "ffffffffffffffff",
+                          "54ce6a6bb8247fa0427cfc75a6b0599",
+                          "fecafe8eca052f154ce6a6bb8247fa019558bfeecce9bb9",
+                          "a87d7a56fa4bfdc7da42ef798b9cf6843d4c54794698cb14d72"
+                          "851dec9586a319f4bb6d5695acbd7c92e7a42a5ede6972adcbc"
+                          "f68425265887f2d721f462b7f1b91531bac29fa648facb8e3c6"
+                          "1bd5ae42d5a59ba1c89a95897bfe541a8ce1d633b98f379c481"
+                          "6f25e21f6ac49286b261adb4b78274fe5f61c187581f213e84b"
+                          "2a821e341ef956ecd5de89e6c1a35418cd74a549379d2d4594a"
+                          "577543147f8e35b3514e62cf3e89d1156cdc91ab5f4c928fbd6"
+                          "9148c35df5962fed381f4d8a62852a36823d5425f7487c13a12"
+                          "523473fb823aa9d6ea5f42e794e15f2c1a8785cf6b7d51a4617"
+                          "947fb3baf674f74a673cf1d38126983a19ed52c7439fab42c2185"
+                          ]
+
+    descr_tpl = '{} #{} N: \"{}\" A: \"{}\".'
+
+    def result(self) -> List[str]:
+        return [self.hex_x]
+
+    def arguments(self) -> List[str]:
+        return [bignum_common.quote_str(n) for n in [self.hex_n,
+                                                     self.hex_a,
+                                                     self.hex_x]]
+
+    def description(self) -> str:
+        return self.descr_tpl.format(self.test_name,
+                                     self.count,
+                                     self.int_n,
+                                     self.int_a)
+
+    @classmethod
+    def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
+        for bil in [32, 64]:
+            for n in cls.test_data_moduli:
+                for i in cls.test_input_numbers:
+                    # Skip invalid combinations where A.limbs > N.limbs
+                    if bignum_common.hex_to_int(i) > bignum_common.hex_to_int(n):
+                        continue
+                    yield cls(n, i, bits_in_limb=bil).create_test_case()
+
+    @property
+    def x(self) -> int: # pylint: disable=invalid-name
+        return (self.int_a * self.r) % self.int_n
+
+    @property
+    def hex_x(self) -> str:
+        return "{:x}".format(self.x).zfill(self.hex_digits)
+
+class BignumModRawConvertFromMont(BignumModRawConvertToMont):
+    """ Test cases for mpi_mod_raw_from_mont_rep(). """
+
+    test_function = "mpi_mod_raw_from_mont_rep"
+    test_name = "Convert from Mont: "
+
+    test_input_numbers = ["0",
+                          "1",
+                          "3ca",
+                          "539ed428",
+                          "7dfe5c6beb35a2d6",
+                          "dca8de1c2adfc6d7aafb9b48e",
+                          "a7d17b6c4be72f3d5c16bf9c1af6fc933",
+                          "2fec97beec546f9553142ed52f147845463f579",
+                          "378dc83b8bc5a7b62cba495af4919578dce6d4f175cadc4f",
+                          "b6415f2a1a8e48a518345db11f56db3829c8f2c6415ab4a395a"
+                          "b3ac2ea4cbef4af86eb18a84eb6ded4c6ecbfc4b59c2879a675"
+                          "487f687adea9d197a84a5242a5cf6125ce19a6ad2e7341f1c57"
+                          "d43ea4f4c852a51cb63dabcd1c9de2b827a3146a3d175b35bea"
+                          "41ae75d2a286a3e9d43623152ac513dcdea1d72a7da846a8ab3"
+                          "58d9be4926c79cfb287cf1cf25b689de3b912176be5dcaf4d4c"
+                          "6e7cb839a4a3243a6c47c1e2c99d65c59d6fa3672575c2f1ca8"
+                          "de6a32e854ec9d8ec635c96af7679fce26d7d159e4a9da3bd74"
+                          "e1272c376cd926d74fe3fb164a5935cff3d5cdb92b35fe2cea32"
+                          "138a7e6bfbc319ebd1725dacb9a359cbf693f2ecb785efb9d627"
+                         ]
+
+    @property
+    def x(self): # pylint: disable=invalid-name
+        return (self.int_a * self.r_inv) % self.int_n
 # END MERGE SLOT 7
 
 # BEGIN MERGE SLOT 8
diff --git a/tests/data_files/Makefile b/tests/data_files/Makefile
index 6187d17..d4f2011 100644
--- a/tests/data_files/Makefile
+++ b/tests/data_files/Makefile
@@ -276,6 +276,9 @@
 server5-othername.crt: server5.key
 	$(OPENSSL) req -x509 -new -subj "/C=UK/O=Mbed TLS/CN=Mbed TLS othername SAN" -set_serial 77 -config $(test_ca_config_file) -extensions othername_san -days 3650 -sha256 -key $< -out $@
 
+server5-nonprintable_othername.crt: server5.key
+	$(OPENSSL) req -x509 -new -subj "/C=UK/O=Mbed TLS/CN=Mbed TLS non-printable othername SAN" -set_serial 77 -config $(test_ca_config_file) -extensions nonprintable_othername_san -days 3650 -sha256 -key $< -out $@
+
 server5-unsupported_othername.crt: server5.key
 	$(OPENSSL) req -x509 -new -subj "/C=UK/O=Mbed TLS/CN=Mbed TLS unsupported othername SAN" -set_serial 77 -config $(test_ca_config_file) -extensions unsupoported_othername_san -days 3650 -sha256 -key $< -out $@
 
@@ -881,6 +884,11 @@
 	$(MBEDTLS_CERT_REQ) output_file=$@ filename=$< subject_name="C=NL,O=PolarSSL,CN=PolarSSL Server 1" md=SHA256
 all_final += server1.req.sha256
 
+server1.req.sha256.ext: server1.key
+	# Generating this with OpenSSL as a comparison point to test we're getting the same result
+	openssl req -new -out $@ -key $< -subj '/C=NL/O=PolarSSL/CN=PolarSSL Server 1' -sha256 -addext "extendedKeyUsage=serverAuth"
+all_final += server1.req.sha256.ext
+
 server1.req.sha384: server1.key
 	$(MBEDTLS_CERT_REQ) output_file=$@ filename=$< subject_name="C=NL,O=PolarSSL,CN=PolarSSL Server 1" md=SHA384
 all_final += server1.req.sha384
diff --git a/tests/data_files/server1.req.sha256.ext b/tests/data_files/server1.req.sha256.ext
new file mode 100644
index 0000000..3f26f09
--- /dev/null
+++ b/tests/data_files/server1.req.sha256.ext
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICpzCCAY8CAQAwPDELMAkGA1UEBhMCTkwxETAPBgNVBAoMCFBvbGFyU1NMMRow
+GAYDVQQDDBFQb2xhclNTTCBTZXJ2ZXIgMTCCASIwDQYJKoZIhvcNAQEBBQADggEP
+ADCCAQoCggEBAKkCHz1AatVVU4v9Nu6CZS4VYV6Jv7joRZDb7ogWUtPxQ1BHlhJZ
+ZIdr/SvgRvlzvt3PkuGRW+1moG+JKXlFgNCDatVBQ3dfOXwJBEeCsFc5cO2j7BUZ
+HqgzCEfBBUKp/UzDtN/dBh9NEFFAZ3MTD0D4bYElXwqxU8YwfhU5rPla7n+SnqYF
+W+cTl4W1I5LZ1CQG1QkliXUH3aYajz8JGb6tZSxk65Wb3P5BXhem2mxbacwCuhQs
+FiScStzN0PdSZ3PxLaAj/X70McotcMqJCwTbLqZPcG6ezr1YieJTWZ5uWpJl4og/
+DJQZo93l6J2VE+0p26twEtxaymsXq1KCVLECAwEAAaAmMCQGCSqGSIb3DQEJDjEX
+MBUwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggEBAHi0yEGu
+Fh5tuLiLuT95UrRnly55+lTY9xchFiKtlcoEdSheybYxqk3JHuSSqojOFKZBlRdk
+oG6Azg56/aMHPWyvtCMSRQX4b+FgjeQsm9IfhYNMquQOxyPxm62vjuU3MfZIofXH
+hKdI6Ci2CDF4Fyvw50KBWniV38eE9+kjsvDLdXD3ESZJGhjjuFl8ReUiA2wdBTcP
+XEZaXUIc6B4tUnlPeqn/2zp4GBqqWzNZx6TXBpApASGG3BEJnM52FVPC7E9p+8YZ
+qIGuiF5Cz/rYZkpwffBWIfS2zZakHLm5TB8FgZkWlyReJU9Ihk2Tl/sZ1kllFdYa
+xLPnLCL82KFL1Co=
+-----END CERTIFICATE REQUEST-----
diff --git a/tests/data_files/server5-nonprintable_othername.crt b/tests/data_files/server5-nonprintable_othername.crt
new file mode 100644
index 0000000..9470bbe
--- /dev/null
+++ b/tests/data_files/server5-nonprintable_othername.crt
@@ -0,0 +1,12 @@
+-----BEGIN CERTIFICATE-----
+MIIBwTCCAWagAwIBAgIBTTAKBggqhkjOPQQDAjBPMQswCQYDVQQGEwJVSzERMA8G
+A1UECgwITWJlZCBUTFMxLTArBgNVBAMMJE1iZWQgVExTIG5vbi1wcmludGFibGUg
+b3RoZXJuYW1lIFNBTjAeFw0yMjA5MDYxNTU2NDdaFw0zMjA5MDMxNTU2NDdaME8x
+CzAJBgNVBAYTAlVLMREwDwYDVQQKDAhNYmVkIFRMUzEtMCsGA1UEAwwkTWJlZCBU
+TFMgbm9uLXByaW50YWJsZSBvdGhlcm5hbWUgU0FOMFkwEwYHKoZIzj0CAQYIKoZI
+zj0DAQcDQgAEN8xW2XYJHlpyPsdZLf8gbu58+QaRdNCtFLX3aCJZYpJO5QDYIxH/
+6i/SNF1dFr2KiMJrdw1VzYoqDvoByLTt/6MzMDEwLwYDVR0RBCgwJqAkBggrBgEF
+BQcIBKAYMBYGBysGAQQBEQMECzEyM4CBAIGAMzIxMAoGCCqGSM49BAMCA0kAMEYC
+IQDATir07PTj5gtf+HAyI+nd27AH9+bdaWdOI2t2bAwUWgIhAO7kvdcsa++yfJdT
+3vnWdvcHRIAdXA0kh+mcBMaXk9B0
+-----END CERTIFICATE-----
diff --git a/tests/data_files/test-ca.opensslconf b/tests/data_files/test-ca.opensslconf
index 64347de..3bb2379 100644
--- a/tests/data_files/test-ca.opensslconf
+++ b/tests/data_files/test-ca.opensslconf
@@ -15,6 +15,9 @@
 [othername_san]
 subjectAltName=otherName:1.3.6.1.5.5.7.8.4;SEQ:hw_module_name
 
+[nonprintable_othername_san]
+subjectAltName=otherName:1.3.6.1.5.5.7.8.4;SEQ:nonprintable_hw_module_name
+
 [unsupoported_othername_san]
 subjectAltName=otherName:1.2.3.4;UTF8:some other identifier
 
@@ -34,6 +37,10 @@
 hwtype = OID:1.3.6.1.4.1.17.3
 hwserial = OCT:123456
 
+[nonprintable_hw_module_name]
+hwtype = OID:1.3.6.1.4.1.17.3
+hwserial = FORMAT:HEX, OCT:3132338081008180333231
+
 [v3_any_policy_ca]
 basicConstraints = CA:true
 certificatePolicies = 2.5.29.32.0
diff --git a/tests/opt-testcases/tls13-kex-modes.sh b/tests/opt-testcases/tls13-kex-modes.sh
index 4f62ed6..974d513 100755
--- a/tests/opt-testcases/tls13-kex-modes.sh
+++ b/tests/opt-testcases/tls13-kex-modes.sh
@@ -18,228 +18,8 @@
 # limitations under the License.
 #
 
-get_srv_psk_list ()
-{
-    case $(( TESTS % 3 )) in
-        0) echo "psk_list=abc,dead,def,beef,Client_identity,6162636465666768696a6b6c6d6e6f70";;
-        1) echo "psk_list=abc,dead,Client_identity,6162636465666768696a6b6c6d6e6f70,def,beef";;
-        2) echo "psk_list=Client_identity,6162636465666768696a6b6c6d6e6f70,abc,dead,def,beef";;
-    esac
-}
-
-requires_gnutls_tls1_3
-requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
-requires_config_enabled MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
-requires_config_enabled MBEDTLS_SSL_SRV_C
-requires_config_enabled MBEDTLS_DEBUG_C
-requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
-
-run_test    "TLS 1.3: PSK: No valid ciphersuite. G->m" \
-            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
-            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-CIPHER-ALL:+AES-256-GCM:+AEAD:+SHA384:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:+VERS-TLS1.3 \
-                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
-                         localhost" \
-            1 \
-            -s "found psk key exchange modes extension" \
-            -s "found pre_shared_key extension" \
-            -s "Found PSK_EPHEMERAL KEX MODE" \
-            -s "Found PSK KEX MODE" \
-            -s "No matched ciphersuite"
-
-requires_openssl_tls1_3
-requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
-requires_config_enabled MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
-requires_config_enabled MBEDTLS_SSL_SRV_C
-requires_config_enabled MBEDTLS_DEBUG_C
-requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
-
-run_test    "TLS 1.3: PSK: No valid ciphersuite. O->m" \
-            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
-            "$O_NEXT_CLI -tls1_3 -msg -allow_no_dhe_kex -ciphersuites TLS_AES_256_GCM_SHA384\
-                         -psk_identity Client_identity -psk 6162636465666768696a6b6c6d6e6f70" \
-            1 \
-            -s "found psk key exchange modes extension" \
-            -s "found pre_shared_key extension" \
-            -s "Found PSK_EPHEMERAL KEX MODE" \
-            -s "Found PSK KEX MODE" \
-            -s "No matched ciphersuite"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Multiple PSKs: valid ticket, reconnect with ticket" \
-         "$P_SRV force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 tickets=8" \
-         "$P_CLI force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 2" \
-         -s "sent selected_identity: 0" \
-         -s "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "key exchange mode: ephemeral$" \
-         -S "ticket is not authentic"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Multiple PSKs: invalid ticket, reconnect with PSK" \
-         "$P_SRV force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 tickets=8 dummy_ticket=1" \
-         "$P_CLI force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 2" \
-         -s "sent selected_identity: 1" \
-         -s "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "key exchange mode: ephemeral$" \
-         -s "ticket is not authentic"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, ticket authentication failed." \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=1" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -s "ticket is not authentic" \
-         -S "ticket is expired" \
-         -S "Invalid ticket start time" \
-         -S "Ticket age exceeds limitation" \
-         -S "Ticket age outside tolerance window"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, ticket expired." \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=2" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "ticket is not authentic" \
-         -s "ticket is expired" \
-         -S "Invalid ticket start time" \
-         -S "Ticket age exceeds limitation" \
-         -S "Ticket age outside tolerance window"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, invalid start time." \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=3" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "ticket is not authentic" \
-         -S "ticket is expired" \
-         -s "Invalid ticket start time" \
-         -S "Ticket age exceeds limitation" \
-         -S "Ticket age outside tolerance window"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, ticket expired. too old" \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=4" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "ticket is not authentic" \
-         -S "ticket is expired" \
-         -S "Invalid ticket start time" \
-         -s "Ticket age exceeds limitation" \
-         -S "Ticket age outside tolerance window"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, age outside tolerance window, too young." \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=5" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "ticket is not authentic" \
-         -S "ticket is expired" \
-         -S "Invalid ticket start time" \
-         -S "Ticket age exceeds limitation" \
-         -s "Ticket age outside tolerance window"
-
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
-                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
-                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
-run_test "TLS 1.3 m->m: Session resumption failure, age outside tolerance window, too old." \
-         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=6" \
-         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
-         0 \
-         -c "Pre-configured PSK number = 1" \
-         -S "sent selected_identity:" \
-         -s "key exchange mode: ephemeral" \
-         -S "key exchange mode: psk_ephemeral" \
-         -S "key exchange mode: psk$" \
-         -S "ticket is not authentic" \
-         -S "ticket is expired" \
-         -S "Invalid ticket start time" \
-         -S "Ticket age exceeds limitation" \
-         -s "Ticket age outside tolerance window"
-
-requires_gnutls_tls1_3
-requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C
-requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
-run_test    "TLS 1.3: G->m: ephemeral_all/psk, fail, no common kex mode" \
-            "$P_SRV force_version=tls13 tls13_kex_modes=psk debug_level=5 $(get_srv_psk_list)" \
-            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:-PSK:+VERS-TLS1.3 \
-                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
-                         localhost" \
-            1 \
-            -s "found psk key exchange modes extension" \
-            -s "found pre_shared_key extension" \
-            -s "Found PSK_EPHEMERAL KEX MODE" \
-            -S "Found PSK KEX MODE" \
-            -S "key exchange mode: psk$"  \
-            -S "key exchange mode: psk_ephemeral"  \
-            -S "key exchange mode: ephemeral"
+# DO NOT ADD NEW TEST CASES INTO THIS FILE. The left cases will be generated by
+# scripts in future(#6280)
 
 requires_gnutls_tls1_3
 requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C
diff --git a/tests/opt-testcases/tls13-misc.sh b/tests/opt-testcases/tls13-misc.sh
new file mode 100755
index 0000000..4ad6faa
--- /dev/null
+++ b/tests/opt-testcases/tls13-misc.sh
@@ -0,0 +1,284 @@
+#!/bin/sh
+
+# tls13-misc.sh
+#
+# 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.
+#
+
+requires_gnutls_tls1_3
+requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
+requires_config_enabled MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
+requires_config_enabled MBEDTLS_SSL_SRV_C
+requires_config_enabled MBEDTLS_DEBUG_C
+requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+
+run_test    "TLS 1.3: PSK: No valid ciphersuite. G->m" \
+            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
+            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-CIPHER-ALL:+AES-256-GCM:+AEAD:+SHA384:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:+VERS-TLS1.3 \
+                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
+                         localhost" \
+            1 \
+            -s "found psk key exchange modes extension" \
+            -s "found pre_shared_key extension" \
+            -s "Found PSK_EPHEMERAL KEX MODE" \
+            -s "Found PSK KEX MODE" \
+            -s "No matched ciphersuite"
+
+requires_openssl_tls1_3
+requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_3
+requires_config_enabled MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
+requires_config_enabled MBEDTLS_SSL_SRV_C
+requires_config_enabled MBEDTLS_DEBUG_C
+requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+
+run_test    "TLS 1.3: PSK: No valid ciphersuite. O->m" \
+            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
+            "$O_NEXT_CLI -tls1_3 -msg -allow_no_dhe_kex -ciphersuites TLS_AES_256_GCM_SHA384\
+                         -psk_identity Client_identity -psk 6162636465666768696a6b6c6d6e6f70" \
+            1 \
+            -s "found psk key exchange modes extension" \
+            -s "found pre_shared_key extension" \
+            -s "Found PSK_EPHEMERAL KEX MODE" \
+            -s "Found PSK KEX MODE" \
+            -s "No matched ciphersuite"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Multiple PSKs: valid ticket, reconnect with ticket" \
+         "$P_SRV force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 tickets=8" \
+         "$P_CLI force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 2" \
+         -s "sent selected_identity: 0" \
+         -s "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "key exchange mode: ephemeral$" \
+         -S "ticket is not authentic"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Multiple PSKs: invalid ticket, reconnect with PSK" \
+         "$P_SRV force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 tickets=8 dummy_ticket=1" \
+         "$P_CLI force_version=tls13 tls13_kex_modes=psk_ephemeral debug_level=5 psk_identity=Client_identity psk=6162636465666768696a6b6c6d6e6f70 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 2" \
+         -s "sent selected_identity: 1" \
+         -s "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "key exchange mode: ephemeral$" \
+         -s "ticket is not authentic"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, ticket authentication failed." \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=1" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -s "ticket is not authentic" \
+         -S "ticket is expired" \
+         -S "Invalid ticket start time" \
+         -S "Ticket age exceeds limitation" \
+         -S "Ticket age outside tolerance window"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, ticket expired." \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=2" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "ticket is not authentic" \
+         -s "ticket is expired" \
+         -S "Invalid ticket start time" \
+         -S "Ticket age exceeds limitation" \
+         -S "Ticket age outside tolerance window"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, invalid start time." \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=3" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "ticket is not authentic" \
+         -S "ticket is expired" \
+         -s "Invalid ticket start time" \
+         -S "Ticket age exceeds limitation" \
+         -S "Ticket age outside tolerance window"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, ticket expired. too old" \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=4" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "ticket is not authentic" \
+         -S "ticket is expired" \
+         -S "Invalid ticket start time" \
+         -s "Ticket age exceeds limitation" \
+         -S "Ticket age outside tolerance window"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, age outside tolerance window, too young." \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=5" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "ticket is not authentic" \
+         -S "ticket is expired" \
+         -S "Invalid ticket start time" \
+         -S "Ticket age exceeds limitation" \
+         -s "Ticket age outside tolerance window"
+
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SESSION_TICKETS MBEDTLS_SSL_SRV_C \
+                             MBEDTLS_SSL_CLI_C MBEDTLS_DEBUG_C MBEDTLS_HAVE_TIME
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+requires_any_configs_enabled MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED \
+                             MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+run_test "TLS 1.3 m->m: Session resumption failure, age outside tolerance window, too old." \
+         "$P_SRV debug_level=4 crt_file=data_files/server5.crt key_file=data_files/server5.key force_version=tls13 tickets=8 dummy_ticket=6" \
+         "$P_CLI debug_level=4 reco_mode=1 reconnect=1" \
+         0 \
+         -c "Pre-configured PSK number = 1" \
+         -S "sent selected_identity:" \
+         -s "key exchange mode: ephemeral" \
+         -S "key exchange mode: psk_ephemeral" \
+         -S "key exchange mode: psk$" \
+         -S "ticket is not authentic" \
+         -S "ticket is expired" \
+         -S "Invalid ticket start time" \
+         -S "Ticket age exceeds limitation" \
+         -s "Ticket age outside tolerance window"
+
+requires_gnutls_tls1_3
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C
+requires_config_enabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+run_test    "TLS 1.3: G->m: ephemeral_all/psk, fail, no common kex mode" \
+            "$P_SRV force_version=tls13 tls13_kex_modes=psk debug_level=5 $(get_srv_psk_list)" \
+            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:-PSK:+VERS-TLS1.3 \
+                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
+                         localhost" \
+            1 \
+            -s "found psk key exchange modes extension" \
+            -s "found pre_shared_key extension" \
+            -s "Found PSK_EPHEMERAL KEX MODE" \
+            -S "Found PSK KEX MODE" \
+            -S "key exchange mode: psk$"  \
+            -S "key exchange mode: psk_ephemeral"  \
+            -S "key exchange mode: ephemeral"
+
+requires_gnutls_tls1_3
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C \
+                             MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE \
+                             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+requires_all_configs_disabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED \
+                              MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+run_test    "TLS 1.3: G->m: PSK: configured psk only, good." \
+            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
+            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:+VERS-TLS1.3:+GROUP-ALL \
+                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
+                         localhost" \
+            0 \
+            -s "found psk key exchange modes extension" \
+            -s "found pre_shared_key extension"         \
+            -s "Found PSK_EPHEMERAL KEX MODE"           \
+            -s "Found PSK KEX MODE"                     \
+            -s "key exchange mode: psk$"
+
+requires_gnutls_tls1_3
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C \
+                             MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE \
+                             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+requires_all_configs_disabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED \
+                              MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+run_test    "TLS 1.3: G->m: PSK: configured psk_ephemeral only, good." \
+            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
+            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:+VERS-TLS1.3:+GROUP-ALL \
+                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
+                         localhost" \
+            0 \
+            -s "found psk key exchange modes extension" \
+            -s "found pre_shared_key extension"         \
+            -s "Found PSK_EPHEMERAL KEX MODE"           \
+            -s "Found PSK KEX MODE"                     \
+            -s "key exchange mode: psk_ephemeral$"
+
+requires_gnutls_tls1_3
+requires_all_configs_enabled MBEDTLS_SSL_PROTO_TLS1_3 MBEDTLS_SSL_SRV_C MBEDTLS_DEBUG_C \
+                             MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE \
+                             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+requires_all_configs_disabled MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED \
+                              MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+run_test    "TLS 1.3: G->m: PSK: configured ephemeral only, good." \
+            "$P_SRV force_version=tls13 tls13_kex_modes=all debug_level=5 $(get_srv_psk_list)" \
+            "$G_NEXT_CLI -d 10 --priority NORMAL:-VERS-ALL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK:+VERS-TLS1.3:+GROUP-ALL \
+                         --pskusername Client_identity --pskkey=6162636465666768696a6b6c6d6e6f70 \
+                         localhost" \
+            0 \
+            -s "key exchange mode: ephemeral$"
+
diff --git a/tests/scripts/generate_bignum_tests.py b/tests/scripts/generate_bignum_tests.py
index 4ac9210..a105203 100755
--- a/tests/scripts/generate_bignum_tests.py
+++ b/tests/scripts/generate_bignum_tests.py
@@ -66,7 +66,7 @@
 # Import modules containing additional test classes
 # Test function classes in these modules will be registered by
 # the framework
-from mbedtls_dev import bignum_core # pylint: disable=unused-import
+from mbedtls_dev import bignum_core, bignum_mod_raw # pylint: disable=unused-import
 
 class BignumTarget(test_data_generation.BaseTarget, metaclass=ABCMeta):
     #pylint: disable=abstract-method
diff --git a/tests/scripts/generate_test_code.py b/tests/scripts/generate_test_code.py
index f5750aa..938f24c 100755
--- a/tests/scripts/generate_test_code.py
+++ b/tests/scripts/generate_test_code.py
@@ -126,33 +126,39 @@
 This script replaces following fields in the template and generates
 the test source file:
 
-$test_common_helpers        <-- All common code from helpers.function
-                                is substituted here.
-$functions_code             <-- Test functions are substituted here
-                                from the input test_suit_xyz.function
-                                file. C preprocessor checks are generated
-                                for the build dependencies specified
-                                in the input file. This script also
-                                generates wrappers for the test
-                                functions with code to expand the
-                                string parameters read from the data
-                                file.
-$expression_code            <-- This script enumerates the
-                                expressions in the .data file and
-                                generates code to handle enumerated
-                                expression Ids and return the values.
-$dep_check_code             <-- This script enumerates all
-                                build dependencies and generate
-                                code to handle enumerated build
-                                dependency Id and return status: if
-                                the dependency is defined or not.
-$dispatch_code              <-- This script enumerates the functions
-                                specified in the input test data file
-                                and generates the initializer for the
-                                function table in the template
-                                file.
-$platform_code              <-- Platform specific setup and test
-                                dispatch code.
+__MBEDTLS_TEST_TEMPLATE__TEST_COMMON_HELPERS
+            All common code from helpers.function
+            is substituted here.
+__MBEDTLS_TEST_TEMPLATE__FUNCTIONS_CODE
+            Test functions are substituted here
+            from the input test_suit_xyz.function
+            file. C preprocessor checks are generated
+            for the build dependencies specified
+            in the input file. This script also
+            generates wrappers for the test
+            functions with code to expand the
+            string parameters read from the data
+            file.
+__MBEDTLS_TEST_TEMPLATE__EXPRESSION_CODE
+            This script enumerates the
+            expressions in the .data file and
+            generates code to handle enumerated
+            expression Ids and return the values.
+__MBEDTLS_TEST_TEMPLATE__DEP_CHECK_CODE
+            This script enumerates all
+            build dependencies and generate
+            code to handle enumerated build
+            dependency Id and return status: if
+            the dependency is defined or not.
+__MBEDTLS_TEST_TEMPLATE__DISPATCH_CODE
+            This script enumerates the functions
+            specified in the input test data file
+            and generates the initializer for the
+            function table in the template
+            file.
+__MBEDTLS_TEST_TEMPLATE__PLATFORM_CODE
+            Platform specific setup and test
+            dispatch code.
 
 """
 
@@ -974,11 +980,27 @@
     :param snippets: Generated and code snippets
     :return:
     """
+
+    # Create a placeholder pattern with the correct named capture groups
+    # to override the default provided with Template.
+    # Match nothing (no way of escaping placeholders).
+    escaped = "(?P<escaped>(?!))"
+    # Match the "__MBEDTLS_TEST_TEMPLATE__PLACEHOLDER_NAME" pattern.
+    named = "__MBEDTLS_TEST_TEMPLATE__(?P<named>[A-Z][_A-Z0-9]*)"
+    # Match nothing (no braced placeholder syntax).
+    braced = "(?P<braced>(?!))"
+    # If not already matched, a "__MBEDTLS_TEST_TEMPLATE__" prefix is invalid.
+    invalid = "(?P<invalid>__MBEDTLS_TEST_TEMPLATE__)"
+    placeholder_pattern = re.compile("|".join([escaped, named, braced, invalid]))
+
     with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
         for line_no, line in enumerate(template_f.readlines(), 1):
             # Update line number. +1 as #line directive sets next line number
             snippets['line_no'] = line_no + 1
-            code = string.Template(line).substitute(**snippets)
+            template = string.Template(line)
+            template.pattern = placeholder_pattern
+            snippets = {k.upper():v for (k, v) in snippets.items()}
+            code = template.substitute(**snippets)
             c_f.write(code)
 
 
diff --git a/tests/scripts/run-test-suites.pl b/tests/scripts/run-test-suites.pl
index 22eadd1..8a5bb93 100755
--- a/tests/scripts/run-test-suites.pl
+++ b/tests/scripts/run-test-suites.pl
@@ -50,11 +50,13 @@
            'verbose|v:1' => \$verbose,
           ) or die;
 
-# All test suites = executable files, excluding source files, debug
-# and profiling information, etc. We can't just grep {! /\./} because
-# some of our test cases' base names contain a dot.
-my @suites = grep { -x $_ || /\.exe$/ } glob 'test_suite_*';
-@suites = grep { !/\.c$/ && !/\.data$/ && -f } @suites;
+# All test suites = executable files derived from a .data file.
+my @suites = ();
+for my $data_file (glob 'suites/test_suite_*.data') {
+    (my $base = $data_file) =~ s#^suites/(.*)\.data$#$1#;
+    push @suites, $base if -x $base;
+    push @suites, "$base.exe" if -e "$base.exe";
+}
 die "$0: no test suite found\n" unless @suites;
 
 # "foo" as a skip pattern skips "test_suite_foo" and "test_suite_foo.bar"
diff --git a/tests/src/helpers.c b/tests/src/helpers.c
index b7c8364..cc23fd7 100644
--- a/tests/src/helpers.c
+++ b/tests/src/helpers.c
@@ -357,8 +357,12 @@
     size_t hex_len = strlen( input );
     size_t byte_len = ( hex_len + 1 ) / 2;
     *plimbs = CHARS_TO_LIMBS( byte_len );
+
+    /* A core bignum is not allowed to be empty. Forbid it as test data,
+     * this way static analyzers have a chance of knowing we don't expect
+     * the bignum functions to support empty inputs. */
     if( *plimbs == 0 )
-        return( 0 );
+        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
 
     *pX = mbedtls_calloc( *plimbs, sizeof( **pX ) );
     if( *pX == NULL )
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index fc892a1..9eb925a 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -1024,6 +1024,16 @@
     esac
 }
 
+# Generate random psk_list argument for ssl_server2
+get_srv_psk_list ()
+{
+    case $(( TESTS % 3 )) in
+        0) echo "psk_list=abc,dead,def,beef,Client_identity,6162636465666768696a6b6c6d6e6f70";;
+        1) echo "psk_list=abc,dead,Client_identity,6162636465666768696a6b6c6d6e6f70,def,beef";;
+        2) echo "psk_list=Client_identity,6162636465666768696a6b6c6d6e6f70,abc,dead,def,beef";;
+    esac
+}
+
 # Determine what calc_verify trace is to be expected, if any.
 #
 # calc_verify is only called for two things: to calculate the
diff --git a/tests/suites/main_test.function b/tests/suites/main_test.function
index e016865..48003d4 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -3,17 +3,17 @@
  * *** THIS FILE HAS BEEN MACHINE GENERATED ***
  *
  * This file has been machine generated using the script:
- * $generator_script
+ * __MBEDTLS_TEST_TEMPLATE__GENERATOR_SCRIPT
  *
- * Test file      : $test_file
+ * Test file      : __MBEDTLS_TEST_TEMPLATE__TEST_FILE
  *
  * The following files were used to create this file.
  *
- *      Main code file      : $test_main_file
- *      Platform code file  : $test_platform_file
- *      Helper file         : $test_common_helper_file
- *      Test suite file     : $test_case_file
- *      Test suite data     : $test_case_data_file
+ *      Main code file      : __MBEDTLS_TEST_TEMPLATE__TEST_MAIN_FILE
+ *      Platform code file  : __MBEDTLS_TEST_TEMPLATE__TEST_PLATFORM_FILE
+ *      Helper file         : __MBEDTLS_TEST_TEMPLATE__TEST_COMMON_HELPER_FILE
+ *      Test suite file     : __MBEDTLS_TEST_TEMPLATE__TEST_CASE_FILE
+ *      Test suite data     : __MBEDTLS_TEST_TEMPLATE__TEST_CASE_DATA_FILE
  *
  */
 
@@ -37,9 +37,9 @@
 /*----------------------------------------------------------------------------*/
 /* Common helper code */
 
-$test_common_helpers
+__MBEDTLS_TEST_TEMPLATE__TEST_COMMON_HELPERS
 
-#line $line_no "suites/main_test.function"
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
 
 
 /*----------------------------------------------------------------------------*/
@@ -48,9 +48,9 @@
 
 #define TEST_SUITE_ACTIVE
 
-$functions_code
+__MBEDTLS_TEST_TEMPLATE__FUNCTIONS_CODE
 
-#line $line_no "suites/main_test.function"
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
 
 
 /*----------------------------------------------------------------------------*/
@@ -62,7 +62,7 @@
  *              For optimizing space for embedded targets each expression/macro
  *              is identified by a unique identifier instead of string literals.
  *              Identifiers and evaluation code is generated by script:
- *              $generator_script
+ *              __MBEDTLS_TEST_TEMPLATE__GENERATOR_SCRIPT
  *
  * \param exp_id    Expression identifier.
  * \param out_value Pointer to int to hold the integer.
@@ -78,8 +78,8 @@
 
     switch( exp_id )
     {
-$expression_code
-#line $line_no "suites/main_test.function"
+__MBEDTLS_TEST_TEMPLATE__EXPRESSION_CODE
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
         default:
            {
                 ret = KEY_VALUE_MAPPING_NOT_FOUND;
@@ -95,7 +95,7 @@
  *              For optimizing space for embedded targets each dependency
  *              is identified by a unique identifier instead of string literals.
  *              Identifiers and check code is generated by script:
- *              $generator_script
+ *              __MBEDTLS_TEST_TEMPLATE__GENERATOR_SCRIPT
  *
  * \param dep_id    Dependency identifier.
  *
@@ -109,8 +109,8 @@
 
     switch( dep_id )
     {
-$dep_check_code
-#line $line_no "suites/main_test.function"
+__MBEDTLS_TEST_TEMPLATE__DEP_CHECK_CODE
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
         default:
             break;
     }
@@ -137,13 +137,13 @@
 /**
  * \brief       Table of test function wrappers. Used by dispatch_test().
  *              This table is populated by script:
- *              $generator_script
+ *              __MBEDTLS_TEST_TEMPLATE__GENERATOR_SCRIPT
  *
  */
 TestWrapper_t test_funcs[] =
 {
-$dispatch_code
-#line $line_no "suites/main_test.function"
+__MBEDTLS_TEST_TEMPLATE__DISPATCH_CODE
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
 };
 
 /**
@@ -219,9 +219,9 @@
 }
 
 
-$platform_code
+__MBEDTLS_TEST_TEMPLATE__PLATFORM_CODE
 
-#line $line_no "suites/main_test.function"
+#line __MBEDTLS_TEST_TEMPLATE__LINE_NO "suites/main_test.function"
 
 /*----------------------------------------------------------------------------*/
 /* Main Test code */
diff --git a/tests/suites/test_suite_bignum.function b/tests/suites/test_suite_bignum.function
index 4cec0a7..5c3d776 100644
--- a/tests/suites/test_suite_bignum.function
+++ b/tests/suites/test_suite_bignum.function
@@ -959,24 +959,57 @@
 /* END_CASE */
 
 /* BEGIN_CASE */
-void mpi_mod_int( char * input_X, int input_Y,
-                  int input_A, int div_result )
+void mpi_mod_int( char * input_X, char * input_Y,
+                  char * input_A, int mod_result )
 {
     mbedtls_mpi X;
+    mbedtls_mpi Y;
+    mbedtls_mpi A;
     int res;
     mbedtls_mpi_uint r;
-    mbedtls_mpi_init( &X );
 
-    TEST_ASSERT( mbedtls_test_read_mpi( &X, input_X ) == 0 );
-    res = mbedtls_mpi_mod_int( &r, &X, input_Y );
-    TEST_ASSERT( res == div_result );
+    mbedtls_mpi_init( &X );
+    mbedtls_mpi_init( &Y );
+    mbedtls_mpi_init( &A );
+
+    /* We use MPIs to read Y and A since the test framework limits us to
+     * ints, so we can't have 64-bit values */
+    TEST_EQUAL( mbedtls_test_read_mpi( &X, input_X ), 0 );
+    TEST_EQUAL( mbedtls_test_read_mpi( &Y, input_Y ), 0 );
+    TEST_EQUAL( mbedtls_test_read_mpi( &A, input_A ), 0 );
+
+    TEST_EQUAL( Y.n, 1 );
+    TEST_EQUAL( A.n, 1 );
+
+    /* Convert the MPIs for Y and A to (signed) mbedtls_mpi_sints */
+
+    /* Since we're converting sign+magnitude to two's complement, we lose one
+     * bit of value in the output. This means there are some values we can't
+     * represent, e.g. (hex) -A0000000 on 32-bit systems. These are technically
+     * invalid test cases, so could be considered "won't happen", but they are
+     * easy to test for, and this helps guard against human error. */
+
+    mbedtls_mpi_sint y = (mbedtls_mpi_sint) Y.p[0];
+    TEST_ASSERT( y >= 0 );      /* If y < 0 here, we can't make negative y */
+    if( Y.s == -1 )
+        y = -y;
+
+    mbedtls_mpi_sint a = (mbedtls_mpi_sint) A.p[0];
+    TEST_ASSERT( a >= 0 );      /* Same goes for a */
+    if( A.s == -1 )
+        a = -a;
+
+    res = mbedtls_mpi_mod_int( &r, &X, y );
+    TEST_EQUAL( res, mod_result );
     if( res == 0 )
     {
-        TEST_ASSERT( r == (mbedtls_mpi_uint) input_A );
+        TEST_EQUAL( r, a );
     }
 
 exit:
     mbedtls_mpi_free( &X );
+    mbedtls_mpi_free( &Y );
+    mbedtls_mpi_free( &A );
 }
 /* END_CASE */
 
diff --git a/tests/suites/test_suite_bignum.misc.data b/tests/suites/test_suite_bignum.misc.data
index 29ba4ab..0b8aa33 100644
--- a/tests/suites/test_suite_bignum.misc.data
+++ b/tests/suites/test_suite_bignum.misc.data
@@ -1205,40 +1205,72 @@
 mpi_mod_mpi:"":"-1":"":MBEDTLS_ERR_MPI_NEGATIVE_VALUE
 
 Base test mbedtls_mpi_mod_int #1
-mpi_mod_int:"3e8":13:12:0
+mpi_mod_int:"3e8":"d":"c":0
 
 Base test mbedtls_mpi_mod_int #2 (Divide by zero)
-mpi_mod_int:"3e8":0:0:MBEDTLS_ERR_MPI_DIVISION_BY_ZERO
+mpi_mod_int:"3e8":"0":"0":MBEDTLS_ERR_MPI_DIVISION_BY_ZERO
 
 Base test mbedtls_mpi_mod_int #3
-mpi_mod_int:"-3e8":13:1:0
+mpi_mod_int:"-3e8":"d":"1":0
 
 Base test mbedtls_mpi_mod_int #4 (Negative modulo)
-mpi_mod_int:"3e8":-13:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+mpi_mod_int:"3e8":"-d":"0":MBEDTLS_ERR_MPI_NEGATIVE_VALUE
 
 Base test mbedtls_mpi_mod_int #5 (Negative modulo)
-mpi_mod_int:"-3e8":-13:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+mpi_mod_int:"-3e8":"-d":"0":MBEDTLS_ERR_MPI_NEGATIVE_VALUE
 
 Base test mbedtls_mpi_mod_int #6 (By 1)
-mpi_mod_int:"3e8":1:0:0
+mpi_mod_int:"3e8":"1":"0":0
 
 Base test mbedtls_mpi_mod_int #7 (By 2)
-mpi_mod_int:"3e9":2:1:0
+mpi_mod_int:"3e9":"2":"1":0
 
 Base test mbedtls_mpi_mod_int #8 (By 2)
-mpi_mod_int:"3e8":2:0:0
+mpi_mod_int:"3e8":"2":"0":0
 
 Test mbedtls_mpi_mod_int: 0 (null) % 1
-mpi_mod_int:"":1:0:0
+mpi_mod_int:"":"1":"0":0
 
 Test mbedtls_mpi_mod_int: 0 (null) % 2
-mpi_mod_int:"":2:0:0
+mpi_mod_int:"":"2":"0":0
 
 Test mbedtls_mpi_mod_int: 0 (null) % -1
-mpi_mod_int:"":-1:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+mpi_mod_int:"":"-1":"0":MBEDTLS_ERR_MPI_NEGATIVE_VALUE
 
 Test mbedtls_mpi_mod_int: 0 (null) % -2
-mpi_mod_int:"":-2:0:MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+mpi_mod_int:"":"-2":"0":MBEDTLS_ERR_MPI_NEGATIVE_VALUE
+
+# CURRENTLY FAILS - SEE GITHUB ISSUE #6540
+#Test mbedtls_mpi_mod_int: 230772460340063000000100500000300000010 % 5178236083361335880 -> 3386266129388798810
+#depends_on:MBEDTLS_HAVE_INT64
+#mpi_mod_int:"AD9D28BF6C4E98FDF156BF0980CEE30A":"47DCCA4847DCCA48":"2EFE6F1A7D28035A":0
+
+Test mbedtls_mpi_mod_mpi: 230772460340063000000100500000300000010 % 5178236083361335880 -> 3386266129388798810
+mpi_mod_mpi:"AD9D28BF6C4E98FDF156BF0980CEE30A":"47DCCA4847DCCA48":"2EFE6F1A7D28035A":0
+
+# CURRENTLY FAILS - SEE GITHUB ISSUE #6540
+#Test mbedtls_mpi_mod_int: 230772460340062999996714233870911201200 % 5178236083361335880 -> 0
+#depends_on:MBEDTLS_HAVE_INT64
+#mpi_mod_int:"AD9D28BF6C4E98FDC2584FEF03A6DFB0":"47DCCA4847DCCA48":"0":0
+
+Test mbedtls_mpi_mod_mpi: 230772460340062999996714233870911201200 % 5178236083361335880 -> 0
+mpi_mod_mpi:"AD9D28BF6C4E98FDC2584FEF03A6DFB0":"47DCCA4847DCCA48":"0":0
+
+# CURRENTLY FAILS WHEN MPIS ARE 32-BIT (ISSUE #6450): WHEN FIXED, REMOVE "depends_on" LINE
+Test mbedtls_mpi_mod_int: 230772460340063000000100500000300000010 % 1205652040 -> 3644370
+depends_on:MBEDTLS_HAVE_INT64
+mpi_mod_int:"AD9D28BF6C4E98FDF156BF0980CEE30A":"47DCCA48":"379BD2":0
+
+Test mbedtls_mpi_mod_mpi: 230772460340063000000100500000300000010 % 1205652040 -> 3644370
+mpi_mod_mpi:"AD9D28BF6C4E98FDF156BF0980CEE30A":"47DCCA48":"379BD2":0
+
+# CURRENTLY FAILS WHEN MPIS ARE 32-BIT (ISSUE #6450): WHEN FIXED, REMOVE "depends_on" LINE
+Test mbedtls_mpi_mod_int: 230772460340063000000100500000296355640 % 1205652040 -> 0
+depends_on:MBEDTLS_HAVE_INT64
+mpi_mod_int:"AD9D28BF6C4E98FDF156BF0980974738":"47DCCA48":"0":0
+
+Test mbedtls_mpi_mod_mpi: 230772460340063000000100500000296355640 % 1205652040 -> 0
+mpi_mod_mpi:"AD9D28BF6C4E98FDF156BF0980974738":"47DCCA48":"0":0
 
 Base test mbedtls_mpi_exp_mod #1
 mpi_exp_mod:"17":"d":"1d":"18":0
diff --git a/tests/suites/test_suite_bignum_core.misc.data b/tests/suites/test_suite_bignum_core.misc.data
index 30c767c..62480e4 100644
--- a/tests/suites/test_suite_bignum_core.misc.data
+++ b/tests/suites/test_suite_bignum_core.misc.data
@@ -167,9 +167,6 @@
 mbedtls_mpi_core_lt_ct: x<y (1 limb)
 mpi_core_lt_ct:"2B5":"2B6":1
 
-mbedtls_mpi_core_lt_ct: x=y (0 limbs)
-mpi_core_lt_ct:"":"":0
-
 mbedtls_mpi_core_lt_ct: x>y (63 bit x, y first byte greater)
 mpi_core_lt_ct:"7FFFFFFFFFFFFFFF":"00000000000000FF":0
 
diff --git a/tests/suites/test_suite_bignum_mod_raw.function b/tests/suites/test_suite_bignum_mod_raw.function
index 4b90675..ff766b9 100644
--- a/tests/suites/test_suite_bignum_mod_raw.function
+++ b/tests/suites/test_suite_bignum_mod_raw.function
@@ -294,7 +294,77 @@
 /* END MERGE SLOT 6 */
 
 /* BEGIN MERGE SLOT 7 */
+/* BEGIN_CASE */
+void mpi_mod_raw_to_mont_rep( char * input_N, char * input_A, char * input_X )
+{
+    mbedtls_mpi_uint *N = NULL;
+    mbedtls_mpi_uint *A = NULL;
+    mbedtls_mpi_uint *X = NULL;
+    size_t n_limbs, a_limbs, x_limbs, x_bytes;
 
+    mbedtls_mpi_mod_modulus m;
+    mbedtls_mpi_mod_modulus_init( &m );
+
+    /* Read inputs */
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &N, &n_limbs, input_N ) );
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &A, &a_limbs, input_A ) );
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &X, &x_limbs, input_X ) );
+    x_bytes = x_limbs * sizeof(mbedtls_mpi_uint);
+
+    /* Test that input does not require more limbs than modulo */
+    TEST_LE_U(a_limbs, n_limbs);
+
+    TEST_EQUAL( 0, mbedtls_mpi_mod_modulus_setup( &m, N, n_limbs,
+                MBEDTLS_MPI_MOD_EXT_REP_BE, MBEDTLS_MPI_MOD_REP_MONTGOMERY ) );
+
+    /* Convert from cannonical into Montgomery representation */
+    TEST_EQUAL(0, mbedtls_mpi_mod_raw_to_mont_rep( A, &m ) );
+
+    /* The result matches expected value */
+    ASSERT_COMPARE( A, x_bytes, X, x_bytes );
+exit:
+    mbedtls_mpi_mod_modulus_free( &m );
+    mbedtls_free( N );
+    mbedtls_free( A );
+    mbedtls_free( X );
+}
+/* END_CASE */
+
+/* BEGIN_CASE */
+void mpi_mod_raw_from_mont_rep( char * input_N, char * input_A, char * input_X )
+{
+    mbedtls_mpi_uint *N = NULL;
+    mbedtls_mpi_uint *A = NULL;
+    mbedtls_mpi_uint *X = NULL;
+    size_t n_limbs, a_limbs, x_limbs, x_bytes;
+
+    mbedtls_mpi_mod_modulus m;
+    mbedtls_mpi_mod_modulus_init( &m );
+
+    /* Read inputs */
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &N, &n_limbs, input_N ) );
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &A, &a_limbs, input_A ) );
+    TEST_EQUAL( 0, mbedtls_test_read_mpi_core( &X, &x_limbs, input_X ) );
+    x_bytes = x_limbs * sizeof(mbedtls_mpi_uint);
+
+    /* Test that input does not require more limbs than modulo */
+    TEST_LE_U(a_limbs, n_limbs);
+
+    TEST_EQUAL( 0, mbedtls_mpi_mod_modulus_setup( &m, N, n_limbs,
+                MBEDTLS_MPI_MOD_EXT_REP_BE, MBEDTLS_MPI_MOD_REP_MONTGOMERY ) );
+
+    /* Convert from Montgomery into cannonical representation */
+    TEST_EQUAL(0, mbedtls_mpi_mod_raw_from_mont_rep( A, &m ) );
+
+    /* The result matches expected value */
+    ASSERT_COMPARE( A, x_bytes, X, x_bytes );
+exit:
+    mbedtls_mpi_mod_modulus_free( &m );
+    mbedtls_free( N );
+    mbedtls_free( A );
+    mbedtls_free( X );
+}
+/* END_CASE */
 /* END MERGE SLOT 7 */
 
 /* BEGIN MERGE SLOT 8 */
diff --git a/tests/suites/test_suite_psa_crypto.function b/tests/suites/test_suite_psa_crypto.function
index 36a8efa..779f594 100644
--- a/tests/suites/test_suite_psa_crypto.function
+++ b/tests/suites/test_suite_psa_crypto.function
@@ -790,8 +790,8 @@
 
             if( inject_error == 1 )
             {
-                buffer0[s_x1_pk_off + 8] >>= 4;
-                buffer0[s_x2_pk_off + 7] <<= 4;
+                buffer0[s_x1_pr_off + 8] ^= 1;
+                buffer0[s_x2_pr_off + 7] ^= 1;
                 expected_status = PSA_ERROR_DATA_INVALID;
             }
 
@@ -1013,8 +1013,8 @@
 
             if( inject_error == 2 )
             {
-                buffer1[c_x1_pk_off + 12] >>= 4;
-                buffer1[c_x2_pk_off + 7] <<= 4;
+                buffer1[c_x1_pr_off + 12] ^= 1;
+                buffer1[c_x2_pr_off + 7] ^= 1;
                 expected_status = PSA_ERROR_DATA_INVALID;
             }
 
diff --git a/tests/suites/test_suite_x509parse.data b/tests/suites/test_suite_x509parse.data
index 8dd3379..bd03016 100644
--- a/tests/suites/test_suite_x509parse.data
+++ b/tests/suites/test_suite_x509parse.data
@@ -88,7 +88,11 @@
 
 X509 CRT information EC, SHA256 Digest, hardware module name SAN
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
-x509_cert_info:"data_files/server5-othername.crt":"cert. version     \: 3\nserial number     \: 4D\nissuer name       \: C=UK, O=Mbed TLS, CN=Mbed TLS othername SAN\nsubject name      \: C=UK, O=Mbed TLS, CN=Mbed TLS othername SAN\nissued  on        \: 2019-03-24 09\:06\:02\nexpires on        \: 2029-03-21 09\:06\:02\nsigned using      \: ECDSA with SHA256\nEC key size       \: 256 bits\nsubject alt name  \:\n    otherName \:\n        hardware module name \:\n            hardware type          \: 1.3.6.1.4.1.17.3\n            hardware serial number \: 123456\n"
+x509_cert_info:"data_files/server5-othername.crt":"cert. version     \: 3\nserial number     \: 4D\nissuer name       \: C=UK, O=Mbed TLS, CN=Mbed TLS othername SAN\nsubject name      \: C=UK, O=Mbed TLS, CN=Mbed TLS othername SAN\nissued  on        \: 2019-03-24 09\:06\:02\nexpires on        \: 2029-03-21 09\:06\:02\nsigned using      \: ECDSA with SHA256\nEC key size       \: 256 bits\nsubject alt name  \:\n    otherName \:\n        hardware module name \:\n            hardware type          \: 1.3.6.1.4.1.17.3\n            hardware serial number \: 313233343536\n"
+
+X509 CRT information EC, SHA256 Digest, binary hardware module name SAN
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
+x509_cert_info:"data_files/server5-nonprintable_othername.crt":"cert. version     \: 3\nserial number     \: 4D\nissuer name       \: C=UK, O=Mbed TLS, CN=Mbed TLS non-printable othername SAN\nsubject name      \: C=UK, O=Mbed TLS, CN=Mbed TLS non-printable othername SAN\nissued  on        \: 2022-09-06 15\:56\:47\nexpires on        \: 2032-09-03 15\:56\:47\nsigned using      \: ECDSA with SHA256\nEC key size       \: 256 bits\nsubject alt name  \:\n    otherName \:\n        hardware module name \:\n            hardware type          \: 1.3.6.1.4.1.17.3\n            hardware serial number \: 3132338081008180333231\n"
 
 X509 CRT information EC, SHA256 Digest, Wisun Fan device
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
@@ -112,7 +116,7 @@
 
 X509 CRT information, Multiple different Subject Alt Name
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
-x509_cert_info:"data_files/multiple_san.crt":"cert. version     \: 3\nserial number     \: 04\nissuer name       \: C=UK, O=Mbed TLS, CN=Mbed TLS multiple othername SAN\nsubject name      \: C=UK, O=Mbed TLS, CN=Mbed TLS multiple othername SAN\nissued  on        \: 2019-04-22 16\:10\:48\nexpires on        \: 2029-04-19 16\:10\:48\nsigned using      \: ECDSA with SHA256\nEC key size       \: 256 bits\nsubject alt name  \:\n    dNSName \: example.com\n    otherName \:\n        hardware module name \:\n            hardware type          \: 1.3.6.1.4.1.17.3\n            hardware serial number \: 123456\n    dNSName \: example.net\n    dNSName \: *.example.org\n"
+x509_cert_info:"data_files/multiple_san.crt":"cert. version     \: 3\nserial number     \: 04\nissuer name       \: C=UK, O=Mbed TLS, CN=Mbed TLS multiple othername SAN\nsubject name      \: C=UK, O=Mbed TLS, CN=Mbed TLS multiple othername SAN\nissued  on        \: 2019-04-22 16\:10\:48\nexpires on        \: 2029-04-19 16\:10\:48\nsigned using      \: ECDSA with SHA256\nEC key size       \: 256 bits\nsubject alt name  \:\n    dNSName \: example.com\n    otherName \:\n        hardware module name \:\n            hardware type          \: 1.3.6.1.4.1.17.3\n            hardware serial number \: 313233343536\n    dNSName \: example.net\n    dNSName \: *.example.org\n"
 
 X509 CRT information, Subject Alt Name + Key Usage
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA
@@ -172,7 +176,11 @@
 
 X509 SAN parsing otherName
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
-x509_parse_san:"data_files/server5-othername.crt":"type \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 123456\n"
+x509_parse_san:"data_files/server5-othername.crt":"type \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 313233343536\n"
+
+X509 SAN parsing binary otherName
+depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
+x509_parse_san:"data_files/server5-nonprintable_othername.crt":"type \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 3132338081008180333231\n"
 
 X509 SAN parsing dNSName
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
@@ -180,7 +188,7 @@
 
 X509 SAN parsing  Multiple different types
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA
-x509_parse_san:"data_files/multiple_san.crt":"type \: 2\ndNSName \: example.com\ntype \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 123456\ntype \: 2\ndNSName \: example.net\ntype \: 2\ndNSName \: *.example.org\n"
+x509_parse_san:"data_files/multiple_san.crt":"type \: 2\ndNSName \: example.com\ntype \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 313233343536\ntype \: 2\ndNSName \: example.net\ntype \: 2\ndNSName \: *.example.org\n"
 
 X509 SAN parsing, no subject alt name
 depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECDSA_C
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index 3369a8a..2585720 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -246,36 +246,30 @@
 
     switch( san->type )
     {
-       case( MBEDTLS_X509_SAN_OTHER_NAME ):
-           ret = mbedtls_snprintf( p, n, "\notherName :");
-           MBEDTLS_X509_SAFE_SNPRINTF;
+        case( MBEDTLS_X509_SAN_OTHER_NAME ):
+            ret = mbedtls_snprintf( p, n, "\notherName :");
+            MBEDTLS_X509_SAFE_SNPRINTF;
 
-           if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME,
-                    &san->san.other_name.value.hardware_module_name.oid ) != 0 )
-           {
-               ret = mbedtls_snprintf( p, n, " hardware module name :" );
-               MBEDTLS_X509_SAFE_SNPRINTF;
-               ret = mbedtls_snprintf( p, n, " hardware type : " );
-               MBEDTLS_X509_SAFE_SNPRINTF;
+            if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME,
+                     &san->san.other_name.value.hardware_module_name.oid ) != 0 )
+            {
+                ret = mbedtls_snprintf( p, n, " hardware module name :" );
+                MBEDTLS_X509_SAFE_SNPRINTF;
+                ret = mbedtls_snprintf( p, n, " hardware type : " );
+                MBEDTLS_X509_SAFE_SNPRINTF;
 
-               ret = mbedtls_oid_get_numeric_string( p, n,
-                          &san->san.other_name.value.hardware_module_name.oid );
-               MBEDTLS_X509_SAFE_SNPRINTF;
+                ret = mbedtls_oid_get_numeric_string( p, n,
+                           &san->san.other_name.value.hardware_module_name.oid );
+                MBEDTLS_X509_SAFE_SNPRINTF;
 
-               ret = mbedtls_snprintf( p, n, ", hardware serial number : " );
-               MBEDTLS_X509_SAFE_SNPRINTF;
+                ret = mbedtls_snprintf( p, n, ", hardware serial number : " );
+                MBEDTLS_X509_SAFE_SNPRINTF;
 
-               if( san->san.other_name.value.hardware_module_name.val.len >= n )
-               {
-                   *p = '\0';
-                   return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
-               }
-
-               for( i=0; i < san->san.other_name.value.hardware_module_name.val.len; i++ )
-               {
-                   *p++ = san->san.other_name.value.hardware_module_name.val.p[i];
-               }
-               n -= san->san.other_name.value.hardware_module_name.val.len;
+                for( i = 0; i < san->san.other_name.value.hardware_module_name.val.len; i++ )
+                {
+                    ret = mbedtls_snprintf( p, n, "%02X", san->san.other_name.value.hardware_module_name.val.p[i] );
+                    MBEDTLS_X509_SAFE_SNPRINTF;
+                }
             }
         break;/* MBEDTLS_OID_ON_HW_MODULE_NAME */
         case(  MBEDTLS_X509_SAN_DNS_NAME ):
diff --git a/tests/suites/test_suite_x509write.data b/tests/suites/test_suite_x509write.data
index 8411557..c55c9d1 100644
--- a/tests/suites/test_suite_x509write.data
+++ b/tests/suites/test_suite_x509write.data
@@ -1,30 +1,30 @@
 Certificate Request check Server1 SHA1
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha1":MBEDTLS_MD_SHA1:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha1":MBEDTLS_MD_SHA1:0:0:0:0:0
 
 Certificate Request check Server1 SHA224
 depends_on:MBEDTLS_HAS_ALG_SHA_224_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha224":MBEDTLS_MD_SHA224:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha224":MBEDTLS_MD_SHA224:0:0:0:0:0
 
 Certificate Request check Server1 SHA256
 depends_on:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha256":MBEDTLS_MD_SHA256:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha256":MBEDTLS_MD_SHA256:0:0:0:0:0
 
 Certificate Request check Server1 SHA384
 depends_on:MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha384":MBEDTLS_MD_SHA384:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha384":MBEDTLS_MD_SHA384:0:0:0:0:0
 
 Certificate Request check Server1 SHA512
 depends_on:MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha512":MBEDTLS_MD_SHA512:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha512":MBEDTLS_MD_SHA512:0:0:0:0:0
 
 Certificate Request check Server1 MD5
 depends_on:MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.md5":MBEDTLS_MD_MD5:0:0:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.md5":MBEDTLS_MD_MD5:0:0:0:0:0
 
 Certificate Request check Server1 key_usage
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.key_usage":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION | MBEDTLS_X509_KU_KEY_ENCIPHERMENT:1:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.key_usage":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION | MBEDTLS_X509_KU_KEY_ENCIPHERMENT:1:0:0:0
 
 Certificate Request check opaque Server1 key_usage
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
@@ -32,23 +32,27 @@
 
 Certificate Request check Server1 key_usage empty
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.key_usage_empty":MBEDTLS_MD_SHA1:0:1:0:0
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.key_usage_empty":MBEDTLS_MD_SHA1:0:1:0:0:0
 
 Certificate Request check Server1 ns_cert_type
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.cert_type":MBEDTLS_MD_SHA1:0:0:MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER:1
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.cert_type":MBEDTLS_MD_SHA1:0:0:MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER:1:0
 
 Certificate Request check Server1 ns_cert_type empty
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.cert_type_empty":MBEDTLS_MD_SHA1:0:0:0:1
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.cert_type_empty":MBEDTLS_MD_SHA1:0:0:0:1:0
 
 Certificate Request check Server1 key_usage + ns_cert_type
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
-x509_csr_check:"data_files/server1.key":"data_files/server1.req.ku-ct":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION | MBEDTLS_X509_KU_KEY_ENCIPHERMENT:1:MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER:1
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.ku-ct":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION | MBEDTLS_X509_KU_KEY_ENCIPHERMENT:1:MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER:1:0
 
 Certificate Request check Server5 ECDSA, key_usage
 depends_on:MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECDSA_C:MBEDTLS_ECDSA_DETERMINISTIC:MBEDTLS_ECP_DP_SECP256R1_ENABLED
-x509_csr_check:"data_files/server5.key":"data_files/server5.req.ku.sha1":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION:1:0:0
+x509_csr_check:"data_files/server5.key":"data_files/server5.req.ku.sha1":MBEDTLS_MD_SHA1:MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_NON_REPUDIATION:1:0:0:0
+
+Certificate Request check Server1, set_extension
+depends_on:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_RSA_C:MBEDTLS_PKCS1_V15
+x509_csr_check:"data_files/server1.key":"data_files/server1.req.sha256.ext":MBEDTLS_MD_SHA256:0:0:0:0:1
 
 Certificate Request check opaque Server5 ECDSA, key_usage
 depends_on:MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA_BASED_ON_USE_PSA:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
diff --git a/tests/suites/test_suite_x509write.function b/tests/suites/test_suite_x509write.function
index aa54072..5bd814a 100644
--- a/tests/suites/test_suite_x509write.function
+++ b/tests/suites/test_suite_x509write.function
@@ -5,6 +5,7 @@
 #include "mbedtls/pem.h"
 #include "mbedtls/oid.h"
 #include "mbedtls/rsa.h"
+#include "mbedtls/asn1write.h"
 
 #include "hash_info.h"
 #include "mbedtls/legacy_or_psa.h"
@@ -74,6 +75,56 @@
 }
 #endif /* MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_PEM_WRITE_C && MBEDTLS_X509_CSR_WRITE_C */
 
+#if defined(MBEDTLS_X509_CSR_WRITE_C)
+
+/*
+ * The size of this temporary buffer is given by the sequence of functions
+ * called hereinafter:
+ * - mbedtls_asn1_write_oid()
+ *     - 8 bytes for MBEDTLS_OID_EXTENDED_KEY_USAGE raw value
+ *     - 1 byte for MBEDTLS_OID_EXTENDED_KEY_USAGE length
+ *     - 1 byte for MBEDTLS_ASN1_OID tag
+ * - mbedtls_asn1_write_len()
+ *     - 1 byte since we're dealing with sizes which are less than 0x80
+ * - mbedtls_asn1_write_tag()
+ *     - 1 byte
+ *
+ * This length is fine as long as this function is called using the
+ * MBEDTLS_OID_SERVER_AUTH OID. If this is changed in the future, then this
+ * buffer's length should be adjusted accordingly.
+ * Unfortunately there's no predefined max size for OIDs which can be used
+ * to set an overall upper boundary which is always guaranteed.
+ */
+#define EXT_KEY_USAGE_TMP_BUF_MAX_LENGTH    12
+
+static int csr_set_extended_key_usage( mbedtls_x509write_csr *ctx,
+                        const char *oid, size_t oid_len )
+{
+    unsigned char buf[EXT_KEY_USAGE_TMP_BUF_MAX_LENGTH] = { 0 };
+    unsigned char *p = buf + sizeof( buf );
+    int ret;
+    size_t len = 0;
+
+    /*
+     * Following functions fail anyway if the temporary buffer is not large,
+     * but we set an extra check here to emphasize a possible source of errors
+     */
+    if ( oid_len > EXT_KEY_USAGE_TMP_BUF_MAX_LENGTH )
+    {
+        return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
+    }
+
+    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_oid( &p, buf, oid, oid_len ) );
+    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, ret ) );
+    MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,
+                        MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
+
+    ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_EXTENDED_KEY_USAGE,
+              MBEDTLS_OID_SIZE( MBEDTLS_OID_EXTENDED_KEY_USAGE ), 0, p, len );
+
+    return ret;
+}
+#endif  /* MBEDTLS_X509_CSR_WRITE_C */
 /* END_HEADER */
 
 /* BEGIN_DEPENDENCIES
@@ -84,7 +135,7 @@
 /* BEGIN_CASE depends_on:MBEDTLS_PEM_WRITE_C:MBEDTLS_X509_CSR_WRITE_C */
 void x509_csr_check( char * key_file, char * cert_req_check_file, int md_type,
                      int key_usage, int set_key_usage, int cert_type,
-                     int set_cert_type )
+                     int set_cert_type, int set_extension )
 {
     mbedtls_pk_context key;
     mbedtls_x509write_csr req;
@@ -117,6 +168,9 @@
         TEST_ASSERT( mbedtls_x509write_csr_set_key_usage( &req, key_usage ) == 0 );
     if( set_cert_type != 0 )
         TEST_ASSERT( mbedtls_x509write_csr_set_ns_cert_type( &req, cert_type ) == 0 );
+    if ( set_extension != 0 )
+        TEST_ASSERT( csr_set_extended_key_usage( &req, MBEDTLS_OID_SERVER_AUTH,
+                            MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH ) ) == 0 );
 
     ret = mbedtls_x509write_csr_pem( &req, buf, sizeof( buf ),
                                      mbedtls_test_rnd_pseudo_rand, &rnd_info );