Merge pull request #8141 from tom-cosgrove-arm/define-psa-macros-to-1

Define all PSA_xxx macros to 1 rather than have them empty, for consistency
diff --git a/ChangeLog.d/config_psa-include-order.txt b/ChangeLog.d/config_psa-include-order.txt
new file mode 100644
index 0000000..674c286
--- /dev/null
+++ b/ChangeLog.d/config_psa-include-order.txt
@@ -0,0 +1,4 @@
+Bugfix
+   * Fix a build error in some configurations with MBEDTLS_PSA_CRYPTO_CONFIG
+     enabled, where some low-level modules required by requested PSA crypto
+     features were not getting automatically enabled. Fixes #7420.
diff --git a/ChangeLog.d/fix-tls-padbuf-zeroization b/ChangeLog.d/fix-tls-padbuf-zeroization
new file mode 100644
index 0000000..36451cb
--- /dev/null
+++ b/ChangeLog.d/fix-tls-padbuf-zeroization
@@ -0,0 +1,4 @@
+Security
+   * Fix a case where potentially sensitive information held in memory would not
+     be completely zeroized during TLS 1.2 handshake, in both server and client
+     configurations.
diff --git a/ChangeLog.d/initialize-struct-get-other-name.txt b/ChangeLog.d/initialize-struct-get-other-name.txt
new file mode 100644
index 0000000..dc8395d
--- /dev/null
+++ b/ChangeLog.d/initialize-struct-get-other-name.txt
@@ -0,0 +1,8 @@
+Bugfix
+   * Fix an issue when parsing an otherName subject alternative name into a
+     mbedtls_x509_san_other_name struct. The type-id of the otherName was not
+     copied to the struct. This meant that the struct had incomplete
+     information about the otherName SAN and contained uninitialized memory.
+   * Fix the detection of HardwareModuleName otherName SANs. These were being
+     detected by comparing the wrong field and the check was erroneously
+     inverted.
diff --git a/include/mbedtls/ccm.h b/include/mbedtls/ccm.h
index 6c22552..a1f601f 100644
--- a/include/mbedtls/ccm.h
+++ b/include/mbedtls/ccm.h
@@ -77,7 +77,8 @@
 typedef struct mbedtls_ccm_context {
     unsigned char MBEDTLS_PRIVATE(y)[16];    /*!< The Y working buffer */
     unsigned char MBEDTLS_PRIVATE(ctr)[16];  /*!< The counter buffer */
-    mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher_ctx);    /*!< The cipher context used. */
+    int MBEDTLS_PRIVATE(state);              /*!< Working value holding context's
+                                                  state. Used for chunked data input */
     size_t MBEDTLS_PRIVATE(plaintext_len);   /*!< Total plaintext length */
     size_t MBEDTLS_PRIVATE(add_len);         /*!< Total authentication data length */
     size_t MBEDTLS_PRIVATE(tag_len);         /*!< Total tag length */
@@ -87,15 +88,13 @@
                                                   and plaintext/ciphertext.
                                                   This variable is set to zero after
                                                   auth data input is finished. */
-    unsigned char MBEDTLS_PRIVATE(q);        /*!< The Q working value */
-    unsigned char MBEDTLS_PRIVATE(mode);     /*!< The operation to perform:
+    unsigned int MBEDTLS_PRIVATE(q);         /*!< The Q working value */
+    unsigned int MBEDTLS_PRIVATE(mode);      /*!< The operation to perform:
                                               #MBEDTLS_CCM_ENCRYPT or
                                               #MBEDTLS_CCM_DECRYPT or
                                               #MBEDTLS_CCM_STAR_ENCRYPT or
                                               #MBEDTLS_CCM_STAR_DECRYPT. */
-    int MBEDTLS_PRIVATE(state);              /*!< Working value holding context's
-                                                  state. Used for chunked data
-                                                  input */
+    mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher_ctx);    /*!< The cipher context used. */
 }
 mbedtls_ccm_context;
 
