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