1 /**
2  * \file ecdh.h
3  *
4  * \brief This file contains ECDH definitions and functions.
5  *
6  * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous
7  * key agreement protocol allowing two parties to establish a shared
8  * secret over an insecure channel. Each party must have an
9  * elliptic-curve public–private key pair.
10  *
11  * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for
12  * Pair-Wise Key Establishment Schemes Using Discrete Logarithm
13  * Cryptography</em>.
14  */
15 /*
16  *  Copyright The Mbed TLS Contributors
17  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
18  */
19 
20 #ifndef MBEDTLS_ECDH_H
21 #define MBEDTLS_ECDH_H
22 #include "mbedtls/private_access.h"
23 
24 #include "mbedtls/build_info.h"
25 
26 #include "mbedtls/ecp.h"
27 
28 /*
29  * Mbed TLS supports two formats for ECDH contexts (#mbedtls_ecdh_context
30  * defined in `ecdh.h`). For most applications, the choice of format makes
31  * no difference, since all library functions can work with either format,
32  * except that the new format is incompatible with MBEDTLS_ECP_RESTARTABLE.
33 
34  * The new format used when this option is disabled is smaller
35  * (56 bytes on a 32-bit platform). In future versions of the library, it
36  * will support alternative implementations of ECDH operations.
37  * The new format is incompatible with applications that access
38  * context fields directly and with restartable ECP operations.
39  */
40 
41 #if defined(MBEDTLS_ECP_RESTARTABLE)
42 #define MBEDTLS_ECDH_LEGACY_CONTEXT
43 #else
44 #undef MBEDTLS_ECDH_LEGACY_CONTEXT
45 #endif
46 
47 #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
48 #undef MBEDTLS_ECDH_LEGACY_CONTEXT
49 #include "everest/everest.h"
50 #endif
51 
52 #ifdef __cplusplus
53 extern "C" {
54 #endif
55 
56 /**
57  * Defines the source of the imported EC key.
58  */
59 typedef enum {
60     MBEDTLS_ECDH_OURS,   /**< Our key. */
61     MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */
62 } mbedtls_ecdh_side;
63 
64 #if !defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
65 /**
66  * Defines the ECDH implementation used.
67  *
68  * Later versions of the library may add new variants, therefore users should
69  * not make any assumptions about them.
70  */
71 typedef enum {
72     MBEDTLS_ECDH_VARIANT_NONE = 0,   /*!< Implementation not defined. */
73     MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */
74 #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
75     MBEDTLS_ECDH_VARIANT_EVEREST     /*!< Everest implementation */
76 #endif
77 } mbedtls_ecdh_variant;
78 
79 /**
80  * The context used by the default ECDH implementation.
81  *
82  * Later versions might change the structure of this context, therefore users
83  * should not make any assumptions about the structure of
84  * mbedtls_ecdh_context_mbed.
85  */
86 typedef struct mbedtls_ecdh_context_mbed {
87     mbedtls_ecp_group MBEDTLS_PRIVATE(grp);   /*!< The elliptic curve used. */
88     mbedtls_mpi MBEDTLS_PRIVATE(d);           /*!< The private key. */
89     mbedtls_ecp_point MBEDTLS_PRIVATE(Q);     /*!< The public key. */
90     mbedtls_ecp_point MBEDTLS_PRIVATE(Qp);    /*!< The value of the public key of the peer. */
91     mbedtls_mpi MBEDTLS_PRIVATE(z);           /*!< The shared secret. */
92 #if defined(MBEDTLS_ECP_RESTARTABLE)
93     mbedtls_ecp_restart_ctx MBEDTLS_PRIVATE(rs); /*!< The restart context for EC computations. */
94 #endif
95 } mbedtls_ecdh_context_mbed;
96 #endif
97 
98 /**
99  *
100  * \warning         Performing multiple operations concurrently on the same
101  *                  ECDSA context is not supported; objects of this type
102  *                  should not be shared between multiple threads.
103  * \brief           The ECDH context structure.
104  */
105 typedef struct mbedtls_ecdh_context {
106 #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
107     mbedtls_ecp_group MBEDTLS_PRIVATE(grp);   /*!< The elliptic curve used. */
108     mbedtls_mpi MBEDTLS_PRIVATE(d);           /*!< The private key. */
109     mbedtls_ecp_point MBEDTLS_PRIVATE(Q);     /*!< The public key. */
110     mbedtls_ecp_point MBEDTLS_PRIVATE(Qp);    /*!< The value of the public key of the peer. */
111     mbedtls_mpi MBEDTLS_PRIVATE(z);           /*!< The shared secret. */
112     int MBEDTLS_PRIVATE(point_format);        /*!< The format of point export in TLS messages. */
113     mbedtls_ecp_point MBEDTLS_PRIVATE(Vi);    /*!< The blinding value. */
114     mbedtls_ecp_point MBEDTLS_PRIVATE(Vf);    /*!< The unblinding value. */
115     mbedtls_mpi MBEDTLS_PRIVATE(_d);          /*!< The previous \p d. */
116 #if defined(MBEDTLS_ECP_RESTARTABLE)
117     int MBEDTLS_PRIVATE(restart_enabled);        /*!< The flag for restartable mode. */
118     mbedtls_ecp_restart_ctx MBEDTLS_PRIVATE(rs); /*!< The restart context for EC computations. */
119 #endif /* MBEDTLS_ECP_RESTARTABLE */
120 #else
121     uint8_t MBEDTLS_PRIVATE(point_format);       /*!< The format of point export in TLS messages
122                                                     as defined in RFC 4492. */
123     mbedtls_ecp_group_id MBEDTLS_PRIVATE(grp_id);/*!< The elliptic curve used. */
124     mbedtls_ecdh_variant MBEDTLS_PRIVATE(var);   /*!< The ECDH implementation/structure used. */
125     union {
126         mbedtls_ecdh_context_mbed   MBEDTLS_PRIVATE(mbed_ecdh);
127 #if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
128         mbedtls_ecdh_context_everest MBEDTLS_PRIVATE(everest_ecdh);
129 #endif
130     } MBEDTLS_PRIVATE(ctx);                      /*!< Implementation-specific context. The
131                                                     context in use is specified by the \c var
132                                                     field. */
133 #if defined(MBEDTLS_ECP_RESTARTABLE)
134     uint8_t MBEDTLS_PRIVATE(restart_enabled);    /*!< The flag for restartable mode. Functions of
135                                                     an alternative implementation not supporting
136                                                     restartable mode must return
137                                                     MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED error
138                                                     if this flag is set. */
139 #endif /* MBEDTLS_ECP_RESTARTABLE */
140 #endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */
141 }
142 mbedtls_ecdh_context;
143 
144 /**
145  * \brief          Return the ECP group for provided context.
146  *
147  * \note           To access group specific fields, users should use
148  *                 `mbedtls_ecp_curve_info_from_grp_id` or
149  *                 `mbedtls_ecp_group_load` on the extracted `group_id`.
150  *
151  * \param ctx      The ECDH context to parse. This must not be \c NULL.
152  *
153  * \return         The \c mbedtls_ecp_group_id of the context.
154  */
155 mbedtls_ecp_group_id mbedtls_ecdh_get_grp_id(mbedtls_ecdh_context *ctx);
156 
157 /**
158  * \brief          Check whether a given group can be used for ECDH.
159  *
160  * \param gid      The ECP group ID to check.
161  *
162  * \return         \c 1 if the group can be used, \c 0 otherwise
163  */
164 int mbedtls_ecdh_can_do(mbedtls_ecp_group_id gid);
165 
166 /**
167  * \brief           This function generates an ECDH keypair on an elliptic
168  *                  curve.
169  *
170  *                  This function performs the first of two core computations
171  *                  implemented during the ECDH key exchange. The second core
172  *                  computation is performed by mbedtls_ecdh_compute_shared().
173  *
174  * \see             ecp.h
175  *
176  * \param grp       The ECP group to use. This must be initialized and have
177  *                  domain parameters loaded, for example through
178  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
179  * \param d         The destination MPI (private key).
180  *                  This must be initialized.
181  * \param Q         The destination point (public key).
182  *                  This must be initialized.
183  * \param f_rng     The RNG function to use. This must not be \c NULL.
184  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
185  *                  \c NULL in case \p f_rng doesn't need a context argument.
186  *
187  * \return          \c 0 on success.
188  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
189  *                  \c MBEDTLS_MPI_XXX error code on failure.
190  */
191 int mbedtls_ecdh_gen_public(mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
192                             int (*f_rng)(void *, unsigned char *, size_t),
193                             void *p_rng);
194 
195 /**
196  * \brief           This function computes the shared secret.
197  *
198  *                  This function performs the second of two core computations
199  *                  implemented during the ECDH key exchange. The first core
200  *                  computation is performed by mbedtls_ecdh_gen_public().
201  *
202  * \see             ecp.h
203  *
204  * \note            If \p f_rng is not NULL, it is used to implement
205  *                  countermeasures against side-channel attacks.
206  *                  For more information, see mbedtls_ecp_mul().
207  *
208  * \param grp       The ECP group to use. This must be initialized and have
209  *                  domain parameters loaded, for example through
210  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
211  * \param z         The destination MPI (shared secret).
212  *                  This must be initialized.
213  * \param Q         The public key from another party.
214  *                  This must be initialized.
215  * \param d         Our secret exponent (private key).
216  *                  This must be initialized.
217  * \param f_rng     The RNG function to use. This must not be \c NULL.
218  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
219  *                  \c NULL if \p f_rng is \c NULL or doesn't need a
220  *                  context argument.
221  *
222  * \return          \c 0 on success.
223  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
224  *                  \c MBEDTLS_MPI_XXX error code on failure.
225  */
226 int mbedtls_ecdh_compute_shared(mbedtls_ecp_group *grp, mbedtls_mpi *z,
227                                 const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
228                                 int (*f_rng)(void *, unsigned char *, size_t),
229                                 void *p_rng);
230 
231 /**
232  * \brief           This function initializes an ECDH context.
233  *
234  * \param ctx       The ECDH context to initialize. This must not be \c NULL.
235  */
236 void mbedtls_ecdh_init(mbedtls_ecdh_context *ctx);
237 
238 /**
239  * \brief           This function sets up the ECDH context with the information
240  *                  given.
241  *
242  *                  This function should be called after mbedtls_ecdh_init() but
243  *                  before mbedtls_ecdh_make_params(). There is no need to call
244  *                  this function before mbedtls_ecdh_read_params().
245  *
246  *                  This is the first function used by a TLS server for ECDHE
247  *                  ciphersuites.
248  *
249  * \param ctx       The ECDH context to set up. This must be initialized.
250  * \param grp_id    The group id of the group to set up the context for.
251  *
252  * \return          \c 0 on success.
253  */
254 int mbedtls_ecdh_setup(mbedtls_ecdh_context *ctx,
255                        mbedtls_ecp_group_id grp_id);
256 
257 /**
258  * \brief           This function frees a context.
259  *
260  * \param ctx       The context to free. This may be \c NULL, in which
261  *                  case this function does nothing. If it is not \c NULL,
262  *                  it must point to an initialized ECDH context.
263  */
264 void mbedtls_ecdh_free(mbedtls_ecdh_context *ctx);
265 
266 /**
267  * \brief           This function generates an EC key pair and exports its
268  *                  in the format used in a TLS ServerKeyExchange handshake
269  *                  message.
270  *
271  *                  This is the second function used by a TLS server for ECDHE
272  *                  ciphersuites. (It is called after mbedtls_ecdh_setup().)
273  *
274  * \see             ecp.h
275  *
276  * \param ctx       The ECDH context to use. This must be initialized
277  *                  and bound to a group, for example via mbedtls_ecdh_setup().
278  * \param olen      The address at which to store the number of Bytes written.
279  * \param buf       The destination buffer. This must be a writable buffer of
280  *                  length \p blen Bytes.
281  * \param blen      The length of the destination buffer \p buf in Bytes.
282  * \param f_rng     The RNG function to use. This must not be \c NULL.
283  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
284  *                  \c NULL in case \p f_rng doesn't need a context argument.
285  *
286  * \return          \c 0 on success.
287  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
288  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
289  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
290  */
291 int mbedtls_ecdh_make_params(mbedtls_ecdh_context *ctx, size_t *olen,
292                              unsigned char *buf, size_t blen,
293                              int (*f_rng)(void *, unsigned char *, size_t),
294                              void *p_rng);
295 
296 /**
297  * \brief           This function parses the ECDHE parameters in a
298  *                  TLS ServerKeyExchange handshake message.
299  *
300  * \note            In a TLS handshake, this is the how the client
301  *                  sets up its ECDHE context from the server's public
302  *                  ECDHE key material.
303  *
304  * \see             ecp.h
305  *
306  * \param ctx       The ECDHE context to use. This must be initialized.
307  * \param buf       On input, \c *buf must be the start of the input buffer.
308  *                  On output, \c *buf is updated to point to the end of the
309  *                  data that has been read. On success, this is the first byte
310  *                  past the end of the ServerKeyExchange parameters.
311  *                  On error, this is the point at which an error has been
312  *                  detected, which is usually not useful except to debug
313  *                  failures.
314  * \param end       The end of the input buffer.
315  *
316  * \return          \c 0 on success.
317  * \return          An \c MBEDTLS_ERR_ECP_XXX error code on failure.
318  *
319  */
320 int mbedtls_ecdh_read_params(mbedtls_ecdh_context *ctx,
321                              const unsigned char **buf,
322                              const unsigned char *end);
323 
324 /**
325  * \brief           This function sets up an ECDH context from an EC key.
326  *
327  *                  It is used by clients and servers in place of the
328  *                  ServerKeyEchange for static ECDH, and imports ECDH
329  *                  parameters from the EC key information of a certificate.
330  *
331  * \see             ecp.h
332  *
333  * \param ctx       The ECDH context to set up. This must be initialized.
334  * \param key       The EC key to use. This must be initialized.
335  * \param side      Defines the source of the key. Possible values are:
336  *                  - #MBEDTLS_ECDH_OURS: The key is ours.
337  *                  - #MBEDTLS_ECDH_THEIRS: The key is that of the peer.
338  *
339  * \return          \c 0 on success.
340  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
341  *
342  */
343 int mbedtls_ecdh_get_params(mbedtls_ecdh_context *ctx,
344                             const mbedtls_ecp_keypair *key,
345                             mbedtls_ecdh_side side);
346 
347 /**
348  * \brief           This function generates a public key and exports it
349  *                  as a TLS ClientKeyExchange payload.
350  *
351  *                  This is the second function used by a TLS client for ECDH(E)
352  *                  ciphersuites.
353  *
354  * \see             ecp.h
355  *
356  * \param ctx       The ECDH context to use. This must be initialized
357  *                  and bound to a group, the latter usually by
358  *                  mbedtls_ecdh_read_params().
359  * \param olen      The address at which to store the number of Bytes written.
360  *                  This must not be \c NULL.
361  * \param buf       The destination buffer. This must be a writable buffer
362  *                  of length \p blen Bytes.
363  * \param blen      The size of the destination buffer \p buf in Bytes.
364  * \param f_rng     The RNG function to use. This must not be \c NULL.
365  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
366  *                  \c NULL in case \p f_rng doesn't need a context argument.
367  *
368  * \return          \c 0 on success.
369  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
370  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
371  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
372  */
373 int mbedtls_ecdh_make_public(mbedtls_ecdh_context *ctx, size_t *olen,
374                              unsigned char *buf, size_t blen,
375                              int (*f_rng)(void *, unsigned char *, size_t),
376                              void *p_rng);
377 
378 /**
379  * \brief       This function parses and processes the ECDHE payload of a
380  *              TLS ClientKeyExchange message.
381  *
382  *              This is the third function used by a TLS server for ECDH(E)
383  *              ciphersuites. (It is called after mbedtls_ecdh_setup() and
384  *              mbedtls_ecdh_make_params().)
385  *
386  * \see         ecp.h
387  *
388  * \param ctx   The ECDH context to use. This must be initialized
389  *              and bound to a group, for example via mbedtls_ecdh_setup().
390  * \param buf   The pointer to the ClientKeyExchange payload. This must
391  *              be a readable buffer of length \p blen Bytes.
392  * \param blen  The length of the input buffer \p buf in Bytes.
393  *
394  * \return      \c 0 on success.
395  * \return      An \c MBEDTLS_ERR_ECP_XXX error code on failure.
396  */
397 int mbedtls_ecdh_read_public(mbedtls_ecdh_context *ctx,
398                              const unsigned char *buf, size_t blen);
399 
400 /**
401  * \brief           This function derives and exports the shared secret.
402  *
403  *                  This is the last function used by both TLS client
404  *                  and servers.
405  *
406  * \note            If \p f_rng is not NULL, it is used to implement
407  *                  countermeasures against side-channel attacks.
408  *                  For more information, see mbedtls_ecp_mul().
409  *
410  * \see             ecp.h
411 
412  * \param ctx       The ECDH context to use. This must be initialized
413  *                  and have its own private key generated and the peer's
414  *                  public key imported.
415  * \param olen      The address at which to store the total number of
416  *                  Bytes written on success. This must not be \c NULL.
417  * \param buf       The buffer to write the generated shared key to. This
418  *                  must be a writable buffer of size \p blen Bytes.
419  * \param blen      The length of the destination buffer \p buf in Bytes.
420  * \param f_rng     The RNG function to use. This must not be \c NULL.
421  * \param p_rng     The RNG context. This may be \c NULL if \p f_rng
422  *                  doesn't need a context argument.
423  *
424  * \return          \c 0 on success.
425  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
426  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
427  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
428  */
429 int mbedtls_ecdh_calc_secret(mbedtls_ecdh_context *ctx, size_t *olen,
430                              unsigned char *buf, size_t blen,
431                              int (*f_rng)(void *, unsigned char *, size_t),
432                              void *p_rng);
433 
434 #if defined(MBEDTLS_ECP_RESTARTABLE)
435 /**
436  * \brief           This function enables restartable EC computations for this
437  *                  context.  (Default: disabled.)
438  *
439  * \see             \c mbedtls_ecp_set_max_ops()
440  *
441  * \note            It is not possible to safely disable restartable
442  *                  computations once enabled, except by free-ing the context,
443  *                  which cancels possible in-progress operations.
444  *
445  * \param ctx       The ECDH context to use. This must be initialized.
446  */
447 void mbedtls_ecdh_enable_restart(mbedtls_ecdh_context *ctx);
448 #endif /* MBEDTLS_ECP_RESTARTABLE */
449 
450 #ifdef __cplusplus
451 }
452 #endif
453 
454 #endif /* ecdh.h */
455