-remove async ecc key generation, not needed
[oweals/gnunet.git] / src / util / crypto_ecc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012, 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/crypto_ecc.c
23  * @brief public key cryptography (ECC) with libgcrypt
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <gcrypt.h>
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30
31 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS 
32
33 #define CURVE "NIST P-256"
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
36
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
38
39 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40
41 /**
42  * Log an error message at log-level 'level' that indicates
43  * a failure of the command 'cmd' with the message given
44  * by gcry_strerror(rc).
45  */
46 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
47
48
49 /**
50  * The private information of an ECC private key.
51  */
52 struct GNUNET_CRYPTO_EccPrivateKey
53 {
54   
55   /**
56    * Libgcrypt S-expression for the ECC key.
57    */
58   gcry_sexp_t sexp;
59 };
60
61
62 /**
63  * Free memory occupied by ECC key
64  *
65  * @param privatekey pointer to the memory to free
66  */
67 void
68 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
69 {
70   gcry_sexp_release (privatekey->sexp);
71   GNUNET_free (privatekey);
72 }
73
74
75 /**
76  * Extract values from an S-expression.
77  *
78  * @param array where to store the result(s)
79  * @param sexp S-expression to parse
80  * @param topname top-level name in the S-expression that is of interest
81  * @param elems names of the elements to extract
82  * @return 0 on success
83  */
84 static int
85 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
86                const char *elems)
87 {
88   gcry_sexp_t list;
89   gcry_sexp_t l2;
90   const char *s;
91   unsigned int i;
92   unsigned int idx;
93
94   list = gcry_sexp_find_token (sexp, topname, 0);
95   if (! list)  
96     return 1;  
97   l2 = gcry_sexp_cadr (list);
98   gcry_sexp_release (list);
99   list = l2;
100   if (! list)  
101     return 2;  
102
103   idx = 0;
104   for (s = elems; *s; s++, idx++)
105   {
106     l2 = gcry_sexp_find_token (list, s, 1);
107     if (! l2)
108     {
109       for (i = 0; i < idx; i++)
110       {
111         gcry_free (array[i]);
112         array[i] = NULL;
113       }
114       gcry_sexp_release (list);
115       return 3;                 /* required parameter not found */
116     }
117     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
118     gcry_sexp_release (l2);
119     if (! array[idx])
120     {
121       for (i = 0; i < idx; i++)
122       {
123         gcry_free (array[i]);
124         array[i] = NULL;
125       }
126       gcry_sexp_release (list);
127       return 4;                 /* required parameter is invalid */
128     }
129   }
130   gcry_sexp_release (list);
131   return 0;
132 }
133
134
135 /**
136  * Extract the public key for the given private key.
137  *
138  * @param priv the private key
139  * @param pub where to write the public key
140  */
141 void
142 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
143                                   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
144 {
145   gcry_mpi_t skey;
146   size_t size;
147   int rc;
148
149   memset (pub, 0, sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
150   rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
151   if (rc)
152     rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
153   if (rc)
154     rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
155   GNUNET_assert (0 == rc);
156   pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
157   size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
158   GNUNET_assert (0 ==
159                  gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
160                                  skey));
161   pub->len = htons (size);
162   gcry_mpi_release (skey);
163 }
164
165
166 /**
167  * Convert a public key to a string.
168  *
169  * @param pub key to convert
170  * @return string representing  'pub'
171  */
172 char *
173 GNUNET_CRYPTO_ecc_public_key_to_string (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
174 {
175   char *pubkeybuf;
176   size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
177   char *end;
178
179   if (keylen % 5 > 0)
180     keylen += 5 - keylen % 5;
181   keylen /= 5;
182   pubkeybuf = GNUNET_malloc (keylen + 1);
183   end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 
184                                        sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded), 
185                                        pubkeybuf, 
186                                        keylen);
187   if (NULL == end)
188   {
189     GNUNET_free (pubkeybuf);
190     return NULL;
191   }
192   *end = '\0';
193   return pubkeybuf;
194 }
195
196
197 /**
198  * Convert a string representing a public key to a public key.
199  *
200  * @param enc encoded public key
201  * @param enclen number of bytes in enc (without 0-terminator)
202  * @param pub where to store the public key
203  * @return GNUNET_OK on success
204  */
205 int
206 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc, 
207                                           size_t enclen,
208                                           struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
209 {
210   size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
211
212   if (keylen % 5 > 0)
213     keylen += 5 - keylen % 5;
214   keylen /= 5;
215   if (enclen != keylen)
216     return GNUNET_SYSERR;
217
218   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
219                                                   pub,
220                                                   sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
221     return GNUNET_SYSERR;
222   if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
223        (ntohs (pub->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH) )
224     return GNUNET_SYSERR;
225   return GNUNET_OK;
226 }
227
228
229 /**
230  * Convert the given public key from the network format to the
231  * S-expression that can be used by libgcrypt.
232  *
233  * @param publicKey public key to decode
234  * @return NULL on error
235  */
236 static gcry_sexp_t
237 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
238 {
239   gcry_sexp_t result;
240   gcry_mpi_t q;
241   size_t size;
242   size_t erroff;
243   int rc;
244
245   if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH) 
246   {
247     GNUNET_break (0);
248     return NULL;
249   }
250   size = ntohs (publicKey->len);
251   if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
252   {
253     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
254     return NULL;
255   }
256
257   rc = gcry_sexp_build (&result, &erroff, 
258                         "(public-key(ecdsa(curve \"" CURVE "\")(q %m)))",
259                         q);
260   gcry_mpi_release (q);
261   if (0 != rc)
262   {
263     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
264     return NULL;
265   }
266 #if EXTRA_CHECKS
267   if (0 != (rc = gcry_pk_testkey (result)))
268   {
269     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
270     gcry_sexp_release (result);
271     return NULL;
272   }
273 #endif
274   return result;
275 }
276
277
278 /**
279  * Encode the private key in a format suitable for
280  * storing it into a file.
281  *
282  * @param key key to encode
283  * @return encoding of the private key.
284  *    The first 4 bytes give the size of the array, as usual.
285  */
286 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
287 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
288 {
289   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
290   char buf[65536];
291   uint16_t be;
292   size_t size;
293
294 #if EXTRA_CHECKS
295   if (0 != gcry_pk_testkey (key->sexp))
296   {
297     GNUNET_break (0);
298     return NULL;
299   }
300 #endif
301   size = gcry_sexp_sprint (key->sexp, 
302                            GCRYSEXP_FMT_DEFAULT,
303                            &buf[2], sizeof (buf) - sizeof (uint16_t));
304   if (0 == size)
305   {
306     GNUNET_break (0);
307     return NULL;
308   }
309   GNUNET_assert (size < 65536 - sizeof (uint16_t));
310   be = htons ((uint16_t) size + (sizeof (be)));
311   memcpy (buf, &be, sizeof (be));
312   size += sizeof (be);
313   retval = GNUNET_malloc (size);
314   memcpy (retval, buf, size);
315   return retval;
316 }
317
318
319 /**
320  * Decode the private key from the file-format back
321  * to the "normal", internal format.
322  *
323  * @param buf the buffer where the private key data is stored
324  * @param len the length of the data in 'buffer'
325  * @param validate GNUNET_YES to validate that the key is well-formed,
326  *                 GNUNET_NO if the key comes from a totally trusted source 
327  *                 and validation is considered too expensive
328  * @return NULL on error
329  */
330 struct GNUNET_CRYPTO_EccPrivateKey *
331 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
332                               size_t len,
333                               int validate)
334 {
335   struct GNUNET_CRYPTO_EccPrivateKey *ret;
336   uint16_t be;
337   gcry_sexp_t sexp;
338   int rc;
339   size_t erroff;
340
341   if (len < sizeof (uint16_t)) 
342     return NULL;
343   memcpy (&be, buf, sizeof (be));
344   if (len < ntohs (be))
345     return NULL;
346   len = ntohs (be);
347   if (0 != (rc = gcry_sexp_sscan (&sexp,
348                                   &erroff,
349                                   &buf[2],
350                                   len - sizeof (uint16_t))))
351   {
352     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
353     return NULL;
354   }  
355   if ( (GNUNET_YES == validate) &&
356        (0 != (rc = gcry_pk_testkey (sexp))) )
357   {
358     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
359     return NULL;
360   }
361   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
362   ret->sexp = sexp;
363   return ret;
364 }
365
366
367 /**
368  * Create a new private key. Caller must free return value.
369  *
370  * @return fresh private key
371  */
372 struct GNUNET_CRYPTO_EccPrivateKey *
373 GNUNET_CRYPTO_ecc_key_create ()
374 {
375   struct GNUNET_CRYPTO_EccPrivateKey *ret;
376   gcry_sexp_t s_key;
377   gcry_sexp_t s_keyparam;
378   int rc;
379
380   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
381                                   "(genkey(ecdsa(curve \"" CURVE "\")))")))
382   {
383     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
384     return NULL;
385   }
386   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
387   {
388     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
389     gcry_sexp_release (s_keyparam);
390     return NULL;
391   }
392   gcry_sexp_release (s_keyparam);
393 #if EXTRA_CHECKS
394   if (0 != (rc = gcry_pk_testkey (s_key)))
395   {
396     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
397     gcry_sexp_release (s_key);
398     return NULL;
399   }
400 #endif
401   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
402   ret->sexp = s_key;
403   return ret;
404 }
405
406
407 /**
408  * Wait for a short time (we're trying to lock a file or want
409  * to give another process a shot at finishing a disk write, etc.).
410  * Sleeps for 100ms (as that should be long enough for virtually all
411  * modern systems to context switch and allow another process to do
412  * some 'real' work).
413  */
414 static void
415 short_wait ()
416 {
417   struct GNUNET_TIME_Relative timeout;
418
419   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
420   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
421 }
422
423
424 /**
425  * Create a new private key by reading it from a file.  If the
426  * files does not exist, create a new key and write it to the
427  * file.  Caller must free return value.  Note that this function
428  * can not guarantee that another process might not be trying
429  * the same operation on the same file at the same time.
430  * If the contents of the file
431  * are invalid the old file is deleted and a fresh key is
432  * created.
433  *
434  * @return new private key, NULL on error (for example,
435  *   permission denied)
436  */
437 struct GNUNET_CRYPTO_EccPrivateKey *
438 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
439 {
440   struct GNUNET_CRYPTO_EccPrivateKey *ret;
441   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
442   uint16_t len;
443   struct GNUNET_DISK_FileHandle *fd;
444   unsigned int cnt;
445   int ec;
446   uint64_t fs;
447   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
448   struct GNUNET_PeerIdentity pid;
449
450   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
451     return NULL;
452   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
453   {
454     fd = GNUNET_DISK_file_open (filename,
455                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
456                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
457                                 GNUNET_DISK_PERM_USER_READ |
458                                 GNUNET_DISK_PERM_USER_WRITE);
459     if (NULL == fd)
460     {
461       if (errno == EEXIST)
462       {
463         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
464         {
465           /* must exist but not be accessible, fail for good! */
466           if (0 != ACCESS (filename, R_OK))
467             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
468           else
469             GNUNET_break (0);   /* what is going on!? */
470           return NULL;
471         }
472         continue;
473       }
474       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
475       return NULL;
476     }
477     cnt = 0;
478
479     while (GNUNET_YES !=
480            GNUNET_DISK_file_lock (fd, 0,
481                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
482                                   GNUNET_YES))
483     {
484       short_wait ();
485       if (0 == ++cnt % 10)
486       {
487         ec = errno;
488         LOG (GNUNET_ERROR_TYPE_ERROR,
489              _("Could not acquire lock on file `%s': %s...\n"), filename,
490              STRERROR (ec));
491       }
492     }
493     LOG (GNUNET_ERROR_TYPE_INFO,
494          _("Creating a new private key.  This may take a while.\n"));
495     ret = GNUNET_CRYPTO_ecc_key_create ();
496     GNUNET_assert (ret != NULL);
497     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
498     GNUNET_assert (enc != NULL);
499     GNUNET_assert (ntohs (enc->size) ==
500                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
501     GNUNET_free (enc);
502
503     GNUNET_DISK_file_sync (fd);
504     if (GNUNET_YES !=
505         GNUNET_DISK_file_unlock (fd, 0,
506                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
507       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
508     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
509     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
510     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
511     return ret;
512   }
513   /* key file exists already, read it! */
514   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
515                               GNUNET_DISK_PERM_NONE);
516   if (NULL == fd)
517   {
518     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
519     return NULL;
520   }
521   cnt = 0;
522   while (1)
523   {
524     if (GNUNET_YES !=
525         GNUNET_DISK_file_lock (fd, 0,
526                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
527                                GNUNET_NO))
528     {
529       if (0 == ++cnt % 60)
530       {
531         ec = errno;
532         LOG (GNUNET_ERROR_TYPE_ERROR,
533              _("Could not acquire lock on file `%s': %s...\n"), filename,
534              STRERROR (ec));
535         LOG (GNUNET_ERROR_TYPE_ERROR,
536              _
537              ("This may be ok if someone is currently generating a private key.\n"));
538       }
539       short_wait ();
540       continue;
541     }
542     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
543     {
544       /* eh, what!? File we opened is now gone!? */
545       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
546       if (GNUNET_YES !=
547           GNUNET_DISK_file_unlock (fd, 0,
548                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
549         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
550       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
551
552       return NULL;
553     }
554     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
555       fs = 0;
556     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
557     {
558       /* maybe we got the read lock before the key generating
559        * process had a chance to get the write lock; give it up! */
560       if (GNUNET_YES !=
561           GNUNET_DISK_file_unlock (fd, 0,
562                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
563         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
564       if (0 == ++cnt % 10)
565       {
566         LOG (GNUNET_ERROR_TYPE_ERROR,
567              _
568              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
569              filename, (unsigned int) fs,
570              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
571         LOG (GNUNET_ERROR_TYPE_ERROR,
572              _
573              ("This may be ok if someone is currently generating a key.\n"));
574       }
575       short_wait ();                /* wait a bit longer! */
576       continue;
577     }
578     break;
579   }
580   enc = GNUNET_malloc (fs);
581   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
582   len = ntohs (enc->size);
583   ret = NULL;
584   if ((len > fs) ||
585       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len, GNUNET_YES))))
586   {
587     LOG (GNUNET_ERROR_TYPE_ERROR,
588          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
589          filename);
590     if (0 != UNLINK (filename))
591     {
592       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
593     }
594   }
595   GNUNET_free (enc);
596   if (GNUNET_YES !=
597       GNUNET_DISK_file_unlock (fd, 0,
598                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
599     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
600   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
601   if (ret != NULL)
602   {
603     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
604     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
605   }
606   return ret;
607 }
608
609
610 /**
611  * Create a new private key by reading our peer's key from
612  * the file specified in the configuration.
613  *
614  * @return new private key, NULL on error (for example,
615  *   permission denied)
616  */
617 struct GNUNET_CRYPTO_EccPrivateKey *
618 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
619 {
620   struct GNUNET_CRYPTO_EccPrivateKey *pk;
621   char *fn;
622
623   if (GNUNET_OK != 
624       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
625     return NULL;
626   pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
627   GNUNET_free (fn);
628   return pk;
629 }
630
631
632 /**
633  * Setup a key file for a peer given the name of the
634  * configuration file (!).  This function is used so that
635  * at a later point code can be certain that reading a
636  * key is fast (for example in time-dependent testcases).
637  *
638  * @param cfg_name name of the configuration file to use
639  */
640 void
641 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
642 {
643   struct GNUNET_CONFIGURATION_Handle *cfg;
644   struct GNUNET_CRYPTO_EccPrivateKey *pk;
645
646   cfg = GNUNET_CONFIGURATION_create ();
647   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
648   pk = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
649   if (NULL != pk)
650     GNUNET_CRYPTO_ecc_key_free (pk);
651   GNUNET_CONFIGURATION_destroy (cfg);
652 }
653
654
655 /**
656  * Retrieve the identity of the host's peer.
657  *
658  * @param cfg configuration to use
659  * @param dst pointer to where to write the peer identity
660  * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
661  *         could not be retrieved
662  */
663 int
664 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
665                                  struct GNUNET_PeerIdentity *dst)
666 {
667   struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
668   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
669
670   if (NULL == (my_private_key = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
671   {
672     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
673                 _("Could not load peer's private key\n"));
674     return GNUNET_SYSERR;
675   }
676   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
677   GNUNET_CRYPTO_ecc_key_free (my_private_key);
678   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &dst->hashPubKey);
679   return GNUNET_OK;
680 }
681
682
683 /**
684  * Convert the data specified in the given purpose argument to an
685  * S-expression suitable for signature operations.
686  *
687  * @param purpose data to convert
688  * @return converted s-expression
689  */
690 static gcry_sexp_t
691 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
692 {
693   struct GNUNET_CRYPTO_ShortHashCode hc;
694   size_t bufSize;
695   gcry_sexp_t data;
696
697   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
698 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
699   bufSize = strlen (FORMATSTRING) + 1;
700   {
701     char buff[bufSize];
702
703     memcpy (buff, FORMATSTRING, bufSize);
704     memcpy (&buff
705             [bufSize -
706              strlen
707              ("01234567890123456789012345678901))")
708              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
709     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
710   }
711 #undef FORMATSTRING
712   return data;
713 }
714
715
716 /**
717  * Sign a given block.
718  *
719  * @param key private key to use for the signing
720  * @param purpose what to sign (size, purpose)
721  * @param sig where to write the signature
722  * @return GNUNET_SYSERR on error, GNUNET_OK on success
723  */
724 int
725 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
726                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
727                         struct GNUNET_CRYPTO_EccSignature *sig)
728 {
729   gcry_sexp_t result;
730   gcry_sexp_t data;
731   size_t ssize;
732   int rc;
733
734   data = data_to_pkcs1 (purpose);
735   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
736   {
737     LOG (GNUNET_ERROR_TYPE_WARNING,
738          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
739          __LINE__, gcry_strerror (rc));
740     gcry_sexp_release (data);
741     return GNUNET_SYSERR;
742   }
743   gcry_sexp_release (data);
744   ssize = gcry_sexp_sprint (result, 
745                             GCRYSEXP_FMT_DEFAULT,
746                             sig->sexpr,
747                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
748   if (0 == ssize)
749   {
750     GNUNET_break (0);
751     return GNUNET_SYSERR;
752   }
753   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
754   /* padd with zeros */
755   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
756   gcry_sexp_release (result);
757   return GNUNET_OK;
758 }
759
760
761 /**
762  * Verify signature.
763  *
764  * @param purpose what is the purpose that the signature should have?
765  * @param validate block to validate (size, purpose, data)
766  * @param sig signature that is being validated
767  * @param publicKey public key of the signer
768  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
769  */
770 int
771 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
772                           const struct GNUNET_CRYPTO_EccSignaturePurpose
773                           *validate,
774                           const struct GNUNET_CRYPTO_EccSignature *sig,
775                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
776                           *publicKey)
777 {
778   gcry_sexp_t data;
779   gcry_sexp_t sigdata;
780   size_t size;
781   gcry_sexp_t psexp;
782   size_t erroff;
783   int rc;
784
785   if (purpose != ntohl (validate->purpose))
786     return GNUNET_SYSERR;       /* purpose mismatch */
787   size = ntohs (sig->size);
788   if ( (size < sizeof (uint16_t)) ||
789        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
790     return GNUNET_SYSERR; /* size out of range */
791   data = data_to_pkcs1 (validate);
792   GNUNET_assert (0 ==
793                  gcry_sexp_sscan (&sigdata, &erroff, 
794                                   sig->sexpr, size - sizeof (uint16_t)));
795   if (! (psexp = decode_public_key (publicKey)))
796   {
797     gcry_sexp_release (data);
798     gcry_sexp_release (sigdata);
799     return GNUNET_SYSERR;
800   }
801   rc = gcry_pk_verify (sigdata, data, psexp);
802   gcry_sexp_release (psexp);
803   gcry_sexp_release (data);
804   gcry_sexp_release (sigdata);
805   if (0 != rc)
806   {
807     LOG (GNUNET_ERROR_TYPE_WARNING,
808          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
809          __LINE__, gcry_strerror (rc));
810     return GNUNET_SYSERR;
811   }
812   return GNUNET_OK;
813 }
814
815
816 /**
817  * Derive key material from a public and a private ECC key.
818  *
819  * @param key private key to use for the ECDH (x)
820  * @param pub public key to use for the ECDY (yG)
821  * @param key_material where to write the key material (xyG)
822  * @return GNUNET_SYSERR on error, GNUNET_OK on success
823  */
824 int
825 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
826                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
827                         struct GNUNET_HashCode *key_material)
828
829   size_t slen;
830   size_t erroff;
831   int rc;
832   unsigned char sdata_buf[2048]; /* big enough to print dh-shared-secret as S-expression */
833   gcry_mpi_point_t result;
834   gcry_mpi_point_t q;
835   gcry_mpi_t d;
836   gcry_ctx_t ctx;
837   gcry_sexp_t psexp;
838   gcry_mpi_t result_x;
839   gcry_mpi_t result_y;
840
841   /* first, extract the q = dP value from the public key */
842   if (! (psexp = decode_public_key (pub)))
843     return GNUNET_SYSERR;
844   if (0 != (rc = gcry_mpi_ec_new (&ctx, psexp, NULL)))
845   {
846     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
847     return GNUNET_SYSERR;
848   }
849   gcry_sexp_release (psexp);
850   q = gcry_mpi_ec_get_point ("q", ctx, 0);
851   gcry_ctx_release (ctx);
852
853   /* second, extract the d value from our private key */
854   rc = key_from_sexp (&d, key->sexp, "private-key", "d");
855   if (rc)
856     rc = key_from_sexp (&d, key->sexp, "ecc", "d");
857   if (0 != rc)
858   {
859     GNUNET_break (0);
860     gcry_mpi_point_release (q);
861     return GNUNET_SYSERR;
862   }
863
864   /* create a new context for definitively the correct curve;
865      theoretically the 'public_key' might not use the right curve */
866   if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
867   {
868     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
869     gcry_mpi_release (d);
870     gcry_mpi_point_release (q);
871     return GNUNET_SYSERR;
872   }
873
874   /* then call the 'multiply' function, to compute the product */
875   GNUNET_assert (NULL != ctx);
876   result = gcry_mpi_point_new (0);
877   gcry_mpi_ec_mul (result, d, q, ctx);
878   gcry_mpi_point_release (q);
879   gcry_mpi_release (d);
880
881   /* finally, convert point to string for hashing */
882   result_x = gcry_mpi_new (256);
883   result_y = gcry_mpi_new (256);
884   if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
885   {
886     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
887     gcry_mpi_point_release (result);
888     gcry_ctx_release (ctx);
889     return GNUNET_SYSERR;
890   }
891   gcry_mpi_point_release (result);
892   gcry_ctx_release (ctx);
893   if (0 != (rc = gcry_sexp_build (&psexp, &erroff, 
894                                   "(dh-shared-secret (x %m)(y %m))",
895                                   result_x,
896                                   result_y)))
897   {
898     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
899     gcry_mpi_release (result_x);
900     gcry_mpi_release (result_y);
901     return GNUNET_SYSERR;
902   }
903   gcry_mpi_release (result_x);
904   gcry_mpi_release (result_y);
905   slen = gcry_sexp_sprint (psexp, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
906   GNUNET_assert (0 != slen);
907   gcry_sexp_release (psexp);
908   /* finally, get a string of the resulting S-expression and hash it to generate the key material */
909   GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
910   return GNUNET_OK;
911 }
912
913
914 /* end of crypto_ecc.c */