diff --git a/include/mbedtls/entropy.h b/include/mbedtls/entropy.h
index e17245e..c2bba41 100644
--- a/include/mbedtls/entropy.h
+++ b/include/mbedtls/entropy.h
@@ -115,10 +115,10 @@
  * \brief           Entropy context structure
  */
 typedef struct mbedtls_entropy_context {
+    mbedtls_md_context_t  MBEDTLS_PRIVATE(accumulator);
     int MBEDTLS_PRIVATE(accumulator_started); /* 0 after init.
                                                * 1 after the first update.
                                                * -1 after free. */
-    mbedtls_md_context_t  MBEDTLS_PRIVATE(accumulator);
     int             MBEDTLS_PRIVATE(source_count); /* Number of entries used in source. */
     mbedtls_entropy_source_state    MBEDTLS_PRIVATE(source)[MBEDTLS_ENTROPY_MAX_SOURCES];
 #if defined(MBEDTLS_THREADING_C)
diff --git a/include/mbedtls/platform_util.h b/include/mbedtls/platform_util.h
index edbde94..3f23fef 100644
--- a/include/mbedtls/platform_util.h
+++ b/include/mbedtls/platform_util.h
@@ -145,6 +145,11 @@
 #define MBEDTLS_IGNORE_RETURN(result) ((void) !(result))
 #endif
 
+/* If the following macro is defined, the library is being built by the test
+ * framework, and the framework is going to provide a replacement
+ * mbedtls_platform_zeroize() using a preprocessor macro, so the function
+ * declaration should be omitted.  */
+#if !defined(MBEDTLS_TEST_DEFINES_ZEROIZE) //no-check-names
 /**
  * \brief       Securely zeroize a buffer
  *
@@ -168,6 +173,7 @@
  *
  */
 void mbedtls_platform_zeroize(void *buf, size_t len);
+#endif
 
 #if defined(MBEDTLS_HAVE_TIME_DATE)
 /**
diff --git a/include/mbedtls/sha256.h b/include/mbedtls/sha256.h
index 87e5cc6..87e259f 100644
--- a/include/mbedtls/sha256.h
+++ b/include/mbedtls/sha256.h
@@ -50,9 +50,9 @@
  *                 made in the call to mbedtls_sha256_starts().
  */
 typedef struct mbedtls_sha256_context {
+    unsigned char MBEDTLS_PRIVATE(buffer)[64];   /*!< The data block being processed. */
     uint32_t MBEDTLS_PRIVATE(total)[2];          /*!< The number of Bytes processed.  */
     uint32_t MBEDTLS_PRIVATE(state)[8];          /*!< The intermediate digest state.  */
-    unsigned char MBEDTLS_PRIVATE(buffer)[64];   /*!< The data block being processed. */
     int MBEDTLS_PRIVATE(is224);                  /*!< Determines which function to use:
                                                     0: Use SHA-256, or 1: Use SHA-224. */
 }
diff --git a/library/ccm.c b/library/ccm.c
index cd689c8..bc61376 100644
--- a/library/ccm.c
+++ b/library/ccm.c
@@ -400,7 +400,6 @@
             mbedtls_xor(ctx->y + offset, ctx->y + offset, local_output, use_len);
 
             memcpy(output, local_output, use_len);
-            mbedtls_platform_zeroize(local_output, 16);
 
             if (use_len + offset == 16 || ctx->processed == ctx->plaintext_len) {
                 if ((ret =
diff --git a/library/ecp.c b/library/ecp.c
index f9b6672..5f2a7b0 100644
--- a/library/ecp.c
+++ b/library/ecp.c
@@ -958,9 +958,8 @@
     /*
      * Next two bytes are the namedcurve value
      */
-    tls_id = *(*buf)++;
-    tls_id <<= 8;
-    tls_id |= *(*buf)++;
+    tls_id = MBEDTLS_GET_UINT16_BE(*buf, 0);
+    *buf += 2;
 
     if ((curve_info = mbedtls_ecp_curve_info_from_tls_id(tls_id)) == NULL) {
         return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
diff --git a/library/platform_util.c b/library/platform_util.c
index 63b7c41..09216ed 100644
--- a/library/platform_util.c
+++ b/library/platform_util.c
@@ -126,6 +126,26 @@
 #else
         memset_func(buf, 0, len);
 #endif
+
+#if defined(__GNUC__)
+        /* For clang and recent gcc, pretend that we have some assembly that reads the
+         * zero'd memory as an additional protection against being optimised away. */
+#if defined(__clang__) || (__GNUC__ >= 10)
+#if defined(__clang__)
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wvla"
+#elif defined(MBEDTLS_COMPILER_IS_GCC)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wvla"
+#endif
+        asm volatile ("" : : "m" (*(char (*)[len]) buf) :);
+#if defined(__clang__)
+#pragma clang diagnostic pop
+#elif defined(MBEDTLS_COMPILER_IS_GCC)
+#pragma GCC diagnostic pop
+#endif
+#endif
+#endif
     }
 }
 #endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */
diff --git a/library/psa_crypto.c b/library/psa_crypto.c
index 84da7ad..456d4e3 100644
--- a/library/psa_crypto.c
+++ b/library/psa_crypto.c
@@ -64,6 +64,7 @@
 #include "mbedtls/cipher.h"
 #include "mbedtls/ccm.h"
 #include "mbedtls/cmac.h"
+#include "mbedtls/constant_time.h"
 #include "mbedtls/des.h"
 #include "mbedtls/ecdh.h"
 #include "mbedtls/ecp.h"
@@ -104,9 +105,9 @@
 #define RNG_SEEDED 2
 
 typedef struct {
-    unsigned initialized : 1;
-    unsigned rng_state : 2;
-    unsigned drivers_initialized : 1;
+    uint8_t initialized;
+    uint8_t rng_state;
+    uint8_t drivers_initialized;
     mbedtls_psa_random_context_t rng;
 } psa_global_data_t;
 
@@ -152,9 +153,15 @@
         case 0:
             return PSA_SUCCESS;
 
+#if defined(MBEDTLS_AES_C)
         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
             return PSA_ERROR_NOT_SUPPORTED;
+        case MBEDTLS_ERR_AES_BAD_INPUT_DATA:
+            return PSA_ERROR_INVALID_ARGUMENT;
+#endif
+
+#if defined(MBEDTLS_ASN1_PARSE_C) || defined(MBEDTLS_ASN1_WRITE_C)
         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
@@ -165,26 +172,34 @@
             return PSA_ERROR_INSUFFICIENT_MEMORY;
         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
             return PSA_ERROR_BUFFER_TOO_SMALL;
-
-#if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
-        case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
 #endif
+
+#if defined(MBEDTLS_CAMELLIA_C)
+        case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
             return PSA_ERROR_NOT_SUPPORTED;
+#endif
 
+#if defined(MBEDTLS_CCM_C)
         case MBEDTLS_ERR_CCM_BAD_INPUT:
             return PSA_ERROR_INVALID_ARGUMENT;
         case MBEDTLS_ERR_CCM_AUTH_FAILED:
             return PSA_ERROR_INVALID_SIGNATURE;
+#endif
 
+#if defined(MBEDTLS_CHACHA20_C)
         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
             return PSA_ERROR_INVALID_ARGUMENT;
+#endif
 
+#if defined(MBEDTLS_CHACHAPOLY_C)
         case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
             return PSA_ERROR_BAD_STATE;
         case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
             return PSA_ERROR_INVALID_SIGNATURE;
+#endif
 
+#if defined(MBEDTLS_CIPHER_C)
         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
             return PSA_ERROR_NOT_SUPPORTED;
         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
@@ -199,6 +214,7 @@
             return PSA_ERROR_INVALID_SIGNATURE;
         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
             return PSA_ERROR_CORRUPTION_DETECTED;
+#endif
 
 #if !(defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) ||      \
             defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE))
@@ -213,20 +229,24 @@
             return PSA_ERROR_INSUFFICIENT_ENTROPY;
 #endif
 
+#if defined(MBEDTLS_DES_C)
         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
             return PSA_ERROR_NOT_SUPPORTED;
+#endif
 
         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
             return PSA_ERROR_INSUFFICIENT_ENTROPY;
 
+#if defined(MBEDTLS_GCM_C)
         case MBEDTLS_ERR_GCM_AUTH_FAILED:
             return PSA_ERROR_INVALID_SIGNATURE;
         case MBEDTLS_ERR_GCM_BUFFER_TOO_SMALL:
             return PSA_ERROR_BUFFER_TOO_SMALL;
         case MBEDTLS_ERR_GCM_BAD_INPUT:
             return PSA_ERROR_INVALID_ARGUMENT;
+#endif
 
 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) &&        \
             defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
