Fix a memory leak in MD serializer
[oweals/gnunet.git] / src / util / crypto_ecc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2012 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 || 1
32
33 #define CURVE "NIST P-521"
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 (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                                                  (unsigned char*) 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   // FIXME: is this key expected to pass pk_testkey?
267 #if 0
268 #if EXTRA_CHECKS 
269   if (0 != (rc = gcry_pk_testkey (result)))
270   {
271     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
272     gcry_sexp_release (result);
273     return NULL;
274   }
275 #endif
276 #endif
277   return result;
278 }
279
280
281 /**
282  * Encode the private key in a format suitable for
283  * storing it into a file.
284  *
285  * @param key key to encode
286  * @return encoding of the private key.
287  *    The first 4 bytes give the size of the array, as usual.
288  */
289 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
290 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
291 {
292   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
293   char buf[65536];
294   uint16_t be;
295   size_t size;
296
297 #if EXTRA_CHECKS
298   if (0 != gcry_pk_testkey (key->sexp))
299   {
300     GNUNET_break (0);
301     return NULL;
302   }
303 #endif
304   size = gcry_sexp_sprint (key->sexp, 
305                            GCRYSEXP_FMT_DEFAULT,
306                            &buf[2], sizeof (buf) - sizeof (uint16_t));
307   if (0 == size)
308   {
309     GNUNET_break (0);
310     return NULL;
311   }
312   GNUNET_assert (size < 65536 - sizeof (uint16_t));
313   be = htons ((uint16_t) size + (sizeof (be)));
314   memcpy (buf, &be, sizeof (be));
315   size += sizeof (be);
316   retval = GNUNET_malloc (size);
317   memcpy (retval, buf, size);
318   return retval;
319 }
320
321
322 /**
323  * Decode the private key from the file-format back
324  * to the "normal", internal format.
325  *
326  * @param buf the buffer where the private key data is stored
327  * @param len the length of the data in 'buffer'
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 {
334   struct GNUNET_CRYPTO_EccPrivateKey *ret;
335   uint16_t be;
336   gcry_sexp_t sexp;
337   int rc;
338   size_t erroff;
339
340   if (len < sizeof (uint16_t)) 
341     return NULL;
342   memcpy (&be, buf, sizeof (be));
343   if (len != ntohs (be))
344     return NULL;
345   if (0 != (rc = gcry_sexp_sscan (&sexp,
346                                   &erroff,
347                                   &buf[2],
348                                   len - sizeof (uint16_t))))
349   {
350     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
351     return NULL;
352   }
353   if (0 != (rc = gcry_pk_testkey (sexp)))
354   {
355     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
356     return NULL;
357   }
358   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
359   ret->sexp = sexp;
360   return ret;
361 }
362
363
364 /**
365  * Create a new private key. Caller must free return value.
366  *
367  * @return fresh private key
368  */
369 static struct GNUNET_CRYPTO_EccPrivateKey *
370 ecc_key_create ()
371 {
372   struct GNUNET_CRYPTO_EccPrivateKey *ret;
373   gcry_sexp_t s_key;
374   gcry_sexp_t s_keyparam;
375   int rc;
376
377   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
378                                   "(genkey(ecdsa(curve \"" CURVE "\")))")))
379   {
380     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
381     return NULL;
382   }
383   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
384   {
385     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
386     gcry_sexp_release (s_keyparam);
387     return NULL;
388   }
389   gcry_sexp_release (s_keyparam);
390 #if EXTRA_CHECKS
391   if (0 != (rc = gcry_pk_testkey (s_key)))
392   {
393     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
394     gcry_sexp_release (s_key);
395     return NULL;
396   }
397 #endif
398   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
399   ret->sexp = s_key;
400   return ret;
401 }
402
403
404 /**
405  * Try to read the private key from the given file.
406  *
407  * @param filename file to read the key from
408  * @return NULL on error
409  */
410 static struct GNUNET_CRYPTO_EccPrivateKey *
411 try_read_key (const char *filename)
412 {
413   struct GNUNET_CRYPTO_EccPrivateKey *ret;
414   struct GNUNET_DISK_FileHandle *fd;
415   OFF_T fs;
416
417   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
418     return NULL;
419
420   /* key file exists already, read it! */
421   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
422                                            GNUNET_DISK_PERM_NONE)))
423   {
424     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
425     return NULL;
426   }
427   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
428   {
429     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
430     (void) GNUNET_DISK_file_close (fd);
431     return NULL;
432   }
433   if (0 == fs)
434   {
435     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
436     return NULL;
437   }
438   if (fs > UINT16_MAX)
439   {
440     LOG (GNUNET_ERROR_TYPE_ERROR,
441          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
442          filename,
443          (unsigned long long) fs);
444     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
445     if (0 != UNLINK (filename))    
446       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
447     return NULL;
448   }
449   {
450     char enc[fs];
451
452     GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
453     if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
454     {
455       LOG (GNUNET_ERROR_TYPE_ERROR,
456            _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
457            filename,
458            (unsigned long long) fs);
459       GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
460       if (0 != UNLINK (filename))    
461         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
462       return NULL;
463     }
464   }
465   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
466   return ret;  
467 }
468
469
470 /**
471  * Wait for a short time (we're trying to lock a file or want
472  * to give another process a shot at finishing a disk write, etc.).
473  * Sleeps for 100ms (as that should be long enough for virtually all
474  * modern systems to context switch and allow another process to do
475  * some 'real' work).
476  */
477 static void
478 short_wait ()
479 {
480   struct GNUNET_TIME_Relative timeout;
481
482   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
483   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
484 }
485
486
487 /**
488  * Create a new private key by reading it from a file.  If the
489  * files does not exist, create a new key and write it to the
490  * file.  Caller must free return value.  Note that this function
491  * can not guarantee that another process might not be trying
492  * the same operation on the same file at the same time.
493  * If the contents of the file
494  * are invalid the old file is deleted and a fresh key is
495  * created.
496  *
497  * @return new private key, NULL on error (for example,
498  *   permission denied)
499  */
500 struct GNUNET_CRYPTO_EccPrivateKey *
501 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
502 {
503   struct GNUNET_CRYPTO_EccPrivateKey *ret;
504   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
505   uint16_t len;
506   struct GNUNET_DISK_FileHandle *fd;
507   unsigned int cnt;
508   int ec;
509   uint64_t fs;
510   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
511   struct GNUNET_PeerIdentity pid;
512
513   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
514     return NULL;
515   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
516   {
517     fd = GNUNET_DISK_file_open (filename,
518                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
519                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
520                                 GNUNET_DISK_PERM_USER_READ |
521                                 GNUNET_DISK_PERM_USER_WRITE);
522     if (NULL == fd)
523     {
524       if (errno == EEXIST)
525       {
526         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
527         {
528           /* must exist but not be accessible, fail for good! */
529           if (0 != ACCESS (filename, R_OK))
530             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
531           else
532             GNUNET_break (0);   /* what is going on!? */
533           return NULL;
534         }
535         continue;
536       }
537       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
538       return NULL;
539     }
540     cnt = 0;
541
542     while (GNUNET_YES !=
543            GNUNET_DISK_file_lock (fd, 0,
544                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
545                                   GNUNET_YES))
546     {
547       short_wait ();
548       if (0 == ++cnt % 10)
549       {
550         ec = errno;
551         LOG (GNUNET_ERROR_TYPE_ERROR,
552              _("Could not acquire lock on file `%s': %s...\n"), filename,
553              STRERROR (ec));
554       }
555     }
556     LOG (GNUNET_ERROR_TYPE_INFO,
557          _("Creating a new private key.  This may take a while.\n"));
558     ret = ecc_key_create ();
559     GNUNET_assert (ret != NULL);
560     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
561     GNUNET_assert (enc != NULL);
562     GNUNET_assert (ntohs (enc->size) ==
563                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
564     GNUNET_free (enc);
565
566     GNUNET_DISK_file_sync (fd);
567     if (GNUNET_YES !=
568         GNUNET_DISK_file_unlock (fd, 0,
569                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
570       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
571     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
572     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
573     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
574     return ret;
575   }
576   /* key file exists already, read it! */
577   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
578                               GNUNET_DISK_PERM_NONE);
579   if (NULL == fd)
580   {
581     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
582     return NULL;
583   }
584   cnt = 0;
585   while (1)
586   {
587     if (GNUNET_YES !=
588         GNUNET_DISK_file_lock (fd, 0,
589                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
590                                GNUNET_NO))
591     {
592       if (0 == ++cnt % 60)
593       {
594         ec = errno;
595         LOG (GNUNET_ERROR_TYPE_ERROR,
596              _("Could not acquire lock on file `%s': %s...\n"), filename,
597              STRERROR (ec));
598         LOG (GNUNET_ERROR_TYPE_ERROR,
599              _
600              ("This may be ok if someone is currently generating a private key.\n"));
601       }
602       short_wait ();
603       continue;
604     }
605     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
606     {
607       /* eh, what!? File we opened is now gone!? */
608       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
609       if (GNUNET_YES !=
610           GNUNET_DISK_file_unlock (fd, 0,
611                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
612         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
613       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
614
615       return NULL;
616     }
617     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
618       fs = 0;
619     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
620     {
621       /* maybe we got the read lock before the key generating
622        * process had a chance to get the write lock; give it up! */
623       if (GNUNET_YES !=
624           GNUNET_DISK_file_unlock (fd, 0,
625                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
626         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
627       if (0 == ++cnt % 10)
628       {
629         LOG (GNUNET_ERROR_TYPE_ERROR,
630              _
631              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
632              filename, (unsigned int) fs,
633              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
634         LOG (GNUNET_ERROR_TYPE_ERROR,
635              _
636              ("This may be ok if someone is currently generating a key.\n"));
637       }
638       short_wait ();                /* wait a bit longer! */
639       continue;
640     }
641     break;
642   }
643   enc = GNUNET_malloc (fs);
644   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
645   len = ntohs (enc->size);
646   ret = NULL;
647   if ((len != fs) ||
648       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
649   {
650     LOG (GNUNET_ERROR_TYPE_ERROR,
651          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
652          filename);
653     if (0 != UNLINK (filename))
654     {
655       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
656     }
657   }
658   GNUNET_free (enc);
659   if (GNUNET_YES !=
660       GNUNET_DISK_file_unlock (fd, 0,
661                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
662     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
663   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
664   if (ret != NULL)
665   {
666     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
667     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
668   }
669   return ret;
670 }
671
672
673 /**
674  * Handle to cancel private key generation and state for the
675  * key generation operation.
676  */
677 struct GNUNET_CRYPTO_EccKeyGenerationContext
678 {
679   
680   /**
681    * Continuation to call upon completion.
682    */
683   GNUNET_CRYPTO_EccKeyCallback cont;
684
685   /**
686    * Closure for 'cont'.
687    */
688   void *cont_cls;
689
690   /**
691    * Name of the file.
692    */
693   char *filename;
694
695   /**
696    * Handle to the helper process which does the key generation.
697    */ 
698   struct GNUNET_OS_Process *gnunet_ecc;
699   
700   /**
701    * Handle to 'stdout' of gnunet-ecc.  We 'read' on stdout to detect
702    * process termination (instead of messing with SIGCHLD).
703    */
704   struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
705
706   /**
707    * Location where we store the private key if it already existed.
708    * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
709    * not be used).
710    */
711   struct GNUNET_CRYPTO_EccPrivateKey *pk;
712   
713   /**
714    * Task reading from 'gnunet_ecc_out' to wait for process termination.
715    */
716   GNUNET_SCHEDULER_TaskIdentifier read_task;
717   
718 };
719
720
721 /**
722  * Abort ECC key generation.
723  *
724  * @param gc key generation context to abort
725  */
726 void
727 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
728 {
729   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
730   {
731     GNUNET_SCHEDULER_cancel (gc->read_task);
732     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
733   }
734   if (NULL != gc->gnunet_ecc)
735   {
736     (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
737     GNUNET_break (GNUNET_OK ==
738                   GNUNET_OS_process_wait (gc->gnunet_ecc));
739     GNUNET_OS_process_destroy (gc->gnunet_ecc);
740     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
741   }
742
743   if (NULL != gc->filename)
744   {
745     if (0 != UNLINK (gc->filename))
746       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
747     GNUNET_free (gc->filename);
748   }
749   if (NULL != gc->pk)
750     GNUNET_CRYPTO_ecc_key_free (gc->pk);
751   GNUNET_free (gc);
752 }
753
754
755 /**
756  * Task called upon shutdown or process termination of 'gnunet-ecc' during
757  * ECC key generation.  Check where we are and perform the appropriate
758  * action.
759  *
760  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
761  * @param tc scheduler context
762  */
763 static void
764 check_key_generation_completion (void *cls,
765                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
766 {
767   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
768   struct GNUNET_CRYPTO_EccPrivateKey *pk;
769
770   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
771   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
772   {
773     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
774     GNUNET_CRYPTO_ecc_key_create_stop (gc);
775     return;
776   }
777   GNUNET_assert (GNUNET_OK == 
778                  GNUNET_OS_process_wait (gc->gnunet_ecc));
779   GNUNET_OS_process_destroy (gc->gnunet_ecc);
780   gc->gnunet_ecc = NULL;
781   if (NULL == (pk = try_read_key (gc->filename)))
782   {
783     GNUNET_break (0);
784     gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
785     GNUNET_CRYPTO_ecc_key_create_stop (gc);
786     return;
787   }
788   gc->cont (gc->cont_cls, pk, NULL);
789   GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
790   GNUNET_free (gc->filename);
791   GNUNET_free (gc);
792 }
793
794
795 /**
796  * Return the private ECC key which already existed on disk
797  * (asynchronously) to the caller.
798  *
799  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
800  * @param tc scheduler context (unused)
801  */
802 static void
803 async_return_key (void *cls,
804                   const struct GNUNET_SCHEDULER_TaskContext *tc)
805 {
806   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
807
808   gc->cont (gc->cont_cls,
809             gc->pk,
810             NULL);
811   GNUNET_free (gc);
812 }
813
814
815 /**
816  * Create a new private key by reading it from a file.  If the files
817  * does not exist, create a new key and write it to the file.  If the
818  * contents of the file are invalid the old file is deleted and a
819  * fresh key is created.
820  *
821  * @param filename name of file to use for storage
822  * @param cont function to call when done (or on errors)
823  * @param cont_cls closure for 'cont'
824  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
825  */
826 struct GNUNET_CRYPTO_EccKeyGenerationContext *
827 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
828                                     GNUNET_CRYPTO_EccKeyCallback cont,
829                                     void *cont_cls)
830 {
831   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
832   struct GNUNET_CRYPTO_EccPrivateKey *pk;
833   const char *weak_random;
834
835   if (NULL != (pk = try_read_key (filename)))
836   {
837     /* quick happy ending: key already exists! */
838     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
839     gc->pk = pk;
840     gc->cont = cont;
841     gc->cont_cls = cont_cls;
842     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
843                                               gc);
844     return gc;
845   }
846   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
847   gc->filename = GNUNET_strdup (filename);
848   gc->cont = cont;
849   gc->cont_cls = cont_cls;
850   gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
851                                          GNUNET_NO,
852                                          GNUNET_NO,
853                                          GNUNET_YES);
854   if (NULL == gc->gnunet_ecc_out)
855   {
856     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
857     GNUNET_free (gc->filename);
858     GNUNET_free (gc);
859     return NULL;
860   }
861   weak_random = NULL;
862   if (GNUNET_YES ==
863       GNUNET_CRYPTO_random_is_weak ())
864     weak_random = "-w";
865   gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
866                                             GNUNET_OS_INHERIT_STD_ERR,
867                                             NULL, 
868                                             gc->gnunet_ecc_out,
869                                             "gnunet-ecc",
870                                             "gnunet-ecc",                                           
871                                             gc->filename,
872                                             weak_random,
873                                             NULL);
874   if (NULL == gc->gnunet_ecc)
875   {
876     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
877     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
878     GNUNET_free (gc->filename);
879     GNUNET_free (gc);
880     return NULL;
881   }
882   GNUNET_assert (GNUNET_OK ==
883                  GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
884                                              GNUNET_DISK_PIPE_END_WRITE));
885   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
886                                                   GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
887                                                                            GNUNET_DISK_PIPE_END_READ),
888                                                   &check_key_generation_completion,
889                                                   gc);
890   return gc;
891 }
892
893
894 /**
895  * Setup a key file for a peer given the name of the
896  * configuration file (!).  This function is used so that
897  * at a later point code can be certain that reading a
898  * key is fast (for example in time-dependent testcases).
899  *
900  * @param cfg_name name of the configuration file to use
901  */
902 void
903 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
904 {
905   struct GNUNET_CONFIGURATION_Handle *cfg;
906   struct GNUNET_CRYPTO_EccPrivateKey *pk;
907   char *fn;
908
909   cfg = GNUNET_CONFIGURATION_create ();
910   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
911   if (GNUNET_OK == 
912       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
913   {
914     pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
915     if (NULL != pk)
916       GNUNET_CRYPTO_ecc_key_free (pk);
917     GNUNET_free (fn);
918   }
919   GNUNET_CONFIGURATION_destroy (cfg);
920 }
921
922
923 /**
924  * Convert the data specified in the given purpose argument to an
925  * S-expression suitable for signature operations.
926  *
927  * @param purpose data to convert
928  * @return converted s-expression
929  */
930 static gcry_sexp_t
931 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
932 {
933   struct GNUNET_CRYPTO_ShortHashCode hc;
934   size_t bufSize;
935   gcry_sexp_t data;
936
937   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
938 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
939 #define FORMATSTRING2 "(4:data(4:hash6:sha25632:01234567890123456789012345678901))"
940   bufSize = strlen (FORMATSTRING) + 1;
941   {
942     char buff[bufSize];
943
944     memcpy (buff, FORMATSTRING, bufSize);
945     memcpy (&buff
946             [bufSize -
947              strlen
948              ("01234567890123456789012345678901))")
949              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
950     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
951   }
952 #undef FORMATSTRING
953   return data;
954 }
955
956
957 /**
958  * Sign a given block.
959  *
960  * @param key private key to use for the signing
961  * @param purpose what to sign (size, purpose)
962  * @param sig where to write the signature
963  * @return GNUNET_SYSERR on error, GNUNET_OK on success
964  */
965 int
966 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
967                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
968                         struct GNUNET_CRYPTO_EccSignature *sig)
969 {
970   gcry_sexp_t result;
971   gcry_sexp_t data;
972   size_t ssize;
973   int rc;
974
975   data = data_to_pkcs1 (purpose);
976   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
977   {
978     LOG (GNUNET_ERROR_TYPE_WARNING,
979          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
980          __LINE__, gcry_strerror (rc));
981   }
982   gcry_sexp_release (data);
983   ssize = gcry_sexp_sprint (result, 
984                             GCRYSEXP_FMT_DEFAULT,
985                             sig->sexpr,
986                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
987   if (0 == ssize)
988   {
989     GNUNET_break (0);
990     return GNUNET_SYSERR;
991   }
992   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
993   /* padd with zeros */
994   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
995   gcry_sexp_release (result);
996   return GNUNET_OK;
997 }
998
999
1000 /**
1001  * Verify signature.
1002  *
1003  * @param purpose what is the purpose that the signature should have?
1004  * @param validate block to validate (size, purpose, data)
1005  * @param sig signature that is being validated
1006  * @param publicKey public key of the signer
1007  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1008  */
1009 int
1010 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1011                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1012                           *validate,
1013                           const struct GNUNET_CRYPTO_EccSignature *sig,
1014                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1015                           *publicKey)
1016 {
1017   gcry_sexp_t data;
1018   gcry_sexp_t sigdata;
1019   size_t size;
1020   gcry_sexp_t psexp;
1021   size_t erroff;
1022   int rc;
1023
1024   if (purpose != ntohl (validate->purpose))
1025     return GNUNET_SYSERR;       /* purpose mismatch */
1026   size = ntohs (sig->size);
1027   if ( (size < sizeof (uint16_t)) ||
1028        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1029     return GNUNET_SYSERR; /* size out of range */
1030   data = data_to_pkcs1 (validate);
1031   GNUNET_assert (0 ==
1032                  gcry_sexp_sscan (&sigdata, &erroff, 
1033                                   sig->sexpr, size - sizeof (uint16_t)));
1034   if (! (psexp = decode_public_key (publicKey)))
1035   {
1036     gcry_sexp_release (data);
1037     gcry_sexp_release (sigdata);
1038     return GNUNET_SYSERR;
1039   }
1040   rc = gcry_pk_verify (sigdata, data, psexp);
1041   gcry_sexp_release (psexp);
1042   gcry_sexp_release (data);
1043   gcry_sexp_release (sigdata);
1044   if (0 != rc)
1045   {
1046     LOG (GNUNET_ERROR_TYPE_WARNING,
1047          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1048          __LINE__, gcry_strerror (rc));
1049     return GNUNET_SYSERR;
1050   }
1051   return GNUNET_OK;
1052 }
1053
1054
1055 /* end of crypto_ecc.c */