-introducing convenience function to load private key of peer
[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  * Try to read the private key from the given file.
409  *
410  * @param filename file to read the key from
411  * @return NULL on error
412  */
413 static struct GNUNET_CRYPTO_EccPrivateKey *
414 try_read_key (const char *filename)
415 {
416   struct GNUNET_CRYPTO_EccPrivateKey *ret;
417   struct GNUNET_DISK_FileHandle *fd;
418   OFF_T fs;
419
420   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
421     return NULL;
422
423   /* key file exists already, read it! */
424   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
425                                            GNUNET_DISK_PERM_NONE)))
426   {
427     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
428     return NULL;
429   }
430   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
431   {
432     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
433     (void) GNUNET_DISK_file_close (fd);
434     return NULL;
435   }
436   if (0 == fs)
437   {
438     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
439     return NULL;
440   }
441   if (fs > UINT16_MAX)
442   {
443     LOG (GNUNET_ERROR_TYPE_ERROR,
444          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
445          filename,
446          (unsigned long long) fs);
447     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
448     if (0 != UNLINK (filename))    
449       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
450     return NULL;
451   }
452   {
453     char enc[fs];
454
455     GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
456     if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs, GNUNET_YES)))
457     {
458       LOG (GNUNET_ERROR_TYPE_ERROR,
459            _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
460            filename,
461            (unsigned long long) fs);
462       GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
463       if (0 != UNLINK (filename))    
464         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
465       return NULL;
466     }
467   }
468   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
469   return ret;  
470 }
471
472
473 /**
474  * Wait for a short time (we're trying to lock a file or want
475  * to give another process a shot at finishing a disk write, etc.).
476  * Sleeps for 100ms (as that should be long enough for virtually all
477  * modern systems to context switch and allow another process to do
478  * some 'real' work).
479  */
480 static void
481 short_wait ()
482 {
483   struct GNUNET_TIME_Relative timeout;
484
485   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
486   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
487 }
488
489
490 /**
491  * Create a new private key by reading it from a file.  If the
492  * files does not exist, create a new key and write it to the
493  * file.  Caller must free return value.  Note that this function
494  * can not guarantee that another process might not be trying
495  * the same operation on the same file at the same time.
496  * If the contents of the file
497  * are invalid the old file is deleted and a fresh key is
498  * created.
499  *
500  * @return new private key, NULL on error (for example,
501  *   permission denied)
502  */
503 struct GNUNET_CRYPTO_EccPrivateKey *
504 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
505 {
506   struct GNUNET_CRYPTO_EccPrivateKey *ret;
507   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
508   uint16_t len;
509   struct GNUNET_DISK_FileHandle *fd;
510   unsigned int cnt;
511   int ec;
512   uint64_t fs;
513   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
514   struct GNUNET_PeerIdentity pid;
515
516   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
517     return NULL;
518   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
519   {
520     fd = GNUNET_DISK_file_open (filename,
521                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
522                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
523                                 GNUNET_DISK_PERM_USER_READ |
524                                 GNUNET_DISK_PERM_USER_WRITE);
525     if (NULL == fd)
526     {
527       if (errno == EEXIST)
528       {
529         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
530         {
531           /* must exist but not be accessible, fail for good! */
532           if (0 != ACCESS (filename, R_OK))
533             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
534           else
535             GNUNET_break (0);   /* what is going on!? */
536           return NULL;
537         }
538         continue;
539       }
540       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
541       return NULL;
542     }
543     cnt = 0;
544
545     while (GNUNET_YES !=
546            GNUNET_DISK_file_lock (fd, 0,
547                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
548                                   GNUNET_YES))
549     {
550       short_wait ();
551       if (0 == ++cnt % 10)
552       {
553         ec = errno;
554         LOG (GNUNET_ERROR_TYPE_ERROR,
555              _("Could not acquire lock on file `%s': %s...\n"), filename,
556              STRERROR (ec));
557       }
558     }
559     LOG (GNUNET_ERROR_TYPE_INFO,
560          _("Creating a new private key.  This may take a while.\n"));
561     ret = GNUNET_CRYPTO_ecc_key_create ();
562     GNUNET_assert (ret != NULL);
563     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
564     GNUNET_assert (enc != NULL);
565     GNUNET_assert (ntohs (enc->size) ==
566                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
567     GNUNET_free (enc);
568
569     GNUNET_DISK_file_sync (fd);
570     if (GNUNET_YES !=
571         GNUNET_DISK_file_unlock (fd, 0,
572                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
573       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
574     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
575     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
576     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
577     return ret;
578   }
579   /* key file exists already, read it! */
580   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
581                               GNUNET_DISK_PERM_NONE);
582   if (NULL == fd)
583   {
584     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
585     return NULL;
586   }
587   cnt = 0;
588   while (1)
589   {
590     if (GNUNET_YES !=
591         GNUNET_DISK_file_lock (fd, 0,
592                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
593                                GNUNET_NO))
594     {
595       if (0 == ++cnt % 60)
596       {
597         ec = errno;
598         LOG (GNUNET_ERROR_TYPE_ERROR,
599              _("Could not acquire lock on file `%s': %s...\n"), filename,
600              STRERROR (ec));
601         LOG (GNUNET_ERROR_TYPE_ERROR,
602              _
603              ("This may be ok if someone is currently generating a private key.\n"));
604       }
605       short_wait ();
606       continue;
607     }
608     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
609     {
610       /* eh, what!? File we opened is now gone!? */
611       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
612       if (GNUNET_YES !=
613           GNUNET_DISK_file_unlock (fd, 0,
614                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
615         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
616       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
617
618       return NULL;
619     }
620     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
621       fs = 0;
622     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
623     {
624       /* maybe we got the read lock before the key generating
625        * process had a chance to get the write lock; give it up! */
626       if (GNUNET_YES !=
627           GNUNET_DISK_file_unlock (fd, 0,
628                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
629         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
630       if (0 == ++cnt % 10)
631       {
632         LOG (GNUNET_ERROR_TYPE_ERROR,
633              _
634              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
635              filename, (unsigned int) fs,
636              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
637         LOG (GNUNET_ERROR_TYPE_ERROR,
638              _
639              ("This may be ok if someone is currently generating a key.\n"));
640       }
641       short_wait ();                /* wait a bit longer! */
642       continue;
643     }
644     break;
645   }
646   enc = GNUNET_malloc (fs);
647   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
648   len = ntohs (enc->size);
649   ret = NULL;
650   if ((len > fs) ||
651       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len, GNUNET_YES))))
652   {
653     LOG (GNUNET_ERROR_TYPE_ERROR,
654          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
655          filename);
656     if (0 != UNLINK (filename))
657     {
658       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
659     }
660   }
661   GNUNET_free (enc);
662   if (GNUNET_YES !=
663       GNUNET_DISK_file_unlock (fd, 0,
664                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
665     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
666   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
667   if (ret != NULL)
668   {
669     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
670     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
671   }
672   return ret;
673 }
674
675
676 /**
677  * Handle to cancel private key generation and state for the
678  * key generation operation.
679  */
680 struct GNUNET_CRYPTO_EccKeyGenerationContext
681 {
682   
683   /**
684    * Continuation to call upon completion.
685    */
686   GNUNET_CRYPTO_EccKeyCallback cont;
687
688   /**
689    * Closure for 'cont'.
690    */
691   void *cont_cls;
692
693   /**
694    * Name of the file.
695    */
696   char *filename;
697
698   /**
699    * Handle to the helper process which does the key generation.
700    */ 
701   struct GNUNET_OS_Process *gnunet_ecc;
702   
703   /**
704    * Handle to 'stdout' of gnunet-ecc.  We 'read' on stdout to detect
705    * process termination (instead of messing with SIGCHLD).
706    */
707   struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
708
709   /**
710    * Location where we store the private key if it already existed.
711    * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
712    * not be used).
713    */
714   struct GNUNET_CRYPTO_EccPrivateKey *pk;
715   
716   /**
717    * Task reading from 'gnunet_ecc_out' to wait for process termination.
718    */
719   GNUNET_SCHEDULER_TaskIdentifier read_task;
720   
721 };
722
723
724 /**
725  * Abort ECC key generation.
726  *
727  * @param gc key generation context to abort
728  */
729 void
730 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
731 {
732   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
733   {
734     GNUNET_SCHEDULER_cancel (gc->read_task);
735     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
736   }
737   if (NULL != gc->gnunet_ecc)
738   {
739     (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
740     GNUNET_break (GNUNET_OK ==
741                   GNUNET_OS_process_wait (gc->gnunet_ecc));
742     GNUNET_OS_process_destroy (gc->gnunet_ecc);
743     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
744   }
745
746   if (NULL != gc->filename)
747   {
748     if ( (0 != UNLINK (gc->filename)) &&
749          (ENOENT != errno) )
750       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
751     GNUNET_free (gc->filename);
752   }
753   if (NULL != gc->pk)
754     GNUNET_CRYPTO_ecc_key_free (gc->pk);
755   GNUNET_free (gc);
756 }
757
758
759 /**
760  * Task called upon shutdown or process termination of 'gnunet-ecc' during
761  * ECC key generation.  Check where we are and perform the appropriate
762  * action.
763  *
764  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
765  * @param tc scheduler context
766  */
767 static void
768 check_key_generation_completion (void *cls,
769                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
770 {
771   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
772   struct GNUNET_CRYPTO_EccPrivateKey *pk;
773
774   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
775   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
776   {
777     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
778     GNUNET_CRYPTO_ecc_key_create_stop (gc);
779     return;
780   }
781   GNUNET_assert (GNUNET_OK == 
782                  GNUNET_OS_process_wait (gc->gnunet_ecc));
783   GNUNET_OS_process_destroy (gc->gnunet_ecc);
784   gc->gnunet_ecc = NULL;
785   if (NULL == (pk = try_read_key (gc->filename)))
786   {
787     GNUNET_break (0);
788     gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
789     GNUNET_CRYPTO_ecc_key_create_stop (gc);
790     return;
791   }
792   gc->cont (gc->cont_cls, pk, NULL);
793   GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
794   GNUNET_free (gc->filename);
795   GNUNET_free (gc);
796 }
797
798
799 /**
800  * Return the private ECC key which already existed on disk
801  * (asynchronously) to the caller.
802  *
803  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
804  * @param tc scheduler context (unused)
805  */
806 static void
807 async_return_key (void *cls,
808                   const struct GNUNET_SCHEDULER_TaskContext *tc)
809 {
810   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
811
812   gc->cont (gc->cont_cls,
813             gc->pk,
814             NULL);
815   GNUNET_free (gc);
816 }
817
818
819 /**
820  * Create a new private key by reading it from a file.  If the files
821  * does not exist, create a new key and write it to the file.  If the
822  * contents of the file are invalid the old file is deleted and a
823  * fresh key is created.
824  *
825  * @param filename name of file to use for storage
826  * @param cont function to call when done (or on errors)
827  * @param cont_cls closure for 'cont'
828  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
829  */
830 struct GNUNET_CRYPTO_EccKeyGenerationContext *
831 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
832                                     GNUNET_CRYPTO_EccKeyCallback cont,
833                                     void *cont_cls)
834 {
835   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
836   struct GNUNET_CRYPTO_EccPrivateKey *pk;
837
838   if (NULL != (pk = try_read_key (filename)))
839   {
840     /* quick happy ending: key already exists! */
841     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
842     gc->pk = pk;
843     gc->cont = cont;
844     gc->cont_cls = cont_cls;
845     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
846                                               gc);
847     return gc;
848   }
849   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
850   gc->filename = GNUNET_strdup (filename);
851   gc->cont = cont;
852   gc->cont_cls = cont_cls;
853   gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
854                                          GNUNET_NO,
855                                          GNUNET_NO,
856                                          GNUNET_YES);
857   if (NULL == gc->gnunet_ecc_out)
858   {
859     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
860     GNUNET_free (gc->filename);
861     GNUNET_free (gc);
862     return NULL;
863   }
864   gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
865                                             GNUNET_OS_INHERIT_STD_ERR,
866                                             NULL, 
867                                             gc->gnunet_ecc_out,
868                                             "gnunet-ecc",
869                                             "gnunet-ecc",                                           
870                                             gc->filename,
871                                             NULL);
872   if (NULL == gc->gnunet_ecc)
873   {
874     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
875     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
876     GNUNET_free (gc->filename);
877     GNUNET_free (gc);
878     return NULL;
879   }
880   GNUNET_assert (GNUNET_OK ==
881                  GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
882                                              GNUNET_DISK_PIPE_END_WRITE));
883   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
884                                                   GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
885                                                                            GNUNET_DISK_PIPE_END_READ),
886                                                   &check_key_generation_completion,
887                                                   gc);
888   return gc;
889 }
890
891
892 /**
893  * Create a new private key by reading our peer's key from
894  * the file specified in the configuration.
895  *
896  * @return new private key, NULL on error (for example,
897  *   permission denied)
898  */
899 struct GNUNET_CRYPTO_EccPrivateKey *
900 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
901 {
902   struct GNUNET_CRYPTO_EccPrivateKey *pk;
903   char *fn;
904
905   if (GNUNET_OK != 
906       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
907     return NULL;
908   pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
909   GNUNET_free (fn);
910   return pk;
911 }
912
913
914 /**
915  * Setup a key file for a peer given the name of the
916  * configuration file (!).  This function is used so that
917  * at a later point code can be certain that reading a
918  * key is fast (for example in time-dependent testcases).
919  *
920  * @param cfg_name name of the configuration file to use
921  */
922 void
923 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
924 {
925   struct GNUNET_CONFIGURATION_Handle *cfg;
926   struct GNUNET_CRYPTO_EccPrivateKey *pk;
927
928   cfg = GNUNET_CONFIGURATION_create ();
929   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
930   pk = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
931   if (NULL != pk)
932     GNUNET_CRYPTO_ecc_key_free (pk);
933   GNUNET_CONFIGURATION_destroy (cfg);
934 }
935
936
937 /**
938  * Retrieve the identity of the host's peer.
939  *
940  * @param cfg configuration to use
941  * @param dst pointer to where to write the peer identity
942  * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
943  *         could not be retrieved
944  */
945 int
946 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
947                                  struct GNUNET_PeerIdentity *dst)
948 {
949   struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
950   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
951
952   if (NULL == (my_private_key = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
953   {
954     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
955                 _("Could not load peer's private key\n"));
956     return GNUNET_SYSERR;
957   }
958   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
959   GNUNET_CRYPTO_ecc_key_free (my_private_key);
960   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &dst->hashPubKey);
961   return GNUNET_OK;
962 }
963
964
965 /**
966  * Convert the data specified in the given purpose argument to an
967  * S-expression suitable for signature operations.
968  *
969  * @param purpose data to convert
970  * @return converted s-expression
971  */
972 static gcry_sexp_t
973 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
974 {
975   struct GNUNET_CRYPTO_ShortHashCode hc;
976   size_t bufSize;
977   gcry_sexp_t data;
978
979   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
980 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
981   bufSize = strlen (FORMATSTRING) + 1;
982   {
983     char buff[bufSize];
984
985     memcpy (buff, FORMATSTRING, bufSize);
986     memcpy (&buff
987             [bufSize -
988              strlen
989              ("01234567890123456789012345678901))")
990              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
991     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
992   }
993 #undef FORMATSTRING
994   return data;
995 }
996
997
998 /**
999  * Sign a given block.
1000  *
1001  * @param key private key to use for the signing
1002  * @param purpose what to sign (size, purpose)
1003  * @param sig where to write the signature
1004  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1005  */
1006 int
1007 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1008                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1009                         struct GNUNET_CRYPTO_EccSignature *sig)
1010 {
1011   gcry_sexp_t result;
1012   gcry_sexp_t data;
1013   size_t ssize;
1014   int rc;
1015
1016   data = data_to_pkcs1 (purpose);
1017   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
1018   {
1019     LOG (GNUNET_ERROR_TYPE_WARNING,
1020          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
1021          __LINE__, gcry_strerror (rc));
1022     gcry_sexp_release (data);
1023     return GNUNET_SYSERR;
1024   }
1025   gcry_sexp_release (data);
1026   ssize = gcry_sexp_sprint (result, 
1027                             GCRYSEXP_FMT_DEFAULT,
1028                             sig->sexpr,
1029                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
1030   if (0 == ssize)
1031   {
1032     GNUNET_break (0);
1033     return GNUNET_SYSERR;
1034   }
1035   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1036   /* padd with zeros */
1037   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
1038   gcry_sexp_release (result);
1039   return GNUNET_OK;
1040 }
1041
1042
1043 /**
1044  * Verify signature.
1045  *
1046  * @param purpose what is the purpose that the signature should have?
1047  * @param validate block to validate (size, purpose, data)
1048  * @param sig signature that is being validated
1049  * @param publicKey public key of the signer
1050  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1051  */
1052 int
1053 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1054                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1055                           *validate,
1056                           const struct GNUNET_CRYPTO_EccSignature *sig,
1057                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1058                           *publicKey)
1059 {
1060   gcry_sexp_t data;
1061   gcry_sexp_t sigdata;
1062   size_t size;
1063   gcry_sexp_t psexp;
1064   size_t erroff;
1065   int rc;
1066
1067   if (purpose != ntohl (validate->purpose))
1068     return GNUNET_SYSERR;       /* purpose mismatch */
1069   size = ntohs (sig->size);
1070   if ( (size < sizeof (uint16_t)) ||
1071        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1072     return GNUNET_SYSERR; /* size out of range */
1073   data = data_to_pkcs1 (validate);
1074   GNUNET_assert (0 ==
1075                  gcry_sexp_sscan (&sigdata, &erroff, 
1076                                   sig->sexpr, size - sizeof (uint16_t)));
1077   if (! (psexp = decode_public_key (publicKey)))
1078   {
1079     gcry_sexp_release (data);
1080     gcry_sexp_release (sigdata);
1081     return GNUNET_SYSERR;
1082   }
1083   rc = gcry_pk_verify (sigdata, data, psexp);
1084   gcry_sexp_release (psexp);
1085   gcry_sexp_release (data);
1086   gcry_sexp_release (sigdata);
1087   if (0 != rc)
1088   {
1089     LOG (GNUNET_ERROR_TYPE_WARNING,
1090          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1091          __LINE__, gcry_strerror (rc));
1092     return GNUNET_SYSERR;
1093   }
1094   return GNUNET_OK;
1095 }
1096
1097
1098 /**
1099  * Derive key material from a public and a private ECC key.
1100  *
1101  * @param key private key to use for the ECDH (x)
1102  * @param pub public key to use for the ECDY (yG)
1103  * @param key_material where to write the key material (xyG)
1104  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1105  */
1106 int
1107 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1108                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1109                         struct GNUNET_HashCode *key_material)
1110
1111   size_t slen;
1112   size_t erroff;
1113   int rc;
1114   unsigned char sdata_buf[2048]; /* big enough to print dh-shared-secret as S-expression */
1115   gcry_mpi_point_t result;
1116   gcry_mpi_point_t q;
1117   gcry_mpi_t d;
1118   gcry_ctx_t ctx;
1119   gcry_sexp_t psexp;
1120   gcry_mpi_t result_x;
1121   gcry_mpi_t result_y;
1122
1123   /* first, extract the q = dP value from the public key */
1124   if (! (psexp = decode_public_key (pub)))
1125     return GNUNET_SYSERR;
1126   if (0 != (rc = gcry_mpi_ec_new (&ctx, psexp, NULL)))
1127   {
1128     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
1129     return GNUNET_SYSERR;
1130   }
1131   gcry_sexp_release (psexp);
1132   q = gcry_mpi_ec_get_point ("q", ctx, 0);
1133   gcry_ctx_release (ctx);
1134
1135   /* second, extract the d value from our private key */
1136   rc = key_from_sexp (&d, key->sexp, "private-key", "d");
1137   if (rc)
1138     rc = key_from_sexp (&d, key->sexp, "ecc", "d");
1139   if (0 != rc)
1140   {
1141     GNUNET_break (0);
1142     gcry_mpi_point_release (q);
1143     return GNUNET_SYSERR;
1144   }
1145
1146   /* create a new context for definitively the correct curve;
1147      theoretically the 'public_key' might not use the right curve */
1148   if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
1149   {
1150     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
1151     gcry_mpi_release (d);
1152     gcry_mpi_point_release (q);
1153     return GNUNET_SYSERR;
1154   }
1155
1156   /* then call the 'multiply' function, to compute the product */
1157   GNUNET_assert (NULL != ctx);
1158   result = gcry_mpi_point_new (0);
1159   gcry_mpi_ec_mul (result, d, q, ctx);
1160   gcry_mpi_point_release (q);
1161   gcry_mpi_release (d);
1162
1163   /* finally, convert point to string for hashing */
1164   result_x = gcry_mpi_new (256);
1165   result_y = gcry_mpi_new (256);
1166   if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
1167   {
1168     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
1169     gcry_mpi_point_release (result);
1170     gcry_ctx_release (ctx);
1171     return GNUNET_SYSERR;
1172   }
1173   gcry_mpi_point_release (result);
1174   gcry_ctx_release (ctx);
1175   if (0 != (rc = gcry_sexp_build (&psexp, &erroff, 
1176                                   "(dh-shared-secret (x %m)(y %m))",
1177                                   result_x,
1178                                   result_y)))
1179   {
1180     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
1181     gcry_mpi_release (result_x);
1182     gcry_mpi_release (result_y);
1183     return GNUNET_SYSERR;
1184   }
1185   gcry_mpi_release (result_x);
1186   gcry_mpi_release (result_y);
1187   slen = gcry_sexp_sprint (psexp, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
1188   GNUNET_assert (0 != slen);
1189   gcry_sexp_release (psexp);
1190   /* finally, get a string of the resulting S-expression and hash it to generate the key material */
1191   GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
1192   return GNUNET_OK;
1193 }
1194
1195
1196 /* end of crypto_ecc.c */