@@ -241,17 +261,24 @@
             return PSA_ERROR_INSUFFICIENT_ENTROPY;
 #endif
 
+#if defined(MBEDTLS_MD_LIGHT)
         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
             return PSA_ERROR_NOT_SUPPORTED;
         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
             return PSA_ERROR_INVALID_ARGUMENT;
         case MBEDTLS_ERR_MD_ALLOC_FAILED:
             return PSA_ERROR_INSUFFICIENT_MEMORY;
+#if defined(MBEDTLS_FS_IO)
         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
             return PSA_ERROR_STORAGE_FAILURE;
+#endif
+#endif
 
+#if defined(MBEDTLS_BIGNUM_C)
+#if defined(MBEDTLS_FS_IO)
         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
             return PSA_ERROR_STORAGE_FAILURE;
+#endif
         case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
             return PSA_ERROR_INVALID_ARGUMENT;
         case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
@@ -266,14 +293,19 @@
             return PSA_ERROR_INVALID_ARGUMENT;
         case MBEDTLS_ERR_MPI_ALLOC_FAILED:
             return PSA_ERROR_INSUFFICIENT_MEMORY;
+#endif
 
+#if defined(MBEDTLS_PK_C)
         case MBEDTLS_ERR_PK_ALLOC_FAILED:
             return PSA_ERROR_INSUFFICIENT_MEMORY;
         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
             return PSA_ERROR_INVALID_ARGUMENT;
+#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || defined(MBEDTLS_FS_IO) || \
+            defined(MBEDTLS_PSA_ITS_FILE_C)
         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
             return PSA_ERROR_STORAGE_FAILURE;
+#endif
         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
             return PSA_ERROR_INVALID_ARGUMENT;
@@ -292,12 +324,14 @@
             return PSA_ERROR_INVALID_SIGNATURE;
         case MBEDTLS_ERR_PK_BUFFER_TOO_SMALL:
             return PSA_ERROR_BUFFER_TOO_SMALL;
+#endif
 
         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
             return PSA_ERROR_HARDWARE_FAILURE;
         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
             return PSA_ERROR_NOT_SUPPORTED;
 
+#if defined(MBEDTLS_RSA_C)
         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
             return PSA_ERROR_INVALID_ARGUMENT;
         case MBEDTLS_ERR_RSA_INVALID_PADDING:
