1 /**
2  * \file psa/crypto_extra.h
3  *
4  * \brief PSA cryptography module: Mbed TLS vendor extensions
5  *
6  * \note This file may not be included directly. Applications must
7  * include psa/crypto.h.
8  *
9  * This file is reserved for vendor-specific definitions.
10  */
11 /*
12  *  Copyright The Mbed TLS Contributors
13  *  SPDX-License-Identifier: Apache-2.0
14  *
15  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
16  *  not use this file except in compliance with the License.
17  *  You may obtain a copy of the License at
18  *
19  *  http://www.apache.org/licenses/LICENSE-2.0
20  *
21  *  Unless required by applicable law or agreed to in writing, software
22  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
23  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24  *  See the License for the specific language governing permissions and
25  *  limitations under the License.
26  */
27 
28 #ifndef PSA_CRYPTO_EXTRA_H
29 #define PSA_CRYPTO_EXTRA_H
30 
31 #include "mbedtls/platform_util.h"
32 
33 #include "crypto_types.h"
34 #include "crypto_compat.h"
35 
36 #ifdef __cplusplus
37 extern "C" {
38 #endif
39 
40 /* UID for secure storage seed */
41 #define PSA_CRYPTO_ITS_RANDOM_SEED_UID 0xFFFFFF52
42 
43 /* See config.h for definition */
44 #if !defined(MBEDTLS_PSA_KEY_SLOT_COUNT)
45 #define MBEDTLS_PSA_KEY_SLOT_COUNT 32
46 #endif
47 
48 /** \addtogroup attributes
49  * @{
50  */
51 
52 /** \brief Declare the enrollment algorithm for a key.
53  *
54  * An operation on a key may indifferently use the algorithm set with
55  * psa_set_key_algorithm() or with this function.
56  *
57  * \param[out] attributes       The attribute structure to write to.
58  * \param alg2                  A second algorithm that the key may be used
59  *                              for, in addition to the algorithm set with
60  *                              psa_set_key_algorithm().
61  *
62  * \warning Setting an enrollment algorithm is not recommended, because
63  *          using the same key with different algorithms can allow some
64  *          attacks based on arithmetic relations between different
65  *          computations made with the same key, or can escalate harmless
66  *          side channels into exploitable ones. Use this function only
67  *          if it is necessary to support a protocol for which it has been
68  *          verified that the usage of the key with multiple algorithms
69  *          is safe.
70  */
psa_set_key_enrollment_algorithm(psa_key_attributes_t * attributes,psa_algorithm_t alg2)71 static inline void psa_set_key_enrollment_algorithm(
72     psa_key_attributes_t *attributes,
73     psa_algorithm_t alg2)
74 {
75     attributes->core.policy.alg2 = alg2;
76 }
77 
78 /** Retrieve the enrollment algorithm policy from key attributes.
79  *
80  * \param[in] attributes        The key attribute structure to query.
81  *
82  * \return The enrollment algorithm stored in the attribute structure.
83  */
psa_get_key_enrollment_algorithm(const psa_key_attributes_t * attributes)84 static inline psa_algorithm_t psa_get_key_enrollment_algorithm(
85     const psa_key_attributes_t *attributes)
86 {
87     return( attributes->core.policy.alg2 );
88 }
89 
90 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
91 
92 /** Retrieve the slot number where a key is stored.
93  *
94  * A slot number is only defined for keys that are stored in a secure
95  * element.
96  *
97  * This information is only useful if the secure element is not entirely
98  * managed through the PSA Cryptography API. It is up to the secure
99  * element driver to decide how PSA slot numbers map to any other interface
100  * that the secure element may have.
101  *
102  * \param[in] attributes        The key attribute structure to query.
103  * \param[out] slot_number      On success, the slot number containing the key.
104  *
105  * \retval #PSA_SUCCESS
106  *         The key is located in a secure element, and \p *slot_number
107  *         indicates the slot number that contains it.
108  * \retval #PSA_ERROR_NOT_PERMITTED
109  *         The caller is not permitted to query the slot number.
110  *         Mbed Crypto currently does not return this error.
111  * \retval #PSA_ERROR_INVALID_ARGUMENT
112  *         The key is not located in a secure element.
113  */
114 psa_status_t psa_get_key_slot_number(
115     const psa_key_attributes_t *attributes,
116     psa_key_slot_number_t *slot_number );
117 
118 /** Choose the slot number where a key is stored.
119  *
120  * This function declares a slot number in the specified attribute
121  * structure.
122  *
123  * A slot number is only meaningful for keys that are stored in a secure
124  * element. It is up to the secure element driver to decide how PSA slot
125  * numbers map to any other interface that the secure element may have.
126  *
127  * \note Setting a slot number in key attributes for a key creation can
128  *       cause the following errors when creating the key:
129  *       - #PSA_ERROR_NOT_SUPPORTED if the selected secure element does
130  *         not support choosing a specific slot number.
131  *       - #PSA_ERROR_NOT_PERMITTED if the caller is not permitted to
132  *         choose slot numbers in general or to choose this specific slot.
133  *       - #PSA_ERROR_INVALID_ARGUMENT if the chosen slot number is not
134  *         valid in general or not valid for this specific key.
135  *       - #PSA_ERROR_ALREADY_EXISTS if there is already a key in the
136  *         selected slot.
137  *
138  * \param[out] attributes       The attribute structure to write to.
139  * \param slot_number           The slot number to set.
140  */
psa_set_key_slot_number(psa_key_attributes_t * attributes,psa_key_slot_number_t slot_number)141 static inline void psa_set_key_slot_number(
142     psa_key_attributes_t *attributes,
143     psa_key_slot_number_t slot_number )
144 {
145     attributes->core.flags |= MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
146     attributes->slot_number = slot_number;
147 }
148 
149 /** Remove the slot number attribute from a key attribute structure.
150  *
151  * This function undoes the action of psa_set_key_slot_number().
152  *
153  * \param[out] attributes       The attribute structure to write to.
154  */
psa_clear_key_slot_number(psa_key_attributes_t * attributes)155 static inline void psa_clear_key_slot_number(
156     psa_key_attributes_t *attributes )
157 {
158     attributes->core.flags &= ~MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
159 }
160 
161 /** Register a key that is already present in a secure element.
162  *
163  * The key must be located in a secure element designated by the
164  * lifetime field in \p attributes, in the slot set with
165  * psa_set_key_slot_number() in the attribute structure.
166  * This function makes the key available through the key identifier
167  * specified in \p attributes.
168  *
169  * \param[in] attributes        The attributes of the existing key.
170  *
171  * \retval #PSA_SUCCESS
172  *         The key was successfully registered.
173  *         Note that depending on the design of the driver, this may or may
174  *         not guarantee that a key actually exists in the designated slot
175  *         and is compatible with the specified attributes.
176  * \retval #PSA_ERROR_ALREADY_EXISTS
177  *         There is already a key with the identifier specified in
178  *         \p attributes.
179  * \retval #PSA_ERROR_NOT_SUPPORTED
180  *         The secure element driver for the specified lifetime does not
181  *         support registering a key.
182  * \retval #PSA_ERROR_INVALID_ARGUMENT
183  *         The identifier in \p attributes is invalid, namely the identifier is
184  *         not in the user range.
185  * \retval #PSA_ERROR_INVALID_ARGUMENT
186  *         \p attributes specifies a lifetime which is not located
187  *         in a secure element.
188  * \retval #PSA_ERROR_INVALID_ARGUMENT
189  *         No slot number is specified in \p attributes,
190  *         or the specified slot number is not valid.
191  * \retval #PSA_ERROR_NOT_PERMITTED
192  *         The caller is not authorized to register the specified key slot.
193  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
194  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE
195  * \retval #PSA_ERROR_COMMUNICATION_FAILURE
196  * \retval #PSA_ERROR_DATA_INVALID
197  * \retval #PSA_ERROR_DATA_CORRUPT
198  * \retval #PSA_ERROR_CORRUPTION_DETECTED
199  * \retval #PSA_ERROR_BAD_STATE
200  *         The library has not been previously initialized by psa_crypto_init().
201  *         It is implementation-dependent whether a failure to initialize
202  *         results in this error code.
203  */
204 psa_status_t mbedtls_psa_register_se_key(
205     const psa_key_attributes_t *attributes);
206 
207 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
208 
209 /**@}*/
210 
211 /**
212  * \brief Library deinitialization.
213  *
214  * This function clears all data associated with the PSA layer,
215  * including the whole key store.
216  *
217  * This is an Mbed TLS extension.
218  */
219 void mbedtls_psa_crypto_free( void );
220 
221 /** \brief Statistics about
222  * resource consumption related to the PSA keystore.
223  *
224  * \note The content of this structure is not part of the stable API and ABI
225  *       of Mbed Crypto and may change arbitrarily from version to version.
226  */
227 typedef struct mbedtls_psa_stats_s
228 {
229     /** Number of slots containing key material for a volatile key. */
230     size_t volatile_slots;
231     /** Number of slots containing key material for a key which is in
232      * internal persistent storage. */
233     size_t persistent_slots;
234     /** Number of slots containing a reference to a key in a
235      * secure element. */
236     size_t external_slots;
237     /** Number of slots which are occupied, but do not contain
238      * key material yet. */
239     size_t half_filled_slots;
240     /** Number of slots that contain cache data. */
241     size_t cache_slots;
242     /** Number of slots that are not used for anything. */
243     size_t empty_slots;
244     /** Number of slots that are locked. */
245     size_t locked_slots;
246     /** Largest key id value among open keys in internal persistent storage. */
247     psa_key_id_t max_open_internal_key_id;
248     /** Largest key id value among open keys in secure elements. */
249     psa_key_id_t max_open_external_key_id;
250 } mbedtls_psa_stats_t;
251 
252 /** \brief Get statistics about
253  * resource consumption related to the PSA keystore.
254  *
255  * \note When Mbed Crypto is built as part of a service, with isolation
256  *       between the application and the keystore, the service may or
257  *       may not expose this function.
258  */
259 void mbedtls_psa_get_stats( mbedtls_psa_stats_t *stats );
260 
261 /**
262  * \brief Inject an initial entropy seed for the random generator into
263  *        secure storage.
264  *
265  * This function injects data to be used as a seed for the random generator
266  * used by the PSA Crypto implementation. On devices that lack a trusted
267  * entropy source (preferably a hardware random number generator),
268  * the Mbed PSA Crypto implementation uses this value to seed its
269  * random generator.
270  *
271  * On devices without a trusted entropy source, this function must be
272  * called exactly once in the lifetime of the device. On devices with
273  * a trusted entropy source, calling this function is optional.
274  * In all cases, this function may only be called before calling any
275  * other function in the PSA Crypto API, including psa_crypto_init().
276  *
277  * When this function returns successfully, it populates a file in
278  * persistent storage. Once the file has been created, this function
279  * can no longer succeed.
280  *
281  * If any error occurs, this function does not change the system state.
282  * You can call this function again after correcting the reason for the
283  * error if possible.
284  *
285  * \warning This function **can** fail! Callers MUST check the return status.
286  *
287  * \warning If you use this function, you should use it as part of a
288  *          factory provisioning process. The value of the injected seed
289  *          is critical to the security of the device. It must be
290  *          *secret*, *unpredictable* and (statistically) *unique per device*.
291  *          You should be generate it randomly using a cryptographically
292  *          secure random generator seeded from trusted entropy sources.
293  *          You should transmit it securely to the device and ensure
294  *          that its value is not leaked or stored anywhere beyond the
295  *          needs of transmitting it from the point of generation to
296  *          the call of this function, and erase all copies of the value
297  *          once this function returns.
298  *
299  * This is an Mbed TLS extension.
300  *
301  * \note This function is only available on the following platforms:
302  * * If the compile-time option MBEDTLS_PSA_INJECT_ENTROPY is enabled.
303  *   Note that you must provide compatible implementations of
304  *   mbedtls_nv_seed_read and mbedtls_nv_seed_write.
305  * * In a client-server integration of PSA Cryptography, on the client side,
306  *   if the server supports this feature.
307  * \param[in] seed          Buffer containing the seed value to inject.
308  * \param[in] seed_size     Size of the \p seed buffer.
309  *                          The size of the seed in bytes must be greater
310  *                          or equal to both #MBEDTLS_ENTROPY_MIN_PLATFORM
311  *                          and #MBEDTLS_ENTROPY_BLOCK_SIZE.
312  *                          It must be less or equal to
313  *                          #MBEDTLS_ENTROPY_MAX_SEED_SIZE.
314  *
315  * \retval #PSA_SUCCESS
316  *         The seed value was injected successfully. The random generator
317  *         of the PSA Crypto implementation is now ready for use.
318  *         You may now call psa_crypto_init() and use the PSA Crypto
319  *         implementation.
320  * \retval #PSA_ERROR_INVALID_ARGUMENT
321  *         \p seed_size is out of range.
322  * \retval #PSA_ERROR_STORAGE_FAILURE
323  *         There was a failure reading or writing from storage.
324  * \retval #PSA_ERROR_NOT_PERMITTED
325  *         The library has already been initialized. It is no longer
326  *         possible to call this function.
327  */
328 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
329                                         size_t seed_size);
330 
331 /** \addtogroup crypto_types
332  * @{
333  */
334 
335 /** DSA public key.
336  *
337  * The import and export format is the
338  * representation of the public key `y = g^x mod p` as a big-endian byte
339  * string. The length of the byte string is the length of the base prime `p`
340  * in bytes.
341  */
342 #define PSA_KEY_TYPE_DSA_PUBLIC_KEY                 ((psa_key_type_t)0x4002)
343 
344 /** DSA key pair (private and public key).
345  *
346  * The import and export format is the
347  * representation of the private key `x` as a big-endian byte string. The
348  * length of the byte string is the private key size in bytes (leading zeroes
349  * are not stripped).
350  *
351  * Determinstic DSA key derivation with psa_generate_derived_key follows
352  * FIPS 186-4 §B.1.2: interpret the byte string as integer
353  * in big-endian order. Discard it if it is not in the range
354  * [0, *N* - 2] where *N* is the boundary of the private key domain
355  * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA,
356  * or the order of the curve's base point for ECC).
357  * Add 1 to the resulting integer and use this as the private key *x*.
358  *
359  */
360 #define PSA_KEY_TYPE_DSA_KEY_PAIR                    ((psa_key_type_t)0x7002)
361 
362 /** Whether a key type is an DSA key (pair or public-only). */
363 #define PSA_KEY_TYPE_IS_DSA(type)                                       \
364     (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY)
365 
366 #define PSA_ALG_DSA_BASE                        ((psa_algorithm_t)0x06000400)
367 /** DSA signature with hashing.
368  *
369  * This is the signature scheme defined by FIPS 186-4,
370  * with a random per-message secret number (*k*).
371  *
372  * \param hash_alg      A hash algorithm (\c PSA_ALG_XXX value such that
373  *                      #PSA_ALG_IS_HASH(\p hash_alg) is true).
374  *                      This includes #PSA_ALG_ANY_HASH
375  *                      when specifying the algorithm in a usage policy.
376  *
377  * \return              The corresponding DSA signature algorithm.
378  * \return              Unspecified if \p hash_alg is not a supported
379  *                      hash algorithm.
380  */
381 #define PSA_ALG_DSA(hash_alg)                             \
382     (PSA_ALG_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
383 #define PSA_ALG_DETERMINISTIC_DSA_BASE          ((psa_algorithm_t)0x06000500)
384 #define PSA_ALG_DSA_DETERMINISTIC_FLAG PSA_ALG_ECDSA_DETERMINISTIC_FLAG
385 /** Deterministic DSA signature with hashing.
386  *
387  * This is the deterministic variant defined by RFC 6979 of
388  * the signature scheme defined by FIPS 186-4.
389  *
390  * \param hash_alg      A hash algorithm (\c PSA_ALG_XXX value such that
391  *                      #PSA_ALG_IS_HASH(\p hash_alg) is true).
392  *                      This includes #PSA_ALG_ANY_HASH
393  *                      when specifying the algorithm in a usage policy.
394  *
395  * \return              The corresponding DSA signature algorithm.
396  * \return              Unspecified if \p hash_alg is not a supported
397  *                      hash algorithm.
398  */
399 #define PSA_ALG_DETERMINISTIC_DSA(hash_alg)                             \
400     (PSA_ALG_DETERMINISTIC_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
401 #define PSA_ALG_IS_DSA(alg)                                             \
402     (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) ==  \
403      PSA_ALG_DSA_BASE)
404 #define PSA_ALG_DSA_IS_DETERMINISTIC(alg)               \
405     (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0)
406 #define PSA_ALG_IS_DETERMINISTIC_DSA(alg)                       \
407     (PSA_ALG_IS_DSA(alg) && PSA_ALG_DSA_IS_DETERMINISTIC(alg))
408 #define PSA_ALG_IS_RANDOMIZED_DSA(alg)                          \
409     (PSA_ALG_IS_DSA(alg) && !PSA_ALG_DSA_IS_DETERMINISTIC(alg))
410 
411 
412 /* We need to expand the sample definition of this macro from
413  * the API definition. */
414 #undef PSA_ALG_IS_VENDOR_HASH_AND_SIGN
415 #define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg)    \
416     PSA_ALG_IS_DSA(alg)
417 
418 /**@}*/
419 
420 /** \addtogroup attributes
421  * @{
422  */
423 
424 /** Custom Diffie-Hellman group.
425  *
426  * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
427  * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM), the group data comes
428  * from domain parameters set by psa_set_key_domain_parameters().
429  */
430 #define PSA_DH_FAMILY_CUSTOM             ((psa_dh_family_t) 0x7e)
431 
432 
433 /**
434  * \brief Set domain parameters for a key.
435  *
436  * Some key types require additional domain parameters in addition to
437  * the key type identifier and the key size. Use this function instead
438  * of psa_set_key_type() when you need to specify domain parameters.
439  *
440  * The format for the required domain parameters varies based on the key type.
441  *
442  * - For RSA keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY or #PSA_KEY_TYPE_RSA_KEY_PAIR),
443  *   the domain parameter data consists of the public exponent,
444  *   represented as a big-endian integer with no leading zeros.
445  *   This information is used when generating an RSA key pair.
446  *   When importing a key, the public exponent is read from the imported
447  *   key data and the exponent recorded in the attribute structure is ignored.
448  *   As an exception, the public exponent 65537 is represented by an empty
449  *   byte string.
450  * - For DSA keys (#PSA_KEY_TYPE_DSA_PUBLIC_KEY or #PSA_KEY_TYPE_DSA_KEY_PAIR),
451  *   the `Dss-Parms` format as defined by RFC 3279 §2.3.2.
452  *   ```
453  *   Dss-Parms ::= SEQUENCE  {
454  *      p       INTEGER,
455  *      q       INTEGER,
456  *      g       INTEGER
457  *   }
458  *   ```
459  * - For Diffie-Hellman key exchange keys
460  *   (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
461  *   #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM)), the
462  *   `DomainParameters` format as defined by RFC 3279 §2.3.3.
463  *   ```
464  *   DomainParameters ::= SEQUENCE {
465  *      p               INTEGER,                    -- odd prime, p=jq +1
466  *      g               INTEGER,                    -- generator, g
467  *      q               INTEGER,                    -- factor of p-1
468  *      j               INTEGER OPTIONAL,           -- subgroup factor
469  *      validationParms ValidationParms OPTIONAL
470  *   }
471  *   ValidationParms ::= SEQUENCE {
472  *      seed            BIT STRING,
473  *      pgenCounter     INTEGER
474  *   }
475  *   ```
476  *
477  * \note This function may allocate memory or other resources.
478  *       Once you have called this function on an attribute structure,
479  *       you must call psa_reset_key_attributes() to free these resources.
480  *
481  * \note This is an experimental extension to the interface. It may change
482  *       in future versions of the library.
483  *
484  * \param[in,out] attributes    Attribute structure where the specified domain
485  *                              parameters will be stored.
486  *                              If this function fails, the content of
487  *                              \p attributes is not modified.
488  * \param type                  Key type (a \c PSA_KEY_TYPE_XXX value).
489  * \param[in] data              Buffer containing the key domain parameters.
490  *                              The content of this buffer is interpreted
491  *                              according to \p type as described above.
492  * \param data_length           Size of the \p data buffer in bytes.
493  *
494  * \retval #PSA_SUCCESS
495  * \retval #PSA_ERROR_INVALID_ARGUMENT
496  * \retval #PSA_ERROR_NOT_SUPPORTED
497  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
498  */
499 psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes,
500                                            psa_key_type_t type,
501                                            const uint8_t *data,
502                                            size_t data_length);
503 
504 /**
505  * \brief Get domain parameters for a key.
506  *
507  * Get the domain parameters for a key with this function, if any. The format
508  * of the domain parameters written to \p data is specified in the
509  * documentation for psa_set_key_domain_parameters().
510  *
511  * \note This is an experimental extension to the interface. It may change
512  *       in future versions of the library.
513  *
514  * \param[in] attributes        The key attribute structure to query.
515  * \param[out] data             On success, the key domain parameters.
516  * \param data_size             Size of the \p data buffer in bytes.
517  *                              The buffer is guaranteed to be large
518  *                              enough if its size in bytes is at least
519  *                              the value given by
520  *                              PSA_KEY_DOMAIN_PARAMETERS_SIZE().
521  * \param[out] data_length      On success, the number of bytes
522  *                              that make up the key domain parameters data.
523  *
524  * \retval #PSA_SUCCESS
525  * \retval #PSA_ERROR_BUFFER_TOO_SMALL
526  */
527 psa_status_t psa_get_key_domain_parameters(
528     const psa_key_attributes_t *attributes,
529     uint8_t *data,
530     size_t data_size,
531     size_t *data_length);
532 
533 /** Safe output buffer size for psa_get_key_domain_parameters().
534  *
535  * This macro returns a compile-time constant if its arguments are
536  * compile-time constants.
537  *
538  * \warning This function may call its arguments multiple times or
539  *          zero times, so you should not pass arguments that contain
540  *          side effects.
541  *
542  * \note This is an experimental extension to the interface. It may change
543  *       in future versions of the library.
544  *
545  * \param key_type  A supported key type.
546  * \param key_bits  The size of the key in bits.
547  *
548  * \return If the parameters are valid and supported, return
549  *         a buffer size in bytes that guarantees that
550  *         psa_get_key_domain_parameters() will not fail with
551  *         #PSA_ERROR_BUFFER_TOO_SMALL.
552  *         If the parameters are a valid combination that is not supported
553  *         by the implementation, this macro shall return either a
554  *         sensible size or 0.
555  *         If the parameters are not valid, the
556  *         return value is unspecified.
557  */
558 #define PSA_KEY_DOMAIN_PARAMETERS_SIZE(key_type, key_bits)              \
559     (PSA_KEY_TYPE_IS_RSA(key_type) ? sizeof(int) :                      \
560      PSA_KEY_TYPE_IS_DH(key_type) ? PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
561      PSA_KEY_TYPE_IS_DSA(key_type) ? PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
562      0)
563 #define PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits)     \
564     (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 3 /*without optional parts*/)
565 #define PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits)    \
566     (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 2 /*p, g*/ + 34 /*q*/)
567 
568 /**@}*/
569 
570 /** \defgroup psa_tls_helpers TLS helper functions
571  * @{
572  */
573 
574 #if defined(MBEDTLS_ECP_C)
575 #include <mbedtls/ecp.h>
576 
577 /** Convert an ECC curve identifier from the Mbed TLS encoding to PSA.
578  *
579  * \note This function is provided solely for the convenience of
580  *       Mbed TLS and may be removed at any time without notice.
581  *
582  * \param grpid         An Mbed TLS elliptic curve identifier
583  *                      (`MBEDTLS_ECP_DP_xxx`).
584  * \param[out] bits     On success, the bit size of the curve.
585  *
586  * \return              The corresponding PSA elliptic curve identifier
587  *                      (`PSA_ECC_FAMILY_xxx`).
588  * \return              \c 0 on failure (\p grpid is not recognized).
589  */
mbedtls_ecc_group_to_psa(mbedtls_ecp_group_id grpid,size_t * bits)590 static inline psa_ecc_family_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid,
591                                                         size_t *bits )
592 {
593     switch( grpid )
594     {
595         case MBEDTLS_ECP_DP_SECP192R1:
596             *bits = 192;
597             return( PSA_ECC_FAMILY_SECP_R1 );
598         case MBEDTLS_ECP_DP_SECP224R1:
599             *bits = 224;
600             return( PSA_ECC_FAMILY_SECP_R1 );
601         case MBEDTLS_ECP_DP_SECP256R1:
602             *bits = 256;
603             return( PSA_ECC_FAMILY_SECP_R1 );
604         case MBEDTLS_ECP_DP_SECP384R1:
605             *bits = 384;
606             return( PSA_ECC_FAMILY_SECP_R1 );
607         case MBEDTLS_ECP_DP_SECP521R1:
608             *bits = 521;
609             return( PSA_ECC_FAMILY_SECP_R1 );
610         case MBEDTLS_ECP_DP_BP256R1:
611             *bits = 256;
612             return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 );
613         case MBEDTLS_ECP_DP_BP384R1:
614             *bits = 384;
615             return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 );
616         case MBEDTLS_ECP_DP_BP512R1:
617             *bits = 512;
618             return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 );
619         case MBEDTLS_ECP_DP_CURVE25519:
620             *bits = 255;
621             return( PSA_ECC_FAMILY_MONTGOMERY );
622         case MBEDTLS_ECP_DP_SECP192K1:
623             *bits = 192;
624             return( PSA_ECC_FAMILY_SECP_K1 );
625         case MBEDTLS_ECP_DP_SECP224K1:
626             *bits = 224;
627             return( PSA_ECC_FAMILY_SECP_K1 );
628         case MBEDTLS_ECP_DP_SECP256K1:
629             *bits = 256;
630             return( PSA_ECC_FAMILY_SECP_K1 );
631         case MBEDTLS_ECP_DP_CURVE448:
632             *bits = 448;
633             return( PSA_ECC_FAMILY_MONTGOMERY );
634         default:
635             *bits = 0;
636             return( 0 );
637     }
638 }
639 
640 /** Convert an ECC curve identifier from the PSA encoding to Mbed TLS.
641  *
642  * \note This function is provided solely for the convenience of
643  *       Mbed TLS and may be removed at any time without notice.
644  *
645  * \param curve         A PSA elliptic curve identifier
646  *                      (`PSA_ECC_FAMILY_xxx`).
647  * \param bits          The bit-length of a private key on \p curve.
648  * \param bits_is_sloppy If true, \p bits may be the bit-length rounded up
649  *                      to the nearest multiple of 8. This allows the caller
650  *                      to infer the exact curve from the length of a key
651  *                      which is supplied as a byte string.
652  *
653  * \return              The corresponding Mbed TLS elliptic curve identifier
654  *                      (`MBEDTLS_ECP_DP_xxx`).
655  * \return              #MBEDTLS_ECP_DP_NONE if \c curve is not recognized.
656  * \return              #MBEDTLS_ECP_DP_NONE if \p bits is not
657  *                      correct for \p curve.
658  */
659 mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve,
660                                                size_t bits,
661                                                int bits_is_sloppy );
662 #endif /* MBEDTLS_ECP_C */
663 
664 /**@}*/
665 
666 /** \defgroup psa_external_rng External random generator
667  * @{
668  */
669 
670 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
671 /** External random generator function, implemented by the platform.
672  *
673  * When the compile-time option #MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG is enabled,
674  * this function replaces Mbed TLS's entropy and DRBG modules for all
675  * random generation triggered via PSA crypto interfaces.
676  *
677  * \note This random generator must deliver random numbers with cryptographic
678  *       quality and high performance. It must supply unpredictable numbers
679  *       with a uniform distribution. The implementation of this function
680  *       is responsible for ensuring that the random generator is seeded
681  *       with sufficient entropy. If you have a hardware TRNG which is slow
682  *       or delivers non-uniform output, declare it as an entropy source
683  *       with mbedtls_entropy_add_source() instead of enabling this option.
684  *
685  * \param[in,out] context       Pointer to the random generator context.
686  *                              This is all-bits-zero on the first call
687  *                              and preserved between successive calls.
688  * \param[out] output           Output buffer. On success, this buffer
689  *                              contains random data with a uniform
690  *                              distribution.
691  * \param output_size           The size of the \p output buffer in bytes.
692  * \param[out] output_length    On success, set this value to \p output_size.
693  *
694  * \retval #PSA_SUCCESS
695  *         Success. The output buffer contains \p output_size bytes of
696  *         cryptographic-quality random data, and \c *output_length is
697  *         set to \p output_size.
698  * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY
699  *         The random generator requires extra entropy and there is no
700  *         way to obtain entropy under current environment conditions.
701  *         This error should not happen under normal circumstances since
702  *         this function is responsible for obtaining as much entropy as
703  *         it needs. However implementations of this function may return
704  *         #PSA_ERROR_INSUFFICIENT_ENTROPY if there is no way to obtain
705  *         entropy without blocking indefinitely.
706  * \retval #PSA_ERROR_HARDWARE_FAILURE
707  *         A failure of the random generator hardware that isn't covered
708  *         by #PSA_ERROR_INSUFFICIENT_ENTROPY.
709  */
710 psa_status_t mbedtls_psa_external_get_random(
711     mbedtls_psa_external_random_context_t *context,
712     uint8_t *output, size_t output_size, size_t *output_length );
713 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
714 
715 /**@}*/
716 
717 /** \defgroup psa_builtin_keys Built-in keys
718  * @{
719  */
720 
721 /** The minimum value for a key identifier that is built into the
722  * implementation.
723  *
724  * The range of key identifiers from #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN
725  * to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX within the range from
726  * #PSA_KEY_ID_VENDOR_MIN and #PSA_KEY_ID_VENDOR_MAX and must not intersect
727  * with any other set of implementation-chosen key identifiers.
728  *
729  * This value is part of the library's ABI since changing it would invalidate
730  * the values of built-in key identifiers in applications.
731  */
732 #define MBEDTLS_PSA_KEY_ID_BUILTIN_MIN          ((psa_key_id_t)0x7fff0000)
733 
734 /** The maximum value for a key identifier that is built into the
735  * implementation.
736  *
737  * See #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN for more information.
738  */
739 #define MBEDTLS_PSA_KEY_ID_BUILTIN_MAX          ((psa_key_id_t)0x7fffefff)
740 
741 /** A slot number identifying a key in a driver.
742  *
743  * Values of this type are used to identify built-in keys.
744  */
745 typedef uint64_t psa_drv_slot_number_t;
746 
747 #if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
748 /** Test whether a key identifier belongs to the builtin key range.
749  *
750  * \param key_id  Key identifier to test.
751  *
752  * \retval 1
753  *         The key identifier is a builtin key identifier.
754  * \retval 0
755  *         The key identifier is not a builtin key identifier.
756  */
psa_key_id_is_builtin(psa_key_id_t key_id)757 static inline int psa_key_id_is_builtin( psa_key_id_t key_id )
758 {
759     return( ( key_id >= MBEDTLS_PSA_KEY_ID_BUILTIN_MIN ) &&
760             ( key_id <= MBEDTLS_PSA_KEY_ID_BUILTIN_MAX ) );
761 }
762 
763 /** Platform function to obtain the location and slot number of a built-in key.
764  *
765  * An application-specific implementation of this function must be provided if
766  * #MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS is enabled. This would typically be provided
767  * as part of a platform's system image.
768  *
769  * #MBEDTLS_SVC_KEY_ID_GET_KEY_ID(\p key_id) needs to be in the range from
770  * #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX.
771  *
772  * In a multi-application configuration
773  * (\c MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER is defined),
774  * this function should check that #MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(\p key_id)
775  * is allowed to use the given key.
776  *
777  * \param key_id                The key ID for which to retrieve the
778  *                              location and slot attributes.
779  * \param[out] lifetime         On success, the lifetime associated with the key
780  *                              corresponding to \p key_id. Lifetime is a
781  *                              combination of which driver contains the key,
782  *                              and with what persistence level the key is
783  *                              intended to be used. If the platform
784  *                              implementation does not contain specific
785  *                              information about the intended key persistence
786  *                              level, the persistence level may be reported as
787  *                              #PSA_KEY_PERSISTENCE_DEFAULT.
788  * \param[out] slot_number      On success, the slot number known to the driver
789  *                              registered at the lifetime location reported
790  *                              through \p lifetime which corresponds to the
791  *                              requested built-in key.
792  *
793  * \retval #PSA_SUCCESS
794  *         The requested key identifier designates a built-in key.
795  *         In a multi-application configuration, the requested owner
796  *         is allowed to access it.
797  * \retval #PSA_ERROR_DOES_NOT_EXIST
798  *         The requested key identifier is not a built-in key which is known
799  *         to this function. If a key exists in the key storage with this
800  *         identifier, the data from the storage will be used.
801  * \return (any other error)
802  *         Any other error is propagated to the function that requested the key.
803  *         Common errors include:
804  *         - #PSA_ERROR_NOT_PERMITTED: the key exists but the requested owner
805  *           is not allowed to access it.
806  */
807 psa_status_t mbedtls_psa_platform_get_builtin_key(
808     mbedtls_svc_key_id_t key_id,
809     psa_key_lifetime_t *lifetime,
810     psa_drv_slot_number_t *slot_number );
811 #endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
812 
813 /** @} */
814 
815 #ifdef __cplusplus
816 }
817 #endif
818 
819 #endif /* PSA_CRYPTO_EXTRA_H */
820