-done
[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  * This is just a first, completely untested, draft hack for future ECC support.
27  * TODO:
28  * - adjust encoding length and other parameters
29  * - actually test it!
30  */
31 #include "platform.h"
32 #include <gcrypt.h>
33 #include "gnunet_common.h"
34 #include "gnunet_util_lib.h"
35
36 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS || 1
37
38 #define CURVE "NIST P-521"
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45
46 /**
47  * Log an error message at log-level 'level' that indicates
48  * a failure of the command 'cmd' with the message given
49  * by gcry_strerror(rc).
50  */
51 #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);
52
53
54 /**
55  * The private information of an ECC private key.
56  */
57 struct GNUNET_CRYPTO_EccPrivateKey
58 {
59   
60   /**
61    * Libgcrypt S-expression for the ECC key.
62    */
63   gcry_sexp_t sexp;
64 };
65
66
67 /**
68  * If target != size, move target bytes to the
69  * end of the size-sized buffer and zero out the
70  * first target-size bytes.
71  *
72  * @param buf original buffer
73  * @param size number of bytes in the buffer
74  * @param target target size of the buffer
75  */
76 static void
77 adjust (unsigned char *buf, size_t size, size_t target)
78 {
79   if (size < target)
80   {
81     memmove (&buf[target - size], buf, size);
82     memset (buf, 0, target - size);
83   }
84 }
85
86
87 /**
88  * Free memory occupied by ECC key
89  *
90  * @param privatekey pointer to the memory to free
91  */
92 void
93 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
94 {
95   gcry_sexp_release (privatekey->sexp);
96   GNUNET_free (privatekey);
97 }
98
99
100 /**
101  * Extract values from an S-expression.
102  *
103  * @param array where to store the result(s)
104  * @param sexp S-expression to parse
105  * @param topname top-level name in the S-expression that is of interest
106  * @param elems names of the elements to extract
107  * @return 0 on success
108  */
109 static int
110 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
111                const char *elems)
112 {
113   gcry_sexp_t list;
114   gcry_sexp_t l2;
115   const char *s;
116   unsigned int i;
117   unsigned int idx;
118
119   list = gcry_sexp_find_token (sexp, topname, 0);
120   if (! list)  
121     return 1;  
122   l2 = gcry_sexp_cadr (list);
123   gcry_sexp_release (list);
124   list = l2;
125   if (! list)  
126     return 2;  
127
128   idx = 0;
129   for (s = elems; *s; s++, idx++)
130   {
131     l2 = gcry_sexp_find_token (list, s, 1);
132     if (! l2)
133     {
134       for (i = 0; i < idx; i++)
135       {
136         gcry_free (array[i]);
137         array[i] = NULL;
138       }
139       gcry_sexp_release (list);
140       return 3;                 /* required parameter not found */
141     }
142     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
143     gcry_sexp_release (l2);
144     if (! array[idx])
145     {
146       for (i = 0; i < idx; i++)
147       {
148         gcry_free (array[i]);
149         array[i] = NULL;
150       }
151       gcry_sexp_release (list);
152       return 4;                 /* required parameter is invalid */
153     }
154   }
155   gcry_sexp_release (list);
156   return 0;
157 }
158
159
160 /**
161  * Extract the public key for the given private key.
162  *
163  * @param priv the private key
164  * @param pub where to write the public key
165  */
166 void
167 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
168                                   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
169 {
170   gcry_mpi_t skey;
171   size_t size;
172   int rc;
173
174   rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
175   if (rc)
176     rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
177   if (rc)
178     rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
179   GNUNET_assert (0 == rc);
180   pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
181   size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
182   GNUNET_assert (0 ==
183                  gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
184                                  skey));
185   pub->len = htons (size);
186   adjust (&pub->key[0], size, GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH);
187   gcry_mpi_release (skey);
188 }
189
190
191 /**
192  * Convert a public key to a string.
193  *
194  * @param pub key to convert
195  * @return string representing  'pub'
196  */
197 char *
198 GNUNET_CRYPTO_ecc_public_key_to_string (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
199 {
200   char *pubkeybuf;
201   size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
202   char *end;
203
204   if (keylen % 5 > 0)
205     keylen += 5 - keylen % 5;
206   keylen /= 5;
207   pubkeybuf = GNUNET_malloc (keylen + 1);
208   end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 
209                                        sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded), 
210                                        pubkeybuf, 
211                                        keylen);
212   if (NULL == end)
213   {
214     GNUNET_free (pubkeybuf);
215     return NULL;
216   }
217   *end = '\0';
218   return pubkeybuf;
219 }
220
221
222 /**
223  * Convert a string representing a public key to a public key.
224  *
225  * @param enc encoded public key
226  * @param enclen number of bytes in enc (without 0-terminator)
227  * @param pub where to store the public key
228  * @return GNUNET_OK on success
229  */
230 int
231 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc, 
232                                           size_t enclen,
233                                           struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
234 {
235   size_t keylen = (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) * 8;
236
237   if (keylen % 5 > 0)
238     keylen += 5 - keylen % 5;
239   keylen /= 5;
240   if (enclen != keylen)
241     return GNUNET_SYSERR;
242
243   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
244                                                  (unsigned char*) pub,
245                                                  sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)))
246     return GNUNET_SYSERR;
247   if ( (ntohs (pub->size) != sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded)) ||
248        (ntohs (pub->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH) )
249     return GNUNET_SYSERR;
250   return GNUNET_OK;
251 }
252
253
254 /**
255  * Convert the given public key from the network format to the
256  * S-expression that can be used by libgcrypt.
257  *
258  * @param publicKey public key to decode
259  * @return NULL on error
260  */
261 static gcry_sexp_t
262 decode_public_key (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *publicKey)
263 {
264   gcry_sexp_t result;
265   gcry_mpi_t q;
266   size_t size;
267   size_t erroff;
268   int rc;
269
270   if (ntohs (publicKey->len) > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH) 
271   {
272     GNUNET_break (0);
273     return NULL;
274   }
275   size = ntohs (publicKey->size);
276   if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG, publicKey->key, size, &size)))
277   {
278     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
279     return NULL;
280   }
281   rc = gcry_sexp_build (&result, &erroff, "(public-key(ecc((curve \"" CURVE "\")(q %m)))", q);
282   gcry_mpi_release (q);
283   if (0 != rc)
284   {
285     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
286     return NULL;
287   }
288   return result;
289 }
290
291
292 /**
293  * Encode the private key in a format suitable for
294  * storing it into a file.
295  *
296  * @param key key to encode
297  * @return encoding of the private key.
298  *    The first 4 bytes give the size of the array, as usual.
299  */
300 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
301 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
302 {
303   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
304   char buf[65536];
305   uint16_t be;
306   size_t size;
307
308 #if EXTRA_CHECKS
309   if (0 != gcry_pk_testkey (key->sexp))
310   {
311     GNUNET_break (0);
312     return NULL;
313   }
314 #endif
315   size = gcry_sexp_sprint (key->sexp, 
316                            GCRYSEXP_FMT_DEFAULT,
317                            &buf[2], sizeof (buf) - sizeof (uint16_t));
318   if (0 == size)
319   {
320     GNUNET_break (0);
321     return NULL;
322   }
323   GNUNET_assert (size < 65536 - sizeof (uint16_t));
324   be = htons ((uint16_t) size + (sizeof (be)));
325   memcpy (buf, &be, sizeof (be));
326   size += sizeof (be);
327   retval = GNUNET_malloc (size);
328   memcpy (retval, buf, size);
329   return retval;
330 }
331
332
333 /**
334  * Decode the private key from the file-format back
335  * to the "normal", internal format.
336  *
337  * @param buf the buffer where the private key data is stored
338  * @param len the length of the data in 'buffer'
339  * @return NULL on error
340  */
341 struct GNUNET_CRYPTO_EccPrivateKey *
342 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
343                               size_t len)
344 {
345   struct GNUNET_CRYPTO_EccPrivateKey *ret;
346   uint16_t be;
347   gcry_sexp_t sexp;
348   int rc;
349   size_t erroff;
350
351   if (len < sizeof (uint16_t)) 
352     return NULL;
353   memcpy (&be, buf, sizeof (be));
354   if (len != ntohs (be))
355     return NULL;
356   if (0 != (rc = gcry_sexp_sscan (&sexp,
357                                   &erroff,
358                                   &buf[2],
359                                   len - sizeof (uint16_t))))
360   {
361     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
362     return NULL;
363   }
364   if (0 != (rc = gcry_pk_testkey (sexp)))
365   {
366     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
367     return NULL;
368   }
369   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
370   ret->sexp = sexp;
371   return ret;
372 }
373
374
375 /**
376  * Create a new private key. Caller must free return value.
377  *
378  * @return fresh private key
379  */
380 static struct GNUNET_CRYPTO_EccPrivateKey *
381 ecc_key_create ()
382 {
383   struct GNUNET_CRYPTO_EccPrivateKey *ret;
384   gcry_sexp_t s_key;
385   gcry_sexp_t s_keyparam;
386   int rc;
387
388   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
389                                   "(genkey(ecdsa(curve 10:NIST P-521)))")))
390   {
391     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
392     return NULL;
393   }
394   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
395   {
396     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
397     gcry_sexp_release (s_keyparam);
398     return NULL;
399   }
400   gcry_sexp_release (s_keyparam);
401 #if EXTRA_CHECKS
402   if (0 != (rc = gcry_pk_testkey (s_key)))
403   {
404     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
405     gcry_sexp_release (s_key);
406     return NULL;
407   }
408 #endif
409   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
410   ret->sexp = s_key;
411   return ret;
412 }
413
414
415 /**
416  * Try to read the private key from the given file.
417  *
418  * @param filename file to read the key from
419  * @return NULL on error
420  */
421 static struct GNUNET_CRYPTO_EccPrivateKey *
422 try_read_key (const char *filename)
423 {
424   struct GNUNET_CRYPTO_EccPrivateKey *ret;
425   struct GNUNET_DISK_FileHandle *fd;
426   OFF_T fs;
427
428   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
429     return NULL;
430
431   /* hostkey file exists already, read it! */
432   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
433                                            GNUNET_DISK_PERM_NONE)))
434   {
435     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
436     return NULL;
437   }
438   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
439   {
440     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
441     (void) GNUNET_DISK_file_close (fd);
442     return NULL;
443   }
444   if (0 == fs)
445   {
446     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
447     return NULL;
448   }
449   if (fs > UINT16_MAX)
450   {
451     LOG (GNUNET_ERROR_TYPE_ERROR,
452          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
453          filename,
454          (unsigned long long) fs);
455     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
456     if (0 != UNLINK (filename))    
457       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
458     return NULL;
459   }
460   {
461     char enc[fs];
462
463     GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
464     if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
465     {
466       LOG (GNUNET_ERROR_TYPE_ERROR,
467            _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
468            filename,
469            (unsigned long long) fs);
470       GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
471       if (0 != UNLINK (filename))    
472         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
473       return NULL;
474     }
475   }
476   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
477   return ret;  
478 }
479
480
481 /**
482  * Wait for a short time (we're trying to lock a file or want
483  * to give another process a shot at finishing a disk write, etc.).
484  * Sleeps for 100ms (as that should be long enough for virtually all
485  * modern systems to context switch and allow another process to do
486  * some 'real' work).
487  */
488 static void
489 short_wait ()
490 {
491   struct GNUNET_TIME_Relative timeout;
492
493   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
494   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
495 }
496
497
498 /**
499  * Create a new private key by reading it from a file.  If the
500  * files does not exist, create a new key and write it to the
501  * file.  Caller must free return value.  Note that this function
502  * can not guarantee that another process might not be trying
503  * the same operation on the same file at the same time.
504  * If the contents of the file
505  * are invalid the old file is deleted and a fresh key is
506  * created.
507  *
508  * @return new private key, NULL on error (for example,
509  *   permission denied)
510  */
511 struct GNUNET_CRYPTO_EccPrivateKey *
512 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
513 {
514   struct GNUNET_CRYPTO_EccPrivateKey *ret;
515   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
516   uint16_t len;
517   struct GNUNET_DISK_FileHandle *fd;
518   unsigned int cnt;
519   int ec;
520   uint64_t fs;
521   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
522   struct GNUNET_PeerIdentity pid;
523
524   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
525     return NULL;
526   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
527   {
528     fd = GNUNET_DISK_file_open (filename,
529                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
530                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
531                                 GNUNET_DISK_PERM_USER_READ |
532                                 GNUNET_DISK_PERM_USER_WRITE);
533     if (NULL == fd)
534     {
535       if (errno == EEXIST)
536       {
537         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
538         {
539           /* must exist but not be accessible, fail for good! */
540           if (0 != ACCESS (filename, R_OK))
541             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
542           else
543             GNUNET_break (0);   /* what is going on!? */
544           return NULL;
545         }
546         continue;
547       }
548       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
549       return NULL;
550     }
551     cnt = 0;
552
553     while (GNUNET_YES !=
554            GNUNET_DISK_file_lock (fd, 0,
555                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
556                                   GNUNET_YES))
557     {
558       short_wait ();
559       if (0 == ++cnt % 10)
560       {
561         ec = errno;
562         LOG (GNUNET_ERROR_TYPE_ERROR,
563              _("Could not acquire lock on file `%s': %s...\n"), filename,
564              STRERROR (ec));
565       }
566     }
567     LOG (GNUNET_ERROR_TYPE_INFO,
568          _("Creating a new private key.  This may take a while.\n"));
569     ret = ecc_key_create ();
570     GNUNET_assert (ret != NULL);
571     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
572     GNUNET_assert (enc != NULL);
573     GNUNET_assert (ntohs (enc->size) ==
574                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
575     GNUNET_free (enc);
576
577     GNUNET_DISK_file_sync (fd);
578     if (GNUNET_YES !=
579         GNUNET_DISK_file_unlock (fd, 0,
580                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
581       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
582     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
583     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
584     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
585     LOG (GNUNET_ERROR_TYPE_INFO,
586          _("I am host `%s'.  Stored new private key in `%s'.\n"),
587          GNUNET_i2s (&pid), filename);
588     return ret;
589   }
590   /* hostkey file exists already, read it! */
591   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
592                               GNUNET_DISK_PERM_NONE);
593   if (NULL == fd)
594   {
595     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
596     return NULL;
597   }
598   cnt = 0;
599   while (1)
600   {
601     if (GNUNET_YES !=
602         GNUNET_DISK_file_lock (fd, 0,
603                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
604                                GNUNET_NO))
605     {
606       if (0 == ++cnt % 60)
607       {
608         ec = errno;
609         LOG (GNUNET_ERROR_TYPE_ERROR,
610              _("Could not acquire lock on file `%s': %s...\n"), filename,
611              STRERROR (ec));
612         LOG (GNUNET_ERROR_TYPE_ERROR,
613              _
614              ("This may be ok if someone is currently generating a hostkey.\n"));
615       }
616       short_wait ();
617       continue;
618     }
619     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
620     {
621       /* eh, what!? File we opened is now gone!? */
622       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
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       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
628
629       return NULL;
630     }
631     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
632       fs = 0;
633     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
634     {
635       /* maybe we got the read lock before the hostkey generating
636        * process had a chance to get the write lock; give it up! */
637       if (GNUNET_YES !=
638           GNUNET_DISK_file_unlock (fd, 0,
639                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
640         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
641       if (0 == ++cnt % 10)
642       {
643         LOG (GNUNET_ERROR_TYPE_ERROR,
644              _
645              ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
646              filename, (unsigned int) fs,
647              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
648         LOG (GNUNET_ERROR_TYPE_ERROR,
649              _
650              ("This may be ok if someone is currently generating a hostkey.\n"));
651       }
652       short_wait ();                /* wait a bit longer! */
653       continue;
654     }
655     break;
656   }
657   enc = GNUNET_malloc (fs);
658   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
659   len = ntohs (enc->size);
660   ret = NULL;
661   if ((len != fs) ||
662       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
663   {
664     LOG (GNUNET_ERROR_TYPE_ERROR,
665          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
666          filename);
667     if (0 != UNLINK (filename))
668     {
669       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
670     }
671   }
672   GNUNET_free (enc);
673   if (GNUNET_YES !=
674       GNUNET_DISK_file_unlock (fd, 0,
675                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
676     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
677   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
678   if (ret != NULL)
679   {
680     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
681     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
682     LOG (GNUNET_ERROR_TYPE_INFO,
683          _("I am host `%s'.  Read private key from `%s'.\n"), GNUNET_i2s (&pid),
684          filename);
685   }
686   return ret;
687 }
688
689
690 /**
691  * Handle to cancel private key generation and state for the
692  * key generation operation.
693  */
694 struct GNUNET_CRYPTO_EccKeyGenerationContext
695 {
696   
697   /**
698    * Continuation to call upon completion.
699    */
700   GNUNET_CRYPTO_EccKeyCallback cont;
701
702   /**
703    * Closure for 'cont'.
704    */
705   void *cont_cls;
706
707   /**
708    * Name of the file.
709    */
710   char *filename;
711
712   /**
713    * Handle to the helper process which does the key generation.
714    */ 
715   struct GNUNET_OS_Process *gnunet_ecc;
716   
717   /**
718    * Handle to 'stdout' of gnunet-ecc.  We 'read' on stdout to detect
719    * process termination (instead of messing with SIGCHLD).
720    */
721   struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
722
723   /**
724    * Location where we store the private key if it already existed.
725    * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
726    * not be used).
727    */
728   struct GNUNET_CRYPTO_EccPrivateKey *pk;
729   
730   /**
731    * Task reading from 'gnunet_ecc_out' to wait for process termination.
732    */
733   GNUNET_SCHEDULER_TaskIdentifier read_task;
734   
735 };
736
737
738 /**
739  * Abort ECC key generation.
740  *
741  * @param gc key generation context to abort
742  */
743 void
744 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
745 {
746   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
747   {
748     GNUNET_SCHEDULER_cancel (gc->read_task);
749     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
750   }
751   if (NULL != gc->gnunet_ecc)
752   {
753     (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
754     GNUNET_break (GNUNET_OK ==
755                   GNUNET_OS_process_wait (gc->gnunet_ecc));
756     GNUNET_OS_process_destroy (gc->gnunet_ecc);
757     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
758   }
759
760   if (NULL != gc->filename)
761   {
762     if (0 != UNLINK (gc->filename))
763       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
764     GNUNET_free (gc->filename);
765   }
766   if (NULL != gc->pk)
767     GNUNET_CRYPTO_ecc_key_free (gc->pk);
768   GNUNET_free (gc);
769 }
770
771
772 /**
773  * Task called upon shutdown or process termination of 'gnunet-ecc' during
774  * ECC key generation.  Check where we are and perform the appropriate
775  * action.
776  *
777  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
778  * @param tc scheduler context
779  */
780 static void
781 check_key_generation_completion (void *cls,
782                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
783 {
784   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
785   struct GNUNET_CRYPTO_EccPrivateKey *pk;
786
787   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
788   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
789   {
790     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
791     GNUNET_CRYPTO_ecc_key_create_stop (gc);
792     return;
793   }
794   GNUNET_assert (GNUNET_OK == 
795                  GNUNET_OS_process_wait (gc->gnunet_ecc));
796   GNUNET_OS_process_destroy (gc->gnunet_ecc);
797   gc->gnunet_ecc = NULL;
798   if (NULL == (pk = try_read_key (gc->filename)))
799   {
800     GNUNET_break (0);
801     gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
802     GNUNET_CRYPTO_ecc_key_create_stop (gc);
803     return;
804   }
805   gc->cont (gc->cont_cls, pk, NULL);
806   GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
807   GNUNET_free (gc->filename);
808   GNUNET_free (gc);
809 }
810
811
812 /**
813  * Return the private ECC key which already existed on disk
814  * (asynchronously) to the caller.
815  *
816  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
817  * @param tc scheduler context (unused)
818  */
819 static void
820 async_return_key (void *cls,
821                   const struct GNUNET_SCHEDULER_TaskContext *tc)
822 {
823   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
824
825   gc->cont (gc->cont_cls,
826             gc->pk,
827             NULL);
828   GNUNET_free (gc);
829 }
830
831
832 /**
833  * Create a new private key by reading it from a file.  If the files
834  * does not exist, create a new key and write it to the file.  If the
835  * contents of the file are invalid the old file is deleted and a
836  * fresh key is created.
837  *
838  * @param filename name of file to use for storage
839  * @param cont function to call when done (or on errors)
840  * @param cont_cls closure for 'cont'
841  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
842  */
843 struct GNUNET_CRYPTO_EccKeyGenerationContext *
844 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
845                                     GNUNET_CRYPTO_EccKeyCallback cont,
846                                     void *cont_cls)
847 {
848   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
849   struct GNUNET_CRYPTO_EccPrivateKey *pk;
850   const char *weak_random;
851
852   if (NULL != (pk = try_read_key (filename)))
853   {
854     /* quick happy ending: key already exists! */
855     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
856     gc->pk = pk;
857     gc->cont = cont;
858     gc->cont_cls = cont_cls;
859     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
860                                               gc);
861     return gc;
862   }
863   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
864   gc->filename = GNUNET_strdup (filename);
865   gc->cont = cont;
866   gc->cont_cls = cont_cls;
867   gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
868                                          GNUNET_NO,
869                                          GNUNET_NO,
870                                          GNUNET_YES);
871   if (NULL == gc->gnunet_ecc_out)
872   {
873     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
874     GNUNET_free (gc->filename);
875     GNUNET_free (gc);
876     return NULL;
877   }
878   weak_random = NULL;
879   if (GNUNET_YES ==
880       GNUNET_CRYPTO_random_is_weak ())
881     weak_random = "-w";
882   gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
883                                             GNUNET_OS_INHERIT_STD_ERR,
884                                             NULL, 
885                                             gc->gnunet_ecc_out,
886                                             "gnunet-ecc",
887                                             "gnunet-ecc",                                           
888                                             gc->filename,
889                                             weak_random,
890                                             NULL);
891   if (NULL == gc->gnunet_ecc)
892   {
893     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
894     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
895     GNUNET_free (gc->filename);
896     GNUNET_free (gc);
897     return NULL;
898   }
899   GNUNET_assert (GNUNET_OK ==
900                  GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
901                                              GNUNET_DISK_PIPE_END_WRITE));
902   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
903                                                   GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
904                                                                            GNUNET_DISK_PIPE_END_READ),
905                                                   &check_key_generation_completion,
906                                                   gc);
907   return gc;
908 }
909
910
911 /**
912  * Setup a hostkey file for a peer given the name of the
913  * configuration file (!).  This function is used so that
914  * at a later point code can be certain that reading a
915  * hostkey is fast (for example in time-dependent testcases).
916  *
917  * @param cfg_name name of the configuration file to use
918  */
919 void
920 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name)
921 {
922   struct GNUNET_CONFIGURATION_Handle *cfg;
923   struct GNUNET_CRYPTO_EccPrivateKey *pk;
924   char *fn;
925
926   cfg = GNUNET_CONFIGURATION_create ();
927   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
928   if (GNUNET_OK == 
929       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
930   {
931     pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
932     if (NULL != pk)
933       GNUNET_CRYPTO_ecc_key_free (pk);
934     GNUNET_free (fn);
935   }
936   GNUNET_CONFIGURATION_destroy (cfg);
937 }
938
939
940 /**
941  * Convert the data specified in the given purpose argument to an
942  * S-expression suitable for signature operations.
943  *
944  * @param purpose data to convert
945  * @return converted s-expression
946  */
947 static gcry_sexp_t
948 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
949 {
950   struct GNUNET_HashCode hc;
951   size_t bufSize;
952   gcry_sexp_t data;
953
954   GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
955 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
956   bufSize = strlen (FORMATSTRING) + 1;
957   {
958     char buff[bufSize];
959
960     memcpy (buff, FORMATSTRING, bufSize);
961     memcpy (&buff
962             [bufSize -
963              strlen
964              ("0123456789012345678901234567890123456789012345678901234567890123))")
965              - 1], &hc, sizeof (struct GNUNET_HashCode));
966     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
967   }
968 #undef FORMATSTRING
969   return data;
970 }
971
972
973 /**
974  * Sign a given block.
975  *
976  * @param key private key to use for the signing
977  * @param purpose what to sign (size, purpose)
978  * @param sig where to write the signature
979  * @return GNUNET_SYSERR on error, GNUNET_OK on success
980  */
981 int
982 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
983                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
984                         struct GNUNET_CRYPTO_EccSignature *sig)
985 {
986   gcry_sexp_t result;
987   gcry_sexp_t data;
988   size_t ssize;
989
990   data = data_to_pkcs1 (purpose);
991   GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
992   gcry_sexp_release (data);
993   ssize = gcry_sexp_sprint (result, 
994                             GCRYSEXP_FMT_DEFAULT,
995                             sig->sexpr,
996                             GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH);
997   if (0 == ssize)
998   {
999     GNUNET_break (0);
1000     return GNUNET_SYSERR;
1001   }
1002   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
1003   /* padd with zeros */
1004   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - ssize);
1005   gcry_sexp_release (result);
1006   return GNUNET_OK;
1007 }
1008
1009
1010 /**
1011  * Verify signature.
1012  *
1013  * @param purpose what is the purpose that the signature should have?
1014  * @param validate block to validate (size, purpose, data)
1015  * @param sig signature that is being validated
1016  * @param publicKey public key of the signer
1017  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1018  */
1019 int
1020 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1021                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1022                           *validate,
1023                           const struct GNUNET_CRYPTO_EccSignature *sig,
1024                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1025                           *publicKey)
1026 {
1027   gcry_sexp_t data;
1028   gcry_sexp_t sigdata;
1029   size_t size;
1030   gcry_sexp_t psexp;
1031   size_t erroff;
1032   int rc;
1033
1034   if (purpose != ntohl (validate->purpose))
1035     return GNUNET_SYSERR;       /* purpose mismatch */
1036   size = ntohs (sig->size);
1037   if ( (size < sizeof (uint16_t)) ||
1038        (size > GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1039     return GNUNET_SYSERR; /* size out of range */
1040   data = data_to_pkcs1 (validate);
1041   GNUNET_assert (0 ==
1042                  gcry_sexp_sscan (&sigdata, &erroff, 
1043                                   sig->sexpr, size - sizeof (uint16_t)));
1044   if (! (psexp = decode_public_key (publicKey)))
1045   {
1046     gcry_sexp_release (data);
1047     gcry_sexp_release (sigdata);
1048     return GNUNET_SYSERR;
1049   }
1050   rc = gcry_pk_verify (sigdata, data, psexp);
1051   gcry_sexp_release (psexp);
1052   gcry_sexp_release (data);
1053   gcry_sexp_release (sigdata);
1054   if (0 != rc)
1055   {
1056     LOG (GNUNET_ERROR_TYPE_WARNING,
1057          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1058          __LINE__, gcry_strerror (rc));
1059     return GNUNET_SYSERR;
1060   }
1061   return GNUNET_OK;
1062 }
1063
1064
1065 /* end of crypto_ecc.c */