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