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