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 (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
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  *  This file is part of Mbed TLS (https://tls.mbed.org)
32  */
33 
34 #ifndef MBEDTLS_ECDH_H
35 #define MBEDTLS_ECDH_H
36 
37 #include "ecp.h"
38 
39 /*
40  * Use a backward compatible ECDH context.
41  *
42  * This flag is always enabled for now and future versions might add a
43  * configuration option that conditionally undefines this flag.
44  * The configuration option in question may have a different name.
45  *
46  * Features undefining this flag, must have a warning in their description in
47  * config.h stating that the feature breaks backward compatibility.
48  */
49 #define MBEDTLS_ECDH_LEGACY_CONTEXT
50 
51 #ifdef __cplusplus
52 extern "C" {
53 #endif
54 
55 /**
56  * Defines the source of the imported EC key.
57  */
58 typedef enum
59 {
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 {
73     MBEDTLS_ECDH_VARIANT_NONE = 0,   /*!< Implementation not defined. */
74     MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */
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     } ctx;                      /*!< Implementation-specific context. The
129                                   context in use is specified by the \c var
130                                   field. */
131 #if defined(MBEDTLS_ECP_RESTARTABLE)
132     uint8_t restart_enabled;    /*!< The flag for restartable mode. Functions of
133                                   an alternative implementation not supporting
134                                   restartable mode must return
135                                   MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED error
136                                   if this flag is set. */
137 #endif /* MBEDTLS_ECP_RESTARTABLE */
138 #endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */
139 }
140 mbedtls_ecdh_context;
141 
142 /**
143  * \brief           This function generates an ECDH keypair on an elliptic
144  *                  curve.
145  *
146  *                  This function performs the first of two core computations
147  *                  implemented during the ECDH key exchange. The second core
148  *                  computation is performed by mbedtls_ecdh_compute_shared().
149  *
150  * \see             ecp.h
151  *
152  * \param grp       The ECP group to use. This must be initialized and have
153  *                  domain parameters loaded, for example through
154  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
155  * \param d         The destination MPI (private key).
156  *                  This must be initialized.
157  * \param Q         The destination point (public key).
158  *                  This must be initialized.
159  * \param f_rng     The RNG function to use. This must not be \c NULL.
160  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
161  *                  \c NULL in case \p f_rng doesn't need a context argument.
162  *
163  * \return          \c 0 on success.
164  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
165  *                  \c MBEDTLS_MPI_XXX error code on failure.
166  */
167 int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
168                      int (*f_rng)(void *, unsigned char *, size_t),
169                      void *p_rng );
170 
171 /**
172  * \brief           This function computes the shared secret.
173  *
174  *                  This function performs the second of two core computations
175  *                  implemented during the ECDH key exchange. The first core
176  *                  computation is performed by mbedtls_ecdh_gen_public().
177  *
178  * \see             ecp.h
179  *
180  * \note            If \p f_rng is not NULL, it is used to implement
181  *                  countermeasures against side-channel attacks.
182  *                  For more information, see mbedtls_ecp_mul().
183  *
184  * \param grp       The ECP group to use. This must be initialized and have
185  *                  domain parameters loaded, for example through
186  *                  mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
187  * \param z         The destination MPI (shared secret).
188  *                  This must be initialized.
189  * \param Q         The public key from another party.
190  *                  This must be initialized.
191  * \param d         Our secret exponent (private key).
192  *                  This must be initialized.
193  * \param f_rng     The RNG function. This may be \c NULL if randomization
194  *                  of intermediate results during the ECP computations is
195  *                  not needed (discouraged). See the documentation of
196  *                  mbedtls_ecp_mul() for more.
197  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
198  *                  \c NULL if \p f_rng is \c NULL or doesn't need a
199  *                  context argument.
200  *
201  * \return          \c 0 on success.
202  * \return          Another \c MBEDTLS_ERR_ECP_XXX or
203  *                  \c MBEDTLS_MPI_XXX error code on failure.
204  */
205 int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
206                          const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
207                          int (*f_rng)(void *, unsigned char *, size_t),
208                          void *p_rng );
209 
210 /**
211  * \brief           This function initializes an ECDH context.
212  *
213  * \param ctx       The ECDH context to initialize. This must not be \c NULL.
214  */
215 void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );
216 
217 /**
218  * \brief           This function sets up the ECDH context with the information
219  *                  given.
220  *
221  *                  This function should be called after mbedtls_ecdh_init() but
222  *                  before mbedtls_ecdh_make_params(). There is no need to call
223  *                  this function before mbedtls_ecdh_read_params().
224  *
225  *                  This is the first function used by a TLS server for ECDHE
226  *                  ciphersuites.
227  *
228  * \param ctx       The ECDH context to set up. This must be initialized.
229  * \param grp_id    The group id of the group to set up the context for.
230  *
231  * \return          \c 0 on success.
232  */
233 int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx,
234                         mbedtls_ecp_group_id grp_id );
235 
236 /**
237  * \brief           This function frees a context.
238  *
239  * \param ctx       The context to free. This may be \c NULL, in which
240  *                  case this function does nothing. If it is not \c NULL,
241  *                  it must point to an initialized ECDH context.
242  */
243 void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );
244 
245 /**
246  * \brief           This function generates an EC key pair and exports its
247  *                  in the format used in a TLS ServerKeyExchange handshake
248  *                  message.
249  *
250  *                  This is the second function used by a TLS server for ECDHE
251  *                  ciphersuites. (It is called after mbedtls_ecdh_setup().)
252  *
253  * \see             ecp.h
254  *
255  * \param ctx       The ECDH context to use. This must be initialized
256  *                  and bound to a group, for example via mbedtls_ecdh_setup().
257  * \param olen      The address at which to store the number of Bytes written.
258  * \param buf       The destination buffer. This must be a writable buffer of
259  *                  length \p blen Bytes.
260  * \param blen      The length of the destination buffer \p buf in Bytes.
261  * \param f_rng     The RNG function to use. This must not be \c NULL.
262  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
263  *                  \c NULL in case \p f_rng doesn't need a context argument.
264  *
265  * \return          \c 0 on success.
266  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
267  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
268  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
269  */
270 int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
271                       unsigned char *buf, size_t blen,
272                       int (*f_rng)(void *, unsigned char *, size_t),
273                       void *p_rng );
274 
275 /**
276  * \brief           This function parses the ECDHE parameters in a
277  *                  TLS ServerKeyExchange handshake message.
278  *
279  * \note            In a TLS handshake, this is the how the client
280  *                  sets up its ECDHE context from the server's public
281  *                  ECDHE key material.
282  *
283  * \see             ecp.h
284  *
285  * \param ctx       The ECDHE context to use. This must be initialized.
286  * \param buf       On input, \c *buf must be the start of the input buffer.
287  *                  On output, \c *buf is updated to point to the end of the
288  *                  data that has been read. On success, this is the first byte
289  *                  past the end of the ServerKeyExchange parameters.
290  *                  On error, this is the point at which an error has been
291  *                  detected, which is usually not useful except to debug
292  *                  failures.
293  * \param end       The end of the input buffer.
294  *
295  * \return          \c 0 on success.
296  * \return          An \c MBEDTLS_ERR_ECP_XXX error code on failure.
297  *
298  */
299 int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
300                               const unsigned char **buf,
301                               const unsigned char *end );
302 
303 /**
304  * \brief           This function sets up an ECDH context from an EC key.
305  *
306  *                  It is used by clients and servers in place of the
307  *                  ServerKeyEchange for static ECDH, and imports ECDH
308  *                  parameters from the EC key information of a certificate.
309  *
310  * \see             ecp.h
311  *
312  * \param ctx       The ECDH context to set up. This must be initialized.
313  * \param key       The EC key to use. This must be initialized.
314  * \param side      Defines the source of the key. Possible values are:
315  *                  - #MBEDTLS_ECDH_OURS: The key is ours.
316  *                  - #MBEDTLS_ECDH_THEIRS: The key is that of the peer.
317  *
318  * \return          \c 0 on success.
319  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
320  *
321  */
322 int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx,
323                              const mbedtls_ecp_keypair *key,
324                              mbedtls_ecdh_side side );
325 
326 /**
327  * \brief           This function generates a public key and exports it
328  *                  as a TLS ClientKeyExchange payload.
329  *
330  *                  This is the second function used by a TLS client for ECDH(E)
331  *                  ciphersuites.
332  *
333  * \see             ecp.h
334  *
335  * \param ctx       The ECDH context to use. This must be initialized
336  *                  and bound to a group, the latter usually by
337  *                  mbedtls_ecdh_read_params().
338  * \param olen      The address at which to store the number of Bytes written.
339  *                  This must not be \c NULL.
340  * \param buf       The destination buffer. This must be a writable buffer
341  *                  of length \p blen Bytes.
342  * \param blen      The size of the destination buffer \p buf in Bytes.
343  * \param f_rng     The RNG function to use. This must not be \c NULL.
344  * \param p_rng     The RNG context to be passed to \p f_rng. This may be
345  *                  \c NULL in case \p f_rng doesn't need a context argument.
346  *
347  * \return          \c 0 on success.
348  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
349  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
350  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
351  */
352 int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
353                       unsigned char *buf, size_t blen,
354                       int (*f_rng)(void *, unsigned char *, size_t),
355                       void *p_rng );
356 
357 /**
358  * \brief       This function parses and processes the ECDHE payload of a
359  *              TLS ClientKeyExchange message.
360  *
361  *              This is the third function used by a TLS server for ECDH(E)
362  *              ciphersuites. (It is called after mbedtls_ecdh_setup() and
363  *              mbedtls_ecdh_make_params().)
364  *
365  * \see         ecp.h
366  *
367  * \param ctx   The ECDH context to use. This must be initialized
368  *              and bound to a group, for example via mbedtls_ecdh_setup().
369  * \param buf   The pointer to the ClientKeyExchange payload. This must
370  *              be a readable buffer of length \p blen Bytes.
371  * \param blen  The length of the input buffer \p buf in Bytes.
372  *
373  * \return      \c 0 on success.
374  * \return      An \c MBEDTLS_ERR_ECP_XXX error code on failure.
375  */
376 int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
377                               const unsigned char *buf, size_t blen );
378 
379 /**
380  * \brief           This function derives and exports the shared secret.
381  *
382  *                  This is the last function used by both TLS client
383  *                  and servers.
384  *
385  * \note            If \p f_rng is not NULL, it is used to implement
386  *                  countermeasures against side-channel attacks.
387  *                  For more information, see mbedtls_ecp_mul().
388  *
389  * \see             ecp.h
390 
391  * \param ctx       The ECDH context to use. This must be initialized
392  *                  and have its own private key generated and the peer's
393  *                  public key imported.
394  * \param olen      The address at which to store the total number of
395  *                  Bytes written on success. This must not be \c NULL.
396  * \param buf       The buffer to write the generated shared key to. This
397  *                  must be a writable buffer of size \p blen Bytes.
398  * \param blen      The length of the destination buffer \p buf in Bytes.
399  * \param f_rng     The RNG function, for blinding purposes. This may
400  *                  b \c NULL if blinding isn't needed.
401  * \param p_rng     The RNG context. This may be \c NULL if \p f_rng
402  *                  doesn't need a context argument.
403  *
404  * \return          \c 0 on success.
405  * \return          #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
406  *                  operations was reached: see \c mbedtls_ecp_set_max_ops().
407  * \return          Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
408  */
409 int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
410                       unsigned char *buf, size_t blen,
411                       int (*f_rng)(void *, unsigned char *, size_t),
412                       void *p_rng );
413 
414 #if defined(MBEDTLS_ECP_RESTARTABLE)
415 /**
416  * \brief           This function enables restartable EC computations for this
417  *                  context.  (Default: disabled.)
418  *
419  * \see             \c mbedtls_ecp_set_max_ops()
420  *
421  * \note            It is not possible to safely disable restartable
422  *                  computations once enabled, except by free-ing the context,
423  *                  which cancels possible in-progress operations.
424  *
425  * \param ctx       The ECDH context to use. This must be initialized.
426  */
427 void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx );
428 #endif /* MBEDTLS_ECP_RESTARTABLE */
429 
430 #ifdef __cplusplus
431 }
432 #endif
433 
434 #endif /* ecdh.h */
435