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 OR GPL-2.0-or-later
14  */
15 
16 #ifndef PSA_CRYPTO_EXTRA_H
17 #define PSA_CRYPTO_EXTRA_H
18 #include "mbedtls/private_access.h"
19 
20 #include "crypto_types.h"
21 #include "crypto_compat.h"
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26 
27 /* UID for secure storage seed */
28 #define PSA_CRYPTO_ITS_RANDOM_SEED_UID 0xFFFFFF52
29 
30 /* See mbedtls_config.h for definition */
31 #if !defined(MBEDTLS_PSA_KEY_SLOT_COUNT)
32 #define MBEDTLS_PSA_KEY_SLOT_COUNT 32
33 #endif
34 
35 /** \addtogroup attributes
36  * @{
37  */
38 
39 /** \brief Declare the enrollment algorithm for a key.
40  *
41  * An operation on a key may indifferently use the algorithm set with
42  * psa_set_key_algorithm() or with this function.
43  *
44  * \param[out] attributes       The attribute structure to write to.
45  * \param alg2                  A second algorithm that the key may be used
46  *                              for, in addition to the algorithm set with
47  *                              psa_set_key_algorithm().
48  *
49  * \warning Setting an enrollment algorithm is not recommended, because
50  *          using the same key with different algorithms can allow some
51  *          attacks based on arithmetic relations between different
52  *          computations made with the same key, or can escalate harmless
53  *          side channels into exploitable ones. Use this function only
54  *          if it is necessary to support a protocol for which it has been
55  *          verified that the usage of the key with multiple algorithms
56  *          is safe.
57  */
psa_set_key_enrollment_algorithm(psa_key_attributes_t * attributes,psa_algorithm_t alg2)58 static inline void psa_set_key_enrollment_algorithm(
59     psa_key_attributes_t *attributes,
60     psa_algorithm_t alg2)
61 {
62     attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg2) = alg2;
63 }
64 
65 /** Retrieve the enrollment algorithm policy from key attributes.
66  *
67  * \param[in] attributes        The key attribute structure to query.
68  *
69  * \return The enrollment algorithm stored in the attribute structure.
70  */
psa_get_key_enrollment_algorithm(const psa_key_attributes_t * attributes)71 static inline psa_algorithm_t psa_get_key_enrollment_algorithm(
72     const psa_key_attributes_t *attributes)
73 {
74     return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg2);
75 }
76 
77 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
78 
79 /** Retrieve the slot number where a key is stored.
80  *
81  * A slot number is only defined for keys that are stored in a secure
82  * element.
83  *
84  * This information is only useful if the secure element is not entirely
85  * managed through the PSA Cryptography API. It is up to the secure
86  * element driver to decide how PSA slot numbers map to any other interface
87  * that the secure element may have.
88  *
89  * \param[in] attributes        The key attribute structure to query.
90  * \param[out] slot_number      On success, the slot number containing the key.
91  *
92  * \retval #PSA_SUCCESS
93  *         The key is located in a secure element, and \p *slot_number
94  *         indicates the slot number that contains it.
95  * \retval #PSA_ERROR_NOT_PERMITTED
96  *         The caller is not permitted to query the slot number.
97  *         Mbed TLS currently does not return this error.
98  * \retval #PSA_ERROR_INVALID_ARGUMENT
99  *         The key is not located in a secure element.
100  */
101 psa_status_t psa_get_key_slot_number(
102     const psa_key_attributes_t *attributes,
103     psa_key_slot_number_t *slot_number);
104 
105 /** Choose the slot number where a key is stored.
106  *
107  * This function declares a slot number in the specified attribute
108  * structure.
109  *
110  * A slot number is only meaningful for keys that are stored in a secure
111  * element. It is up to the secure element driver to decide how PSA slot
112  * numbers map to any other interface that the secure element may have.
113  *
114  * \note Setting a slot number in key attributes for a key creation can
115  *       cause the following errors when creating the key:
116  *       - #PSA_ERROR_NOT_SUPPORTED if the selected secure element does
117  *         not support choosing a specific slot number.
118  *       - #PSA_ERROR_NOT_PERMITTED if the caller is not permitted to
119  *         choose slot numbers in general or to choose this specific slot.
120  *       - #PSA_ERROR_INVALID_ARGUMENT if the chosen slot number is not
121  *         valid in general or not valid for this specific key.
122  *       - #PSA_ERROR_ALREADY_EXISTS if there is already a key in the
123  *         selected slot.
124  *
125  * \param[out] attributes       The attribute structure to write to.
126  * \param slot_number           The slot number to set.
127  */
psa_set_key_slot_number(psa_key_attributes_t * attributes,psa_key_slot_number_t slot_number)128 static inline void psa_set_key_slot_number(
129     psa_key_attributes_t *attributes,
130     psa_key_slot_number_t slot_number)
131 {
132     attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(flags) |= MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
133     attributes->MBEDTLS_PRIVATE(slot_number) = slot_number;
134 }
135 
136 /** Remove the slot number attribute from a key attribute structure.
137  *
138  * This function undoes the action of psa_set_key_slot_number().
139  *
140  * \param[out] attributes       The attribute structure to write to.
141  */
psa_clear_key_slot_number(psa_key_attributes_t * attributes)142 static inline void psa_clear_key_slot_number(
143     psa_key_attributes_t *attributes)
144 {
145     attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(flags) &=
146         ~MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
147 }
148 
149 /** Register a key that is already present in a secure element.
150  *
151  * The key must be located in a secure element designated by the
152  * lifetime field in \p attributes, in the slot set with
153  * psa_set_key_slot_number() in the attribute structure.
154  * This function makes the key available through the key identifier
155  * specified in \p attributes.
156  *
157  * \param[in] attributes        The attributes of the existing key.
158  *
159  * \retval #PSA_SUCCESS
160  *         The key was successfully registered.
161  *         Note that depending on the design of the driver, this may or may
162  *         not guarantee that a key actually exists in the designated slot
163  *         and is compatible with the specified attributes.
164  * \retval #PSA_ERROR_ALREADY_EXISTS
165  *         There is already a key with the identifier specified in
166  *         \p attributes.
167  * \retval #PSA_ERROR_NOT_SUPPORTED
168  *         The secure element driver for the specified lifetime does not
169  *         support registering a key.
170  * \retval #PSA_ERROR_INVALID_ARGUMENT
171  *         The identifier in \p attributes is invalid, namely the identifier is
172  *         not in the user range, or
173  *         \p attributes specifies a lifetime which is not located
174  *         in a secure element, or no slot number is specified in \p attributes,
175  *         or the specified slot number is not valid.
176  * \retval #PSA_ERROR_NOT_PERMITTED
177  *         The caller is not authorized to register the specified key slot.
178  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
179  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
180  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
181  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
182  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
183  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
184  * \retval #PSA_ERROR_BAD_STATE
185  *         The library has not been previously initialized by psa_crypto_init().
186  *         It is implementation-dependent whether a failure to initialize
187  *         results in this error code.
188  */
189 psa_status_t mbedtls_psa_register_se_key(
190     const psa_key_attributes_t *attributes);
191 
192 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
193 
194 /**@}*/
195 
196 /**
197  * \brief Library deinitialization.
198  *
199  * This function clears all data associated with the PSA layer,
200  * including the whole key store.
201  *
202  * This is an Mbed TLS extension.
203  */
204 void mbedtls_psa_crypto_free(void);
205 
206 /** \brief Statistics about
207  * resource consumption related to the PSA keystore.
208  *
209  * \note The content of this structure is not part of the stable API and ABI
210  *       of Mbed TLS and may change arbitrarily from version to version.
211  */
212 typedef struct mbedtls_psa_stats_s {
213     /** Number of slots containing key material for a volatile key. */
214     size_t MBEDTLS_PRIVATE(volatile_slots);
215     /** Number of slots containing key material for a key which is in
216      * internal persistent storage. */
217     size_t MBEDTLS_PRIVATE(persistent_slots);
218     /** Number of slots containing a reference to a key in a
219      * secure element. */
220     size_t MBEDTLS_PRIVATE(external_slots);
221     /** Number of slots which are occupied, but do not contain
222      * key material yet. */
223     size_t MBEDTLS_PRIVATE(half_filled_slots);
224     /** Number of slots that contain cache data. */
225     size_t MBEDTLS_PRIVATE(cache_slots);
226     /** Number of slots that are not used for anything. */
227     size_t MBEDTLS_PRIVATE(empty_slots);
228     /** Number of slots that are locked. */
229     size_t MBEDTLS_PRIVATE(locked_slots);
230     /** Largest key id value among open keys in internal persistent storage. */
231     psa_key_id_t MBEDTLS_PRIVATE(max_open_internal_key_id);
232     /** Largest key id value among open keys in secure elements. */
233     psa_key_id_t MBEDTLS_PRIVATE(max_open_external_key_id);
234 } mbedtls_psa_stats_t;
235 
236 /** \brief Get statistics about
237  * resource consumption related to the PSA keystore.
238  *
239  * \note When Mbed TLS is built as part of a service, with isolation
240  *       between the application and the keystore, the service may or
241  *       may not expose this function.
242  */
243 void mbedtls_psa_get_stats(mbedtls_psa_stats_t *stats);
244 
245 /**
246  * \brief Inject an initial entropy seed for the random generator into
247  *        secure storage.
248  *
249  * This function injects data to be used as a seed for the random generator
250  * used by the PSA Crypto implementation. On devices that lack a trusted
251  * entropy source (preferably a hardware random number generator),
252  * the Mbed PSA Crypto implementation uses this value to seed its
253  * random generator.
254  *
255  * On devices without a trusted entropy source, this function must be
256  * called exactly once in the lifetime of the device. On devices with
257  * a trusted entropy source, calling this function is optional.
258  * In all cases, this function may only be called before calling any
259  * other function in the PSA Crypto API, including psa_crypto_init().
260  *
261  * When this function returns successfully, it populates a file in
262  * persistent storage. Once the file has been created, this function
263  * can no longer succeed.
264  *
265  * If any error occurs, this function does not change the system state.
266  * You can call this function again after correcting the reason for the
267  * error if possible.
268  *
269  * \warning This function **can** fail! Callers MUST check the return status.
270  *
271  * \warning If you use this function, you should use it as part of a
272  *          factory provisioning process. The value of the injected seed
273  *          is critical to the security of the device. It must be
274  *          *secret*, *unpredictable* and (statistically) *unique per device*.
275  *          You should be generate it randomly using a cryptographically
276  *          secure random generator seeded from trusted entropy sources.
277  *          You should transmit it securely to the device and ensure
278  *          that its value is not leaked or stored anywhere beyond the
279  *          needs of transmitting it from the point of generation to
280  *          the call of this function, and erase all copies of the value
281  *          once this function returns.
282  *
283  * This is an Mbed TLS extension.
284  *
285  * \note This function is only available on the following platforms:
286  * * If the compile-time option MBEDTLS_PSA_INJECT_ENTROPY is enabled.
287  *   Note that you must provide compatible implementations of
288  *   mbedtls_nv_seed_read and mbedtls_nv_seed_write.
289  * * In a client-server integration of PSA Cryptography, on the client side,
290  *   if the server supports this feature.
291  * \param[in] seed          Buffer containing the seed value to inject.
292  * \param[in] seed_size     Size of the \p seed buffer.
293  *                          The size of the seed in bytes must be greater
294  *                          or equal to both #MBEDTLS_ENTROPY_BLOCK_SIZE
295  *                          and the value of \c MBEDTLS_ENTROPY_MIN_PLATFORM
296  *                          in `library/entropy_poll.h` in the Mbed TLS source
297  *                          code.
298  *                          It must be less or equal to
299  *                          #MBEDTLS_ENTROPY_MAX_SEED_SIZE.
300  *
301  * \retval #PSA_SUCCESS
302  *         The seed value was injected successfully. The random generator
303  *         of the PSA Crypto implementation is now ready for use.
304  *         You may now call psa_crypto_init() and use the PSA Crypto
305  *         implementation.
306  * \retval #PSA_ERROR_INVALID_ARGUMENT
307  *         \p seed_size is out of range.
308  * \retval #PSA_ERROR_STORAGE_FAILURE
309  *         There was a failure reading or writing from storage.
310  * \retval #PSA_ERROR_NOT_PERMITTED
311  *         The library has already been initialized. It is no longer
312  *         possible to call this function.
313  */
314 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
315                                         size_t seed_size);
316 
317 /** \addtogroup crypto_types
318  * @{
319  */
320 
321 /** DSA public key.
322  *
323  * The import and export format is the
324  * representation of the public key `y = g^x mod p` as a big-endian byte
325  * string. The length of the byte string is the length of the base prime `p`
326  * in bytes.
327  */
328 #define PSA_KEY_TYPE_DSA_PUBLIC_KEY                 ((psa_key_type_t) 0x4002)
329 
330 /** DSA key pair (private and public key).
331  *
332  * The import and export format is the
333  * representation of the private key `x` as a big-endian byte string. The
334  * length of the byte string is the private key size in bytes (leading zeroes
335  * are not stripped).
336  *
337  * Deterministic DSA key derivation with psa_generate_derived_key follows
338  * FIPS 186-4 §B.1.2: interpret the byte string as integer
339  * in big-endian order. Discard it if it is not in the range
340  * [0, *N* - 2] where *N* is the boundary of the private key domain
341  * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA,
342  * or the order of the curve's base point for ECC).
343  * Add 1 to the resulting integer and use this as the private key *x*.
344  *
345  */
346 #define PSA_KEY_TYPE_DSA_KEY_PAIR                    ((psa_key_type_t) 0x7002)
347 
348 /** Whether a key type is a DSA key (pair or public-only). */
349 #define PSA_KEY_TYPE_IS_DSA(type)                                       \
350     (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY)
351 
352 #define PSA_ALG_DSA_BASE                        ((psa_algorithm_t) 0x06000400)
353 /** DSA signature with hashing.
354  *
355  * This is the signature scheme defined by FIPS 186-4,
356  * with a random per-message secret number (*k*).
357  *
358  * \param hash_alg      A hash algorithm (\c PSA_ALG_XXX value such that
359  *                      #PSA_ALG_IS_HASH(\p hash_alg) is true).
360  *                      This includes #PSA_ALG_ANY_HASH
361  *                      when specifying the algorithm in a usage policy.
362  *
363  * \return              The corresponding DSA signature algorithm.
364  * \return              Unspecified if \p hash_alg is not a supported
365  *                      hash algorithm.
366  */
367 #define PSA_ALG_DSA(hash_alg)                             \
368     (PSA_ALG_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
369 #define PSA_ALG_DETERMINISTIC_DSA_BASE          ((psa_algorithm_t) 0x06000500)
370 #define PSA_ALG_DSA_DETERMINISTIC_FLAG PSA_ALG_ECDSA_DETERMINISTIC_FLAG
371 /** Deterministic DSA signature with hashing.
372  *
373  * This is the deterministic variant defined by RFC 6979 of
374  * the signature scheme defined by FIPS 186-4.
375  *
376  * \param hash_alg      A hash algorithm (\c PSA_ALG_XXX value such that
377  *                      #PSA_ALG_IS_HASH(\p hash_alg) is true).
378  *                      This includes #PSA_ALG_ANY_HASH
379  *                      when specifying the algorithm in a usage policy.
380  *
381  * \return              The corresponding DSA signature algorithm.
382  * \return              Unspecified if \p hash_alg is not a supported
383  *                      hash algorithm.
384  */
385 #define PSA_ALG_DETERMINISTIC_DSA(hash_alg)                             \
386     (PSA_ALG_DETERMINISTIC_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
387 #define PSA_ALG_IS_DSA(alg)                                             \
388     (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) ==  \
389      PSA_ALG_DSA_BASE)
390 #define PSA_ALG_DSA_IS_DETERMINISTIC(alg)               \
391     (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0)
392 #define PSA_ALG_IS_DETERMINISTIC_DSA(alg)                       \
393     (PSA_ALG_IS_DSA(alg) && PSA_ALG_DSA_IS_DETERMINISTIC(alg))
394 #define PSA_ALG_IS_RANDOMIZED_DSA(alg)                          \
395     (PSA_ALG_IS_DSA(alg) && !PSA_ALG_DSA_IS_DETERMINISTIC(alg))
396 
397 
398 /* We need to expand the sample definition of this macro from
399  * the API definition. */
400 #undef PSA_ALG_IS_VENDOR_HASH_AND_SIGN
401 #define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg)    \
402     PSA_ALG_IS_DSA(alg)
403 
404 /**@}*/
405 
406 /** \addtogroup attributes
407  * @{
408  */
409 
410 /** Custom Diffie-Hellman group.
411  *
412  * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
413  * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM), the group data comes
414  * from domain parameters set by psa_set_key_domain_parameters().
415  */
416 #define PSA_DH_FAMILY_CUSTOM             ((psa_dh_family_t) 0x7e)
417 
418 /** PAKE operation stages. */
419 #define PSA_PAKE_OPERATION_STAGE_SETUP 0
420 #define PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS 1
421 #define PSA_PAKE_OPERATION_STAGE_COMPUTATION 2
422 
423 /**
424  * \brief Set domain parameters for a key.
425  *
426  * Some key types require additional domain parameters in addition to
427  * the key type identifier and the key size. Use this function instead
428  * of psa_set_key_type() when you need to specify domain parameters.
429  *
430  * The format for the required domain parameters varies based on the key type.
431  *
432  * - For RSA keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY or #PSA_KEY_TYPE_RSA_KEY_PAIR),
433  *   the domain parameter data consists of the public exponent,
434  *   represented as a big-endian integer with no leading zeros.
435  *   This information is used when generating an RSA key pair.
436  *   When importing a key, the public exponent is read from the imported
437  *   key data and the exponent recorded in the attribute structure is ignored.
438  *   As an exception, the public exponent 65537 is represented by an empty
439  *   byte string.
440  * - For DSA keys (#PSA_KEY_TYPE_DSA_PUBLIC_KEY or #PSA_KEY_TYPE_DSA_KEY_PAIR),
441  *   the `Dss-Params` format as defined by RFC 3279 §2.3.2.
442  *   ```
443  *   Dss-Params ::= SEQUENCE  {
444  *      p       INTEGER,
445  *      q       INTEGER,
446  *      g       INTEGER
447  *   }
448  *   ```
449  * - For Diffie-Hellman key exchange keys
450  *   (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
451  *   #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM)), the
452  *   `DomainParameters` format as defined by RFC 3279 §2.3.3.
453  *   ```
454  *   DomainParameters ::= SEQUENCE {
455  *      p               INTEGER,                    -- odd prime, p=jq +1
456  *      g               INTEGER,                    -- generator, g
457  *      q               INTEGER,                    -- factor of p-1
458  *      j               INTEGER OPTIONAL,           -- subgroup factor
459  *      validationParams ValidationParams OPTIONAL
460  *   }
461  *   ValidationParams ::= SEQUENCE {
462  *      seed            BIT STRING,
463  *      pgenCounter     INTEGER
464  *   }
465  *   ```
466  *
467  * \note This function may allocate memory or other resources.
468  *       Once you have called this function on an attribute structure,
469  *       you must call psa_reset_key_attributes() to free these resources.
470  *
471  * \note This is an experimental extension to the interface. It may change
472  *       in future versions of the library.
473  *
474  * \param[in,out] attributes    Attribute structure where the specified domain
475  *                              parameters will be stored.
476  *                              If this function fails, the content of
477  *                              \p attributes is not modified.
478  * \param type                  Key type (a \c PSA_KEY_TYPE_XXX value).
479  * \param[in] data              Buffer containing the key domain parameters.
480  *                              The content of this buffer is interpreted
481  *                              according to \p type as described above.
482  * \param data_length           Size of the \p data buffer in bytes.
483  *
484  * \retval #PSA_SUCCESS \emptydescription
485  * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
486  * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
487  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
488  */
489 psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes,
490                                            psa_key_type_t type,
491                                            const uint8_t *data,
492                                            size_t data_length);
493 
494 /**
495  * \brief Get domain parameters for a key.
496  *
497  * Get the domain parameters for a key with this function, if any. The format
498  * of the domain parameters written to \p data is specified in the
499  * documentation for psa_set_key_domain_parameters().
500  *
501  * \note This is an experimental extension to the interface. It may change
502  *       in future versions of the library.
503  *
504  * \param[in] attributes        The key attribute structure to query.
505  * \param[out] data             On success, the key domain parameters.
506  * \param data_size             Size of the \p data buffer in bytes.
507  *                              The buffer is guaranteed to be large
508  *                              enough if its size in bytes is at least
509  *                              the value given by
510  *                              PSA_KEY_DOMAIN_PARAMETERS_SIZE().
511  * \param[out] data_length      On success, the number of bytes
512  *                              that make up the key domain parameters data.
513  *
514  * \retval #PSA_SUCCESS \emptydescription
515  * \retval #PSA_ERROR_BUFFER_TOO_SMALL \emptydescription
516  */
517 psa_status_t psa_get_key_domain_parameters(
518     const psa_key_attributes_t *attributes,
519     uint8_t *data,
520     size_t data_size,
521     size_t *data_length);
522 
523 /** Safe output buffer size for psa_get_key_domain_parameters().
524  *
525  * This macro returns a compile-time constant if its arguments are
526  * compile-time constants.
527  *
528  * \warning This function may call its arguments multiple times or
529  *          zero times, so you should not pass arguments that contain
530  *          side effects.
531  *
532  * \note This is an experimental extension to the interface. It may change
533  *       in future versions of the library.
534  *
535  * \param key_type  A supported key type.
536  * \param key_bits  The size of the key in bits.
537  *
538  * \return If the parameters are valid and supported, return
539  *         a buffer size in bytes that guarantees that
540  *         psa_get_key_domain_parameters() will not fail with
541  *         #PSA_ERROR_BUFFER_TOO_SMALL.
542  *         If the parameters are a valid combination that is not supported
543  *         by the implementation, this macro shall return either a
544  *         sensible size or 0.
545  *         If the parameters are not valid, the
546  *         return value is unspecified.
547  */
548 #define PSA_KEY_DOMAIN_PARAMETERS_SIZE(key_type, key_bits)              \
549     (PSA_KEY_TYPE_IS_RSA(key_type) ? sizeof(int) :                      \
550      PSA_KEY_TYPE_IS_DH(key_type) ? PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
551      PSA_KEY_TYPE_IS_DSA(key_type) ? PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
552      0)
553 #define PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits)     \
554     (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 3 /*without optional parts*/)
555 #define PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits)    \
556     (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 2 /*p, g*/ + 34 /*q*/)
557 
558 /**@}*/
559 
560 
561 /** \defgroup psa_external_rng External random generator
562  * @{
563  */
564 
565 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
566 /** External random generator function, implemented by the platform.
567  *
568  * When the compile-time option #MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG is enabled,
569  * this function replaces Mbed TLS's entropy and DRBG modules for all
570  * random generation triggered via PSA crypto interfaces.
571  *
572  * \note This random generator must deliver random numbers with cryptographic
573  *       quality and high performance. It must supply unpredictable numbers
574  *       with a uniform distribution. The implementation of this function
575  *       is responsible for ensuring that the random generator is seeded
576  *       with sufficient entropy. If you have a hardware TRNG which is slow
577  *       or delivers non-uniform output, declare it as an entropy source
578  *       with mbedtls_entropy_add_source() instead of enabling this option.
579  *
580  * \param[in,out] context       Pointer to the random generator context.
581  *                              This is all-bits-zero on the first call
582  *                              and preserved between successive calls.
583  * \param[out] output           Output buffer. On success, this buffer
584  *                              contains random data with a uniform
585  *                              distribution.
586  * \param output_size           The size of the \p output buffer in bytes.
587  * \param[out] output_length    On success, set this value to \p output_size.
588  *
589  * \retval #PSA_SUCCESS
590  *         Success. The output buffer contains \p output_size bytes of
591  *         cryptographic-quality random data, and \c *output_length is
592  *         set to \p output_size.
593  * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY
594  *         The random generator requires extra entropy and there is no
595  *         way to obtain entropy under current environment conditions.
596  *         This error should not happen under normal circumstances since
597  *         this function is responsible for obtaining as much entropy as
598  *         it needs. However implementations of this function may return
599  *         #PSA_ERROR_INSUFFICIENT_ENTROPY if there is no way to obtain
600  *         entropy without blocking indefinitely.
601  * \retval #PSA_ERROR_HARDWARE_FAILURE
602  *         A failure of the random generator hardware that isn't covered
603  *         by #PSA_ERROR_INSUFFICIENT_ENTROPY.
604  */
605 psa_status_t mbedtls_psa_external_get_random(
606     mbedtls_psa_external_random_context_t *context,
607     uint8_t *output, size_t output_size, size_t *output_length);
608 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
609 
610 /**@}*/
611 
612 /** \defgroup psa_builtin_keys Built-in keys
613  * @{
614  */
615 
616 /** The minimum value for a key identifier that is built into the
617  * implementation.
618  *
619  * The range of key identifiers from #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN
620  * to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX within the range from
621  * #PSA_KEY_ID_VENDOR_MIN and #PSA_KEY_ID_VENDOR_MAX and must not intersect
622  * with any other set of implementation-chosen key identifiers.
623  *
624  * This value is part of the library's ABI since changing it would invalidate
625  * the values of built-in key identifiers in applications.
626  */
627 #define MBEDTLS_PSA_KEY_ID_BUILTIN_MIN          ((psa_key_id_t) 0x7fff0000)
628 
629 /** The maximum value for a key identifier that is built into the
630  * implementation.
631  *
632  * See #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN for more information.
633  */
634 #define MBEDTLS_PSA_KEY_ID_BUILTIN_MAX          ((psa_key_id_t) 0x7fffefff)
635 
636 /** A slot number identifying a key in a driver.
637  *
638  * Values of this type are used to identify built-in keys.
639  */
640 typedef uint64_t psa_drv_slot_number_t;
641 
642 #if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
643 /** Test whether a key identifier belongs to the builtin key range.
644  *
645  * \param key_id  Key identifier to test.
646  *
647  * \retval 1
648  *         The key identifier is a builtin key identifier.
649  * \retval 0
650  *         The key identifier is not a builtin key identifier.
651  */
psa_key_id_is_builtin(psa_key_id_t key_id)652 static inline int psa_key_id_is_builtin(psa_key_id_t key_id)
653 {
654     return (key_id >= MBEDTLS_PSA_KEY_ID_BUILTIN_MIN) &&
655            (key_id <= MBEDTLS_PSA_KEY_ID_BUILTIN_MAX);
656 }
657 
658 /** Platform function to obtain the location and slot number of a built-in key.
659  *
660  * An application-specific implementation of this function must be provided if
661  * #MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS is enabled. This would typically be provided
662  * as part of a platform's system image.
663  *
664  * #MBEDTLS_SVC_KEY_ID_GET_KEY_ID(\p key_id) needs to be in the range from
665  * #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX.
666  *
667  * In a multi-application configuration
668  * (\c MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER is defined),
669  * this function should check that #MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(\p key_id)
670  * is allowed to use the given key.
671  *
672  * \param key_id                The key ID for which to retrieve the
673  *                              location and slot attributes.
674  * \param[out] lifetime         On success, the lifetime associated with the key
675  *                              corresponding to \p key_id. Lifetime is a
676  *                              combination of which driver contains the key,
677  *                              and with what persistence level the key is
678  *                              intended to be used. If the platform
679  *                              implementation does not contain specific
680  *                              information about the intended key persistence
681  *                              level, the persistence level may be reported as
682  *                              #PSA_KEY_PERSISTENCE_DEFAULT.
683  * \param[out] slot_number      On success, the slot number known to the driver
684  *                              registered at the lifetime location reported
685  *                              through \p lifetime which corresponds to the
686  *                              requested built-in key.
687  *
688  * \retval #PSA_SUCCESS
689  *         The requested key identifier designates a built-in key.
690  *         In a multi-application configuration, the requested owner
691  *         is allowed to access it.
692  * \retval #PSA_ERROR_DOES_NOT_EXIST
693  *         The requested key identifier is not a built-in key which is known
694  *         to this function. If a key exists in the key storage with this
695  *         identifier, the data from the storage will be used.
696  * \return (any other error)
697  *         Any other error is propagated to the function that requested the key.
698  *         Common errors include:
699  *         - #PSA_ERROR_NOT_PERMITTED: the key exists but the requested owner
700  *           is not allowed to access it.
701  */
702 psa_status_t mbedtls_psa_platform_get_builtin_key(
703     mbedtls_svc_key_id_t key_id,
704     psa_key_lifetime_t *lifetime,
705     psa_drv_slot_number_t *slot_number);
706 #endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
707 
708 /** @} */
709 
710 /** \addtogroup crypto_types
711  * @{
712  */
713 
714 #define PSA_ALG_CATEGORY_PAKE                   ((psa_algorithm_t) 0x0a000000)
715 
716 /** Whether the specified algorithm is a password-authenticated key exchange.
717  *
718  * \param alg An algorithm identifier (value of type #psa_algorithm_t).
719  *
720  * \return 1 if \p alg is a password-authenticated key exchange (PAKE)
721  *         algorithm, 0 otherwise.
722  *         This macro may return either 0 or 1 if \p alg is not a supported
723  *         algorithm identifier.
724  */
725 #define PSA_ALG_IS_PAKE(alg)                                        \
726     (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_PAKE)
727 
728 /** The Password-authenticated key exchange by juggling (J-PAKE) algorithm.
729  *
730  * This is J-PAKE as defined by RFC 8236, instantiated with the following
731  * parameters:
732  *
733  * - The group can be either an elliptic curve or defined over a finite field.
734  * - Schnorr NIZK proof as defined by RFC 8235 and using the same group as the
735  *   J-PAKE algorithm.
736  * - A cryptographic hash function.
737  *
738  * To select these parameters and set up the cipher suite, call these functions
739  * in any order:
740  *
741  * \code
742  * psa_pake_cs_set_algorithm(cipher_suite, PSA_ALG_JPAKE);
743  * psa_pake_cs_set_primitive(cipher_suite,
744  *                           PSA_PAKE_PRIMITIVE(type, family, bits));
745  * psa_pake_cs_set_hash(cipher_suite, hash);
746  * \endcode
747  *
748  * For more information on how to set a specific curve or field, refer to the
749  * documentation of the individual \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
750  *
751  * After initializing a J-PAKE operation, call
752  *
753  * \code
754  * psa_pake_setup(operation, cipher_suite);
755  * psa_pake_set_user(operation, ...);
756  * psa_pake_set_peer(operation, ...);
757  * psa_pake_set_password_key(operation, ...);
758  * \endcode
759  *
760  * The password is provided as a key. This can be the password text itself,
761  * in an agreed character encoding, or some value derived from the password
762  * as required by a higher level protocol.
763  *
764  * (The implementation converts the key material to a number as described in
765  * Section 2.3.8 of _SEC 1: Elliptic Curve Cryptography_
766  * (https://www.secg.org/sec1-v2.pdf), before reducing it modulo \c q. Here
767  * \c q is order of the group defined by the primitive set in the cipher suite.
768  * The \c psa_pake_set_password_key() function returns an error if the result
769  * of the reduction is 0.)
770  *
771  * The key exchange flow for J-PAKE is as follows:
772  * -# To get the first round data that needs to be sent to the peer, call
773  *    \code
774  *    // Get g1
775  *    psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
776  *    // Get the ZKP public key for x1
777  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
778  *    // Get the ZKP proof for x1
779  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
780  *    // Get g2
781  *    psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
782  *    // Get the ZKP public key for x2
783  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
784  *    // Get the ZKP proof for x2
785  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
786  *    \endcode
787  * -# To provide the first round data received from the peer to the operation,
788  *    call
789  *    \code
790  *    // Set g3
791  *    psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
792  *    // Set the ZKP public key for x3
793  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
794  *    // Set the ZKP proof for x3
795  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
796  *    // Set g4
797  *    psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
798  *    // Set the ZKP public key for x4
799  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
800  *    // Set the ZKP proof for x4
801  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
802  *    \endcode
803  * -# To get the second round data that needs to be sent to the peer, call
804  *    \code
805  *    // Get A
806  *    psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
807  *    // Get ZKP public key for x2*s
808  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
809  *    // Get ZKP proof for x2*s
810  *    psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
811  *    \endcode
812  * -# To provide the second round data received from the peer to the operation,
813  *    call
814  *    \code
815  *    // Set B
816  *    psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
817  *    // Set ZKP public key for x4*s
818  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
819  *    // Set ZKP proof for x4*s
820  *    psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
821  *    \endcode
822  * -# To access the shared secret call
823  *    \code
824  *    // Get Ka=Kb=K
825  *    psa_pake_get_implicit_key()
826  *    \endcode
827  *
828  * For more information consult the documentation of the individual
829  * \c PSA_PAKE_STEP_XXX constants.
830  *
831  * At this point there is a cryptographic guarantee that only the authenticated
832  * party who used the same password is able to compute the key. But there is no
833  * guarantee that the peer is the party it claims to be and was able to do so.
834  *
835  * That is, the authentication is only implicit (the peer is not authenticated
836  * at this point, and no action should be taken that assume that they are - like
837  * for example accessing restricted files).
838  *
839  * To make the authentication explicit there are various methods, see Section 5
840  * of RFC 8236 for two examples.
841  *
842  */
843 #define PSA_ALG_JPAKE                   ((psa_algorithm_t) 0x0a000100)
844 
845 /** @} */
846 
847 /** \defgroup pake Password-authenticated key exchange (PAKE)
848  *
849  * This is a proposed PAKE interface for the PSA Crypto API. It is not part of
850  * the official PSA Crypto API yet.
851  *
852  * \note The content of this section is not part of the stable API and ABI
853  *       of Mbed TLS and may change arbitrarily from version to version.
854  *       Same holds for the corresponding macros #PSA_ALG_CATEGORY_PAKE and
855  *       #PSA_ALG_JPAKE.
856  * @{
857  */
858 
859 /** \brief Encoding of the application role of PAKE
860  *
861  * Encodes the application's role in the algorithm is being executed. For more
862  * information see the documentation of individual \c PSA_PAKE_ROLE_XXX
863  * constants.
864  */
865 typedef uint8_t psa_pake_role_t;
866 
867 /** Encoding of input and output indicators for PAKE.
868  *
869  * Some PAKE algorithms need to exchange more data than just a single key share.
870  * This type is for encoding additional input and output data for such
871  * algorithms.
872  */
873 typedef uint8_t psa_pake_step_t;
874 
875 /** Encoding of the type of the PAKE's primitive.
876  *
877  * Values defined by this standard will never be in the range 0x80-0xff.
878  * Vendors who define additional types must use an encoding in this range.
879  *
880  * For more information see the documentation of individual
881  * \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
882  */
883 typedef uint8_t psa_pake_primitive_type_t;
884 
885 /** \brief Encoding of the family of the primitive associated with the PAKE.
886  *
887  * For more information see the documentation of individual
888  * \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
889  */
890 typedef uint8_t psa_pake_family_t;
891 
892 /** \brief Encoding of the primitive associated with the PAKE.
893  *
894  * For more information see the documentation of the #PSA_PAKE_PRIMITIVE macro.
895  */
896 typedef uint32_t psa_pake_primitive_t;
897 
898 /** A value to indicate no role in a PAKE algorithm.
899  * This value can be used in a call to psa_pake_set_role() for symmetric PAKE
900  * algorithms which do not assign roles.
901  */
902 #define PSA_PAKE_ROLE_NONE                  ((psa_pake_role_t) 0x00)
903 
904 /** The first peer in a balanced PAKE.
905  *
906  * Although balanced PAKE algorithms are symmetric, some of them needs an
907  * ordering of peers for the transcript calculations. If the algorithm does not
908  * need this, both #PSA_PAKE_ROLE_FIRST and #PSA_PAKE_ROLE_SECOND are
909  * accepted.
910  */
911 #define PSA_PAKE_ROLE_FIRST                ((psa_pake_role_t) 0x01)
912 
913 /** The second peer in a balanced PAKE.
914  *
915  * Although balanced PAKE algorithms are symmetric, some of them needs an
916  * ordering of peers for the transcript calculations. If the algorithm does not
917  * need this, either #PSA_PAKE_ROLE_FIRST or #PSA_PAKE_ROLE_SECOND are
918  * accepted.
919  */
920 #define PSA_PAKE_ROLE_SECOND                ((psa_pake_role_t) 0x02)
921 
922 /** The client in an augmented PAKE.
923  *
924  * Augmented PAKE algorithms need to differentiate between client and server.
925  */
926 #define PSA_PAKE_ROLE_CLIENT                ((psa_pake_role_t) 0x11)
927 
928 /** The server in an augmented PAKE.
929  *
930  * Augmented PAKE algorithms need to differentiate between client and server.
931  */
932 #define PSA_PAKE_ROLE_SERVER                ((psa_pake_role_t) 0x12)
933 
934 /** The PAKE primitive type indicating the use of elliptic curves.
935  *
936  * The values of the \c family and \c bits fields of the cipher suite identify a
937  * specific elliptic curve, using the same mapping that is used for ECC
938  * (::psa_ecc_family_t) keys.
939  *
940  * (Here \c family means the value returned by psa_pake_cs_get_family() and
941  * \c bits means the value returned by psa_pake_cs_get_bits().)
942  *
943  * Input and output during the operation can involve group elements and scalar
944  * values:
945  * -# The format for group elements is the same as for public keys on the
946  *  specific curve would be. For more information, consult the documentation of
947  *  psa_export_public_key().
948  * -# The format for scalars is the same as for private keys on the specific
949  *  curve would be. For more information, consult the documentation of
950  *  psa_export_key().
951  */
952 #define PSA_PAKE_PRIMITIVE_TYPE_ECC       ((psa_pake_primitive_type_t) 0x01)
953 
954 /** The PAKE primitive type indicating the use of Diffie-Hellman groups.
955  *
956  * The values of the \c family and \c bits fields of the cipher suite identify
957  * a specific Diffie-Hellman group, using the same mapping that is used for
958  * Diffie-Hellman (::psa_dh_family_t) keys.
959  *
960  * (Here \c family means the value returned by psa_pake_cs_get_family() and
961  * \c bits means the value returned by psa_pake_cs_get_bits().)
962  *
963  * Input and output during the operation can involve group elements and scalar
964  * values:
965  * -# The format for group elements is the same as for public keys on the
966  *  specific group would be. For more information, consult the documentation of
967  *  psa_export_public_key().
968  * -# The format for scalars is the same as for private keys on the specific
969  *  group would be. For more information, consult the documentation of
970  *  psa_export_key().
971  */
972 #define PSA_PAKE_PRIMITIVE_TYPE_DH       ((psa_pake_primitive_type_t) 0x02)
973 
974 /** Construct a PAKE primitive from type, family and bit-size.
975  *
976  * \param pake_type     The type of the primitive
977  *                      (value of type ::psa_pake_primitive_type_t).
978  * \param pake_family   The family of the primitive
979  *                      (the type and interpretation of this parameter depends
980  *                      on \p pake_type, for more information consult the
981  *                      documentation of individual ::psa_pake_primitive_type_t
982  *                      constants).
983  * \param pake_bits     The bit-size of the primitive
984  *                      (Value of type \c size_t. The interpretation
985  *                      of this parameter depends on \p pake_family, for more
986  *                      information consult the documentation of individual
987  *                      ::psa_pake_primitive_type_t constants).
988  *
989  * \return The constructed primitive value of type ::psa_pake_primitive_t.
990  *         Return 0 if the requested primitive can't be encoded as
991  *         ::psa_pake_primitive_t.
992  */
993 #define PSA_PAKE_PRIMITIVE(pake_type, pake_family, pake_bits) \
994     ((pake_bits & 0xFFFF) != pake_bits) ? 0 :                 \
995     ((psa_pake_primitive_t) (((pake_type) << 24 |             \
996                               (pake_family) << 16) | (pake_bits)))
997 
998 /** The key share being sent to or received from the peer.
999  *
1000  * The format for both input and output at this step is the same as for public
1001  * keys on the group determined by the primitive (::psa_pake_primitive_t) would
1002  * be.
1003  *
1004  * For more information on the format, consult the documentation of
1005  * psa_export_public_key().
1006  *
1007  * For information regarding how the group is determined, consult the
1008  * documentation #PSA_PAKE_PRIMITIVE.
1009  */
1010 #define PSA_PAKE_STEP_KEY_SHARE                 ((psa_pake_step_t) 0x01)
1011 
1012 /** A Schnorr NIZKP public key.
1013  *
1014  * This is the ephemeral public key in the Schnorr Non-Interactive
1015  * Zero-Knowledge Proof (the value denoted by the letter 'V' in RFC 8235).
1016  *
1017  * The format for both input and output at this step is the same as for public
1018  * keys on the group determined by the primitive (::psa_pake_primitive_t) would
1019  * be.
1020  *
1021  * For more information on the format, consult the documentation of
1022  * psa_export_public_key().
1023  *
1024  * For information regarding how the group is determined, consult the
1025  * documentation #PSA_PAKE_PRIMITIVE.
1026  */
1027 #define PSA_PAKE_STEP_ZK_PUBLIC                 ((psa_pake_step_t) 0x02)
1028 
1029 /** A Schnorr NIZKP proof.
1030  *
1031  * This is the proof in the Schnorr Non-Interactive Zero-Knowledge Proof (the
1032  * value denoted by the letter 'r' in RFC 8235).
1033  *
1034  * Both for input and output, the value at this step is an integer less than
1035  * the order of the group selected in the cipher suite. The format depends on
1036  * the group as well:
1037  *
1038  * - For Montgomery curves, the encoding is little endian.
1039  * - For everything else the encoding is big endian (see Section 2.3.8 of
1040  *   _SEC 1: Elliptic Curve Cryptography_ at https://www.secg.org/sec1-v2.pdf).
1041  *
1042  * In both cases leading zeroes are allowed as long as the length in bytes does
1043  * not exceed the byte length of the group order.
1044  *
1045  * For information regarding how the group is determined, consult the
1046  * documentation #PSA_PAKE_PRIMITIVE.
1047  */
1048 #define PSA_PAKE_STEP_ZK_PROOF                  ((psa_pake_step_t) 0x03)
1049 
1050 /** The type of the data structure for PAKE cipher suites.
1051  *
1052  * This is an implementation-defined \c struct. Applications should not
1053  * make any assumptions about the content of this structure.
1054  * Implementation details can change in future versions without notice.
1055  */
1056 typedef struct psa_pake_cipher_suite_s psa_pake_cipher_suite_t;
1057 
1058 /** Return an initial value for a PAKE cipher suite object.
1059  */
1060 static psa_pake_cipher_suite_t psa_pake_cipher_suite_init(void);
1061 
1062 /** Retrieve the PAKE algorithm from a PAKE cipher suite.
1063  *
1064  * \param[in] cipher_suite     The cipher suite structure to query.
1065  *
1066  * \return The PAKE algorithm stored in the cipher suite structure.
1067  */
1068 static psa_algorithm_t psa_pake_cs_get_algorithm(
1069     const psa_pake_cipher_suite_t *cipher_suite);
1070 
1071 /** Declare the PAKE algorithm for the cipher suite.
1072  *
1073  * This function overwrites any PAKE algorithm
1074  * previously set in \p cipher_suite.
1075  *
1076  * \param[out] cipher_suite    The cipher suite structure to write to.
1077  * \param algorithm            The PAKE algorithm to write.
1078  *                             (`PSA_ALG_XXX` values of type ::psa_algorithm_t
1079  *                             such that #PSA_ALG_IS_PAKE(\c alg) is true.)
1080  *                             If this is 0, the PAKE algorithm in
1081  *                             \p cipher_suite becomes unspecified.
1082  */
1083 static void psa_pake_cs_set_algorithm(psa_pake_cipher_suite_t *cipher_suite,
1084                                       psa_algorithm_t algorithm);
1085 
1086 /** Retrieve the primitive from a PAKE cipher suite.
1087  *
1088  * \param[in] cipher_suite     The cipher suite structure to query.
1089  *
1090  * \return The primitive stored in the cipher suite structure.
1091  */
1092 static psa_pake_primitive_t psa_pake_cs_get_primitive(
1093     const psa_pake_cipher_suite_t *cipher_suite);
1094 
1095 /** Declare the primitive for a PAKE cipher suite.
1096  *
1097  * This function overwrites any primitive previously set in \p cipher_suite.
1098  *
1099  * \param[out] cipher_suite    The cipher suite structure to write to.
1100  * \param primitive            The primitive to write. If this is 0, the
1101  *                             primitive type in \p cipher_suite becomes
1102  *                             unspecified.
1103  */
1104 static void psa_pake_cs_set_primitive(psa_pake_cipher_suite_t *cipher_suite,
1105                                       psa_pake_primitive_t primitive);
1106 
1107 /** Retrieve the PAKE family from a PAKE cipher suite.
1108  *
1109  * \param[in] cipher_suite     The cipher suite structure to query.
1110  *
1111  * \return The PAKE family stored in the cipher suite structure.
1112  */
1113 static psa_pake_family_t psa_pake_cs_get_family(
1114     const psa_pake_cipher_suite_t *cipher_suite);
1115 
1116 /** Retrieve the PAKE primitive bit-size from a PAKE cipher suite.
1117  *
1118  * \param[in] cipher_suite     The cipher suite structure to query.
1119  *
1120  * \return The PAKE primitive bit-size stored in the cipher suite structure.
1121  */
1122 static uint16_t psa_pake_cs_get_bits(
1123     const psa_pake_cipher_suite_t *cipher_suite);
1124 
1125 /** Retrieve the hash algorithm from a PAKE cipher suite.
1126  *
1127  * \param[in] cipher_suite      The cipher suite structure to query.
1128  *
1129  * \return The hash algorithm stored in the cipher suite structure. The return
1130  *         value is 0 if the PAKE is not parametrised by a hash algorithm or if
1131  *         the hash algorithm is not set.
1132  */
1133 static psa_algorithm_t psa_pake_cs_get_hash(
1134     const psa_pake_cipher_suite_t *cipher_suite);
1135 
1136 /** Declare the hash algorithm for a PAKE cipher suite.
1137  *
1138  * This function overwrites any hash algorithm
1139  * previously set in \p cipher_suite.
1140  *
1141  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1142  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1143  * for more information.
1144  *
1145  * \param[out] cipher_suite     The cipher suite structure to write to.
1146  * \param hash                  The hash involved in the cipher suite.
1147  *                              (`PSA_ALG_XXX` values of type ::psa_algorithm_t
1148  *                              such that #PSA_ALG_IS_HASH(\c alg) is true.)
1149  *                              If this is 0, the hash algorithm in
1150  *                              \p cipher_suite becomes unspecified.
1151  */
1152 static void psa_pake_cs_set_hash(psa_pake_cipher_suite_t *cipher_suite,
1153                                  psa_algorithm_t hash);
1154 
1155 /** The type of the state data structure for PAKE operations.
1156  *
1157  * Before calling any function on a PAKE operation object, the application
1158  * must initialize it by any of the following means:
1159  * - Set the structure to all-bits-zero, for example:
1160  *   \code
1161  *   psa_pake_operation_t operation;
1162  *   memset(&operation, 0, sizeof(operation));
1163  *   \endcode
1164  * - Initialize the structure to logical zero values, for example:
1165  *   \code
1166  *   psa_pake_operation_t operation = {0};
1167  *   \endcode
1168  * - Initialize the structure to the initializer #PSA_PAKE_OPERATION_INIT,
1169  *   for example:
1170  *   \code
1171  *   psa_pake_operation_t operation = PSA_PAKE_OPERATION_INIT;
1172  *   \endcode
1173  * - Assign the result of the function psa_pake_operation_init()
1174  *   to the structure, for example:
1175  *   \code
1176  *   psa_pake_operation_t operation;
1177  *   operation = psa_pake_operation_init();
1178  *   \endcode
1179  *
1180  * This is an implementation-defined \c struct. Applications should not
1181  * make any assumptions about the content of this structure.
1182  * Implementation details can change in future versions without notice. */
1183 typedef struct psa_pake_operation_s psa_pake_operation_t;
1184 
1185 /** The type of input values for PAKE operations. */
1186 typedef struct psa_crypto_driver_pake_inputs_s psa_crypto_driver_pake_inputs_t;
1187 
1188 /** The type of computation stage for J-PAKE operations. */
1189 typedef struct psa_jpake_computation_stage_s psa_jpake_computation_stage_t;
1190 
1191 /** Return an initial value for a PAKE operation object.
1192  */
1193 static psa_pake_operation_t psa_pake_operation_init(void);
1194 
1195 /** Get the length of the password in bytes from given inputs.
1196  *
1197  * \param[in]  inputs           Operation inputs.
1198  * \param[out] password_len     Password length.
1199  *
1200  * \retval #PSA_SUCCESS
1201  *         Success.
1202  * \retval #PSA_ERROR_BAD_STATE
1203  *         Password hasn't been set yet.
1204  */
1205 psa_status_t psa_crypto_driver_pake_get_password_len(
1206     const psa_crypto_driver_pake_inputs_t *inputs,
1207     size_t *password_len);
1208 
1209 /** Get the password from given inputs.
1210  *
1211  * \param[in]  inputs           Operation inputs.
1212  * \param[out] buffer           Return buffer for password.
1213  * \param      buffer_size      Size of the return buffer in bytes.
1214  * \param[out] buffer_length    Actual size of the password in bytes.
1215  *
1216  * \retval #PSA_SUCCESS
1217  *         Success.
1218  * \retval #PSA_ERROR_BAD_STATE
1219  *         Password hasn't been set yet.
1220  */
1221 psa_status_t psa_crypto_driver_pake_get_password(
1222     const psa_crypto_driver_pake_inputs_t *inputs,
1223     uint8_t *buffer, size_t buffer_size, size_t *buffer_length);
1224 
1225 /** Get the length of the user id in bytes from given inputs.
1226  *
1227  * \param[in]  inputs           Operation inputs.
1228  * \param[out] user_len         User id length.
1229  *
1230  * \retval #PSA_SUCCESS
1231  *         Success.
1232  * \retval #PSA_ERROR_BAD_STATE
1233  *         User id hasn't been set yet.
1234  */
1235 psa_status_t psa_crypto_driver_pake_get_user_len(
1236     const psa_crypto_driver_pake_inputs_t *inputs,
1237     size_t *user_len);
1238 
1239 /** Get the length of the peer id in bytes from given inputs.
1240  *
1241  * \param[in]  inputs           Operation inputs.
1242  * \param[out] peer_len         Peer id length.
1243  *
1244  * \retval #PSA_SUCCESS
1245  *         Success.
1246  * \retval #PSA_ERROR_BAD_STATE
1247  *         Peer id hasn't been set yet.
1248  */
1249 psa_status_t psa_crypto_driver_pake_get_peer_len(
1250     const psa_crypto_driver_pake_inputs_t *inputs,
1251     size_t *peer_len);
1252 
1253 /** Get the user id from given inputs.
1254  *
1255  * \param[in]  inputs           Operation inputs.
1256  * \param[out] user_id          User id.
1257  * \param      user_id_size     Size of \p user_id in bytes.
1258  * \param[out] user_id_len      Size of the user id in bytes.
1259  *
1260  * \retval #PSA_SUCCESS
1261  *         Success.
1262  * \retval #PSA_ERROR_BAD_STATE
1263  *         User id hasn't been set yet.
1264  * \retval #PSA_ERROR_BUFFER_TOO_SMALL
1265  *         The size of the \p user_id is too small.
1266  */
1267 psa_status_t psa_crypto_driver_pake_get_user(
1268     const psa_crypto_driver_pake_inputs_t *inputs,
1269     uint8_t *user_id, size_t user_id_size, size_t *user_id_len);
1270 
1271 /** Get the peer id from given inputs.
1272  *
1273  * \param[in]  inputs           Operation inputs.
1274  * \param[out] peer_id          Peer id.
1275  * \param      peer_id_size     Size of \p peer_id in bytes.
1276  * \param[out] peer_id_length   Size of the peer id in bytes.
1277  *
1278  * \retval #PSA_SUCCESS
1279  *         Success.
1280  * \retval #PSA_ERROR_BAD_STATE
1281  *         Peer id hasn't been set yet.
1282  * \retval #PSA_ERROR_BUFFER_TOO_SMALL
1283  *         The size of the \p peer_id is too small.
1284  */
1285 psa_status_t psa_crypto_driver_pake_get_peer(
1286     const psa_crypto_driver_pake_inputs_t *inputs,
1287     uint8_t *peer_id, size_t peer_id_size, size_t *peer_id_length);
1288 
1289 /** Get the cipher suite from given inputs.
1290  *
1291  * \param[in]  inputs           Operation inputs.
1292  * \param[out] cipher_suite     Return buffer for role.
1293  *
1294  * \retval #PSA_SUCCESS
1295  *         Success.
1296  * \retval #PSA_ERROR_BAD_STATE
1297  *         Cipher_suite hasn't been set yet.
1298  */
1299 psa_status_t psa_crypto_driver_pake_get_cipher_suite(
1300     const psa_crypto_driver_pake_inputs_t *inputs,
1301     psa_pake_cipher_suite_t *cipher_suite);
1302 
1303 /** Set the session information for a password-authenticated key exchange.
1304  *
1305  * The sequence of operations to set up a password-authenticated key exchange
1306  * is as follows:
1307  * -# Allocate an operation object which will be passed to all the functions
1308  *    listed here.
1309  * -# Initialize the operation object with one of the methods described in the
1310  *    documentation for #psa_pake_operation_t, e.g.
1311  *    #PSA_PAKE_OPERATION_INIT.
1312  * -# Call psa_pake_setup() to specify the cipher suite.
1313  * -# Call \c psa_pake_set_xxx() functions on the operation to complete the
1314  *    setup. The exact sequence of \c psa_pake_set_xxx() functions that needs
1315  *    to be called depends on the algorithm in use.
1316  *
1317  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1318  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1319  * for more information.
1320  *
1321  * A typical sequence of calls to perform a password-authenticated key
1322  * exchange:
1323  * -# Call psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...) to get the
1324  *    key share that needs to be sent to the peer.
1325  * -# Call psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...) to provide
1326  *    the key share that was received from the peer.
1327  * -# Depending on the algorithm additional calls to psa_pake_output() and
1328  *    psa_pake_input() might be necessary.
1329  * -# Call psa_pake_get_implicit_key() for accessing the shared secret.
1330  *
1331  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1332  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1333  * for more information.
1334  *
1335  * If an error occurs at any step after a call to psa_pake_setup(),
1336  * the operation will need to be reset by a call to psa_pake_abort(). The
1337  * application may call psa_pake_abort() at any time after the operation
1338  * has been initialized.
1339  *
1340  * After a successful call to psa_pake_setup(), the application must
1341  * eventually terminate the operation. The following events terminate an
1342  * operation:
1343  * - A call to psa_pake_abort().
1344  * - A successful call to psa_pake_get_implicit_key().
1345  *
1346  * \param[in,out] operation     The operation object to set up. It must have
1347  *                              been initialized but not set up yet.
1348  * \param[in] cipher_suite      The cipher suite to use. (A cipher suite fully
1349  *                              characterizes a PAKE algorithm and determines
1350  *                              the algorithm as well.)
1351  *
1352  * \retval #PSA_SUCCESS
1353  *         Success.
1354  * \retval #PSA_ERROR_INVALID_ARGUMENT
1355  *         The algorithm in \p cipher_suite is not a PAKE algorithm, or the
1356  *         PAKE primitive in \p cipher_suite is not compatible with the
1357  *         PAKE algorithm, or the hash algorithm in \p cipher_suite is invalid
1358  *         or not compatible with the PAKE algorithm and primitive.
1359  * \retval #PSA_ERROR_NOT_SUPPORTED
1360  *         The algorithm in \p cipher_suite is not a supported PAKE algorithm,
1361  *         or the PAKE primitive in \p cipher_suite is not supported or not
1362  *         compatible with the PAKE algorithm, or the hash algorithm in
1363  *         \p cipher_suite is not supported or not compatible with the PAKE
1364  *         algorithm and primitive.
1365  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1366  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1367  * \retval #PSA_ERROR_BAD_STATE
1368  *         The operation state is not valid, or
1369  *         the library has not been previously initialized by psa_crypto_init().
1370  *         It is implementation-dependent whether a failure to initialize
1371  *         results in this error code.
1372  */
1373 psa_status_t psa_pake_setup(psa_pake_operation_t *operation,
1374                             const psa_pake_cipher_suite_t *cipher_suite);
1375 
1376 /** Set the password for a password-authenticated key exchange from key ID.
1377  *
1378  * Call this function when the password, or a value derived from the password,
1379  * is already present in the key store.
1380  *
1381  * \param[in,out] operation     The operation object to set the password for. It
1382  *                              must have been set up by psa_pake_setup() and
1383  *                              not yet in use (neither psa_pake_output() nor
1384  *                              psa_pake_input() has been called yet). It must
1385  *                              be on operation for which the password hasn't
1386  *                              been set yet (psa_pake_set_password_key()
1387  *                              hasn't been called yet).
1388  * \param password              Identifier of the key holding the password or a
1389  *                              value derived from the password (eg. by a
1390  *                              memory-hard function).  It must remain valid
1391  *                              until the operation terminates. It must be of
1392  *                              type #PSA_KEY_TYPE_PASSWORD or
1393  *                              #PSA_KEY_TYPE_PASSWORD_HASH. It has to allow
1394  *                              the usage #PSA_KEY_USAGE_DERIVE.
1395  *
1396  * \retval #PSA_SUCCESS
1397  *         Success.
1398  * \retval #PSA_ERROR_INVALID_HANDLE
1399  *         \p password is not a valid key identifier.
1400  * \retval #PSA_ERROR_NOT_PERMITTED
1401  *         The key does not have the #PSA_KEY_USAGE_DERIVE flag, or it does not
1402  *         permit the \p operation's algorithm.
1403  * \retval #PSA_ERROR_INVALID_ARGUMENT
1404  *         The key type for \p password is not #PSA_KEY_TYPE_PASSWORD or
1405  *         #PSA_KEY_TYPE_PASSWORD_HASH, or \p password is not compatible with
1406  *         the \p operation's cipher suite.
1407  * \retval #PSA_ERROR_NOT_SUPPORTED
1408  *         The key type or key size of \p password is not supported with the
1409  *         \p operation's cipher suite.
1410  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1411  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1412  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1413  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1414  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1415  * \retval #PSA_ERROR_BAD_STATE
1416  *         The operation state is not valid (it must have been set up.), or
1417  *         the library has not been previously initialized by psa_crypto_init().
1418  *         It is implementation-dependent whether a failure to initialize
1419  *         results in this error code.
1420  */
1421 psa_status_t psa_pake_set_password_key(psa_pake_operation_t *operation,
1422                                        mbedtls_svc_key_id_t password);
1423 
1424 /** Set the user ID for a password-authenticated key exchange.
1425  *
1426  * Call this function to set the user ID. For PAKE algorithms that associate a
1427  * user identifier with each side of the session you need to call
1428  * psa_pake_set_peer() as well. For PAKE algorithms that associate a single
1429  * user identifier with the session, call psa_pake_set_user() only.
1430  *
1431  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1432  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1433  * for more information.
1434  *
1435  * \param[in,out] operation     The operation object to set the user ID for. It
1436  *                              must have been set up by psa_pake_setup() and
1437  *                              not yet in use (neither psa_pake_output() nor
1438  *                              psa_pake_input() has been called yet). It must
1439  *                              be on operation for which the user ID hasn't
1440  *                              been set (psa_pake_set_user() hasn't been
1441  *                              called yet).
1442  * \param[in] user_id           The user ID to authenticate with.
1443  * \param user_id_len           Size of the \p user_id buffer in bytes.
1444  *
1445  * \retval #PSA_SUCCESS
1446  *         Success.
1447  * \retval #PSA_ERROR_INVALID_ARGUMENT
1448  *         \p user_id is not valid for the \p operation's algorithm and cipher
1449  *         suite.
1450  * \retval #PSA_ERROR_NOT_SUPPORTED
1451  *         The value of \p user_id is not supported by the implementation.
1452  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1453  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1454  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1455  * \retval #PSA_ERROR_BAD_STATE
1456  *         The operation state is not valid, or
1457  *         the library has not been previously initialized by psa_crypto_init().
1458  *         It is implementation-dependent whether a failure to initialize
1459  *         results in this error code.
1460  */
1461 psa_status_t psa_pake_set_user(psa_pake_operation_t *operation,
1462                                const uint8_t *user_id,
1463                                size_t user_id_len);
1464 
1465 /** Set the peer ID for a password-authenticated key exchange.
1466  *
1467  * Call this function in addition to psa_pake_set_user() for PAKE algorithms
1468  * that associate a user identifier with each side of the session. For PAKE
1469  * algorithms that associate a single user identifier with the session, call
1470  * psa_pake_set_user() only.
1471  *
1472  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1473  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1474  * for more information.
1475  *
1476  * \param[in,out] operation     The operation object to set the peer ID for. It
1477  *                              must have been set up by psa_pake_setup() and
1478  *                              not yet in use (neither psa_pake_output() nor
1479  *                              psa_pake_input() has been called yet). It must
1480  *                              be on operation for which the peer ID hasn't
1481  *                              been set (psa_pake_set_peer() hasn't been
1482  *                              called yet).
1483  * \param[in] peer_id           The peer's ID to authenticate.
1484  * \param peer_id_len           Size of the \p peer_id buffer in bytes.
1485  *
1486  * \retval #PSA_SUCCESS
1487  *         Success.
1488  * \retval #PSA_ERROR_INVALID_ARGUMENT
1489  *         \p peer_id is not valid for the \p operation's algorithm and cipher
1490  *         suite.
1491  * \retval #PSA_ERROR_NOT_SUPPORTED
1492  *         The algorithm doesn't associate a second identity with the session.
1493  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1494  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1495  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1496  * \retval #PSA_ERROR_BAD_STATE
1497  *         Calling psa_pake_set_peer() is invalid with the \p operation's
1498  *         algorithm, the operation state is not valid, or the library has not
1499  *         been previously initialized by psa_crypto_init().
1500  *         It is implementation-dependent whether a failure to initialize
1501  *         results in this error code.
1502  */
1503 psa_status_t psa_pake_set_peer(psa_pake_operation_t *operation,
1504                                const uint8_t *peer_id,
1505                                size_t peer_id_len);
1506 
1507 /** Set the application role for a password-authenticated key exchange.
1508  *
1509  * Not all PAKE algorithms need to differentiate the communicating entities.
1510  * It is optional to call this function for PAKEs that don't require a role
1511  * to be specified. For such PAKEs the application role parameter is ignored,
1512  * or #PSA_PAKE_ROLE_NONE can be passed as \c role.
1513  *
1514  * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
1515  * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
1516  * for more information.
1517  *
1518  * \param[in,out] operation     The operation object to specify the
1519  *                              application's role for. It must have been set up
1520  *                              by psa_pake_setup() and not yet in use (neither
1521  *                              psa_pake_output() nor psa_pake_input() has been
1522  *                              called yet). It must be on operation for which
1523  *                              the application's role hasn't been specified
1524  *                              (psa_pake_set_role() hasn't been called yet).
1525  * \param role                  A value of type ::psa_pake_role_t indicating the
1526  *                              application's role in the PAKE the algorithm
1527  *                              that is being set up. For more information see
1528  *                              the documentation of \c PSA_PAKE_ROLE_XXX
1529  *                              constants.
1530  *
1531  * \retval #PSA_SUCCESS
1532  *         Success.
1533  * \retval #PSA_ERROR_INVALID_ARGUMENT
1534  *         The \p role is not a valid PAKE role in the \p operation’s algorithm.
1535  * \retval #PSA_ERROR_NOT_SUPPORTED
1536  *         The \p role for this algorithm is not supported or is not valid.
1537  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1538  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1539  * \retval #PSA_ERROR_BAD_STATE
1540  *         The operation state is not valid, or
1541  *         the library has not been previously initialized by psa_crypto_init().
1542  *         It is implementation-dependent whether a failure to initialize
1543  *         results in this error code.
1544  */
1545 psa_status_t psa_pake_set_role(psa_pake_operation_t *operation,
1546                                psa_pake_role_t role);
1547 
1548 /** Get output for a step of a password-authenticated key exchange.
1549  *
1550  * Depending on the algorithm being executed, you might need to call this
1551  * function several times or you might not need to call this at all.
1552  *
1553  * The exact sequence of calls to perform a password-authenticated key
1554  * exchange depends on the algorithm in use.  Refer to the documentation of
1555  * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
1556  * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
1557  * information.
1558  *
1559  * If this function returns an error status, the operation enters an error
1560  * state and must be aborted by calling psa_pake_abort().
1561  *
1562  * \param[in,out] operation    Active PAKE operation.
1563  * \param step                 The step of the algorithm for which the output is
1564  *                             requested.
1565  * \param[out] output          Buffer where the output is to be written in the
1566  *                             format appropriate for this \p step. Refer to
1567  *                             the documentation of the individual
1568  *                             \c PSA_PAKE_STEP_XXX constants for more
1569  *                             information.
1570  * \param output_size          Size of the \p output buffer in bytes. This must
1571  *                             be at least #PSA_PAKE_OUTPUT_SIZE(\c alg, \c
1572  *                             primitive, \p output_step) where \c alg and
1573  *                             \p primitive are the PAKE algorithm and primitive
1574  *                             in the operation's cipher suite, and \p step is
1575  *                             the output step.
1576  *
1577  * \param[out] output_length   On success, the number of bytes of the returned
1578  *                             output.
1579  *
1580  * \retval #PSA_SUCCESS
1581  *         Success.
1582  * \retval #PSA_ERROR_BUFFER_TOO_SMALL
1583  *         The size of the \p output buffer is too small.
1584  * \retval #PSA_ERROR_INVALID_ARGUMENT
1585  *         \p step is not compatible with the operation's algorithm.
1586  * \retval #PSA_ERROR_NOT_SUPPORTED
1587  *         \p step is not supported with the operation's algorithm.
1588  * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
1589  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1590  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1591  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1592  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1593  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1594  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1595  * \retval #PSA_ERROR_BAD_STATE
1596  *         The operation state is not valid (it must be active, and fully set
1597  *         up, and this call must conform to the algorithm's requirements
1598  *         for ordering of input and output steps), or
1599  *         the library has not been previously initialized by psa_crypto_init().
1600  *         It is implementation-dependent whether a failure to initialize
1601  *         results in this error code.
1602  */
1603 psa_status_t psa_pake_output(psa_pake_operation_t *operation,
1604                              psa_pake_step_t step,
1605                              uint8_t *output,
1606                              size_t output_size,
1607                              size_t *output_length);
1608 
1609 /** Provide input for a step of a password-authenticated key exchange.
1610  *
1611  * Depending on the algorithm being executed, you might need to call this
1612  * function several times or you might not need to call this at all.
1613  *
1614  * The exact sequence of calls to perform a password-authenticated key
1615  * exchange depends on the algorithm in use.  Refer to the documentation of
1616  * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
1617  * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
1618  * information.
1619  *
1620  * If this function returns an error status, the operation enters an error
1621  * state and must be aborted by calling psa_pake_abort().
1622  *
1623  * \param[in,out] operation    Active PAKE operation.
1624  * \param step                 The step for which the input is provided.
1625  * \param[in] input            Buffer containing the input in the format
1626  *                             appropriate for this \p step. Refer to the
1627  *                             documentation of the individual
1628  *                             \c PSA_PAKE_STEP_XXX constants for more
1629  *                             information.
1630  * \param input_length         Size of the \p input buffer in bytes.
1631  *
1632  * \retval #PSA_SUCCESS
1633  *         Success.
1634  * \retval #PSA_ERROR_INVALID_SIGNATURE
1635  *         The verification fails for a #PSA_PAKE_STEP_ZK_PROOF input step.
1636  * \retval #PSA_ERROR_INVALID_ARGUMENT
1637  *         \p input_length is not compatible with the \p operation’s algorithm,
1638  *         or the \p input is not valid for the \p operation's algorithm,
1639  *         cipher suite or \p step.
1640  * \retval #PSA_ERROR_NOT_SUPPORTED
1641  *         \p step p is not supported with the \p operation's algorithm, or the
1642  *         \p input is not supported for the \p operation's algorithm, cipher
1643  *         suite or \p step.
1644  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1645  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1646  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1647  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1648  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1649  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1650  * \retval #PSA_ERROR_BAD_STATE
1651  *         The operation state is not valid (it must be active, and fully set
1652  *         up, and this call must conform to the algorithm's requirements
1653  *         for ordering of input and output steps), or
1654  *         the library has not been previously initialized by psa_crypto_init().
1655  *         It is implementation-dependent whether a failure to initialize
1656  *         results in this error code.
1657  */
1658 psa_status_t psa_pake_input(psa_pake_operation_t *operation,
1659                             psa_pake_step_t step,
1660                             const uint8_t *input,
1661                             size_t input_length);
1662 
1663 /** Get implicitly confirmed shared secret from a PAKE.
1664  *
1665  * At this point there is a cryptographic guarantee that only the authenticated
1666  * party who used the same password is able to compute the key. But there is no
1667  * guarantee that the peer is the party it claims to be and was able to do so.
1668  *
1669  * That is, the authentication is only implicit. Since the peer is not
1670  * authenticated yet, no action should be taken yet that assumes that the peer
1671  * is who it claims to be. For example, do not access restricted files on the
1672  * peer's behalf until an explicit authentication has succeeded.
1673  *
1674  * This function can be called after the key exchange phase of the operation
1675  * has completed. It imports the shared secret output of the PAKE into the
1676  * provided derivation operation. The input step
1677  * #PSA_KEY_DERIVATION_INPUT_SECRET is used when placing the shared key
1678  * material in the key derivation operation.
1679  *
1680  * The exact sequence of calls to perform a password-authenticated key
1681  * exchange depends on the algorithm in use.  Refer to the documentation of
1682  * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
1683  * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
1684  * information.
1685  *
1686  * When this function returns successfully, \p operation becomes inactive.
1687  * If this function returns an error status, both \p operation
1688  * and \c key_derivation operations enter an error state and must be aborted by
1689  * calling psa_pake_abort() and psa_key_derivation_abort() respectively.
1690  *
1691  * \param[in,out] operation    Active PAKE operation.
1692  * \param[out] output          A key derivation operation that is ready
1693  *                             for an input step of type
1694  *                             #PSA_KEY_DERIVATION_INPUT_SECRET.
1695  *
1696  * \retval #PSA_SUCCESS
1697  *         Success.
1698  * \retval #PSA_ERROR_INVALID_ARGUMENT
1699  *         #PSA_KEY_DERIVATION_INPUT_SECRET is not compatible with the
1700  *         algorithm in the \p output key derivation operation.
1701  * \retval #PSA_ERROR_NOT_SUPPORTED
1702  *         Input from a PAKE is not supported by the algorithm in the \p output
1703  *         key derivation operation.
1704  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1705  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1706  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1707  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1708  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1709  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1710  * \retval #PSA_ERROR_BAD_STATE
1711  *         The PAKE operation state is not valid (it must be active, but beyond
1712  *         that validity is specific to the algorithm), or
1713  *         the library has not been previously initialized by psa_crypto_init(),
1714  *         or the state of \p output is not valid for
1715  *         the #PSA_KEY_DERIVATION_INPUT_SECRET step. This can happen if the
1716  *         step is out of order or the application has done this step already
1717  *         and it may not be repeated.
1718  *         It is implementation-dependent whether a failure to initialize
1719  *         results in this error code.
1720  */
1721 psa_status_t psa_pake_get_implicit_key(psa_pake_operation_t *operation,
1722                                        psa_key_derivation_operation_t *output);
1723 
1724 /** Abort a PAKE operation.
1725  *
1726  * Aborting an operation frees all associated resources except for the \c
1727  * operation structure itself. Once aborted, the operation object can be reused
1728  * for another operation by calling psa_pake_setup() again.
1729  *
1730  * This function may be called at any time after the operation
1731  * object has been initialized as described in #psa_pake_operation_t.
1732  *
1733  * In particular, calling psa_pake_abort() after the operation has been
1734  * terminated by a call to psa_pake_abort() or psa_pake_get_implicit_key()
1735  * is safe and has no effect.
1736  *
1737  * \param[in,out] operation    The operation to abort.
1738  *
1739  * \retval #PSA_SUCCESS
1740  *         Success.
1741  * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
1742  * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
1743  * \retval #PSA_ERROR_BAD_STATE
1744  *         The library has not been previously initialized by psa_crypto_init().
1745  *         It is implementation-dependent whether a failure to initialize
1746  *         results in this error code.
1747  */
1748 psa_status_t psa_pake_abort(psa_pake_operation_t *operation);
1749 
1750 /**@}*/
1751 
1752 /** A sufficient output buffer size for psa_pake_output().
1753  *
1754  * If the size of the output buffer is at least this large, it is guaranteed
1755  * that psa_pake_output() will not fail due to an insufficient output buffer
1756  * size. The actual size of the output might be smaller in any given call.
1757  *
1758  * See also #PSA_PAKE_OUTPUT_MAX_SIZE
1759  *
1760  * \param alg           A PAKE algorithm (\c PSA_ALG_XXX value such that
1761  *                      #PSA_ALG_IS_PAKE(\p alg) is true).
1762  * \param primitive     A primitive of type ::psa_pake_primitive_t that is
1763  *                      compatible with algorithm \p alg.
1764  * \param output_step   A value of type ::psa_pake_step_t that is valid for the
1765  *                      algorithm \p alg.
1766  * \return              A sufficient output buffer size for the specified
1767  *                      PAKE algorithm, primitive, and output step. If the
1768  *                      PAKE algorithm, primitive, or output step is not
1769  *                      recognized, or the parameters are incompatible,
1770  *                      return 0.
1771  */
1772 #define PSA_PAKE_OUTPUT_SIZE(alg, primitive, output_step)               \
1773     (alg == PSA_ALG_JPAKE &&                                           \
1774      primitive == PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC,      \
1775                                      PSA_ECC_FAMILY_SECP_R1, 256) ?    \
1776      (                                                                 \
1777          output_step == PSA_PAKE_STEP_KEY_SHARE ? 65 :                   \
1778          output_step == PSA_PAKE_STEP_ZK_PUBLIC ? 65 :                   \
1779          32                                                              \
1780      ) :                                                               \
1781      0)
1782 
1783 /** A sufficient input buffer size for psa_pake_input().
1784  *
1785  * The value returned by this macro is guaranteed to be large enough for any
1786  * valid input to psa_pake_input() in an operation with the specified
1787  * parameters.
1788  *
1789  * See also #PSA_PAKE_INPUT_MAX_SIZE
1790  *
1791  * \param alg           A PAKE algorithm (\c PSA_ALG_XXX value such that
1792  *                      #PSA_ALG_IS_PAKE(\p alg) is true).
1793  * \param primitive     A primitive of type ::psa_pake_primitive_t that is
1794  *                      compatible with algorithm \p alg.
1795  * \param input_step    A value of type ::psa_pake_step_t that is valid for the
1796  *                      algorithm \p alg.
1797  * \return              A sufficient input buffer size for the specified
1798  *                      input, cipher suite and algorithm. If the cipher suite,
1799  *                      the input type or PAKE algorithm is not recognized, or
1800  *                      the parameters are incompatible, return 0.
1801  */
1802 #define PSA_PAKE_INPUT_SIZE(alg, primitive, input_step)                 \
1803     (alg == PSA_ALG_JPAKE &&                                           \
1804      primitive == PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC,      \
1805                                      PSA_ECC_FAMILY_SECP_R1, 256) ?    \
1806      (                                                                 \
1807          input_step == PSA_PAKE_STEP_KEY_SHARE ? 65 :                    \
1808          input_step == PSA_PAKE_STEP_ZK_PUBLIC ? 65 :                    \
1809          32                                                              \
1810      ) :                                                               \
1811      0)
1812 
1813 /** Output buffer size for psa_pake_output() for any of the supported PAKE
1814  * algorithm and primitive suites and output step.
1815  *
1816  * This macro must expand to a compile-time constant integer.
1817  *
1818  * The value of this macro must be at least as large as the largest value
1819  * returned by PSA_PAKE_OUTPUT_SIZE()
1820  *
1821  * See also #PSA_PAKE_OUTPUT_SIZE(\p alg, \p primitive, \p output_step).
1822  */
1823 #define PSA_PAKE_OUTPUT_MAX_SIZE 65
1824 
1825 /** Input buffer size for psa_pake_input() for any of the supported PAKE
1826  * algorithm and primitive suites and input step.
1827  *
1828  * This macro must expand to a compile-time constant integer.
1829  *
1830  * The value of this macro must be at least as large as the largest value
1831  * returned by PSA_PAKE_INPUT_SIZE()
1832  *
1833  * See also #PSA_PAKE_INPUT_SIZE(\p alg, \p primitive, \p output_step).
1834  */
1835 #define PSA_PAKE_INPUT_MAX_SIZE 65
1836 
1837 /** Returns a suitable initializer for a PAKE cipher suite object of type
1838  * psa_pake_cipher_suite_t.
1839  */
1840 #define PSA_PAKE_CIPHER_SUITE_INIT { PSA_ALG_NONE, 0, 0, 0, PSA_ALG_NONE }
1841 
1842 /** Returns a suitable initializer for a PAKE operation object of type
1843  * psa_pake_operation_t.
1844  */
1845 #define PSA_PAKE_OPERATION_INIT { 0, PSA_ALG_NONE, 0, PSA_PAKE_OPERATION_STAGE_SETUP, \
1846                                   { 0 }, { { 0 } } }
1847 
1848 struct psa_pake_cipher_suite_s {
1849     psa_algorithm_t algorithm;
1850     psa_pake_primitive_type_t type;
1851     psa_pake_family_t family;
1852     uint16_t  bits;
1853     psa_algorithm_t hash;
1854 };
1855 
psa_pake_cs_get_algorithm(const psa_pake_cipher_suite_t * cipher_suite)1856 static inline psa_algorithm_t psa_pake_cs_get_algorithm(
1857     const psa_pake_cipher_suite_t *cipher_suite)
1858 {
1859     return cipher_suite->algorithm;
1860 }
1861 
psa_pake_cs_set_algorithm(psa_pake_cipher_suite_t * cipher_suite,psa_algorithm_t algorithm)1862 static inline void psa_pake_cs_set_algorithm(
1863     psa_pake_cipher_suite_t *cipher_suite,
1864     psa_algorithm_t algorithm)
1865 {
1866     if (!PSA_ALG_IS_PAKE(algorithm)) {
1867         cipher_suite->algorithm = 0;
1868     } else {
1869         cipher_suite->algorithm = algorithm;
1870     }
1871 }
1872 
psa_pake_cs_get_primitive(const psa_pake_cipher_suite_t * cipher_suite)1873 static inline psa_pake_primitive_t psa_pake_cs_get_primitive(
1874     const psa_pake_cipher_suite_t *cipher_suite)
1875 {
1876     return PSA_PAKE_PRIMITIVE(cipher_suite->type, cipher_suite->family,
1877                               cipher_suite->bits);
1878 }
1879 
psa_pake_cs_set_primitive(psa_pake_cipher_suite_t * cipher_suite,psa_pake_primitive_t primitive)1880 static inline void psa_pake_cs_set_primitive(
1881     psa_pake_cipher_suite_t *cipher_suite,
1882     psa_pake_primitive_t primitive)
1883 {
1884     cipher_suite->type = (psa_pake_primitive_type_t) (primitive >> 24);
1885     cipher_suite->family = (psa_pake_family_t) (0xFF & (primitive >> 16));
1886     cipher_suite->bits = (uint16_t) (0xFFFF & primitive);
1887 }
1888 
psa_pake_cs_get_family(const psa_pake_cipher_suite_t * cipher_suite)1889 static inline psa_pake_family_t psa_pake_cs_get_family(
1890     const psa_pake_cipher_suite_t *cipher_suite)
1891 {
1892     return cipher_suite->family;
1893 }
1894 
psa_pake_cs_get_bits(const psa_pake_cipher_suite_t * cipher_suite)1895 static inline uint16_t psa_pake_cs_get_bits(
1896     const psa_pake_cipher_suite_t *cipher_suite)
1897 {
1898     return cipher_suite->bits;
1899 }
1900 
psa_pake_cs_get_hash(const psa_pake_cipher_suite_t * cipher_suite)1901 static inline psa_algorithm_t psa_pake_cs_get_hash(
1902     const psa_pake_cipher_suite_t *cipher_suite)
1903 {
1904     return cipher_suite->hash;
1905 }
1906 
psa_pake_cs_set_hash(psa_pake_cipher_suite_t * cipher_suite,psa_algorithm_t hash)1907 static inline void psa_pake_cs_set_hash(psa_pake_cipher_suite_t *cipher_suite,
1908                                         psa_algorithm_t hash)
1909 {
1910     if (!PSA_ALG_IS_HASH(hash)) {
1911         cipher_suite->hash = 0;
1912     } else {
1913         cipher_suite->hash = hash;
1914     }
1915 }
1916 
1917 struct psa_crypto_driver_pake_inputs_s {
1918     uint8_t *MBEDTLS_PRIVATE(password);
1919     size_t MBEDTLS_PRIVATE(password_len);
1920     uint8_t *MBEDTLS_PRIVATE(user);
1921     size_t MBEDTLS_PRIVATE(user_len);
1922     uint8_t *MBEDTLS_PRIVATE(peer);
1923     size_t MBEDTLS_PRIVATE(peer_len);
1924     psa_key_attributes_t MBEDTLS_PRIVATE(attributes);
1925     psa_pake_cipher_suite_t MBEDTLS_PRIVATE(cipher_suite);
1926 };
1927 
1928 typedef enum psa_crypto_driver_pake_step {
1929     PSA_JPAKE_STEP_INVALID        = 0,  /* Invalid step */
1930     PSA_JPAKE_X1_STEP_KEY_SHARE   = 1,  /* Round 1: input/output key share (for ephemeral private key X1).*/
1931     PSA_JPAKE_X1_STEP_ZK_PUBLIC   = 2,  /* Round 1: input/output Schnorr NIZKP public key for the X1 key */
1932     PSA_JPAKE_X1_STEP_ZK_PROOF    = 3,  /* Round 1: input/output Schnorr NIZKP proof for the X1 key */
1933     PSA_JPAKE_X2_STEP_KEY_SHARE   = 4,  /* Round 1: input/output key share (for ephemeral private key X2).*/
1934     PSA_JPAKE_X2_STEP_ZK_PUBLIC   = 5,  /* Round 1: input/output Schnorr NIZKP public key for the X2 key */
1935     PSA_JPAKE_X2_STEP_ZK_PROOF    = 6,  /* Round 1: input/output Schnorr NIZKP proof for the X2 key */
1936     PSA_JPAKE_X2S_STEP_KEY_SHARE  = 7,  /* Round 2: output X2S key (our key) */
1937     PSA_JPAKE_X2S_STEP_ZK_PUBLIC  = 8,  /* Round 2: output Schnorr NIZKP public key for the X2S key (our key) */
1938     PSA_JPAKE_X2S_STEP_ZK_PROOF   = 9,  /* Round 2: output Schnorr NIZKP proof for the X2S key (our key) */
1939     PSA_JPAKE_X4S_STEP_KEY_SHARE  = 10, /* Round 2: input X4S key (from peer) */
1940     PSA_JPAKE_X4S_STEP_ZK_PUBLIC  = 11, /* Round 2: input Schnorr NIZKP public key for the X4S key (from peer) */
1941     PSA_JPAKE_X4S_STEP_ZK_PROOF   = 12  /* Round 2: input Schnorr NIZKP proof for the X4S key (from peer) */
1942 } psa_crypto_driver_pake_step_t;
1943 
1944 typedef enum psa_jpake_round {
1945     PSA_JPAKE_FIRST = 0,
1946     PSA_JPAKE_SECOND = 1,
1947     PSA_JPAKE_FINISHED = 2
1948 } psa_jpake_round_t;
1949 
1950 typedef enum psa_jpake_io_mode {
1951     PSA_JPAKE_INPUT = 0,
1952     PSA_JPAKE_OUTPUT = 1
1953 } psa_jpake_io_mode_t;
1954 
1955 struct psa_jpake_computation_stage_s {
1956     /* The J-PAKE round we are currently on */
1957     psa_jpake_round_t MBEDTLS_PRIVATE(round);
1958     /* The 'mode' we are currently in (inputting or outputting) */
1959     psa_jpake_io_mode_t MBEDTLS_PRIVATE(io_mode);
1960     /* The number of completed inputs so far this round */
1961     uint8_t MBEDTLS_PRIVATE(inputs);
1962     /* The number of completed outputs so far this round */
1963     uint8_t MBEDTLS_PRIVATE(outputs);
1964     /* The next expected step (KEY_SHARE, ZK_PUBLIC or ZK_PROOF) */
1965     psa_pake_step_t MBEDTLS_PRIVATE(step);
1966 };
1967 
1968 #define PSA_JPAKE_EXPECTED_INPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
1969                                           ((round) == PSA_JPAKE_FIRST ? 2 : 1))
1970 #define PSA_JPAKE_EXPECTED_OUTPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
1971                                            ((round) == PSA_JPAKE_FIRST ? 2 : 1))
1972 
1973 struct psa_pake_operation_s {
1974     /** Unique ID indicating which driver got assigned to do the
1975      * operation. Since driver contexts are driver-specific, swapping
1976      * drivers halfway through the operation is not supported.
1977      * ID values are auto-generated in psa_crypto_driver_wrappers.h
1978      * ID value zero means the context is not valid or not assigned to
1979      * any driver (i.e. none of the driver contexts are active). */
1980     unsigned int MBEDTLS_PRIVATE(id);
1981     /* Algorithm of the PAKE operation */
1982     psa_algorithm_t MBEDTLS_PRIVATE(alg);
1983     /* A primitive of type compatible with algorithm */
1984     psa_pake_primitive_t MBEDTLS_PRIVATE(primitive);
1985     /* Stage of the PAKE operation: waiting for the setup, collecting inputs
1986      * or computing. */
1987     uint8_t MBEDTLS_PRIVATE(stage);
1988     /* Holds computation stage of the PAKE algorithms. */
1989     union {
1990         uint8_t MBEDTLS_PRIVATE(dummy);
1991 #if defined(PSA_WANT_ALG_JPAKE)
1992         psa_jpake_computation_stage_t MBEDTLS_PRIVATE(jpake);
1993 #endif
1994     } MBEDTLS_PRIVATE(computation_stage);
1995     union {
1996         psa_driver_pake_context_t MBEDTLS_PRIVATE(ctx);
1997         psa_crypto_driver_pake_inputs_t MBEDTLS_PRIVATE(inputs);
1998     } MBEDTLS_PRIVATE(data);
1999 };
2000 
psa_pake_cipher_suite_init(void)2001 static inline struct psa_pake_cipher_suite_s psa_pake_cipher_suite_init(void)
2002 {
2003     const struct psa_pake_cipher_suite_s v = PSA_PAKE_CIPHER_SUITE_INIT;
2004     return v;
2005 }
2006 
psa_pake_operation_init(void)2007 static inline struct psa_pake_operation_s psa_pake_operation_init(void)
2008 {
2009     const struct psa_pake_operation_s v = PSA_PAKE_OPERATION_INIT;
2010     return v;
2011 }
2012 
2013 #ifdef __cplusplus
2014 }
2015 #endif
2016 
2017 #endif /* PSA_CRYPTO_EXTRA_H */
2018