@@ -315,7 +349,9 @@
             return PSA_ERROR_BUFFER_TOO_SMALL;
         case MBEDTLS_ERR_RSA_RNG_FAILED:
             return PSA_ERROR_INSUFFICIENT_ENTROPY;
+#endif
 
+#if defined(MBEDTLS_ECP_LIGHT)
         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
         case MBEDTLS_ERR_ECP_INVALID_KEY:
             return PSA_ERROR_INVALID_ARGUMENT;
@@ -331,8 +367,11 @@
         case MBEDTLS_ERR_ECP_RANDOM_FAILED:
             return PSA_ERROR_INSUFFICIENT_ENTROPY;
 
+#if defined(MBEDTLS_ECP_RESTARTABLE)
         case MBEDTLS_ERR_ECP_IN_PROGRESS:
             return PSA_OPERATION_INCOMPLETE;
+#endif
+#endif
 
         case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
             return PSA_ERROR_CORRUPTION_DETECTED;
@@ -392,45 +431,71 @@
                                           size_t *bits)
 {
     switch (grpid) {
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
         case MBEDTLS_ECP_DP_SECP192R1:
             *bits = 192;
             return PSA_ECC_FAMILY_SECP_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
         case MBEDTLS_ECP_DP_SECP224R1:
             *bits = 224;
             return PSA_ECC_FAMILY_SECP_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
         case MBEDTLS_ECP_DP_SECP256R1:
             *bits = 256;
             return PSA_ECC_FAMILY_SECP_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
         case MBEDTLS_ECP_DP_SECP384R1:
             *bits = 384;
             return PSA_ECC_FAMILY_SECP_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
         case MBEDTLS_ECP_DP_SECP521R1:
             *bits = 521;
             return PSA_ECC_FAMILY_SECP_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
         case MBEDTLS_ECP_DP_BP256R1:
             *bits = 256;
             return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
         case MBEDTLS_ECP_DP_BP384R1:
             *bits = 384;
             return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
         case MBEDTLS_ECP_DP_BP512R1:
             *bits = 512;
             return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
         case MBEDTLS_ECP_DP_CURVE25519:
             *bits = 255;
             return PSA_ECC_FAMILY_MONTGOMERY;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
         case MBEDTLS_ECP_DP_SECP192K1:
             *bits = 192;
             return PSA_ECC_FAMILY_SECP_K1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
         case MBEDTLS_ECP_DP_SECP224K1:
             *bits = 224;
             return PSA_ECC_FAMILY_SECP_K1;
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
         case MBEDTLS_ECP_DP_SECP256K1:
             *bits = 256;
             return PSA_ECC_FAMILY_SECP_K1;
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
         case MBEDTLS_ECP_DP_CURVE448:
             *bits = 448;
             return PSA_ECC_FAMILY_MONTGOMERY;
+#endif
         default:
             *bits = 0;
             return 0;
@@ -2356,7 +2421,7 @@
         goto exit;
     }
 
-    if (mbedtls_psa_safer_memcmp(hash, actual_hash, actual_hash_length) != 0) {
+    if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
         status = PSA_ERROR_INVALID_SIGNATURE;
     }
 
@@ -2405,7 +2470,7 @@
         status = PSA_ERROR_INVALID_SIGNATURE;
         goto exit;
     }
-    if (mbedtls_psa_safer_memcmp(hash, actual_hash, actual_hash_length) != 0) {
+    if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
         status = PSA_ERROR_INVALID_SIGNATURE;
     }
 
@@ -2787,7 +2852,7 @@
         status = PSA_ERROR_INVALID_SIGNATURE;
         goto exit;
     }
-    if (mbedtls_psa_safer_memcmp(mac, actual_mac, actual_mac_length) != 0) {
+    if (mbedtls_ct_memcmp(mac, actual_mac, actual_mac_length) != 0) {
         status = PSA_ERROR_INVALID_SIGNATURE;
         goto exit;
     }
diff --git a/library/psa_crypto_core.h b/library/psa_crypto_core.h
index 8bc1b64..2b4afd7 100644
--- a/library/psa_crypto_core.h
+++ b/library/psa_crypto_core.h
@@ -38,27 +38,6 @@
  */
 int psa_can_do_hash(psa_algorithm_t hash_alg);
 
-/** Constant-time buffer comparison
- *
- * \param[in]  a    Left-hand buffer for comparison.
- * \param[in]  b    Right-hand buffer for comparison.
- * \param n         Amount of bytes to compare.
- *
- * \return 0 if the buffer contents are equal, non-zero otherwise
- */
-static inline int mbedtls_psa_safer_memcmp(
-    const uint8_t *a, const uint8_t *b, size_t n)
-{
-    size_t i;
-    unsigned char diff = 0;
-
-    for (i = 0; i < n; i++) {
-        diff |= a[i] ^ b[i];
-    }
-
-    return diff;
-}
-
 /** The data structure representing a key slot, containing key material
  * and metadata for one key.
  */
diff --git a/library/psa_crypto_mac.c b/library/psa_crypto_mac.c
index 07f123e..2f2c51d 100644
--- a/library/psa_crypto_mac.c
+++ b/library/psa_crypto_mac.c
@@ -29,6 +29,7 @@
 #include <mbedtls/md.h>
 
 #include <mbedtls/error.h>
+#include "mbedtls/constant_time.h"
 #include <string.h>
 
 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
@@ -453,7 +454,7 @@
         goto cleanup;
     }
 
