1 /*
2  * Helper functions for tests that use the PSA Crypto API.
3  */
4 /*
5  *  Copyright The Mbed TLS Contributors
6  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7  */
8 
9 #ifndef PSA_CRYPTO_HELPERS_H
10 #define PSA_CRYPTO_HELPERS_H
11 
12 #include "test/helpers.h"
13 
14 #if defined(MBEDTLS_PSA_CRYPTO_C)
15 #include "test/psa_helpers.h"
16 #include <psa/crypto.h>
17 #endif
18 
19 #include <mbedtls/ctr_drbg.h>
20 
21 #if defined(MBEDTLS_PSA_CRYPTO_C)
22 /** Initialize the PSA Crypto subsystem. */
23 #define PSA_INIT() PSA_ASSERT(psa_crypto_init())
24 
25 /** Shut down the PSA Crypto subsystem and destroy persistent keys.
26  * Expect a clean shutdown, with no slots in use.
27  *
28  * If some key slots are still in use, record the test case as failed,
29  * but continue executing. This macro is suitable (and primarily intended)
30  * for use in the cleanup section of test functions.
31  *
32  * \note Persistent keys must be recorded with #TEST_USES_KEY_ID before
33  *       creating them.
34  */
35 #define PSA_DONE()                                                      \
36     do                                                                  \
37     {                                                                   \
38         mbedtls_test_fail_if_psa_leaking(__LINE__, __FILE__);           \
39         mbedtls_test_psa_purge_key_storage();                           \
40         mbedtls_psa_crypto_free();                                      \
41     }                                                                   \
42     while (0)
43 #else /*MBEDTLS_PSA_CRYPTO_C */
44 #define PSA_INIT() ((void) 0)
45 #define PSA_DONE() ((void) 0)
46 #endif /* MBEDTLS_PSA_CRYPTO_C */
47 
48 #if defined(MBEDTLS_PSA_CRYPTO_C)
49 
50 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
51 
52 /* Internal function for #TEST_USES_KEY_ID. Return 1 on success, 0 on failure. */
53 int mbedtls_test_uses_key_id(mbedtls_svc_key_id_t key_id);
54 
55 /** Destroy persistent keys recorded with #TEST_USES_KEY_ID.
56  */
57 void mbedtls_test_psa_purge_key_storage(void);
58 
59 /** Purge the in-memory cache of persistent keys recorded with
60  * #TEST_USES_KEY_ID.
61  *
62  * Call this function before calling PSA_DONE() if it's ok for
63  * persistent keys to still exist at this point.
64  */
65 void mbedtls_test_psa_purge_key_cache(void);
66 
67 /** \def TEST_USES_KEY_ID
68  *
69  * Call this macro in a test function before potentially creating a
70  * persistent key. Test functions that use this mechanism must call
71  * mbedtls_test_psa_purge_key_storage() in their cleanup code.
72  *
73  * This macro records a persistent key identifier as potentially used in the
74  * current test case. Recorded key identifiers will be cleaned up at the end
75  * of the test case, even on failure.
76  *
77  * This macro has no effect on volatile keys. Therefore, it is safe to call
78  * this macro in a test function that creates either volatile or persistent
79  * keys depending on the test data.
80  *
81  * This macro currently has no effect on special identifiers
82  * used to store implementation-specific files.
83  *
84  * Calling this macro multiple times on the same key identifier in the same
85  * test case has no effect.
86  *
87  * This macro can fail the test case if there isn't enough memory to
88  * record the key id.
89  *
90  * \param key_id    The PSA key identifier to record.
91  */
92 #define TEST_USES_KEY_ID(key_id)                      \
93     TEST_ASSERT(mbedtls_test_uses_key_id(key_id))
94 
95 #else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
96 
97 #define TEST_USES_KEY_ID(key_id) ((void) (key_id))
98 #define mbedtls_test_psa_purge_key_storage() ((void) 0)
99 #define mbedtls_test_psa_purge_key_cache() ((void) 0)
100 
101 #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
102 
103 /** Check for things that have not been cleaned up properly in the
104  * PSA subsystem.
105  *
106  * \return NULL if nothing has leaked.
107  * \return A string literal explaining what has not been cleaned up
108  *         if applicable.
109  */
110 const char *mbedtls_test_helper_is_psa_leaking(void);
111 
112 /** Check that no PSA Crypto key slots are in use.
113  *
114  * If any slots are in use, mark the current test as failed and jump to
115  * the exit label. This is equivalent to
116  * `TEST_ASSERT( ! mbedtls_test_helper_is_psa_leaking( ) )`
117  * but with a more informative message.
118  */
119 #define ASSERT_PSA_PRISTINE()                                           \
120     do                                                                  \
121     {                                                                   \
122         if (mbedtls_test_fail_if_psa_leaking(__LINE__, __FILE__))       \
123         goto exit;                                                      \
124     }                                                                   \
125     while (0)
126 
127 /** Shut down the PSA Crypto subsystem, allowing persistent keys to survive.
128  * Expect a clean shutdown, with no slots in use.
129  *
130  * If some key slots are still in use, record the test case as failed and
131  * jump to the `exit` label.
132  */
133 #define PSA_SESSION_DONE()                                             \
134     do                                                                  \
135     {                                                                   \
136         mbedtls_test_psa_purge_key_cache();                            \
137         ASSERT_PSA_PRISTINE();                                         \
138         mbedtls_psa_crypto_free();                                     \
139     }                                                                   \
140     while (0)
141 
142 
143 
144 #if defined(RECORD_PSA_STATUS_COVERAGE_LOG)
145 psa_status_t mbedtls_test_record_status(psa_status_t status,
146                                         const char *func,
147                                         const char *file, int line,
148                                         const char *expr);
149 
150 /** Return value logging wrapper macro.
151  *
152  * Evaluate \p expr. Write a line recording its value to the log file
153  * #STATUS_LOG_FILE_NAME and return the value. The line is a colon-separated
154  * list of fields:
155  * ```
156  * value of expr:string:__FILE__:__LINE__:expr
157  * ```
158  *
159  * The test code does not call this macro explicitly because that would
160  * be very invasive. Instead, we instrument the source code by defining
161  * a bunch of wrapper macros like
162  * ```
163  * #define psa_crypto_init() RECORD_STATUS("psa_crypto_init", psa_crypto_init())
164  * ```
165  * These macro definitions must be present in `instrument_record_status.h`
166  * when building the test suites.
167  *
168  * \param string    A string, normally a function name.
169  * \param expr      An expression to evaluate, normally a call of the function
170  *                  whose name is in \p string. This expression must return
171  *                  a value of type #psa_status_t.
172  * \return          The value of \p expr.
173  */
174 #define RECORD_STATUS(string, expr)                                   \
175     mbedtls_test_record_status((expr), string, __FILE__, __LINE__, #expr)
176 
177 #include "instrument_record_status.h"
178 
179 #endif /* defined(RECORD_PSA_STATUS_COVERAGE_LOG) */
180 
181 /** Return extended key usage policies.
182  *
183  * Do a key policy permission extension on key usage policies always involves
184  * permissions of other usage policies
185  * (like PSA_KEY_USAGE_SIGN_HASH involves PSA_KEY_USAGE_SIGN_MESSAGE).
186  */
187 psa_key_usage_t mbedtls_test_update_key_usage_flags(psa_key_usage_t usage_flags);
188 
189 /** Check that no PSA Crypto key slots are in use.
190  *
191  * If any slots are in use, mark the current test as failed.
192  *
193  * \return 0 if the key store is empty, 1 otherwise.
194  */
195 int mbedtls_test_fail_if_psa_leaking(int line_no, const char *filename);
196 
197 
198 
199 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
200 /* The #MBEDTLS_PSA_INJECT_ENTROPY feature requires two extra platform
201  * functions, which must be configured as #MBEDTLS_PLATFORM_NV_SEED_READ_MACRO
202  * and #MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO. The job of these functions
203  * is to read and write from the entropy seed file, which is located
204  * in the PSA ITS file whose uid is #PSA_CRYPTO_ITS_RANDOM_SEED_UID.
205  * (These could have been provided as library functions, but for historical
206  * reasons, they weren't, and so each integrator has to provide a copy
207  * of these functions.)
208  *
209  * Provide implementations of these functions for testing. */
210 int mbedtls_test_inject_entropy_seed_read(unsigned char *buf, size_t len);
211 int mbedtls_test_inject_entropy_seed_write(unsigned char *buf, size_t len);
212 
213 
214 /** Make sure that the injected entropy is present.
215  *
216  * When MBEDTLS_PSA_INJECT_ENTROPY is enabled, psa_crypto_init()
217  * will fail if the PSA entropy seed is not present.
218  * This function must be called at least once in a test suite or other
219  * program before any call to psa_crypto_init().
220  * It does not need to be called in each test case.
221  *
222  * The test framework calls this function before running any test case.
223  *
224  * The few tests that might remove the entropy file must call this function
225  * in their cleanup.
226  */
227 int mbedtls_test_inject_entropy_restore(void);
228 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
229 
230 /** Parse binary string and convert it to a long integer
231  */
232 uint64_t mbedtls_test_parse_binary_string(data_t *bin_string);
233 
234 /** Skip a test case if the given key is a 192 bits AES key and the AES
235  *  implementation is at least partially provided by an accelerator or
236  *  alternative implementation.
237  *
238  *  Call this macro in a test case when a cryptographic operation that may
239  *  involve an AES operation returns a #PSA_ERROR_NOT_SUPPORTED error code.
240  *  The macro call will skip and not fail the test case in case the operation
241  *  involves a 192 bits AES key and the AES implementation is at least
242  *  partially provided by an accelerator or alternative implementation.
243  *
244  *  Hardware AES implementations not supporting 192 bits keys commonly exist.
245  *  Consequently, PSA test cases aim at not failing when an AES operation with
246  *  a 192 bits key performed by an alternative AES implementation returns
247  *  with the #PSA_ERROR_NOT_SUPPORTED error code. The purpose of this macro
248  *  is to facilitate this and make the test case code more readable.
249  *
250  *  \param key_type  Key type
251  *  \param key_bits  Key length in number of bits.
252  */
253 #if defined(MBEDTLS_AES_ALT) || \
254     defined(MBEDTLS_AES_SETKEY_ENC_ALT) || \
255     defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_AES)
256 #define MBEDTLS_TEST_HAVE_ALT_AES 1
257 #else
258 #define MBEDTLS_TEST_HAVE_ALT_AES 0
259 #endif
260 
261 #define MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_bits)        \
262     do                                                                    \
263     {                                                                     \
264         if ((MBEDTLS_TEST_HAVE_ALT_AES) &&                              \
265             ((key_type) == PSA_KEY_TYPE_AES) &&                       \
266             (key_bits == 192))                                         \
267         {                                                                 \
268             mbedtls_test_skip("AES-192 not supported", __LINE__, __FILE__);     \
269             goto exit;                                                    \
270         }                                                                 \
271     }                                                                     \
272     while (0)
273 
274 /** Skip a test case if a GCM operation with a nonce length different from
275  *  12 bytes fails and was performed by an accelerator or alternative
276  *  implementation.
277  *
278  *  Call this macro in a test case when an AEAD cryptography operation that
279  *  may involve the GCM mode returns with a #PSA_ERROR_NOT_SUPPORTED error
280  *  code. The macro call will skip and not fail the test case in case the
281  *  operation involves the GCM mode, a nonce with a length different from
282  *  12 bytes and the GCM mode implementation is an alternative one.
283  *
284  *  Hardware GCM implementations not supporting nonce lengths different from
285  *  12 bytes commonly exist, as supporting a non-12-byte nonce requires
286  *  additional computations involving the GHASH function.
287  *  Consequently, PSA test cases aim at not failing when an AEAD operation in
288  *  GCM mode with a nonce length different from 12 bytes is performed by an
289  *  alternative GCM implementation and returns with a #PSA_ERROR_NOT_SUPPORTED
290  *  error code. The purpose of this macro is to facilitate this check and make
291  *  the test case code more readable.
292  *
293  *  \param  alg             The AEAD algorithm.
294  *  \param  nonce_length    The nonce length in number of bytes.
295  */
296 #if defined(MBEDTLS_GCM_ALT) || \
297     defined(MBEDTLS_PSA_ACCEL_ALG_GCM)
298 #define MBEDTLS_TEST_HAVE_ALT_GCM  1
299 #else
300 #define MBEDTLS_TEST_HAVE_ALT_GCM  0
301 #endif
302 
303 #define MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg,           \
304                                                            nonce_length) \
305     do                                                                     \
306     {                                                                      \
307         if ((MBEDTLS_TEST_HAVE_ALT_GCM) &&                               \
308             (PSA_ALG_AEAD_WITH_SHORTENED_TAG((alg), 0) ==            \
309              PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0)) &&       \
310             ((nonce_length) != 12))                                   \
311         {                                                                  \
312             mbedtls_test_skip("GCM with non-12-byte IV is not supported", __LINE__, __FILE__); \
313             goto exit;                                                     \
314         }                                                                  \
315     }                                                                      \
316     while (0)
317 
318 #endif /* MBEDTLS_PSA_CRYPTO_C */
319 
320 /** \def USE_PSA_INIT
321  *
322  * Call this macro to initialize the PSA subsystem if #MBEDTLS_USE_PSA_CRYPTO
323  * or #MBEDTLS_SSL_PROTO_TLS1_3 (In contrast to TLS 1.2 implementation, the
324  * TLS 1.3 one uses PSA independently of the definition of
325  * #MBEDTLS_USE_PSA_CRYPTO) is enabled and do nothing otherwise.
326  *
327  * If the initialization fails, mark the test case as failed and jump to the
328  * \p exit label.
329  */
330 /** \def USE_PSA_DONE
331  *
332  * Call this macro at the end of a test case if you called #USE_PSA_INIT.
333  *
334  * This is like #PSA_DONE except it does nothing under the same conditions as
335  * #USE_PSA_INIT.
336  */
337 #if defined(MBEDTLS_USE_PSA_CRYPTO)
338 #define USE_PSA_INIT() PSA_INIT()
339 #define USE_PSA_DONE() PSA_DONE()
340 #elif defined(MBEDTLS_SSL_PROTO_TLS1_3)
341 /* TLS 1.3 must work without having called psa_crypto_init(), for backward
342  * compatibility with Mbed TLS <= 3.5 when connecting with a peer that
343  * supports both TLS 1.2 and TLS 1.3. See mbedtls_ssl_tls13_crypto_init()
344  * and https://github.com/Mbed-TLS/mbedtls/issues/9072 . */
345 #define USE_PSA_INIT() ((void) 0)
346 /* TLS 1.3 may have initialized the PSA subsystem. Shut it down cleanly,
347  * otherwise Asan and Valgrind would notice a resource leak. */
348 #define USE_PSA_DONE() PSA_DONE()
349 #else /* MBEDTLS_USE_PSA_CRYPTO || MBEDTLS_SSL_PROTO_TLS1_3 */
350 /* Define empty macros so that we can use them in the preamble and teardown
351  * of every test function that uses PSA conditionally based on
352  * MBEDTLS_USE_PSA_CRYPTO. */
353 #define USE_PSA_INIT() ((void) 0)
354 #define USE_PSA_DONE() ((void) 0)
355 #endif /* !MBEDTLS_USE_PSA_CRYPTO && !MBEDTLS_SSL_PROTO_TLS1_3 */
356 
357 /** \def MD_PSA_INIT
358  *
359  * Call this macro to initialize the PSA subsystem if MD uses a driver,
360  * and do nothing otherwise.
361  *
362  * If the initialization fails, mark the test case as failed and jump to the
363  * \p exit label.
364  */
365 /** \def MD_PSA_DONE
366  *
367  * Call this macro at the end of a test case if you called #MD_PSA_INIT.
368  *
369  * This is like #PSA_DONE except it does nothing under the same conditions as
370  * #MD_PSA_INIT.
371  */
372 #if defined(MBEDTLS_MD_SOME_PSA)
373 #define MD_PSA_INIT()   PSA_INIT()
374 #define MD_PSA_DONE()   PSA_DONE()
375 #else /* MBEDTLS_MD_SOME_PSA */
376 #define MD_PSA_INIT() ((void) 0)
377 #define MD_PSA_DONE() ((void) 0)
378 #endif /* MBEDTLS_MD_SOME_PSA */
379 
380 /** \def BLOCK_CIPHER_PSA_INIT
381  *
382  * Call this macro to initialize the PSA subsystem if BLOCK_CIPHER uses a driver,
383  * and do nothing otherwise.
384  *
385  * If the initialization fails, mark the test case as failed and jump to the
386  * \p exit label.
387  */
388 /** \def BLOCK_CIPHER_PSA_DONE
389  *
390  * Call this macro at the end of a test case if you called #BLOCK_CIPHER_PSA_INIT.
391  *
392  * This is like #PSA_DONE except it does nothing under the same conditions as
393  * #BLOCK_CIPHER_PSA_INIT.
394  */
395 #if defined(MBEDTLS_BLOCK_CIPHER_SOME_PSA)
396 #define BLOCK_CIPHER_PSA_INIT()   PSA_INIT()
397 #define BLOCK_CIPHER_PSA_DONE()   PSA_DONE()
398 #else /* MBEDTLS_MD_SOME_PSA */
399 #define BLOCK_CIPHER_PSA_INIT() ((void) 0)
400 #define BLOCK_CIPHER_PSA_DONE() ((void) 0)
401 #endif /* MBEDTLS_MD_SOME_PSA */
402 
403 
404 /** \def MD_OR_USE_PSA_INIT
405  *
406  * Call this macro to initialize the PSA subsystem if MD uses a driver,
407  * or if #MBEDTLS_USE_PSA_CRYPTO or #MBEDTLS_SSL_PROTO_TLS1_3 is enabled,
408  * and do nothing otherwise.
409  *
410  * If the initialization fails, mark the test case as failed and jump to the
411  * \p exit label.
412  */
413 /** \def MD_OR_USE_PSA_DONE
414  *
415  * Call this macro at the end of a test case if you called #MD_OR_USE_PSA_INIT.
416  *
417  * This is like #PSA_DONE except it does nothing under the same conditions as
418  * #MD_OR_USE_PSA_INIT.
419  */
420 #if defined(MBEDTLS_MD_SOME_PSA)
421 #define MD_OR_USE_PSA_INIT()   PSA_INIT()
422 #define MD_OR_USE_PSA_DONE()   PSA_DONE()
423 #else
424 #define MD_OR_USE_PSA_INIT()   USE_PSA_INIT()
425 #define MD_OR_USE_PSA_DONE()   USE_PSA_DONE()
426 #endif
427 
428 /** \def AES_PSA_INIT
429  *
430  * Call this macro to initialize the PSA subsystem if AES_C is not defined,
431  * so that CTR_DRBG uses PSA implementation to get AES-ECB.
432  *
433  * If the initialization fails, mark the test case as failed and jump to the
434  * \p exit label.
435  */
436 /** \def AES_PSA_DONE
437  *
438  * Call this macro at the end of a test case if you called #AES_PSA_INIT.
439  *
440  * This is like #PSA_DONE except it does nothing under the same conditions as
441  * #AES_PSA_INIT.
442  */
443 #if defined(MBEDTLS_CTR_DRBG_USE_PSA_CRYPTO)
444 #define AES_PSA_INIT()   PSA_INIT()
445 #define AES_PSA_DONE()   PSA_DONE()
446 #else /* MBEDTLS_CTR_DRBG_USE_PSA_CRYPTO */
447 #define AES_PSA_INIT() ((void) 0)
448 #define AES_PSA_DONE() ((void) 0)
449 #endif /* MBEDTLS_CTR_DRBG_USE_PSA_CRYPTO */
450 
451 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) &&                        \
452     defined(MBEDTLS_CTR_DRBG_C) &&                                      \
453     defined(MBEDTLS_CTR_DRBG_USE_PSA_CRYPTO)
454 /* When AES_C is not defined and PSA does not have an external RNG,
455  * then CTR_DRBG uses PSA to perform AES-ECB. In this scenario 1 key
456  * slot is used internally from PSA to hold the AES key and it should
457  * not be taken into account when evaluating remaining open slots. */
458 #define MBEDTLS_TEST_PSA_INTERNAL_KEYS_FOR_DRBG 1
459 #else
460 #define MBEDTLS_TEST_PSA_INTERNAL_KEYS_FOR_DRBG 0
461 #endif
462 
463 /** The number of volatile keys that PSA crypto uses internally.
464  *
465  * We expect that many volatile keys to be in use after a successful
466  * psa_crypto_init().
467  */
468 #define MBEDTLS_TEST_PSA_INTERNAL_KEYS          \
469     MBEDTLS_TEST_PSA_INTERNAL_KEYS_FOR_DRBG
470 
471 #endif /* PSA_CRYPTO_HELPERS_H */
472