LCOV - code coverage report
Current view: top level - g10 - ecdh.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 115 200 57.5 %
Date: 2016-12-01 18:37:21 Functions: 4 5 80.0 %

          Line data    Source code
       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           0 : pk_ecdh_default_params (unsigned int qbits)
      54             : {
      55             :   byte *kek_params;
      56             :   int i;
      57             : 
      58           0 :   kek_params = xtrymalloc (4);
      59           0 :   if (!kek_params)
      60           0 :     return NULL;
      61           0 :   kek_params[0] = 3; /* Number of bytes to follow. */
      62           0 :   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           0 :   for (i=0; i < DIM (kek_params_table); i++)
      68             :     {
      69           0 :       if (kek_params_table[i].qbits >= qbits
      70           0 :           || i+1 == DIM (kek_params_table))
      71             :         {
      72           0 :           kek_params[2] = kek_params_table[i].openpgp_hash_id;
      73           0 :           kek_params[3] = kek_params_table[i].openpgp_cipher_id;
      74           0 :           break;
      75             :         }
      76             :     }
      77           0 :   log_assert (i < DIM (kek_params_table));
      78           0 :   if (DBG_CRYPTO)
      79           0 :     log_printhex ("ECDH KEK params are", kek_params, sizeof(kek_params) );
      80             : 
      81           0 :   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          48 : 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          48 :   *r_result = NULL;
     110             : 
     111          48 :   nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
     112          48 :   if (!nbits)
     113           0 :     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          48 :     nbytes = (mpi_get_nbits (pkey[1] /* public point */)+7)/8;
     121          48 :     secret_x = xtrymalloc_secure (nbytes);
     122          48 :     if (!secret_x)
     123           0 :       return gpg_error_from_syserror ();
     124             : 
     125          48 :     err = gcry_mpi_print (GCRYMPI_FMT_USG, secret_x, nbytes,
     126             :                           &nbytes, shared_mpi);
     127          48 :     if (err)
     128             :       {
     129           0 :         xfree (secret_x);
     130           0 :         log_error ("ECDH ephemeral export of shared point failed: %s\n",
     131             :                    gpg_strerror (err));
     132           0 :         return err;
     133             :       }
     134             : 
     135             :     /* Expected size of the x component */
     136          48 :     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          48 :     if (nbytes < secret_x_size)
     148             :       {
     149           0 :         xfree (secret_x);
     150           0 :         return gpg_error (GPG_ERR_BAD_DATA);
     151             :       }
     152             : 
     153             :     /* Remove the prefix.  */
     154          48 :     if ((nbytes & 1))
     155          48 :       memmove (secret_x, secret_x+1, secret_x_size);
     156             : 
     157             :     /* Clear the rest of data.  */
     158          48 :     if (nbytes - secret_x_size)
     159          48 :       memset (secret_x+secret_x_size, 0, nbytes-secret_x_size);
     160             : 
     161          48 :     if (DBG_CRYPTO)
     162           0 :       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          48 :   if (!gcry_mpi_get_flag (pkey[2], GCRYMPI_FLAG_OPAQUE))
     174             :     {
     175           0 :       xfree (secret_x);
     176           0 :       return gpg_error (GPG_ERR_BUG);
     177             :     }
     178          48 :   kek_params = gcry_mpi_get_opaque (pkey[2], &nbits);
     179          48 :   kek_params_size = (nbits+7)/8;
     180             : 
     181          48 :   if (DBG_CRYPTO)
     182           0 :     log_printhex ("ecdh KDF params:", kek_params, kek_params_size);
     183             : 
     184             :   /* Expect 4 bytes  03 01 hash_alg symm_alg.  */
     185          48 :   if (kek_params_size != 4 || kek_params[0] != 3 || kek_params[1] != 1)
     186             :     {
     187           0 :       xfree (secret_x);
     188           0 :       return gpg_error (GPG_ERR_BAD_PUBKEY);
     189             :     }
     190             : 
     191          48 :   kdf_hash_algo = kek_params[2];
     192          48 :   kdf_encr_algo = kek_params[3];
     193             : 
     194          48 :   if (DBG_CRYPTO)
     195           0 :     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          48 :   if (kdf_hash_algo != GCRY_MD_SHA256
     200          30 :       && kdf_hash_algo != GCRY_MD_SHA384
     201          15 :       && kdf_hash_algo != GCRY_MD_SHA512)
     202             :     {
     203           0 :       xfree (secret_x);
     204           0 :       return gpg_error (GPG_ERR_BAD_PUBKEY);
     205             :     }
     206          48 :   if (kdf_encr_algo != CIPHER_ALGO_AES
     207          30 :       && kdf_encr_algo != CIPHER_ALGO_AES192
     208          30 :       && kdf_encr_algo != CIPHER_ALGO_AES256)
     209             :     {
     210           0 :       xfree (secret_x);
     211           0 :       return gpg_error (GPG_ERR_BAD_PUBKEY);
     212             :     }
     213             : 
     214             :   /* Build kdf_params.  */
     215             :   {
     216             :     IOBUF obuf;
     217             : 
     218          48 :     obuf = iobuf_temp();
     219             :     /* variable-length field 1, curve name OID */
     220          48 :     err = gpg_mpi_write_nohdr (obuf, pkey[0]);
     221             :     /* fixed-length field 2 */
     222          48 :     iobuf_put (obuf, PUBKEY_ALGO_ECDH);
     223             :     /* variable-length field 3, KDF params */
     224          48 :     err = (err ? err : gpg_mpi_write_nohdr (obuf, pkey[2]));
     225             :     /* fixed-length field 4 */
     226          48 :     iobuf_write (obuf, "Anonymous Sender    ", 20);
     227             :     /* fixed-length field 5, recipient fp */
     228          48 :     iobuf_write (obuf, pk_fp, 20);
     229             : 
     230          48 :     message_size = iobuf_temp_to_buffer (obuf, message, sizeof message);
     231          48 :     iobuf_close (obuf);
     232          48 :     if (err)
     233             :       {
     234           0 :         xfree (secret_x);
     235           0 :         return err;
     236             :       }
     237             : 
     238          48 :     if(DBG_CRYPTO)
     239           0 :       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          48 :     err = gcry_md_open (&h, kdf_hash_algo, 0);
     248          48 :     if (err)
     249             :       {
     250           0 :         log_error ("gcry_md_open failed for kdf_hash_algo %d: %s",
     251             :                    kdf_hash_algo, gpg_strerror (err));
     252           0 :         xfree (secret_x);
     253           0 :         return err;
     254             :       }
     255          48 :     gcry_md_write(h, "\x00\x00\x00\x01", 4);      /* counter = 1 */
     256          48 :     gcry_md_write(h, secret_x, secret_x_size);    /* x of the point X */
     257          48 :     gcry_md_write(h, message, message_size);      /* KDF parameters */
     258             : 
     259          48 :     gcry_md_final (h);
     260             : 
     261          48 :     log_assert( gcry_md_get_algo_dlen (kdf_hash_algo) >= 32 );
     262             : 
     263          48 :     memcpy (secret_x, gcry_md_read (h, kdf_hash_algo),
     264          48 :             gcry_md_get_algo_dlen (kdf_hash_algo));
     265          48 :     gcry_md_close (h);
     266             : 
     267          48 :     old_size = secret_x_size;
     268          48 :     log_assert( old_size >= gcry_cipher_get_algo_keylen( kdf_encr_algo ) );
     269          48 :     secret_x_size = gcry_cipher_get_algo_keylen( kdf_encr_algo );
     270          48 :     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          48 :     memset (secret_x+secret_x_size, 0, old_size - secret_x_size);
     274          48 :     if (DBG_CRYPTO)
     275           0 :       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          48 :     err = gcry_cipher_open (&hd, kdf_encr_algo, GCRY_CIPHER_MODE_AESWRAP, 0);
     289          48 :     if (err)
     290             :       {
     291           0 :         log_error ("ecdh failed to initialize AESWRAP: %s\n",
     292             :                    gpg_strerror (err));
     293           0 :         xfree (secret_x);
     294           0 :         return err;
     295             :       }
     296             : 
     297          48 :     err = gcry_cipher_setkey (hd, secret_x, secret_x_size);
     298          48 :     xfree (secret_x);
     299          48 :     secret_x = NULL;
     300          48 :     if (err)
     301             :       {
     302           0 :         gcry_cipher_close (hd);
     303           0 :         log_error ("ecdh failed in gcry_cipher_setkey: %s\n",
     304             :                    gpg_strerror (err));
     305           0 :         return err;
     306             :       }
     307             : 
     308          48 :     data_buf_size = (gcry_mpi_get_nbits(data)+7)/8;
     309          48 :     if ((data_buf_size & 7) != (is_encrypt ? 0 : 1))
     310             :       {
     311           0 :         log_error ("can't use a shared secret of %d bytes for ecdh\n",
     312             :                    data_buf_size);
     313           0 :         return gpg_error (GPG_ERR_BAD_DATA);
     314             :       }
     315             : 
     316          48 :     data_buf = xtrymalloc_secure( 1 + 2*data_buf_size + 8);
     317          48 :     if (!data_buf)
     318             :       {
     319           0 :         err = gpg_error_from_syserror ();
     320           0 :         gcry_cipher_close (hd);
     321           0 :         return err;
     322             :       }
     323             : 
     324          48 :     if (is_encrypt)
     325             :       {
     326          24 :         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          24 :         err = gcry_mpi_print (GCRYMPI_FMT_USG, in,
     331             :                              data_buf_size, &nbytes, data/*in*/);
     332          24 :         if (err)
     333             :           {
     334           0 :             log_error ("ecdh failed to export DEK: %s\n", gpg_strerror (err));
     335           0 :             gcry_cipher_close (hd);
     336           0 :             xfree (data_buf);
     337           0 :             return err;
     338             :           }
     339             : 
     340          24 :         if (DBG_CRYPTO)
     341           0 :           log_printhex ("ecdh encrypting  :", in, data_buf_size );
     342             : 
     343          24 :         err = gcry_cipher_encrypt (hd, data_buf+1, data_buf_size+8,
     344             :                                    in, data_buf_size);
     345          24 :         memset (in, 0, data_buf_size);
     346          24 :         gcry_cipher_close (hd);
     347          24 :         if (err)
     348             :           {
     349           0 :             log_error ("ecdh failed in gcry_cipher_encrypt: %s\n",
     350             :                        gpg_strerror (err));
     351           0 :             xfree (data_buf);
     352           0 :             return err;
     353             :           }
     354          24 :         data_buf[0] = data_buf_size+8;
     355             : 
     356          24 :         if (DBG_CRYPTO)
     357           0 :           log_printhex ("ecdh encrypted to:", data_buf+1, data_buf[0] );
     358             : 
     359          24 :         result = gcry_mpi_set_opaque (NULL, data_buf, 8 * (1+data_buf[0]));
     360          24 :         if (!result)
     361             :           {
     362           0 :             err = gpg_error_from_syserror ();
     363           0 :             xfree (data_buf);
     364           0 :             log_error ("ecdh failed to create an MPI: %s\n",
     365             :                        gpg_strerror (err));
     366           0 :             return err;
     367             :           }
     368             : 
     369          24 :         *r_result = result;
     370             :       }
     371             :     else
     372             :       {
     373             :         byte *in;
     374             :         const void *p;
     375             : 
     376          24 :         p = gcry_mpi_get_opaque (data, &nbits);
     377          24 :         nbytes = (nbits+7)/8;
     378          24 :         if (!p || nbytes > data_buf_size || !nbytes)
     379             :           {
     380           0 :             xfree (data_buf);
     381           0 :             return gpg_error (GPG_ERR_BAD_MPI);
     382             :           }
     383          24 :         memcpy (data_buf, p, nbytes);
     384          24 :         if (data_buf[0] != nbytes-1)
     385             :           {
     386           0 :             log_error ("ecdh inconsistent size\n");
     387           0 :             xfree (data_buf);
     388           0 :             return gpg_error (GPG_ERR_BAD_MPI);
     389             :           }
     390          24 :         in = data_buf+data_buf_size;
     391          24 :         data_buf_size = data_buf[0];
     392             : 
     393          24 :         if (DBG_CRYPTO)
     394           0 :           log_printhex ("ecdh decrypting :", data_buf+1, data_buf_size);
     395             : 
     396          24 :         err = gcry_cipher_decrypt (hd, in, data_buf_size, data_buf+1,
     397             :                                    data_buf_size);
     398          24 :         gcry_cipher_close (hd);
     399          24 :         if (err)
     400             :           {
     401           0 :             log_error ("ecdh failed in gcry_cipher_decrypt: %s\n",
     402             :                        gpg_strerror (err));
     403           0 :             xfree (data_buf);
     404           0 :             return err;
     405             :           }
     406             : 
     407          24 :         data_buf_size -= 8;
     408             : 
     409          24 :         if (DBG_CRYPTO)
     410           0 :           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          24 :         err = gcry_mpi_scan (&result, GCRYMPI_FMT_USG, in, data_buf_size, NULL);
     421          24 :         xfree (data_buf);
     422          24 :         if (err)
     423             :           {
     424           0 :             log_error ("ecdh failed to create a plain text MPI: %s\n",
     425             :                        gpg_strerror (err));
     426           0 :             return err;
     427             :           }
     428             : 
     429          24 :         *r_result = result;
     430             :       }
     431             :   }
     432             : 
     433          48 :   return err;
     434             : }
     435             : 
     436             : 
     437             : static gcry_mpi_t
     438          24 : gen_k (unsigned nbits)
     439             : {
     440             :   gcry_mpi_t k;
     441             : 
     442          24 :   k = gcry_mpi_snew (nbits);
     443          24 :   if (DBG_CRYPTO)
     444           0 :     log_debug ("choosing a random k of %u bits\n", nbits);
     445             : 
     446          24 :   gcry_mpi_randomize (k, nbits-1, GCRY_STRONG_RANDOM);
     447             : 
     448          24 :   if (DBG_CRYPTO)
     449             :     {
     450             :       unsigned char *buffer;
     451           0 :       if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buffer, NULL, k))
     452           0 :         BUG ();
     453           0 :       log_debug ("ephemeral scalar MPI #0: %s\n", buffer);
     454           0 :       gcry_free (buffer);
     455             :     }
     456             : 
     457          24 :   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          24 : 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          24 :   *r_k = NULL;
     471             : 
     472          24 :   nbits = pubkey_nbits (PUBKEY_ALGO_ECDH, pkey);
     473          24 :   if (!nbits)
     474           0 :     return gpg_error (GPG_ERR_TOO_SHORT);
     475          24 :   k = gen_k (nbits);
     476          24 :   if (!k)
     477           0 :     BUG ();
     478             : 
     479          24 :   *r_k = k;
     480          24 :   return 0;
     481             : }
     482             : 
     483             : 
     484             : 
     485             : /* Perform ECDH decryption.   */
     486             : int
     487          24 : 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          24 :   if (!data)
     491           0 :     return gpg_error (GPG_ERR_BAD_MPI);
     492          24 :   return pk_ecdh_encrypt_with_shared_point (0 /*=decryption*/, shared,
     493             :                                             sk_fp, data/*encr data as an MPI*/,
     494             :                                             skey, result);
     495             : }

Generated by: LCOV version 1.11