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          Check whether a given group can be used for ECDH.
146  *
147  * \param gid      The ECP group ID to check.
148  *
149  * \return         \c 1 if the group can be used, \c 0 otherwise
150  */
151 int mbedtls_ecdh_can_do(mbedtls_ecp_group_id gid);
152 
153 /**
154  * \brief           This function generates an ECDH keypair on an elliptic
155  *                  curve.
156  *
157  *                  This function performs the first of two core computations
158  *                  implemented during the ECDH key exchange. The second core
159  *                  computation is performed by mbedtls_ecdh_compute_shared().
160  *
161  * \see             ecp.h
162  *
163  * \param grp       The ECP group to use. This must be initialized and have
164  *                  domain parameters loaded, for example through
165  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
166  * \param d         The destination MPI (private key).
167  *                  This must be initialized.
168  * \param Q         The destination point (public key).
169  *                  This must be initialized.
170  * \param f_rng     The RNG function to use. This must not be \c NULL.
171  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
172  *                  \c NULL in case \p f_rng doesn't need a context argument.
173  *
174  * \return          \c 0 on success.
175  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
176  *                  \c MBEDTLS_MPI_XXX error code on failure.
177  */
178 int mbedtls_ecdh_gen_public(mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
179                             int (*f_rng)(void *, unsigned char *, size_t),
180                             void *p_rng);
181 
182 /**
183  * \brief           This function computes the shared secret.
184  *
185  *                  This function performs the second of two core computations
186  *                  implemented during the ECDH key exchange. The first core
187  *                  computation is performed by mbedtls_ecdh_gen_public().
188  *
189  * \see             ecp.h
190  *
191  * \note            If \p f_rng is not NULL, it is used to implement
192  *                  countermeasures against side-channel attacks.
193  *                  For more information, see mbedtls_ecp_mul().
194  *
195  * \param grp       The ECP group to use. This must be initialized and have
196  *                  domain parameters loaded, for example through
197  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
198  * \param z         The destination MPI (shared secret).
199  *                  This must be initialized.
200  * \param Q         The public key from another party.
201  *                  This must be initialized.
202  * \param d         Our secret exponent (private key).
203  *                  This must be initialized.
204  * \param f_rng     The RNG function to use. This must not be \c NULL.
205  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
206  *                  \c NULL if \p f_rng is \c NULL or doesn't need a
207  *                  context argument.
208  *
209  * \return          \c 0 on success.
210  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
211  *                  \c MBEDTLS_MPI_XXX error code on failure.
212  */
213 int mbedtls_ecdh_compute_shared(mbedtls_ecp_group *grp, mbedtls_mpi *z,
214                                 const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
215                                 int (*f_rng)(void *, unsigned char *, size_t),
216                                 void *p_rng);
217 
218 /**
219  * \brief           This function initializes an ECDH context.
220  *
221  * \param ctx       The ECDH context to initialize. This must not be \c NULL.
222  */
223 void mbedtls_ecdh_init(mbedtls_ecdh_context *ctx);
224 
225 /**
226  * \brief           This function sets up the ECDH context with the information
227  *                  given.
228  *
229  *                  This function should be called after mbedtls_ecdh_init() but
230  *                  before mbedtls_ecdh_make_params(). There is no need to call
231  *                  this function before mbedtls_ecdh_read_params().
232  *
233  *                  This is the first function used by a TLS server for ECDHE
234  *                  ciphersuites.
235  *
236  * \param ctx       The ECDH context to set up. This must be initialized.
237  * \param grp_id    The group id of the group to set up the context for.
238  *
239  * \return          \c 0 on success.
240  */
241 int mbedtls_ecdh_setup(mbedtls_ecdh_context *ctx,
242                        mbedtls_ecp_group_id grp_id);
243 
244 /**
245  * \brief           This function frees a context.
246  *
247  * \param ctx       The context to free. This may be \c NULL, in which
248  *                  case this function does nothing. If it is not \c NULL,
249  *                  it must point to an initialized ECDH context.
250  */
251 void mbedtls_ecdh_free(mbedtls_ecdh_context *ctx);
252 
253 /**
254  * \brief           This function generates an EC key pair and exports its
255  *                  in the format used in a TLS ServerKeyExchange handshake
256  *                  message.
257  *
258  *                  This is the second function used by a TLS server for ECDHE
259  *                  ciphersuites. (It is called after mbedtls_ecdh_setup().)
260  *
261  * \see             ecp.h
262  *
263  * \param ctx       The ECDH context to use. This must be initialized
264  *                  and bound to a group, for example via mbedtls_ecdh_setup().
265  * \param olen      The address at which to store the number of Bytes written.
266  * \param buf       The destination buffer. This must be a writable buffer of
267  *                  length \p blen Bytes.
268  * \param blen      The length of the destination buffer \p buf in Bytes.
269  * \param f_rng     The RNG function to use. This must not be \c NULL.
270  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
271  *                  \c NULL in case \p f_rng doesn't need a context argument.
272  *
273  * \return          \c 0 on success.
274  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
275  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
276  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
277  */
278 int mbedtls_ecdh_make_params(mbedtls_ecdh_context *ctx, size_t *olen,
279                              unsigned char *buf, size_t blen,
280                              int (*f_rng)(void *, unsigned char *, size_t),
281                              void *p_rng);
282 
283 /**
284  * \brief           This function parses the ECDHE parameters in a
285  *                  TLS ServerKeyExchange handshake message.
286  *
287  * \note            In a TLS handshake, this is the how the client
288  *                  sets up its ECDHE context from the server's public
289  *                  ECDHE key material.
290  *
291  * \see             ecp.h
292  *
293  * \param ctx       The ECDHE context to use. This must be initialized.
294  * \param buf       On input, \c *buf must be the start of the input buffer.
295  *                  On output, \c *buf is updated to point to the end of the
296  *                  data that has been read. On success, this is the first byte
297  *                  past the end of the ServerKeyExchange parameters.
298  *                  On error, this is the point at which an error has been
299  *                  detected, which is usually not useful except to debug
300  *                  failures.
301  * \param end       The end of the input buffer.
302  *
303  * \return          \c 0 on success.
304  * \return          An \c MBEDTLS_ERR_ECP_XXX error code on failure.
305  *
306  */
307 int mbedtls_ecdh_read_params(mbedtls_ecdh_context *ctx,
308                              const unsigned char **buf,
309                              const unsigned char *end);
310 
311 /**
312  * \brief           This function sets up an ECDH context from an EC key.
313  *
314  *                  It is used by clients and servers in place of the
315  *                  ServerKeyEchange for static ECDH, and imports ECDH
316  *                  parameters from the EC key information of a certificate.
317  *
318  * \see             ecp.h
319  *
320  * \param ctx       The ECDH context to set up. This must be initialized.
321  * \param key       The EC key to use. This must be initialized.
322  * \param side      Defines the source of the key. Possible values are:
323  *                  - #MBEDTLS_ECDH_OURS: The key is ours.
324  *                  - #MBEDTLS_ECDH_THEIRS: The key is that of the peer.
325  *
326  * \return          \c 0 on success.
327  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
328  *
329  */
330 int mbedtls_ecdh_get_params(mbedtls_ecdh_context *ctx,
331                             const mbedtls_ecp_keypair *key,
332                             mbedtls_ecdh_side side);
333 
334 /**
335  * \brief           This function generates a public key and exports it
336  *                  as a TLS ClientKeyExchange payload.
337  *
338  *                  This is the second function used by a TLS client for ECDH(E)
339  *                  ciphersuites.
340  *
341  * \see             ecp.h
342  *
343  * \param ctx       The ECDH context to use. This must be initialized
344  *                  and bound to a group, the latter usually by
345  *                  mbedtls_ecdh_read_params().
346  * \param olen      The address at which to store the number of Bytes written.
347  *                  This must not be \c NULL.
348  * \param buf       The destination buffer. This must be a writable buffer
349  *                  of length \p blen Bytes.
350  * \param blen      The size of the destination buffer \p buf in Bytes.
351  * \param f_rng     The RNG function to use. This must not be \c NULL.
352  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
353  *                  \c NULL in case \p f_rng doesn't need a context argument.
354  *
355  * \return          \c 0 on success.
356  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
357  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
358  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
359  */
360 int mbedtls_ecdh_make_public(mbedtls_ecdh_context *ctx, size_t *olen,
361                              unsigned char *buf, size_t blen,
362                              int (*f_rng)(void *, unsigned char *, size_t),
363                              void *p_rng);
364 
365 /**
366  * \brief       This function parses and processes the ECDHE payload of a
367  *              TLS ClientKeyExchange message.
368  *
369  *              This is the third function used by a TLS server for ECDH(E)
370  *              ciphersuites. (It is called after mbedtls_ecdh_setup() and
371  *              mbedtls_ecdh_make_params().)
372  *
373  * \see         ecp.h
374  *
375  * \param ctx   The ECDH context to use. This must be initialized
376  *              and bound to a group, for example via mbedtls_ecdh_setup().
377  * \param buf   The pointer to the ClientKeyExchange payload. This must
378  *              be a readable buffer of length \p blen Bytes.
379  * \param blen  The length of the input buffer \p buf in Bytes.
380  *
381  * \return      \c 0 on success.
382  * \return      An \c MBEDTLS_ERR_ECP_XXX error code on failure.
383  */
384 int mbedtls_ecdh_read_public(mbedtls_ecdh_context *ctx,
385                              const unsigned char *buf, size_t blen);
386 
387 /**
388  * \brief           This function derives and exports the shared secret.
389  *
390  *                  This is the last function used by both TLS client
391  *                  and servers.
392  *
393  * \note            If \p f_rng is not NULL, it is used to implement
394  *                  countermeasures against side-channel attacks.
395  *                  For more information, see mbedtls_ecp_mul().
396  *
397  * \see             ecp.h
398 
399  * \param ctx       The ECDH context to use. This must be initialized
400  *                  and have its own private key generated and the peer's
401  *                  public key imported.
402  * \param olen      The address at which to store the total number of
403  *                  Bytes written on success. This must not be \c NULL.
404  * \param buf       The buffer to write the generated shared key to. This
405  *                  must be a writable buffer of size \p blen Bytes.
406  * \param blen      The length of the destination buffer \p buf in Bytes.
407  * \param f_rng     The RNG function to use. This must not be \c NULL.
408  * \param p_rng     The RNG context. This may be \c NULL if \p f_rng
409  *                  doesn't need a context argument.
410  *
411  * \return          \c 0 on success.
412  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
413  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
414  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
415  */
416 int mbedtls_ecdh_calc_secret(mbedtls_ecdh_context *ctx, size_t *olen,
417                              unsigned char *buf, size_t blen,
418                              int (*f_rng)(void *, unsigned char *, size_t),
419                              void *p_rng);
420 
421 #if defined(MBEDTLS_ECP_RESTARTABLE)
422 /**
423  * \brief           This function enables restartable EC computations for this
424  *                  context.  (Default: disabled.)
425  *
426  * \see             \c mbedtls_ecp_set_max_ops()
427  *
428  * \note            It is not possible to safely disable restartable
429  *                  computations once enabled, except by free-ing the context,
430  *                  which cancels possible in-progress operations.
431  *
432  * \param ctx       The ECDH context to use. This must be initialized.
433  */
434 void mbedtls_ecdh_enable_restart(mbedtls_ecdh_context *ctx);
435 #endif /* MBEDTLS_ECP_RESTARTABLE */
436 
437 #ifdef __cplusplus
438 }
439 #endif
440 
441 #endif /* ecdh.h */
442