-    if (mbedtls_psa_safer_memcmp(mac, actual_mac, mac_length) != 0) {
+    if (mbedtls_ct_memcmp(mac, actual_mac, mac_length) != 0) {
         status = PSA_ERROR_INVALID_SIGNATURE;
     }
 
diff --git a/library/psa_crypto_slot_management.c b/library/psa_crypto_slot_management.c
index a10cb2b..ef285ac 100644
--- a/library/psa_crypto_slot_management.c
+++ b/library/psa_crypto_slot_management.c
@@ -38,7 +38,7 @@
 
 typedef struct {
     psa_key_slot_t key_slots[MBEDTLS_PSA_KEY_SLOT_COUNT];
-    unsigned key_slots_initialized : 1;
+    uint8_t key_slots_initialized;
 } psa_global_data_t;
 
 static psa_global_data_t global_data;
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 6ed8a86..7a1f855 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -7722,7 +7722,7 @@
 
     MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
 
-    mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
+    mbedtls_platform_zeroize(padbuf, hlen);
 
     MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc finished"));
 
diff --git a/library/x509.c b/library/x509.c
index ba8d719..ee7a2b2 100644
--- a/library/x509.c
+++ b/library/x509.c
@@ -1097,6 +1097,7 @@
     if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME, &cur_oid) != 0) {
         return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
     }
+    other_name->type_id = cur_oid;
 
     p += len;
     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
@@ -1488,7 +1489,7 @@
                 MBEDTLS_X509_SAFE_SNPRINTF;
 
                 if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME,
