d89989bd4c8287a4cfff2ec6aa59db7ff4d40e7b
[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 
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 (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                                                  (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  * @param validate GNUNET_YES to validate that the key is well-formed,
329  *                 GNUNET_NO if the key comes from a totally trusted source 
330  *                 and validation is considered too expensive
331  * @return NULL on error
332  */
333 struct GNUNET_CRYPTO_EccPrivateKey *
334 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
335                               size_t len,
336                               int validate)
337 {
338   struct GNUNET_CRYPTO_EccPrivateKey *ret;
339   uint16_t be;
340   gcry_sexp_t sexp;
341   int rc;
342   size_t erroff;
343
344   if (len < sizeof (uint16_t)) 
345     return NULL;
346   memcpy (&be, buf, sizeof (be));
347   if (len < ntohs (be))
348     return NULL;
349   len = ntohs (be);
350   if (0 != (rc = gcry_sexp_sscan (&sexp,
351                                   &erroff,
352                                   &buf[2],
353                                   len - sizeof (uint16_t))))
354   {
355     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
356     return NULL;
357   }  
358   if ( (GNUNET_YES == validate) &&
359        (0 != (rc = gcry_pk_testkey (sexp))) )
360   {
361     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
362     return NULL;
363   }
364   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
365   ret->sexp = sexp;
366   return ret;
367 }
368
369
370 /**
371  * Create a new private key. Caller must free return value.
372  *
373  * @return fresh private key
374  */
375 struct GNUNET_CRYPTO_EccPrivateKey *
376 GNUNET_CRYPTO_ecc_key_create ()
377 {
378   struct GNUNET_CRYPTO_EccPrivateKey *ret;
379   gcry_sexp_t s_key;
380   gcry_sexp_t s_keyparam;
381   int rc;
382
383   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
384                                   "(genkey(ecdsa(curve \"" CURVE "\")))")))
385   {
386     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
387     return NULL;
388   }
389   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
390   {
391     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
392     gcry_sexp_release (s_keyparam);
393     return NULL;
394   }
395   gcry_sexp_release (s_keyparam);
396 #if EXTRA_CHECKS
397   if (0 != (rc = gcry_pk_testkey (s_key)))
398   {
399     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
400     gcry_sexp_release (s_key);
401     return NULL;
402   }
403 #endif
404   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
405   ret->sexp = s_key;
406   return ret;
407 }
408
409
410 /**
411  * Try to read the private key from the given file.
412  *
413  * @param filename file to read the key from
414  * @return NULL on error
415  */
416 static struct GNUNET_CRYPTO_EccPrivateKey *
417 try_read_key (const char *filename)
418 {
419   struct GNUNET_CRYPTO_EccPrivateKey *ret;
420   struct GNUNET_DISK_FileHandle *fd;
421   OFF_T fs;
422
423   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
424     return NULL;
425
426   /* key file exists already, read it! */
427   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
428                                            GNUNET_DISK_PERM_NONE)))
429   {
430     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
431     return NULL;
432   }
433   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
434   {
435     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
436     (void) GNUNET_DISK_file_close (fd);
437     return NULL;
438   }
439   if (0 == fs)
440   {
441     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
442     return NULL;
443   }
444   if (fs > UINT16_MAX)
445   {
446     LOG (GNUNET_ERROR_TYPE_ERROR,
447          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
448          filename,
449          (unsigned long long) fs);
450     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
451     if (0 != UNLINK (filename))    
452       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
453     return NULL;
454   }
455   {
456     char enc[fs];
457
458     GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
459     if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs, GNUNET_YES)))
460     {
461       LOG (GNUNET_ERROR_TYPE_ERROR,
462            _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
463            filename,
464            (unsigned long long) fs);
465       GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
466       if (0 != UNLINK (filename))    
467         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
468       return NULL;
469     }
470   }
471   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
472   return ret;  
473 }
474
475
476 /**
477  * Wait for a short time (we're trying to lock a file or want
478  * to give another process a shot at finishing a disk write, etc.).
479  * Sleeps for 100ms (as that should be long enough for virtually all
480  * modern systems to context switch and allow another process to do
481  * some 'real' work).
482  */
483 static void
484 short_wait ()
485 {
486   struct GNUNET_TIME_Relative timeout;
487
488   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
489   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
490 }
491
492
493 /**
494  * Create a new private key by reading it from a file.  If the
495  * files does not exist, create a new key and write it to the
496  * file.  Caller must free return value.  Note that this function
497  * can not guarantee that another process might not be trying
498  * the same operation on the same file at the same time.
499  * If the contents of the file
500  * are invalid the old file is deleted and a fresh key is
501  * created.
502  *
503  * @return new private key, NULL on error (for example,
504  *   permission denied)
505  */
506 struct GNUNET_CRYPTO_EccPrivateKey *
507 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
508 {
509   struct GNUNET_CRYPTO_EccPrivateKey *ret;
510   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
511   uint16_t len;
512   struct GNUNET_DISK_FileHandle *fd;
513   unsigned int cnt;
514   int ec;
515   uint64_t fs;
516   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
517   struct GNUNET_PeerIdentity pid;
518
519   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
520     return NULL;
521   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
522   {
523     fd = GNUNET_DISK_file_open (filename,
524                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
525                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
526                                 GNUNET_DISK_PERM_USER_READ |
527                                 GNUNET_DISK_PERM_USER_WRITE);
528     if (NULL == fd)
529     {
530       if (errno == EEXIST)
531       {
532         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
533         {
534           /* must exist but not be accessible, fail for good! */
535           if (0 != ACCESS (filename, R_OK))
536             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
537           else
538             GNUNET_break (0);   /* what is going on!? */
539           return NULL;
540         }
541         continue;
542       }
543       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
544       return NULL;
545     }
546     cnt = 0;
547
548     while (GNUNET_YES !=
549            GNUNET_DISK_file_lock (fd, 0,
550                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
551                                   GNUNET_YES))
552     {
553       short_wait ();
554       if (0 == ++cnt % 10)
555       {
556         ec = errno;
557         LOG (GNUNET_ERROR_TYPE_ERROR,
558              _("Could not acquire lock on file `%s': %s...\n"), filename,
559              STRERROR (ec));
560       }
561     }
562     LOG (GNUNET_ERROR_TYPE_INFO,
563          _("Creating a new private key.  This may take a while.\n"));
564     ret = GNUNET_CRYPTO_ecc_key_create ();
565     GNUNET_assert (ret != NULL);
566     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
567     GNUNET_assert (enc != NULL);
568     GNUNET_assert (ntohs (enc->size) ==
569                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
570     GNUNET_free (enc);
571
572     GNUNET_DISK_file_sync (fd);
573     if (GNUNET_YES !=
574         GNUNET_DISK_file_unlock (fd, 0,
575                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
576       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
577     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
578     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
579     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
580     return ret;
581   }
582   /* key file exists already, read it! */
583   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
584                               GNUNET_DISK_PERM_NONE);
585   if (NULL == fd)
586   {
587     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
588     return NULL;
589   }
590   cnt = 0;
591   while (1)
592   {
593     if (GNUNET_YES !=
594         GNUNET_DISK_file_lock (fd, 0,
595                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
596                                GNUNET_NO))
597     {
598       if (0 == ++cnt % 60)
599       {
600         ec = errno;
601         LOG (GNUNET_ERROR_TYPE_ERROR,
602              _("Could not acquire lock on file `%s': %s...\n"), filename,
603              STRERROR (ec));
604         LOG (GNUNET_ERROR_TYPE_ERROR,
605              _
606              ("This may be ok if someone is currently generating a private key.\n"));
607       }
608       short_wait ();
609       continue;
610     }
611     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
612     {
613       /* eh, what!? File we opened is now gone!? */
614       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
615       if (GNUNET_YES !=
616           GNUNET_DISK_file_unlock (fd, 0,
617                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
618         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
619       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
620
621       return NULL;
622     }
623     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
624       fs = 0;
625     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
626     {
627       /* maybe we got the read lock before the key generating
628        * process had a chance to get the write lock; give it up! */
629       if (GNUNET_YES !=
630           GNUNET_DISK_file_unlock (fd, 0,
631                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
632         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
633       if (0 == ++cnt % 10)
634       {
635         LOG (GNUNET_ERROR_TYPE_ERROR,
636              _
637              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
638              filename, (unsigned int) fs,
639              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
640         LOG (GNUNET_ERROR_TYPE_ERROR,
641              _
642              ("This may be ok if someone is currently generating a key.\n"));
643       }
644       short_wait ();                /* wait a bit longer! */
645       continue;
646     }
647     break;
648   }
649   enc = GNUNET_malloc (fs);
650   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
651   len = ntohs (enc->size);
652   ret = NULL;
653   if ((len > fs) ||
654       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len, GNUNET_YES))))
655   {
656     LOG (GNUNET_ERROR_TYPE_ERROR,
657          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
658          filename);
659     if (0 != UNLINK (filename))
660     {
661       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
662     }
663   }
664   GNUNET_free (enc);
665   if (GNUNET_YES !=
666       GNUNET_DISK_file_unlock (fd, 0,
667                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
668     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
669   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
670   if (ret != NULL)
671   {
672     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
673     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
674   }
675   return ret;
676 }
677
678
679 /**
680  * Handle to cancel private key generation and state for the
681  * key generation operation.
682  */
683 struct GNUNET_CRYPTO_EccKeyGenerationContext
684 {
685   
686   /**
687    * Continuation to call upon completion.
688    */
689   GNUNET_CRYPTO_EccKeyCallback cont;
690
691   /**
692    * Closure for 'cont'.
693    */
694   void *cont_cls;
695
696   /**
697    * Name of the file.
698    */
699   char *filename;
700
701   /**
702    * Handle to the helper process which does the key generation.
703    */ 
704   struct GNUNET_OS_Process *gnunet_ecc;
705   
706   /**
707    * Handle to 'stdout' of gnunet-ecc.  We 'read' on stdout to detect
708    * process termination (instead of messing with SIGCHLD).
709    */
710   struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
711
712   /**
713    * Location where we store the private key if it already existed.
714    * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
715    * not be used).
716    */
717   struct GNUNET_CRYPTO_EccPrivateKey *pk;
718   
719   /**
720    * Task reading from 'gnunet_ecc_out' to wait for process termination.
721    */
722   GNUNET_SCHEDULER_TaskIdentifier read_task;
723   
724 };
725
726
727 /**
728  * Abort ECC key generation.
729  *
730  * @param gc key generation context to abort
731  */
732 void
733 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
734 {
735   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
736   {
737     GNUNET_SCHEDULER_cancel (gc->read_task);
738     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
739   }
740   if (NULL != gc->gnunet_ecc)
741   {
742     (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
743     GNUNET_break (GNUNET_OK ==
744                   GNUNET_OS_process_wait (gc->gnunet_ecc));
745     GNUNET_OS_process_destroy (gc->gnunet_ecc);
746     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
747   }
748
749   if (NULL != gc->filename)
750   {
751     if (0 != UNLINK (gc->filename))
752       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
753     GNUNET_free (gc->filename);
754   }
755   if (NULL != gc->pk)
756     GNUNET_CRYPTO_ecc_key_free (gc->pk);
757   GNUNET_free (gc);
758 }
759
760
761 /**
762  * Task called upon shutdown or process termination of 'gnunet-ecc' during
763  * ECC key generation.  Check where we are and perform the appropriate
764  * action.
765  *
766  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
767  * @param tc scheduler context
768  */
769 static void
770 check_key_generation_completion (void *cls,
771                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
772 {
773   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
774   struct GNUNET_CRYPTO_EccPrivateKey *pk;
775
776   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
777   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
778   {
779     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
780     GNUNET_CRYPTO_ecc_key_create_stop (gc);
781     return;
782   }
783   GNUNET_assert (GNUNET_OK == 
784                  GNUNET_OS_process_wait (gc->gnunet_ecc));
785   GNUNET_OS_process_destroy (gc->gnunet_ecc);
786   gc->gnunet_ecc = NULL;
787   if (NULL == (pk = try_read_key (gc->filename)))
788   {
789     GNUNET_break (0);
790     gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
791     GNUNET_CRYPTO_ecc_key_create_stop (gc);
792     return;
793   }
794   gc->cont (gc->cont_cls, pk, NULL);
795   GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
796   GNUNET_free (gc->filename);
797   GNUNET_free (gc);
798 }
799
800
801 /**
802  * Return the private ECC key which already existed on disk
803  * (asynchronously) to the caller.
804  *
805  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
806  * @param tc scheduler context (unused)
807  */
808 static void
809 async_return_key (void *cls,
810                   const struct GNUNET_SCHEDULER_TaskContext *tc)
811 {
812   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
813
814   gc->cont (gc->cont_cls,
815             gc->pk,
816             NULL);
817   GNUNET_free (gc);
818 }
819
820
821 /**
822  * Create a new private key by reading it from a file.  If the files
823  * does not exist, create a new key and write it to the file.  If the
824  * contents of the file are invalid the old file is deleted and a
825  * fresh key is created.
826  *
827  * @param filename name of file to use for storage
828  * @param cont function to call when done (or on errors)
829  * @param cont_cls closure for 'cont'
830  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
831  */
832 struct GNUNET_CRYPTO_EccKeyGenerationContext *
833 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
834                                     GNUNET_CRYPTO_EccKeyCallback cont,
835                                     void *cont_cls)
836 {
837   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
838   struct GNUNET_CRYPTO_EccPrivateKey *pk;
839
840   if (NULL != (pk = try_read_key (filename)))
841   {
842     /* quick happy ending: key already exists! */
843     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
844     gc->pk = pk;
845     gc->cont = cont;
846     gc->cont_cls = cont_cls;
847     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
848                                               gc);
849     return gc;
850   }
851   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
852   gc->filename = GNUNET_strdup (filename);
853   gc->cont = cont;
854   gc->cont_cls = cont_cls;
855   gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
856                                          GNUNET_NO,
857                                          GNUNET_NO,
858                                          GNUNET_YES);
859   if (NULL == gc->gnunet_ecc_out)
860   {
861     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
862     GNUNET_free (gc->filename);
863     GNUNET_free (gc);
864     return NULL;
865   }
866   gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
867                                             GNUNET_OS_INHERIT_STD_ERR,
868                                             NULL, 
869                                             gc->gnunet_ecc_out,
870                                             "gnunet-ecc",
871                                             "gnunet-ecc",                                           
872                                             gc->filename,
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   bufSize = strlen (FORMATSTRING) + 1;
940   {
941     char buff[bufSize];
942
943     memcpy (buff, FORMATSTRING, bufSize);
944     memcpy (&buff
945             [bufSize -
946              strlen
947              ("01234567890123456789012345678901))")
948              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
949     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
950   }
951 #undef FORMATSTRING
952   return data;
953 }
954
955
956 /**
957  * Sign a given block.
958  *
959  * @param key private key to use for the signing
960  * @param purpose what to sign (size, purpose)
961  * @param sig where to write the signature
962  * @return GNUNET_SYSERR on error, GNUNET_OK on success
963  */
964 int
965 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
966                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
967                         struct GNUNET_CRYPTO_EccSignature *sig)
968 {
969   gcry_sexp_t result;
970   gcry_sexp_t data;
971   size_t ssize;
972   int rc;
973
974   data = data_to_pkcs1 (purpose);
975   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
976   {
977     LOG (GNUNET_ERROR_TYPE_WARNING,
978          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
979          __LINE__, gcry_strerror (rc));
980   }
981   gcry_sexp_release (data);
982   ssize = gcry_sexp_sprint (result, 
983                             GCRYSEXP_FMT_DEFAULT,
984                             sig->sexpr,
985                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
986   if (0 == ssize)
987   {
988     GNUNET_break (0);
989     return GNUNET_SYSERR;
990   }
991   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
992   /* padd with zeros */
993   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
994   gcry_sexp_release (result);
995   return GNUNET_OK;
996 }
997
998
999 /**
1000  * Verify signature.
1001  *
1002  * @param purpose what is the purpose that the signature should have?
1003  * @param validate block to validate (size, purpose, data)
1004  * @param sig signature that is being validated
1005  * @param publicKey public key of the signer
1006  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1007  */
1008 int
1009 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1010                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1011                           *validate,
1012                           const struct GNUNET_CRYPTO_EccSignature *sig,
1013                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1014                           *publicKey)
1015 {
1016   gcry_sexp_t data;
1017   gcry_sexp_t sigdata;
1018   size_t size;
1019   gcry_sexp_t psexp;
1020   size_t erroff;
1021   int rc;
1022
1023   if (purpose != ntohl (validate->purpose))
1024     return GNUNET_SYSERR;       /* purpose mismatch */
1025   size = ntohs (sig->size);
1026   if ( (size < sizeof (uint16_t)) ||
1027        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1028     return GNUNET_SYSERR; /* size out of range */
1029   data = data_to_pkcs1 (validate);
1030   GNUNET_assert (0 ==
1031                  gcry_sexp_sscan (&sigdata, &erroff, 
1032                                   sig->sexpr, size - sizeof (uint16_t)));
1033   if (! (psexp = decode_public_key (publicKey)))
1034   {
1035     gcry_sexp_release (data);
1036     gcry_sexp_release (sigdata);
1037     return GNUNET_SYSERR;
1038   }
1039   rc = gcry_pk_verify (sigdata, data, psexp);
1040   gcry_sexp_release (psexp);
1041   gcry_sexp_release (data);
1042   gcry_sexp_release (sigdata);
1043   if (0 != rc)
1044   {
1045     LOG (GNUNET_ERROR_TYPE_WARNING,
1046          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1047          __LINE__, gcry_strerror (rc));
1048     return GNUNET_SYSERR;
1049   }
1050   return GNUNET_OK;
1051 }
1052
1053
1054 /**
1055  * Derive key material from a public and a private ECC key.
1056  *
1057  * @param key private key to use for the ECDH (x)
1058  * @param pub public key to use for the ECDY (yG)
1059  * @param key_material where to write the key material (xyG)
1060  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1061  */
1062 int
1063 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1064                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1065                         struct GNUNET_HashCode *key_material)
1066
1067   size_t size;
1068   size_t slen;
1069   int rc;
1070   gcry_sexp_t data;  
1071   unsigned char sdata_buf[2048]; /* big enough to print 'sdata' and 'r_sig' */
1072
1073   /* first, extract the q value from the public key */
1074   {
1075     gcry_sexp_t psexp;
1076     gcry_mpi_t sdata;
1077     
1078     if (! (psexp = decode_public_key (pub)))
1079       return GNUNET_SYSERR;
1080     rc = key_from_sexp (&sdata, psexp, "public-key", "q");
1081     if (rc)
1082       rc = key_from_sexp (&sdata, psexp, "ecc", "q");
1083     GNUNET_assert (0 == rc);  
1084     gcry_sexp_release (psexp);
1085     size = sizeof (sdata_buf);
1086     GNUNET_assert (0 ==
1087                    gcry_mpi_print (GCRYMPI_FMT_USG, sdata_buf, size, &size,
1088                                    sdata));
1089     gcry_mpi_release (sdata);
1090   }
1091   /* convert q value into an S-expression -- whatever format libgcrypt wants,
1092      re-using format from sign operation for now... */
1093   {
1094     char *sexp_string;
1095
1096 #define FORMATPREFIX "(4:data(5:flags3:raw)(5:value%u:"
1097 #define FORMATPOSTFIX "))"
1098     sexp_string = GNUNET_malloc (strlen (FORMATPREFIX) + size + 12 +
1099                                   strlen (FORMATPOSTFIX) + 1);
1100     GNUNET_snprintf (sexp_string,
1101                      strlen (FORMATPREFIX) + 12,
1102                      FORMATPREFIX,
1103                      size);
1104     slen = strlen (sexp_string);
1105     memcpy (&sexp_string[slen],
1106             sdata_buf, 
1107             size);
1108     memcpy (&sexp_string[slen + size],
1109             FORMATPOSTFIX,
1110             strlen (FORMATPOSTFIX) + 1);  
1111     GNUNET_assert (0 == gcry_sexp_new (&data, 
1112                                        sexp_string, 
1113                                        slen + size + strlen (FORMATPOSTFIX), 
1114                                        0));
1115     GNUNET_free (sexp_string);
1116   }
1117   /* then call the 'multiply' function, hoping it simply multiplies the points;
1118      here we need essentially a WRAPPER around _gcry_mpi_ex_mul_point! - FIXME-WK!*/
1119 #if WK
1120   {
1121     gcry_sexp_t result;
1122     
1123     rc = gcry_ecc_mul_point (&result, data /* scalar */, key->sexp /* point and ctx */);
1124     GNUNET_assert (0 == rc);
1125     slen = gcry_sexp_sprint (result, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
1126     GNUNET_assert (0 != slen);
1127   }
1128 #else
1129   /* use broken version, insecure! */
1130   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("To be implemented: not secure at the moment, please read README\n"));
1131   slen = sprintf ((char*) sdata_buf, "FIXME-this is not key material");
1132 #endif
1133   gcry_sexp_release (data);
1134
1135   /* finally, get a string of the resulting S-expression and hash it to generate the key material */
1136   GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
1137   return GNUNET_OK;
1138 }
1139
1140
1141 /* end of crypto_ecc.c */