Add tests for optionally safe codepaths

The new test hooks allow to check whether there was an unsafe call of an
optionally safe function in the codepath. For the sake of simplicity the
MBEDTLS_MPI_IS_* macros are reused for signalling safe/unsafe codepaths
here too.

Signed-off-by: Janos Follath <janos.follath@arm.com>
diff --git a/library/bignum_core.c b/library/bignum_core.c
index 260a1f2..f46df0c 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -765,6 +765,9 @@
             *E_limb_index = E_bits / biL;
             *E_bit_index = E_bits % biL;
         }
+#if defined(MBEDTLS_TEST_HOOKS)
+        mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_PUBLIC;
+#endif
     } else {
         /*
          * Here we need to be constant time with respect to E and can't do anything better than
@@ -772,6 +775,12 @@
          */
         *E_limb_index = E_limbs;
         *E_bit_index = 0;
+#if defined(MBEDTLS_TEST_HOOKS)
+        // Only mark the codepath safe if there wasn't an unsafe codepath before
+        if (mbedtls_mpi_optionally_safe_codepath != MBEDTLS_MPI_IS_PUBLIC) {
+            mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_SECRET;
+        }
+#endif
     }
 }
 
@@ -788,11 +797,20 @@
 {
     if (window_public == MBEDTLS_MPI_IS_PUBLIC) {
         memcpy(Wselect, Wtable + window * AN_limbs, AN_limbs * ciL);
+#if defined(MBEDTLS_TEST_HOOKS)
+        mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_PUBLIC;
+#endif
     } else {
         /* Select Wtable[window] without leaking window through
          * memory access patterns. */
         mbedtls_mpi_core_ct_uint_table_lookup(Wselect, Wtable,
                                               AN_limbs, welem, window);
+#if defined(MBEDTLS_TEST_HOOKS)
+        // Only mark the codepath safe if there wasn't an unsafe codepath before
+        if (mbedtls_mpi_optionally_safe_codepath != MBEDTLS_MPI_IS_PUBLIC) {
+            mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_SECRET;
+        }
+#endif
     }
 }
 
diff --git a/library/bignum_core.h b/library/bignum_core.h
index 6c214a5..50c53e6 100644
--- a/library/bignum_core.h
+++ b/library/bignum_core.h
@@ -817,4 +817,14 @@
                                     mbedtls_mpi_uint mm,
                                     mbedtls_mpi_uint *T);
 
+#if defined(MBEDTLS_TEST_HOOKS)
+int mbedtls_mpi_optionally_safe_codepath;
+
+static inline void mbedtls_mpi_optionally_safe_codepath_reset()
+{
+    // Set to a default that is neither MBEDTLS_MPI_IS_PUBLIC nor MBEDTLS_MPI_IS_SECRET
+    mbedtls_mpi_optionally_safe_codepath = MBEDTLS_MPI_IS_PUBLIC + MBEDTLS_MPI_IS_SECRET + 1;
+}
+#endif
+
 #endif /* MBEDTLS_BIGNUM_CORE_H */