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