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