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