chiark / gitweb /
gnupg2 (2.1.17-3) unstable; urgency=medium
[gnupg2.git] / g10 / ecdh.c
1 /* ecdh.c - ECDH public key operations used in public key glue code
2  *      Copyright (C) 2010, 2011 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25
26 #include "gpg.h"
27 #include "util.h"
28 #include "pkglue.h"
29 #include "main.h"
30 #include "options.h"
31
32 /* A table with the default KEK parameters used by GnuPG.  */
33 static const struct
34 {
35   unsigned int qbits;
36   int openpgp_hash_id;   /* KEK digest algorithm. */
37   int openpgp_cipher_id; /* KEK cipher algorithm. */
38 } kek_params_table[] =
39   /* Note: Must be sorted by ascending values for QBITS.  */
40   {
41     { 256, DIGEST_ALGO_SHA256, CIPHER_ALGO_AES    },
42     { 384, DIGEST_ALGO_SHA384, CIPHER_ALGO_AES256 },
43
44     /* Note: 528 is 521 rounded to the 8 bit boundary */
45     { 528, DIGEST_ALGO_SHA512, CIPHER_ALGO_AES256 }
46   };
47
48
49
50 /* Return KEK parameters as an opaque MPI The caller must free the
51    returned value.  Returns NULL and sets ERRNO on error.  */
52 gcry_mpi_t
53 pk_ecdh_default_params (unsigned int qbits)
54 {
55   byte *kek_params;
56   int i;
57
58   kek_params = xtrymalloc (4);
59   if (!kek_params)
60     return NULL;
61   kek_params[0] = 3; /* Number of bytes to follow. */
62   kek_params[1] = 1; /* Version for KDF+AESWRAP.   */
63
64   /* Search for matching KEK parameter.  Defaults to the strongest
65      possible choices.  Performance is not an issue here, only
66      interoperability.  */
67   for (i=0; i < DIM (kek_params_table); i++)
68     {
69       if (kek_params_table[i].qbits >= qbits
70           || i+1 == DIM (kek_params_table))
71         {
72           kek_params[2] = kek_params_table[i].openpgp_hash_id;
73           kek_params[3] = kek_params_table[i].openpgp_cipher_id;
74           break;
75         }
76     }
77   log_assert (i < DIM (kek_params_table));
78   if (DBG_CRYPTO)
79     log_printhex ("ECDH KEK params are", kek_params, sizeof(kek_params) );
80
81   return gcry_mpi_set_opaque (NULL, kek_params, 4 * 8);
82 }
83
84
85 /* Encrypts/decrypts DATA using a key derived from the ECC shared
86    point SHARED_MPI using the FIPS SP 800-56A compliant method
87    key_derivation+key_wrapping.  If IS_ENCRYPT is true the function
88    encrypts; if false, it decrypts.  PKEY is the public key and PK_FP
89    the fingerprint of this public key.  On success the result is
90    stored at R_RESULT; on failure NULL is stored at R_RESULT and an
91    error code returned.  */
92 gpg_error_t
93 pk_ecdh_encrypt_with_shared_point (int is_encrypt, gcry_mpi_t shared_mpi,
94                                    const byte pk_fp[MAX_FINGERPRINT_LEN],
95                                    gcry_mpi_t data, gcry_mpi_t *pkey,
96                                    gcry_mpi_t *r_result)
97 {
98   gpg_error_t err;
99   byte *secret_x;
100   int secret_x_size;
101   unsigned int nbits;
102   const unsigned char *kek_params;
103   size_t kek_params_size;
104   int kdf_hash_algo;
105   int kdf_encr_algo;
106   unsigned char message[256];
107   size_t message_size;
108
109   *r_result = NULL;
110
111   nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
112   if (!nbits)
113     return gpg_error (GPG_ERR_TOO_SHORT);
114
115   {
116     size_t nbytes;
117
118     /* Extract x component of the shared point: this is the actual
119        shared secret. */
120     nbytes = (mpi_get_nbits (pkey[1] /* public point */)+7)/8;
121     secret_x = xtrymalloc_secure (nbytes);
122     if (!secret_x)
123       return gpg_error_from_syserror ();
124
125     err = gcry_mpi_print (GCRYMPI_FMT_USG, secret_x, nbytes,
126                           &nbytes, shared_mpi);
127     if (err)
128       {
129         xfree (secret_x);
130         log_error ("ECDH ephemeral export of shared point failed: %s\n",
131                    gpg_strerror (err));
132         return err;
133       }
134
135     /* Expected size of the x component */
136     secret_x_size = (nbits+7)/8;
137
138     /* Extract X from the result.  It must be in the format of:
139            04 || X || Y
140            40 || X
141            41 || X
142
143        Since it always comes with the prefix, it's larger than X.  In
144        old experimental version of libgcrypt, there is a case where it
145        returns X with no prefix of 40, so, nbytes == secret_x_size
146        is allowed.  */
147     if (nbytes < secret_x_size)
148       {
149         xfree (secret_x);
150         return gpg_error (GPG_ERR_BAD_DATA);
151       }
152
153     /* Remove the prefix.  */
154     if ((nbytes & 1))
155       memmove (secret_x, secret_x+1, secret_x_size);
156
157     /* Clear the rest of data.  */
158     if (nbytes - secret_x_size)
159       memset (secret_x+secret_x_size, 0, nbytes-secret_x_size);
160
161     if (DBG_CRYPTO)
162       log_printhex ("ECDH shared secret X is:", secret_x, secret_x_size );
163   }
164
165   /*** We have now the shared secret bytes in secret_x. ***/
166
167   /* At this point we are done with PK encryption and the rest of the
168    * function uses symmetric key encryption techniques to protect the
169    * input DATA.  The following two sections will simply replace
170    * current secret_x with a value derived from it.  This will become
171    * a KEK.
172    */
173   if (!gcry_mpi_get_flag (pkey[2], GCRYMPI_FLAG_OPAQUE))
174     {
175       xfree (secret_x);
176       return gpg_error (GPG_ERR_BUG);
177     }
178   kek_params = gcry_mpi_get_opaque (pkey[2], &nbits);
179   kek_params_size = (nbits+7)/8;
180
181   if (DBG_CRYPTO)
182     log_printhex ("ecdh KDF params:", kek_params, kek_params_size);
183
184   /* Expect 4 bytes  03 01 hash_alg symm_alg.  */
185   if (kek_params_size != 4 || kek_params[0] != 3 || kek_params[1] != 1)
186     {
187       xfree (secret_x);
188       return gpg_error (GPG_ERR_BAD_PUBKEY);
189     }
190
191   kdf_hash_algo = kek_params[2];
192   kdf_encr_algo = kek_params[3];
193
194   if (DBG_CRYPTO)
195     log_debug ("ecdh KDF algorithms %s+%s with aeswrap\n",
196                openpgp_md_algo_name (kdf_hash_algo),
197                openpgp_cipher_algo_name (kdf_encr_algo));
198
199   if (kdf_hash_algo != GCRY_MD_SHA256
200       && kdf_hash_algo != GCRY_MD_SHA384
201       && kdf_hash_algo != GCRY_MD_SHA512)
202     {
203       xfree (secret_x);
204       return gpg_error (GPG_ERR_BAD_PUBKEY);
205     }
206   if (kdf_encr_algo != CIPHER_ALGO_AES
207       && kdf_encr_algo != CIPHER_ALGO_AES192
208       && kdf_encr_algo != CIPHER_ALGO_AES256)
209     {
210       xfree (secret_x);
211       return gpg_error (GPG_ERR_BAD_PUBKEY);
212     }
213
214   /* Build kdf_params.  */
215   {
216     IOBUF obuf;
217
218     obuf = iobuf_temp();
219     /* variable-length field 1, curve name OID */
220     err = gpg_mpi_write_nohdr (obuf, pkey[0]);
221     /* fixed-length field 2 */
222     iobuf_put (obuf, PUBKEY_ALGO_ECDH);
223     /* variable-length field 3, KDF params */
224     err = (err ? err : gpg_mpi_write_nohdr (obuf, pkey[2]));
225     /* fixed-length field 4 */
226     iobuf_write (obuf, "Anonymous Sender    ", 20);
227     /* fixed-length field 5, recipient fp */
228     iobuf_write (obuf, pk_fp, 20);
229
230     message_size = iobuf_temp_to_buffer (obuf, message, sizeof message);
231     iobuf_close (obuf);
232     if (err)
233       {
234         xfree (secret_x);
235         return err;
236       }
237
238     if(DBG_CRYPTO)
239       log_printhex ("ecdh KDF message params are:", message, message_size);
240   }
241
242   /* Derive a KEK (key wrapping key) using MESSAGE and SECRET_X. */
243   {
244     gcry_md_hd_t h;
245     int old_size;
246
247     err = gcry_md_open (&h, kdf_hash_algo, 0);
248     if (err)
249       {
250         log_error ("gcry_md_open failed for kdf_hash_algo %d: %s",
251                    kdf_hash_algo, gpg_strerror (err));
252         xfree (secret_x);
253         return err;
254       }
255     gcry_md_write(h, "\x00\x00\x00\x01", 4);      /* counter = 1 */
256     gcry_md_write(h, secret_x, secret_x_size);    /* x of the point X */
257     gcry_md_write(h, message, message_size);      /* KDF parameters */
258
259     gcry_md_final (h);
260
261     log_assert( gcry_md_get_algo_dlen (kdf_hash_algo) >= 32 );
262
263     memcpy (secret_x, gcry_md_read (h, kdf_hash_algo),
264             gcry_md_get_algo_dlen (kdf_hash_algo));
265     gcry_md_close (h);
266
267     old_size = secret_x_size;
268     log_assert( old_size >= gcry_cipher_get_algo_keylen( kdf_encr_algo ) );
269     secret_x_size = gcry_cipher_get_algo_keylen( kdf_encr_algo );
270     log_assert( secret_x_size <= gcry_md_get_algo_dlen (kdf_hash_algo) );
271
272     /* We could have allocated more, so clean the tail before returning.  */
273     memset (secret_x+secret_x_size, 0, old_size - secret_x_size);
274     if (DBG_CRYPTO)
275       log_printhex ("ecdh KEK is:", secret_x, secret_x_size );
276   }
277
278   /* And, finally, aeswrap with key secret_x.  */
279   {
280     gcry_cipher_hd_t hd;
281     size_t nbytes;
282
283     byte *data_buf;
284     int data_buf_size;
285
286     gcry_mpi_t result;
287
288     err = gcry_cipher_open (&hd, kdf_encr_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
289     if (err)
290       {
291         log_error ("ecdh failed to initialize AESWRAP: %s\n",
292                    gpg_strerror (err));
293         xfree (secret_x);
294         return err;
295       }
296
297     err = gcry_cipher_setkey (hd, secret_x, secret_x_size);
298     xfree (secret_x);
299     secret_x = NULL;
300     if (err)
301       {
302         gcry_cipher_close (hd);
303         log_error ("ecdh failed in gcry_cipher_setkey: %s\n",
304                    gpg_strerror (err));
305         return err;
306       }
307
308     data_buf_size = (gcry_mpi_get_nbits(data)+7)/8;
309     if ((data_buf_size & 7) != (is_encrypt ? 0 : 1))
310       {
311         log_error ("can't use a shared secret of %d bytes for ecdh\n",
312                    data_buf_size);
313         return gpg_error (GPG_ERR_BAD_DATA);
314       }
315
316     data_buf = xtrymalloc_secure( 1 + 2*data_buf_size + 8);
317     if (!data_buf)
318       {
319         err = gpg_error_from_syserror ();
320         gcry_cipher_close (hd);
321         return err;
322       }
323
324     if (is_encrypt)
325       {
326         byte *in = data_buf+1+data_buf_size+8;
327
328         /* Write data MPI into the end of data_buf. data_buf is size
329            aeswrap data.  */
330         err = gcry_mpi_print (GCRYMPI_FMT_USG, in,
331                              data_buf_size, &nbytes, data/*in*/);
332         if (err)
333           {
334             log_error ("ecdh failed to export DEK: %s\n", gpg_strerror (err));
335             gcry_cipher_close (hd);
336             xfree (data_buf);
337             return err;
338           }
339
340         if (DBG_CRYPTO)
341           log_printhex ("ecdh encrypting  :", in, data_buf_size );
342
343         err = gcry_cipher_encrypt (hd, data_buf+1, data_buf_size+8,
344                                    in, data_buf_size);
345         memset (in, 0, data_buf_size);
346         gcry_cipher_close (hd);
347         if (err)
348           {
349             log_error ("ecdh failed in gcry_cipher_encrypt: %s\n",
350                        gpg_strerror (err));
351             xfree (data_buf);
352             return err;
353           }
354         data_buf[0] = data_buf_size+8;
355
356         if (DBG_CRYPTO)
357           log_printhex ("ecdh encrypted to:", data_buf+1, data_buf[0] );
358
359         result = gcry_mpi_set_opaque (NULL, data_buf, 8 * (1+data_buf[0]));
360         if (!result)
361           {
362             err = gpg_error_from_syserror ();
363             xfree (data_buf);
364             log_error ("ecdh failed to create an MPI: %s\n",
365                        gpg_strerror (err));
366             return err;
367           }
368
369         *r_result = result;
370       }
371     else
372       {
373         byte *in;
374         const void *p;
375
376         p = gcry_mpi_get_opaque (data, &nbits);
377         nbytes = (nbits+7)/8;
378         if (!p || nbytes > data_buf_size || !nbytes)
379           {
380             xfree (data_buf);
381             return gpg_error (GPG_ERR_BAD_MPI);
382           }
383         memcpy (data_buf, p, nbytes);
384         if (data_buf[0] != nbytes-1)
385           {
386             log_error ("ecdh inconsistent size\n");
387             xfree (data_buf);
388             return gpg_error (GPG_ERR_BAD_MPI);
389           }
390         in = data_buf+data_buf_size;
391         data_buf_size = data_buf[0];
392
393         if (DBG_CRYPTO)
394           log_printhex ("ecdh decrypting :", data_buf+1, data_buf_size);
395
396         err = gcry_cipher_decrypt (hd, in, data_buf_size, data_buf+1,
397                                    data_buf_size);
398         gcry_cipher_close (hd);
399         if (err)
400           {
401             log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",
402                        gpg_strerror (err));
403             xfree (data_buf);
404             return err;
405           }
406
407         data_buf_size -= 8;
408
409         if (DBG_CRYPTO)
410           log_printhex ("ecdh decrypted to :", in, data_buf_size);
411
412         /* Padding is removed later.  */
413         /* if (in[data_buf_size-1] > 8 ) */
414         /*   { */
415         /*     log_error ("ecdh failed at decryption: invalid padding." */
416         /*                " 0x%02x > 8\n", in[data_buf_size-1] ); */
417         /*     return gpg_error (GPG_ERR_BAD_KEY); */
418         /*   } */
419
420         err = gcry_mpi_scan (&result, GCRYMPI_FMT_USG, in, data_buf_size, NULL);
421         xfree (data_buf);
422         if (err)
423           {
424             log_error ("ecdh failed to create a plain text MPI: %s\n",
425                        gpg_strerror (err));
426             return err;
427           }
428
429         *r_result = result;
430       }
431   }
432
433   return err;
434 }
435
436
437 static gcry_mpi_t
438 gen_k (unsigned nbits)
439 {
440   gcry_mpi_t k;
441
442   k = gcry_mpi_snew (nbits);
443   if (DBG_CRYPTO)
444     log_debug ("choosing a random k of %u bits\n", nbits);
445
446   gcry_mpi_randomize (k, nbits-1, GCRY_STRONG_RANDOM);
447
448   if (DBG_CRYPTO)
449     {
450       unsigned char *buffer;
451       if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, k))
452         BUG ();
453       log_debug ("ephemeral scalar MPI #0: %s\n", buffer);
454       gcry_free (buffer);
455     }
456
457   return k;
458 }
459
460
461 /* Generate an ephemeral key for the public ECDH key in PKEY.  On
462    success the generated key is stored at R_K; on failure NULL is
463    stored at R_K and an error code returned.  */
464 gpg_error_t
465 pk_ecdh_generate_ephemeral_key (gcry_mpi_t *pkey, gcry_mpi_t *r_k)
466 {
467   unsigned int nbits;
468   gcry_mpi_t k;
469
470   *r_k = NULL;
471
472   nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
473   if (!nbits)
474     return gpg_error (GPG_ERR_TOO_SHORT);
475   k = gen_k (nbits);
476   if (!k)
477     BUG ();
478
479   *r_k = k;
480   return 0;
481 }
482
483
484
485 /* Perform ECDH decryption.   */
486 int
487 pk_ecdh_decrypt (gcry_mpi_t * result, const byte sk_fp[MAX_FINGERPRINT_LEN],
488                  gcry_mpi_t data, gcry_mpi_t shared, gcry_mpi_t * skey)
489 {
490   if (!data)
491     return gpg_error (GPG_ERR_BAD_MPI);
492   return pk_ecdh_encrypt_with_shared_point (0 /*=decryption*/, shared,
493                                             sk_fp, data/*encr data as an MPI*/,
494                                             skey, result);
495 }