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