1 /**
2  * \file psa_crypto_storage.h
3  *
4  * \brief PSA cryptography module: Mbed TLS key storage
5  */
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9  */
10 
11 #ifndef PSA_CRYPTO_STORAGE_H
12 #define PSA_CRYPTO_STORAGE_H
13 
14 #ifdef __cplusplus
15 extern "C" {
16 #endif
17 
18 #include "psa/crypto.h"
19 #include "psa/crypto_se_driver.h"
20 
21 #include <stdint.h>
22 #include <string.h>
23 
24 /* Limit the maximum key size in storage. This should have no effect
25  * since the key size is limited in memory. */
26 #define PSA_CRYPTO_MAX_STORAGE_SIZE (PSA_BITS_TO_BYTES(PSA_MAX_KEY_BITS))
27 /* Sanity check: a file size must fit in 32 bits. Allow a generous
28  * 64kB of metadata. */
29 #if PSA_CRYPTO_MAX_STORAGE_SIZE > 0xffff0000
30 #error "PSA_CRYPTO_MAX_STORAGE_SIZE > 0xffff0000"
31 #endif
32 
33 /** The maximum permitted persistent slot number.
34  *
35  * In Mbed Crypto 0.1.0b:
36  * - Using the file backend, all key ids are ok except 0.
37  * - Using the ITS backend, all key ids are ok except 0xFFFFFF52
38  *   (#PSA_CRYPTO_ITS_RANDOM_SEED_UID) for which the file contains the
39  *   device's random seed (if this feature is enabled).
40  * - Only key ids from 1 to #MBEDTLS_PSA_KEY_SLOT_COUNT are actually used.
41  *
42  * Since we need to preserve the random seed, avoid using that key slot.
43  * Reserve a whole range of key slots just in case something else comes up.
44  *
45  * This limitation will probably become moot when we implement client
46  * separation for key storage.
47  */
48 #define PSA_MAX_PERSISTENT_KEY_IDENTIFIER PSA_KEY_ID_VENDOR_MAX
49 
50 /**
51  * \brief Checks if persistent data is stored for the given key slot number
52  *
53  * This function checks if any key data or metadata exists for the key slot in
54  * the persistent storage.
55  *
56  * \param key           Persistent identifier to check.
57  *
58  * \retval 0
59  *         No persistent data present for slot number
60  * \retval 1
61  *         Persistent data present for slot number
62  */
63 int psa_is_key_present_in_storage(const mbedtls_svc_key_id_t key);
64 
65 /**
66  * \brief Format key data and metadata and save to a location for given key
67  *        slot.
68  *
69  * This function formats the key data and metadata and saves it to a
70  * persistent storage backend. The storage location corresponding to the
71  * key slot must be empty, otherwise this function will fail. This function
72  * should be called after loading the key into an internal slot to ensure the
73  * persistent key is not saved into a storage location corresponding to an
74  * already occupied non-persistent key, as well as ensuring the key data is
75  * validated.
76  *
77  * Note: This function will only succeed for key buffers which are not
78  * empty. If passed a NULL pointer or zero-length, the function will fail
79  * with #PSA_ERROR_INVALID_ARGUMENT.
80  *
81  * \param[in] attr          The attributes of the key to save.
82  *                          The key identifier field in the attributes
83  *                          determines the key's location.
84  * \param[in] data          Buffer containing the key data.
85  * \param data_length       The number of bytes that make up the key data.
86  *
87  * \retval #PSA_SUCCESS \emptydescription
88  * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
89  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
90  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
91  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
92  * \retval #PSA_ERROR_ALREADY_EXISTS \emptydescription
93  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
94  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
95  */
96 psa_status_t psa_save_persistent_key(const psa_core_key_attributes_t *attr,
97                                      const uint8_t *data,
98                                      const size_t data_length);
99 
100 /**
101  * \brief Parses key data and metadata and load persistent key for given
102  * key slot number.
103  *
104  * This function reads from a storage backend, parses the key data and
105  * metadata and writes them to the appropriate output parameters.
106  *
107  * Note: This function allocates a buffer and returns a pointer to it through
108  * the data parameter. On successful return, the pointer is guaranteed to be
109  * valid and the buffer contains at least one byte of data.
110  * psa_free_persistent_key_data() must be called on the data buffer
111  * afterwards to zeroize and free this buffer.
112  *
113  * \param[in,out] attr      On input, the key identifier field identifies
114  *                          the key to load. Other fields are ignored.
115  *                          On success, the attribute structure contains
116  *                          the key metadata that was loaded from storage.
117  * \param[out] data         Pointer to an allocated key data buffer on return.
118  * \param[out] data_length  The number of bytes that make up the key data.
119  *
120  * \retval #PSA_SUCCESS \emptydescription
121  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
122  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
123  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
124  * \retval #PSA_ERROR_DOES_NOT_EXIST \emptydescription
125  */
126 psa_status_t psa_load_persistent_key(psa_core_key_attributes_t *attr,
127                                      uint8_t **data,
128                                      size_t *data_length);
129 
130 /**
131  * \brief Remove persistent data for the given key slot number.
132  *
133  * \param key           Persistent identifier of the key to remove
134  *                      from persistent storage.
135  *
136  * \retval #PSA_SUCCESS
137  *         The key was successfully removed,
138  *         or the key did not exist.
139  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
140  */
141 psa_status_t psa_destroy_persistent_key(const mbedtls_svc_key_id_t key);
142 
143 /**
144  * \brief Free the temporary buffer allocated by psa_load_persistent_key().
145  *
146  * This function must be called at some point after psa_load_persistent_key()
147  * to zeroize and free the memory allocated to the buffer in that function.
148  *
149  * \param key_data        Buffer for the key data.
150  * \param key_data_length Size of the key data buffer.
151  *
152  */
153 void psa_free_persistent_key_data(uint8_t *key_data, size_t key_data_length);
154 
155 /**
156  * \brief Formats key data and metadata for persistent storage
157  *
158  * \param[in] data          Buffer containing the key data.
159  * \param data_length       Length of the key data buffer.
160  * \param[in] attr          The core attributes of the key.
161  * \param[out] storage_data Output buffer for the formatted data.
162  *
163  */
164 void psa_format_key_data_for_storage(const uint8_t *data,
165                                      const size_t data_length,
166                                      const psa_core_key_attributes_t *attr,
167                                      uint8_t *storage_data);
168 
169 /**
170  * \brief Parses persistent storage data into key data and metadata
171  *
172  * \param[in] storage_data     Buffer for the storage data.
173  * \param storage_data_length  Length of the storage data buffer
174  * \param[out] key_data        On output, pointer to a newly allocated buffer
175  *                             containing the key data. This must be freed
176  *                             using psa_free_persistent_key_data()
177  * \param[out] key_data_length Length of the key data buffer
178  * \param[out] attr            On success, the attribute structure is filled
179  *                             with the loaded key metadata.
180  *
181  * \retval #PSA_SUCCESS \emptydescription
182  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
183  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
184  */
185 psa_status_t psa_parse_key_data_from_storage(const uint8_t *storage_data,
186                                              size_t storage_data_length,
187                                              uint8_t **key_data,
188                                              size_t *key_data_length,
189                                              psa_core_key_attributes_t *attr);
190 
191 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
192 /** This symbol is defined if transaction support is required. */
193 #define PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS 1
194 #endif
195 
196 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
197 
198 /** The type of transaction that is in progress.
199  */
200 /* This is an integer type rather than an enum for two reasons: to support
201  * unknown values when loading a transaction file, and to ensure that the
202  * type has a known size.
203  */
204 typedef uint16_t psa_crypto_transaction_type_t;
205 
206 /** No transaction is in progress.
207  *
208  * This has the value 0, so zero-initialization sets a transaction's type to
209  * this value.
210  */
211 #define PSA_CRYPTO_TRANSACTION_NONE             ((psa_crypto_transaction_type_t) 0x0000)
212 
213 /** A key creation transaction.
214  *
215  * This is only used for keys in an external cryptoprocessor (secure element).
216  * Keys in RAM or in internal storage are created atomically in storage
217  * (simple file creation), so they do not need a transaction mechanism.
218  */
219 #define PSA_CRYPTO_TRANSACTION_CREATE_KEY       ((psa_crypto_transaction_type_t) 0x0001)
220 
221 /** A key destruction transaction.
222  *
223  * This is only used for keys in an external cryptoprocessor (secure element).
224  * Keys in RAM or in internal storage are destroyed atomically in storage
225  * (simple file deletion), so they do not need a transaction mechanism.
226  */
227 #define PSA_CRYPTO_TRANSACTION_DESTROY_KEY      ((psa_crypto_transaction_type_t) 0x0002)
228 
229 /** Transaction data.
230  *
231  * This type is designed to be serialized by writing the memory representation
232  * and reading it back on the same device.
233  *
234  * \note The transaction mechanism is designed for a single active transaction
235  *       at a time. The transaction object is #psa_crypto_transaction.
236  *
237  * \note If an API call starts a transaction, it must complete this transaction
238  *       before returning to the application.
239  *
240  * The lifetime of a transaction is the following (note that only one
241  * transaction may be active at a time):
242  *
243  * -# Call psa_crypto_prepare_transaction() to initialize the transaction
244  *    object in memory and declare the type of transaction that is starting.
245  * -# Fill in the type-specific fields of #psa_crypto_transaction.
246  * -# Call psa_crypto_save_transaction() to start the transaction. This
247  *    saves the transaction data to internal storage.
248  * -# Perform the work of the transaction by modifying files, contacting
249  *    external entities, or whatever needs doing. Note that the transaction
250  *    may be interrupted by a power failure, so you need to have a way
251  *    recover from interruptions either by undoing what has been done
252  *    so far or by resuming where you left off.
253  * -# If there are intermediate stages in the transaction, update
254  *    the fields of #psa_crypto_transaction and call
255  *    psa_crypto_save_transaction() again when each stage is reached.
256  * -# When the transaction is over, call psa_crypto_stop_transaction() to
257  *    remove the transaction data in storage and in memory.
258  *
259  * If the system crashes while a transaction is in progress, psa_crypto_init()
260  * calls psa_crypto_load_transaction() and takes care of completing or
261  * rewinding the transaction. This is done in psa_crypto_recover_transaction()
262  * in psa_crypto.c. If you add a new type of transaction, be
263  * sure to add code for it in psa_crypto_recover_transaction().
264  */
265 typedef union {
266     /* Each element of this union must have the following properties
267      * to facilitate serialization and deserialization:
268      *
269      * - The element is a struct.
270      * - The first field of the struct is `psa_crypto_transaction_type_t type`.
271      * - Elements of the struct are arranged such a way that there is
272      *   no padding.
273      */
274     struct psa_crypto_transaction_unknown_s {
275         psa_crypto_transaction_type_t type;
276         uint16_t unused1;
277         uint32_t unused2;
278         uint64_t unused3;
279         uint64_t unused4;
280     } unknown;
281     /* ::type is #PSA_CRYPTO_TRANSACTION_CREATE_KEY or
282      * #PSA_CRYPTO_TRANSACTION_DESTROY_KEY. */
283     struct psa_crypto_transaction_key_s {
284         psa_crypto_transaction_type_t type;
285         uint16_t unused1;
286         psa_key_lifetime_t lifetime;
287         psa_key_slot_number_t slot;
288         mbedtls_svc_key_id_t id;
289     } key;
290 } psa_crypto_transaction_t;
291 
292 /** The single active transaction.
293  */
294 extern psa_crypto_transaction_t psa_crypto_transaction;
295 
296 /** Prepare for a transaction.
297  *
298  * There must not be an ongoing transaction.
299  *
300  * \param type          The type of transaction to start.
301  */
psa_crypto_prepare_transaction(psa_crypto_transaction_type_t type)302 static inline void psa_crypto_prepare_transaction(
303     psa_crypto_transaction_type_t type)
304 {
305     psa_crypto_transaction.unknown.type = type;
306 }
307 
308 /** Save the transaction data to storage.
309  *
310  * You may call this function multiple times during a transaction to
311  * atomically update the transaction state.
312  *
313  * \retval #PSA_SUCCESS \emptydescription
314  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
315  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
316  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
317  */
318 psa_status_t psa_crypto_save_transaction(void);
319 
320 /** Load the transaction data from storage, if any.
321  *
322  * This function is meant to be called from psa_crypto_init() to recover
323  * in case a transaction was interrupted by a system crash.
324  *
325  * \retval #PSA_SUCCESS
326  *         The data about the ongoing transaction has been loaded to
327  *         #psa_crypto_transaction.
328  * \retval #PSA_ERROR_DOES_NOT_EXIST
329  *         There is no ongoing transaction.
330  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
331  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
332  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
333  */
334 psa_status_t psa_crypto_load_transaction(void);
335 
336 /** Indicate that the current transaction is finished.
337  *
338  * Call this function at the very end of transaction processing.
339  * This function does not "commit" or "abort" the transaction: the storage
340  * subsystem has no concept of "commit" and "abort", just saving and
341  * removing the transaction information in storage.
342  *
343  * This function erases the transaction data in storage (if any) and
344  * resets the transaction data in memory.
345  *
346  * \retval #PSA_SUCCESS
347  *         There was transaction data in storage.
348  * \retval #PSA_ERROR_DOES_NOT_EXIST
349  *         There was no transaction data in storage.
350  * \retval #PSA_ERROR_STORAGE_FAILURE
351  *         It was impossible to determine whether there was transaction data
352  *         in storage, or the transaction data could not be erased.
353  */
354 psa_status_t psa_crypto_stop_transaction(void);
355 
356 /** The ITS file identifier for the transaction data.
357  *
358  * 0xffffffNN = special file; 0x74 = 't' for transaction.
359  */
360 #define PSA_CRYPTO_ITS_TRANSACTION_UID ((psa_key_id_t) 0xffffff74)
361 
362 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
363 
364 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
365 /** Backend side of mbedtls_psa_inject_entropy().
366  *
367  * This function stores the supplied data into the entropy seed file.
368  *
369  * \retval #PSA_SUCCESS
370  *         Success
371  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
372  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
373  * \retval #PSA_ERROR_NOT_PERMITTED
374  *         The entropy seed file already exists.
375  */
376 psa_status_t mbedtls_psa_storage_inject_entropy(const unsigned char *seed,
377                                                 size_t seed_size);
378 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
379 
380 #ifdef __cplusplus
381 }
382 #endif
383 
384 #endif /* PSA_CRYPTO_STORAGE_H */
385