-                                    &other_name->value.hardware_module_name.oid) != 0) {
+                                    &other_name->type_id) == 0) {
                     ret = mbedtls_snprintf(p, n, "\n%s        hardware module name :", prefix);
                     MBEDTLS_X509_SAFE_SNPRINTF;
                     ret =
diff --git a/scripts/data_files/driver_templates/psa_crypto_driver_wrappers.c.jinja b/scripts/data_files/driver_templates/psa_crypto_driver_wrappers.c.jinja
index 3ecd74d..1b52066 100644
--- a/scripts/data_files/driver_templates/psa_crypto_driver_wrappers.c.jinja
+++ b/scripts/data_files/driver_templates/psa_crypto_driver_wrappers.c.jinja
@@ -32,6 +32,7 @@
 #include "psa_crypto_rsa.h"
 
 #include "mbedtls/platform.h"
+#include "mbedtls/constant_time.h"
 /* END-common headers */
 
 #if defined(MBEDTLS_PSA_CRYPTO_C)
@@ -2253,7 +2254,7 @@
                 if( status == PSA_SUCCESS )
                 {
                     if( tag_length != check_tag_length ||
-                        mbedtls_psa_safer_memcmp( tag, check_tag, tag_length )
+                        mbedtls_ct_memcmp( tag, check_tag, tag_length )
                         != 0 )
                         status = PSA_ERROR_INVALID_SIGNATURE;
                 }
diff --git a/scripts/mbedtls_dev/build_tree.py b/scripts/mbedtls_dev/build_tree.py
index f52b785..b48a277 100644
--- a/scripts/mbedtls_dev/build_tree.py
+++ b/scripts/mbedtls_dev/build_tree.py
@@ -19,12 +19,19 @@
 import os
 import inspect
 
+def looks_like_psa_crypto_root(path: str) -> bool:
+    """Whether the given directory looks like the root of the PSA Crypto source tree."""
+    return all(os.path.isdir(os.path.join(path, subdir))
+               for subdir in ['include', 'core', 'drivers', 'programs', 'tests'])
 
 def looks_like_mbedtls_root(path: str) -> bool:
     """Whether the given directory looks like the root of the Mbed TLS source tree."""
     return all(os.path.isdir(os.path.join(path, subdir))
                for subdir in ['include', 'library', 'programs', 'tests'])
 
+def looks_like_root(path: str) -> bool:
+    return looks_like_psa_crypto_root(path) or looks_like_mbedtls_root(path)
+
 def check_repo_path():
     """
     Check that the current working directory is the project root, and throw
@@ -42,7 +49,7 @@
     for d in [os.path.curdir,
               os.path.pardir,
               os.path.join(os.path.pardir, os.path.pardir)]:
-        if looks_like_mbedtls_root(d):
+        if looks_like_root(d):
             os.chdir(d)
             return
     raise Exception('Mbed TLS source tree not found')
@@ -62,6 +69,6 @@
             if d in dirs:
                 continue
             dirs.add(d)
-            if looks_like_mbedtls_root(d):
+            if looks_like_root(d):
                 return d
     raise Exception('Mbed TLS source tree not found')
diff --git a/scripts/mbedtls_dev/psa_storage.py b/scripts/mbedtls_dev/psa_storage.py
index bae9938..a2e4c74 100644
--- a/scripts/mbedtls_dev/psa_storage.py
+++ b/scripts/mbedtls_dev/psa_storage.py
@@ -27,6 +27,7 @@
 import unittest
 
 from . import c_build_helper
+from . import build_tree
 
 
 class Expr:
@@ -51,13 +52,16 @@
     def update_cache(self) -> None:
         """Update `value_cache` for expressions registered in `unknown_values`."""
         expressions = sorted(self.unknown_values)
+        includes = ['include']
+        if build_tree.looks_like_psa_crypto_root('.'):
+            includes.append('drivers/builtin/include')
         values = c_build_helper.get_c_expression_values(
             'unsigned long', '%lu',
             expressions,
             header="""
             #include <psa/crypto.h>
             """,
-            include_path=['include']) #type: List[str]
+            include_path=includes) #type: List[str]
         for e, v in zip(expressions, values):
             self.value_cache[e] = int(v, 0)
         self.unknown_values.clear()
diff --git a/tests/configs/user-config-zeroize-memset.h b/tests/configs/user-config-zeroize-memset.h
new file mode 100644
index 0000000..fcdd1f0
--- /dev/null
+++ b/tests/configs/user-config-zeroize-memset.h
@@ -0,0 +1,29 @@
+/* mbedtls_config.h modifier that defines mbedtls_platform_zeroize() to be
+ * memset(), so that the compile can check arguments for us.
+ * Used for testing.
+ */
+/*
+ *  Copyright The Mbed TLS Contributors
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include <string.h>
+
+/* Define _ALT so we don't get the built-in implementation. The test code will
+ * also need to define MBEDTLS_TEST_DEFINES_ZEROIZE so we don't get the
+ * declaration. */
+#define MBEDTLS_PLATFORM_ZEROIZE_ALT
+
+#define mbedtls_platform_zeroize(buf, len) memset(buf, 0, len)
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index c3c1275..ffac222 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -123,15 +123,27 @@
 # Enable ksh/bash extended file matching patterns
 shopt -s extglob
 
+in_mbedtls_repo () {
+    test -d include -a -d library -a -d programs -a -d tests
+}
+
+in_psa_crypto_repo () {
+    test -d include -a -d core -a -d drivers -a -d programs -a -d tests
+}
+
 pre_check_environment () {
-    if [ -d library -a -d include -a -d tests ]; then :; else
-        echo "Must be run from mbed TLS root" >&2
+    if in_mbedtls_repo || in_psa_crypto_repo; then :; else
+        echo "Must be run from Mbed TLS / psa-crypto root" >&2
         exit 1
     fi
 }
 
 pre_initialize_variables () {
-    CONFIG_H='include/mbedtls/mbedtls_config.h'
+    if in_mbedtls_repo; then
+        CONFIG_H='include/mbedtls/mbedtls_config.h'
+    else
+        CONFIG_H='drivers/builtin/include/mbedtls/mbedtls_config.h'
+    fi
     CRYPTO_CONFIG_H='include/psa/crypto_config.h'
     CONFIG_TEST_DRIVER_H='tests/include/test/drivers/config_test_driver.h'
 
@@ -141,8 +153,10 @@
     backup_suffix='.all.bak'
     # Files clobbered by config.py
     files_to_back_up="$CONFIG_H $CRYPTO_CONFIG_H $CONFIG_TEST_DRIVER_H"
-    # Files clobbered by in-tree cmake
-    files_to_back_up="$files_to_back_up Makefile library/Makefile programs/Makefile tests/Makefile programs/fuzz/Makefile"
+    if in_mbedtls_repo; then
+        # Files clobbered by in-tree cmake
+        files_to_back_up="$files_to_back_up Makefile library/Makefile programs/Makefile tests/Makefile programs/fuzz/Makefile"
+    fi
 
     append_outcome=0
     MEMORY=0
@@ -299,7 +313,9 @@
 # Does not remove generated source files.
 cleanup()
 {
-    command make clean
+    if in_mbedtls_repo; then
+        command make clean
+    fi
 
     # Remove CMake artefacts
     find . -name .git -prune -o \
@@ -556,7 +572,7 @@
         fi
 
         if ! git diff --quiet "$CONFIG_H"; then
-            err_msg "Warning - the configuration file 'include/mbedtls/mbedtls_config.h' has been edited. "
+            err_msg "Warning - the configuration file '$CONFIG_H' has been edited. "
             echo "You can either delete or preserve your work, or force the test by rerunning the"
             echo "script as: $0 --force"
             exit 1
@@ -5101,6 +5117,16 @@
 }
 
 
+component_build_zeroize_checks () {
+    msg "build: check for obviously wrong calls to mbedtls_platform_zeroize()"
+
+    scripts/config.py full
+
+    # Only compile - we're looking for sizeof-pointer-memaccess warnings
+    make CC=gcc CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/user-config-zeroize-memset.h\"' -DMBEDTLS_TEST_DEFINES_ZEROIZE -Werror -Wsizeof-pointer-memaccess"
+}
+
+
 component_test_zeroize () {
     # Test that the function mbedtls_platform_zeroize() is not optimized away by
     # different combinations of compilers and optimization flags by using an
@@ -5284,7 +5310,9 @@
 pre_print_configuration
 pre_check_tools
 cleanup
-pre_generate_files
+if in_mbedtls_repo; then
+    pre_generate_files
+fi
 
 # Run the requested tests.
 for ((error_test_i=1; error_test_i <= error_test; error_test_i++)); do
diff --git a/tests/scripts/test_psa_compliance.py b/tests/scripts/test_psa_compliance.py
index 92db417..3590436 100755
--- a/tests/scripts/test_psa_compliance.py
+++ b/tests/scripts/test_psa_compliance.py
@@ -1,10 +1,10 @@
 #!/usr/bin/env python3
 """Run the PSA Crypto API compliance test suite.
 Clone the repo and check out the commit specified by PSA_ARCH_TEST_REPO and PSA_ARCH_TEST_REF,
-then compile and run the test suite. The clone is stored at <Mbed TLS root>/psa-arch-tests.
-Known defects in either the test suite or mbedtls - identified by their test number - are ignored,
-while unexpected failures AND successes are reported as errors,
-to help keep the list of known defects as up to date as possible.
+then compile and run the test suite. The clone is stored at <repository root>/psa-arch-tests.
+Known defects in either the test suite or mbedtls / psa-crypto - identified by their test
+number - are ignored, while unexpected failures AND successes are reported as errors, to help
+keep the list of known defects as up to date as possible.
 """
 
 # Copyright The Mbed TLS Contributors
@@ -22,13 +22,20 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import argparse
 import os
 import re
 import shutil
 import subprocess
 import sys
+from typing import List
 
-# PSA Compliance tests we expect to fail due to known defects in Mbed TLS (or the test suite)
+#pylint: disable=unused-import
+import scripts_path
+from mbedtls_dev import build_tree
+
+# PSA Compliance tests we expect to fail due to known defects in Mbed TLS / PSA Crypto
+# (or the test suite).
 # The test numbers correspond to the numbers used by the console output of the test suite.
 # Test number 2xx corresponds to the files in the folder
 # psa-arch-tests/api-tests/dev_apis/crypto/test_c0xx
@@ -49,12 +56,32 @@
 PSA_ARCH_TESTS_REPO = 'https://github.com/bensze01/psa-arch-tests.git'
 PSA_ARCH_TESTS_REF = 'fix-pr-5736'
 
-#pylint: disable=too-many-branches,too-many-statements
-def main():
-    mbedtls_dir = os.getcwd()
+#pylint: disable=too-many-branches,too-many-statements,too-many-locals
+def main(library_build_dir: str):
+    root_dir = os.getcwd()
 
-    if not os.path.exists('library/libmbedcrypto.a'):
-        subprocess.check_call(['make', '-C', 'library', 'libmbedcrypto.a'])
+    in_psa_crypto_repo = build_tree.looks_like_psa_crypto_root(root_dir)
+
+    if in_psa_crypto_repo:
+        crypto_name = 'psacrypto'
+        library_subdir = 'core'
+    else:
+        crypto_name = 'mbedcrypto'
+        library_subdir = 'library'
+
+    crypto_lib_filename = (library_build_dir + '/' +
+                           library_subdir + '/' +
+                           'lib' + crypto_name + '.a')
+
+    if not os.path.exists(crypto_lib_filename):
+        #pylint: disable=bad-continuation
+        subprocess.check_call([
+            'cmake', '.',
+                     '-GUnix Makefiles',
+                     '-B' + library_build_dir
+        ])
+        subprocess.check_call(['cmake', '--build', library_build_dir,
+                               '--target', crypto_name])
 
     psa_arch_tests_dir = 'psa-arch-tests'
     os.makedirs(psa_arch_tests_dir, exist_ok=True)
@@ -74,6 +101,9 @@
         os.mkdir(build_dir)
         os.chdir(build_dir)
 
+        extra_includes = (';{}/drivers/builtin/include'.format(root_dir)
+                          if in_psa_crypto_repo else '')
+
         #pylint: disable=bad-continuation
         subprocess.check_call([
             'cmake', '..',
@@ -81,8 +111,9 @@
                      '-DTARGET=tgt_dev_apis_stdc',
                      '-DTOOLCHAIN=HOST_GCC',
                      '-DSUITE=CRYPTO',
-                     '-DPSA_CRYPTO_LIB_FILENAME={}/library/libmbedcrypto.a'.format(mbedtls_dir),
-                     '-DPSA_INCLUDE_PATHS={}/include'.format(mbedtls_dir)
+                     '-DPSA_CRYPTO_LIB_FILENAME={}/{}'.format(root_dir,
+                                                              crypto_lib_filename),
+                     ('-DPSA_INCLUDE_PATHS={}/include' + extra_includes).format(root_dir)
         ])
         subprocess.check_call(['cmake', '--build', '.'])
 
@@ -95,8 +126,11 @@
         )
         test = -1
         unexpected_successes = set(EXPECTED_FAILURES)
-        expected_failures = []
-        unexpected_failures = []
+        expected_failures = [] # type: List[int]
+        unexpected_failures = [] # type: List[int]
+        if proc.stdout is None:
+            return 1
+
         for line in proc.stdout:
             print(line, end='')
             match = test_re.match(line)
@@ -136,7 +170,18 @@
             print('SUCCESS')
             return 0
     finally:
-        os.chdir(mbedtls_dir)
+        os.chdir(root_dir)
 
 if __name__ == '__main__':
-    sys.exit(main())
+    BUILD_DIR = 'out_of_source_build'
+
+    # pylint: disable=invalid-name
+    parser = argparse.ArgumentParser()
+    parser.add_argument('--build-dir', nargs=1,
+                        help='path to Mbed TLS / PSA Crypto build directory')
+    args = parser.parse_args()
+
+    if args.build_dir is not None:
+        BUILD_DIR = args.build_dir[0]
+
+    sys.exit(main(BUILD_DIR))
diff --git a/tests/src/drivers/test_driver_aead.c b/tests/src/drivers/test_driver_aead.c
index 8eb5547..6dadf52 100644
--- a/tests/src/drivers/test_driver_aead.c
+++ b/tests/src/drivers/test_driver_aead.c
@@ -25,6 +25,8 @@
 
 #include "test/drivers/aead.h"
 
+#include "mbedtls/constant_time.h"
+
 #if defined(MBEDTLS_TEST_LIBTESTDRIVER1)
 #include "libtestdriver1/library/psa_crypto_aead.h"
 #endif
@@ -431,7 +433,7 @@
 
         if (mbedtls_test_driver_aead_hooks.driver_status == PSA_SUCCESS) {
             if (tag_length != check_tag_length ||
-                mbedtls_psa_safer_memcmp(tag, check_tag, tag_length)
+                mbedtls_ct_memcmp(tag, check_tag, tag_length)
                 != 0) {
                 mbedtls_test_driver_aead_hooks.driver_status =
                     PSA_ERROR_INVALID_SIGNATURE;
diff --git a/tests/suites/test_suite_ecp.function b/tests/suites/test_suite_ecp.function
index c4408df..619a5dd 100644
--- a/tests/suites/test_suite_ecp.function
+++ b/tests/suites/test_suite_ecp.function
@@ -1324,8 +1324,8 @@
 #endif
 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && defined(MBEDTLS_ECP_NIST_OPTIM)
         case MBEDTLS_ECP_DP_SECP521R1:
-            limbs = BITS_TO_LIMBS(522) * 2;
-            curve_bits = 522;
+            limbs = BITS_TO_LIMBS(521) * 2;
+            curve_bits = 521;
             curve_func = &mbedtls_ecp_mod_p521_raw;
             break;
 #endif
@@ -1377,8 +1377,8 @@
 
     TEST_EQUAL((*curve_func)(X, limbs_X), 0);
 
-    TEST_LE_U(mbedtls_mpi_core_bitlen(X, limbs_X), curve_bits);
     mbedtls_mpi_mod_raw_fix_quasi_reduction(X, &m);
+    TEST_LE_U(mbedtls_mpi_core_bitlen(X, limbs_X), curve_bits);
     TEST_MEMORY_COMPARE(X, bytes, res, bytes);
 
 exit:
diff --git a/tests/suites/test_suite_pkwrite.function b/tests/suites/test_suite_pkwrite.function
index 37c06c8..730bb88 100644
--- a/tests/suites/test_suite_pkwrite.function
+++ b/tests/suites/test_suite_pkwrite.function
@@ -194,7 +194,7 @@
                         pub_key_raw, pub_key_len);
 
 #if defined(MBEDTLS_USE_PSA_CRYPTO)
-    mbedtls_platform_zeroize(derived_key_raw, sizeof(derived_key_raw));
+    mbedtls_platform_zeroize(derived_key_raw, derived_key_len);
 
     TEST_EQUAL(mbedtls_pk_wrap_as_opaque(&priv_key, &opaque_key_id,
                                          PSA_ALG_NONE, PSA_KEY_USAGE_EXPORT,
diff --git a/tests/suites/test_suite_x509parse.function b/tests/suites/test_suite_x509parse.function
index 1b08bc3..e6bce1d 100644
--- a/tests/suites/test_suite_x509parse.function
+++ b/tests/suites/test_suite_x509parse.function
@@ -242,7 +242,7 @@
             MBEDTLS_X509_SAFE_SNPRINTF;
 
             if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME,
-                                &san->san.other_name.value.hardware_module_name.oid) != 0) {
+                                &san->san.other_name.type_id) == 0) {
                 ret = mbedtls_snprintf(p, n, " hardware module name :");
                 MBEDTLS_X509_SAFE_SNPRINTF;
                 ret = mbedtls_snprintf(p, n, " hardware type : ");