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