- verboser log, faster start
[oweals/gnunet.git] / src / util / crypto_ecc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/crypto_ecc.c
23  * @brief public key cryptography (ECC) with libgcrypt
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <gcrypt.h>
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30
31 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS || 1
32
33 #define CURVE "NIST P-521"
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
36
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
38
39 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40
41 /**
42  * Log an error message at log-level 'level' that indicates
43  * a failure of the command 'cmd' with the message given
44  * by gcry_strerror(rc).
45  */
46 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
47
48
49 /**
50  * The private information of an ECC private key.
51  */
52 struct GNUNET_CRYPTO_EccPrivateKey
53 {
54   
55   /**
56    * Libgcrypt S-expression for the ECC key.
57    */
58   gcry_sexp_t sexp;
59 };
60
61
62 /**
63  * Free memory occupied by ECC key
64  *
65  * @param privatekey pointer to the memory to free
66  */
67 void
68 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey)
69 {
70   gcry_sexp_release (privatekey->sexp);
71   GNUNET_free (privatekey);
72 }
73
74
75 /**
76  * Extract values from an S-expression.
77  *
78  * @param array where to store the result(s)
79  * @param sexp S-expression to parse
80  * @param topname top-level name in the S-expression that is of interest
81  * @param elems names of the elements to extract
82  * @return 0 on success
83  */
84 static int
85 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
86                const char *elems)
87 {
88   gcry_sexp_t list;
89   gcry_sexp_t l2;
90   const char *s;
91   unsigned int i;
92   unsigned int idx;
93
94   list = gcry_sexp_find_token (sexp, topname, 0);
95   if (! list)  
96     return 1;  
97   l2 = gcry_sexp_cadr (list);
98   gcry_sexp_release (list);
99   list = l2;
100   if (! list)  
101     return 2;  
102
103   idx = 0;
104   for (s = elems; *s; s++, idx++)
105   {
106     l2 = gcry_sexp_find_token (list, s, 1);
107     if (! l2)
108     {
109       for (i = 0; i < idx; i++)
110       {
111         gcry_free (array[i]);
112         array[i] = NULL;
113       }
114       gcry_sexp_release (list);
115       return 3;                 /* required parameter not found */
116     }
117     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
118     gcry_sexp_release (l2);
119     if (! array[idx])
120     {
121       for (i = 0; i < idx; i++)
122       {
123         gcry_free (array[i]);
124         array[i] = NULL;
125       }
126       gcry_sexp_release (list);
127       return 4;                 /* required parameter is invalid */
128     }
129   }
130   gcry_sexp_release (list);
131   return 0;
132 }
133
134
135 /**
136  * Extract the public key for the given private key.
137  *
138  * @param priv the private key
139  * @param pub where to write the public key
140  */
141 void
142 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
143                                   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub)
144 {
145   gcry_mpi_t skey;
146   size_t size;
147   int rc;
148
149   memset (pub, 0, sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
150   rc = key_from_sexp (&skey, priv->sexp, "public-key", "q");
151   if (rc)
152     rc = key_from_sexp (&skey, priv->sexp, "private-key", "q");
153   if (rc)
154     rc = key_from_sexp (&skey, priv->sexp, "ecc", "q");
155   GNUNET_assert (0 == rc);
156   pub->size = htons (sizeof (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded));
157   size = GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH;
158   GNUNET_assert (0 ==
159                  gcry_mpi_print (GCRYMPI_FMT_USG, pub->key, size, &size,
160                                  skey));
161   pub->len = htons (size);
162   gcry_mpi_release (skey);
163 }
164
165
166 /**
167  * Convert a public key to a string.
168  *
169  * @param pub key to convert
170  * @return string representing  'pub'
171  */
172 char *
173 GNUNET_CRYPTO_ecc_public_key_to_string (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  * @return NULL on error
329  */
330 struct GNUNET_CRYPTO_EccPrivateKey *
331 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
332                               size_t len)
333 {
334   struct GNUNET_CRYPTO_EccPrivateKey *ret;
335   uint16_t be;
336   gcry_sexp_t sexp;
337   int rc;
338   size_t erroff;
339
340   if (len < sizeof (uint16_t)) 
341     return NULL;
342   memcpy (&be, buf, sizeof (be));
343   if (len < ntohs (be))
344     return NULL;
345   len = ntohs (be);
346   if (0 != (rc = gcry_sexp_sscan (&sexp,
347                                   &erroff,
348                                   &buf[2],
349                                   len - sizeof (uint16_t))))
350   {
351     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
352     return NULL;
353   }
354   if (0 != (rc = gcry_pk_testkey (sexp)))
355   {
356     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
357     return NULL;
358   }
359   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
360   ret->sexp = sexp;
361   return ret;
362 }
363
364
365 /**
366  * Create a new private key. Caller must free return value.
367  *
368  * @return fresh private key
369  */
370 struct GNUNET_CRYPTO_EccPrivateKey *
371 GNUNET_CRYPTO_ecc_key_create ()
372 {
373   struct GNUNET_CRYPTO_EccPrivateKey *ret;
374   gcry_sexp_t s_key;
375   gcry_sexp_t s_keyparam;
376   int rc;
377
378   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
379                                   "(genkey(ecdsa(curve \"" CURVE "\")))")))
380   {
381     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
382     return NULL;
383   }
384   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
385   {
386     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
387     gcry_sexp_release (s_keyparam);
388     return NULL;
389   }
390   gcry_sexp_release (s_keyparam);
391 #if EXTRA_CHECKS
392   if (0 != (rc = gcry_pk_testkey (s_key)))
393   {
394     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
395     gcry_sexp_release (s_key);
396     return NULL;
397   }
398 #endif
399   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
400   ret->sexp = s_key;
401   return ret;
402 }
403
404
405 /**
406  * Try to read the private key from the given file.
407  *
408  * @param filename file to read the key from
409  * @return NULL on error
410  */
411 static struct GNUNET_CRYPTO_EccPrivateKey *
412 try_read_key (const char *filename)
413 {
414   struct GNUNET_CRYPTO_EccPrivateKey *ret;
415   struct GNUNET_DISK_FileHandle *fd;
416   OFF_T fs;
417
418   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
419     return NULL;
420
421   /* key file exists already, read it! */
422   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
423                                            GNUNET_DISK_PERM_NONE)))
424   {
425     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
426     return NULL;
427   }
428   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
429   {
430     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
431     (void) GNUNET_DISK_file_close (fd);
432     return NULL;
433   }
434   if (0 == fs)
435   {
436     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
437     return NULL;
438   }
439   if (fs > UINT16_MAX)
440   {
441     LOG (GNUNET_ERROR_TYPE_ERROR,
442          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
443          filename,
444          (unsigned long long) fs);
445     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
446     if (0 != UNLINK (filename))    
447       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
448     return NULL;
449   }
450   {
451     char enc[fs];
452
453     GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
454     if (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, fs)))
455     {
456       LOG (GNUNET_ERROR_TYPE_ERROR,
457            _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
458            filename,
459            (unsigned long long) fs);
460       GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
461       if (0 != UNLINK (filename))    
462         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
463       return NULL;
464     }
465   }
466   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
467   return ret;  
468 }
469
470
471 /**
472  * Wait for a short time (we're trying to lock a file or want
473  * to give another process a shot at finishing a disk write, etc.).
474  * Sleeps for 100ms (as that should be long enough for virtually all
475  * modern systems to context switch and allow another process to do
476  * some 'real' work).
477  */
478 static void
479 short_wait ()
480 {
481   struct GNUNET_TIME_Relative timeout;
482
483   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
484   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
485 }
486
487
488 /**
489  * Create a new private key by reading it from a file.  If the
490  * files does not exist, create a new key and write it to the
491  * file.  Caller must free return value.  Note that this function
492  * can not guarantee that another process might not be trying
493  * the same operation on the same file at the same time.
494  * If the contents of the file
495  * are invalid the old file is deleted and a fresh key is
496  * created.
497  *
498  * @return new private key, NULL on error (for example,
499  *   permission denied)
500  */
501 struct GNUNET_CRYPTO_EccPrivateKey *
502 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
503 {
504   struct GNUNET_CRYPTO_EccPrivateKey *ret;
505   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
506   uint16_t len;
507   struct GNUNET_DISK_FileHandle *fd;
508   unsigned int cnt;
509   int ec;
510   uint64_t fs;
511   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
512   struct GNUNET_PeerIdentity pid;
513
514   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
515     return NULL;
516   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
517   {
518     fd = GNUNET_DISK_file_open (filename,
519                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
520                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
521                                 GNUNET_DISK_PERM_USER_READ |
522                                 GNUNET_DISK_PERM_USER_WRITE);
523     if (NULL == fd)
524     {
525       if (errno == EEXIST)
526       {
527         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
528         {
529           /* must exist but not be accessible, fail for good! */
530           if (0 != ACCESS (filename, R_OK))
531             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
532           else
533             GNUNET_break (0);   /* what is going on!? */
534           return NULL;
535         }
536         continue;
537       }
538       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
539       return NULL;
540     }
541     cnt = 0;
542
543     while (GNUNET_YES !=
544            GNUNET_DISK_file_lock (fd, 0,
545                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
546                                   GNUNET_YES))
547     {
548       short_wait ();
549       if (0 == ++cnt % 10)
550       {
551         ec = errno;
552         LOG (GNUNET_ERROR_TYPE_ERROR,
553              _("Could not acquire lock on file `%s': %s...\n"), filename,
554              STRERROR (ec));
555       }
556     }
557     LOG (GNUNET_ERROR_TYPE_INFO,
558          _("Creating a new private key.  This may take a while.\n"));
559     ret = GNUNET_CRYPTO_ecc_key_create ();
560     GNUNET_assert (ret != NULL);
561     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
562     GNUNET_assert (enc != NULL);
563     GNUNET_assert (ntohs (enc->size) ==
564                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
565     GNUNET_free (enc);
566
567     GNUNET_DISK_file_sync (fd);
568     if (GNUNET_YES !=
569         GNUNET_DISK_file_unlock (fd, 0,
570                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
571       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
572     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
573     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
574     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
575     return ret;
576   }
577   /* key file exists already, read it! */
578   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
579                               GNUNET_DISK_PERM_NONE);
580   if (NULL == fd)
581   {
582     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
583     return NULL;
584   }
585   cnt = 0;
586   while (1)
587   {
588     if (GNUNET_YES !=
589         GNUNET_DISK_file_lock (fd, 0,
590                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
591                                GNUNET_NO))
592     {
593       if (0 == ++cnt % 60)
594       {
595         ec = errno;
596         LOG (GNUNET_ERROR_TYPE_ERROR,
597              _("Could not acquire lock on file `%s': %s...\n"), filename,
598              STRERROR (ec));
599         LOG (GNUNET_ERROR_TYPE_ERROR,
600              _
601              ("This may be ok if someone is currently generating a private key.\n"));
602       }
603       short_wait ();
604       continue;
605     }
606     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
607     {
608       /* eh, what!? File we opened is now gone!? */
609       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
610       if (GNUNET_YES !=
611           GNUNET_DISK_file_unlock (fd, 0,
612                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
613         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
614       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
615
616       return NULL;
617     }
618     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
619       fs = 0;
620     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
621     {
622       /* maybe we got the read lock before the key generating
623        * process had a chance to get the write lock; give it up! */
624       if (GNUNET_YES !=
625           GNUNET_DISK_file_unlock (fd, 0,
626                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
627         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
628       if (0 == ++cnt % 10)
629       {
630         LOG (GNUNET_ERROR_TYPE_ERROR,
631              _
632              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
633              filename, (unsigned int) fs,
634              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
635         LOG (GNUNET_ERROR_TYPE_ERROR,
636              _
637              ("This may be ok if someone is currently generating a key.\n"));
638       }
639       short_wait ();                /* wait a bit longer! */
640       continue;
641     }
642     break;
643   }
644   enc = GNUNET_malloc (fs);
645   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
646   len = ntohs (enc->size);
647   ret = NULL;
648   if ((len > fs) ||
649       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len))))
650   {
651     LOG (GNUNET_ERROR_TYPE_ERROR,
652          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
653          filename);
654     if (0 != UNLINK (filename))
655     {
656       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
657     }
658   }
659   GNUNET_free (enc);
660   if (GNUNET_YES !=
661       GNUNET_DISK_file_unlock (fd, 0,
662                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
663     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
664   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
665   if (ret != NULL)
666   {
667     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
668     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
669   }
670   return ret;
671 }
672
673
674 /**
675  * Handle to cancel private key generation and state for the
676  * key generation operation.
677  */
678 struct GNUNET_CRYPTO_EccKeyGenerationContext
679 {
680   
681   /**
682    * Continuation to call upon completion.
683    */
684   GNUNET_CRYPTO_EccKeyCallback cont;
685
686   /**
687    * Closure for 'cont'.
688    */
689   void *cont_cls;
690
691   /**
692    * Name of the file.
693    */
694   char *filename;
695
696   /**
697    * Handle to the helper process which does the key generation.
698    */ 
699   struct GNUNET_OS_Process *gnunet_ecc;
700   
701   /**
702    * Handle to 'stdout' of gnunet-ecc.  We 'read' on stdout to detect
703    * process termination (instead of messing with SIGCHLD).
704    */
705   struct GNUNET_DISK_PipeHandle *gnunet_ecc_out;
706
707   /**
708    * Location where we store the private key if it already existed.
709    * (if this is used, 'filename', 'gnunet_ecc' and 'gnunet_ecc_out' will
710    * not be used).
711    */
712   struct GNUNET_CRYPTO_EccPrivateKey *pk;
713   
714   /**
715    * Task reading from 'gnunet_ecc_out' to wait for process termination.
716    */
717   GNUNET_SCHEDULER_TaskIdentifier read_task;
718   
719 };
720
721
722 /**
723  * Abort ECC key generation.
724  *
725  * @param gc key generation context to abort
726  */
727 void
728 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc)
729 {
730   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
731   {
732     GNUNET_SCHEDULER_cancel (gc->read_task);
733     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
734   }
735   if (NULL != gc->gnunet_ecc)
736   {
737     (void) GNUNET_OS_process_kill (gc->gnunet_ecc, SIGKILL);
738     GNUNET_break (GNUNET_OK ==
739                   GNUNET_OS_process_wait (gc->gnunet_ecc));
740     GNUNET_OS_process_destroy (gc->gnunet_ecc);
741     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
742   }
743
744   if (NULL != gc->filename)
745   {
746     if (0 != UNLINK (gc->filename))
747       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
748     GNUNET_free (gc->filename);
749   }
750   if (NULL != gc->pk)
751     GNUNET_CRYPTO_ecc_key_free (gc->pk);
752   GNUNET_free (gc);
753 }
754
755
756 /**
757  * Task called upon shutdown or process termination of 'gnunet-ecc' during
758  * ECC key generation.  Check where we are and perform the appropriate
759  * action.
760  *
761  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
762  * @param tc scheduler context
763  */
764 static void
765 check_key_generation_completion (void *cls,
766                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
767 {
768   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
769   struct GNUNET_CRYPTO_EccPrivateKey *pk;
770
771   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
772   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
773   {
774     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
775     GNUNET_CRYPTO_ecc_key_create_stop (gc);
776     return;
777   }
778   GNUNET_assert (GNUNET_OK == 
779                  GNUNET_OS_process_wait (gc->gnunet_ecc));
780   GNUNET_OS_process_destroy (gc->gnunet_ecc);
781   gc->gnunet_ecc = NULL;
782   if (NULL == (pk = try_read_key (gc->filename)))
783   {
784     GNUNET_break (0);
785     gc->cont (gc->cont_cls, NULL, _("gnunet-ecc failed"));
786     GNUNET_CRYPTO_ecc_key_create_stop (gc);
787     return;
788   }
789   gc->cont (gc->cont_cls, pk, NULL);
790   GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
791   GNUNET_free (gc->filename);
792   GNUNET_free (gc);
793 }
794
795
796 /**
797  * Return the private ECC key which already existed on disk
798  * (asynchronously) to the caller.
799  *
800  * @param cls the 'struct GNUNET_CRYPTO_EccKeyGenerationContext'
801  * @param tc scheduler context (unused)
802  */
803 static void
804 async_return_key (void *cls,
805                   const struct GNUNET_SCHEDULER_TaskContext *tc)
806 {
807   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc = cls;
808
809   gc->cont (gc->cont_cls,
810             gc->pk,
811             NULL);
812   GNUNET_free (gc);
813 }
814
815
816 /**
817  * Create a new private key by reading it from a file.  If the files
818  * does not exist, create a new key and write it to the file.  If the
819  * contents of the file are invalid the old file is deleted and a
820  * fresh key is created.
821  *
822  * @param filename name of file to use for storage
823  * @param cont function to call when done (or on errors)
824  * @param cont_cls closure for 'cont'
825  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
826  */
827 struct GNUNET_CRYPTO_EccKeyGenerationContext *
828 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
829                                     GNUNET_CRYPTO_EccKeyCallback cont,
830                                     void *cont_cls)
831 {
832   struct GNUNET_CRYPTO_EccKeyGenerationContext *gc;
833   struct GNUNET_CRYPTO_EccPrivateKey *pk;
834
835   if (NULL != (pk = try_read_key (filename)))
836   {
837     /* quick happy ending: key already exists! */
838     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
839     gc->pk = pk;
840     gc->cont = cont;
841     gc->cont_cls = cont_cls;
842     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
843                                               gc);
844     return gc;
845   }
846   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccKeyGenerationContext));
847   gc->filename = GNUNET_strdup (filename);
848   gc->cont = cont;
849   gc->cont_cls = cont_cls;
850   gc->gnunet_ecc_out = GNUNET_DISK_pipe (GNUNET_NO,
851                                          GNUNET_NO,
852                                          GNUNET_NO,
853                                          GNUNET_YES);
854   if (NULL == gc->gnunet_ecc_out)
855   {
856     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
857     GNUNET_free (gc->filename);
858     GNUNET_free (gc);
859     return NULL;
860   }
861   gc->gnunet_ecc = GNUNET_OS_start_process (GNUNET_NO,
862                                             GNUNET_OS_INHERIT_STD_ERR,
863                                             NULL, 
864                                             gc->gnunet_ecc_out,
865                                             "gnunet-ecc",
866                                             "gnunet-ecc",                                           
867                                             gc->filename,
868                                             NULL);
869   if (NULL == gc->gnunet_ecc)
870   {
871     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
872     GNUNET_DISK_pipe_close (gc->gnunet_ecc_out);
873     GNUNET_free (gc->filename);
874     GNUNET_free (gc);
875     return NULL;
876   }
877   GNUNET_assert (GNUNET_OK ==
878                  GNUNET_DISK_pipe_close_end (gc->gnunet_ecc_out,
879                                              GNUNET_DISK_PIPE_END_WRITE));
880   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
881                                                   GNUNET_DISK_pipe_handle (gc->gnunet_ecc_out,
882                                                                            GNUNET_DISK_PIPE_END_READ),
883                                                   &check_key_generation_completion,
884                                                   gc);
885   return gc;
886 }
887
888
889 /**
890  * Setup a key file for a peer given the name of the
891  * configuration file (!).  This function is used so that
892  * at a later point code can be certain that reading a
893  * key is fast (for example in time-dependent testcases).
894  *
895  * @param cfg_name name of the configuration file to use
896  */
897 void
898 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
899 {
900   struct GNUNET_CONFIGURATION_Handle *cfg;
901   struct GNUNET_CRYPTO_EccPrivateKey *pk;
902   char *fn;
903
904   cfg = GNUNET_CONFIGURATION_create ();
905   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
906   if (GNUNET_OK == 
907       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
908   {
909     pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
910     if (NULL != pk)
911       GNUNET_CRYPTO_ecc_key_free (pk);
912     GNUNET_free (fn);
913   }
914   GNUNET_CONFIGURATION_destroy (cfg);
915 }
916
917
918 /**
919  * Convert the data specified in the given purpose argument to an
920  * S-expression suitable for signature operations.
921  *
922  * @param purpose data to convert
923  * @return converted s-expression
924  */
925 static gcry_sexp_t
926 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
927 {
928   struct GNUNET_CRYPTO_ShortHashCode hc;
929   size_t bufSize;
930   gcry_sexp_t data;
931
932   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
933 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
934   bufSize = strlen (FORMATSTRING) + 1;
935   {
936     char buff[bufSize];
937
938     memcpy (buff, FORMATSTRING, bufSize);
939     memcpy (&buff
940             [bufSize -
941              strlen
942              ("01234567890123456789012345678901))")
943              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
944     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
945   }
946 #undef FORMATSTRING
947   return data;
948 }
949
950
951 /**
952  * Sign a given block.
953  *
954  * @param key private key to use for the signing
955  * @param purpose what to sign (size, purpose)
956  * @param sig where to write the signature
957  * @return GNUNET_SYSERR on error, GNUNET_OK on success
958  */
959 int
960 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
961                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
962                         struct GNUNET_CRYPTO_EccSignature *sig)
963 {
964   gcry_sexp_t result;
965   gcry_sexp_t data;
966   size_t ssize;
967   int rc;
968
969   data = data_to_pkcs1 (purpose);
970   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
971   {
972     LOG (GNUNET_ERROR_TYPE_WARNING,
973          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
974          __LINE__, gcry_strerror (rc));
975   }
976   gcry_sexp_release (data);
977   ssize = gcry_sexp_sprint (result, 
978                             GCRYSEXP_FMT_DEFAULT,
979                             sig->sexpr,
980                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
981   if (0 == ssize)
982   {
983     GNUNET_break (0);
984     return GNUNET_SYSERR;
985   }
986   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
987   /* padd with zeros */
988   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
989   gcry_sexp_release (result);
990   return GNUNET_OK;
991 }
992
993
994 /**
995  * Verify signature.
996  *
997  * @param purpose what is the purpose that the signature should have?
998  * @param validate block to validate (size, purpose, data)
999  * @param sig signature that is being validated
1000  * @param publicKey public key of the signer
1001  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1002  */
1003 int
1004 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1005                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1006                           *validate,
1007                           const struct GNUNET_CRYPTO_EccSignature *sig,
1008                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1009                           *publicKey)
1010 {
1011   gcry_sexp_t data;
1012   gcry_sexp_t sigdata;
1013   size_t size;
1014   gcry_sexp_t psexp;
1015   size_t erroff;
1016   int rc;
1017
1018   if (purpose != ntohl (validate->purpose))
1019     return GNUNET_SYSERR;       /* purpose mismatch */
1020   size = ntohs (sig->size);
1021   if ( (size < sizeof (uint16_t)) ||
1022        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
1023     return GNUNET_SYSERR; /* size out of range */
1024   data = data_to_pkcs1 (validate);
1025   GNUNET_assert (0 ==
1026                  gcry_sexp_sscan (&sigdata, &erroff, 
1027                                   sig->sexpr, size - sizeof (uint16_t)));
1028   if (! (psexp = decode_public_key (publicKey)))
1029   {
1030     gcry_sexp_release (data);
1031     gcry_sexp_release (sigdata);
1032     return GNUNET_SYSERR;
1033   }
1034   rc = gcry_pk_verify (sigdata, data, psexp);
1035   gcry_sexp_release (psexp);
1036   gcry_sexp_release (data);
1037   gcry_sexp_release (sigdata);
1038   if (0 != rc)
1039   {
1040     LOG (GNUNET_ERROR_TYPE_WARNING,
1041          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
1042          __LINE__, gcry_strerror (rc));
1043     return GNUNET_SYSERR;
1044   }
1045   return GNUNET_OK;
1046 }
1047
1048
1049 /**
1050  * Derive key material from a public and a private ECC key.
1051  *
1052  * @param key private key to use for the ECDH (x)
1053  * @param pub public key to use for the ECDY (yG)
1054  * @param key_material where to write the key material (xyG)
1055  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1056  */
1057 int
1058 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1059                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1060                         struct GNUNET_HashCode *key_material)
1061
1062   size_t size;
1063   size_t slen;
1064   int rc;
1065   gcry_sexp_t data;  
1066   unsigned char sdata_buf[2048]; /* big enough to print 'sdata' and 'r_sig' */
1067
1068   /* first, extract the q value from the public key */
1069   {
1070     gcry_sexp_t psexp;
1071     gcry_mpi_t sdata;
1072     
1073     if (! (psexp = decode_public_key (pub)))
1074       return GNUNET_SYSERR;
1075     rc = key_from_sexp (&sdata, psexp, "public-key", "q");
1076     if (rc)
1077       rc = key_from_sexp (&sdata, psexp, "ecc", "q");
1078     GNUNET_assert (0 == rc);  
1079     gcry_sexp_release (psexp);
1080     size = sizeof (sdata_buf);
1081     GNUNET_assert (0 ==
1082                    gcry_mpi_print (GCRYMPI_FMT_USG, sdata_buf, size, &size,
1083                                    sdata));
1084     gcry_mpi_release (sdata);
1085   }
1086   /* convert q value into an S-expression -- whatever format libgcrypt wants,
1087      re-using format from sign operation for now... */
1088   {
1089     char *sexp_string;
1090
1091 #define FORMATPREFIX "(4:data(5:flags3:raw)(5:value%u:"
1092 #define FORMATPOSTFIX "))"
1093     sexp_string = GNUNET_malloc (strlen (FORMATPREFIX) + size + 12 +
1094                                   strlen (FORMATPOSTFIX) + 1);
1095     GNUNET_snprintf (sexp_string,
1096                      strlen (FORMATPREFIX) + 12,
1097                      FORMATPREFIX,
1098                      size);
1099     slen = strlen (sexp_string);
1100     memcpy (&sexp_string[slen],
1101             sdata_buf, 
1102             size);
1103     memcpy (&sexp_string[slen + size],
1104             FORMATPOSTFIX,
1105             strlen (FORMATPOSTFIX) + 1);  
1106     GNUNET_assert (0 == gcry_sexp_new (&data, 
1107                                        sexp_string, 
1108                                        slen + size + strlen (FORMATPOSTFIX), 
1109                                        0));
1110     GNUNET_free (sexp_string);
1111   }
1112   /* then call the 'multiply' function, hoping it simply multiplies the points;
1113      here we need essentially a WRAPPER around _gcry_mpi_ex_mul_point! - FIXME-WK!*/
1114 #if WK
1115   {
1116     gcry_sexp_t result;
1117     
1118     rc = gcry_ecc_mul_point (&result, data /* scalar */, key->sexp /* point and ctx */);
1119     GNUNET_assert (0 == rc);
1120     slen = gcry_sexp_sprint (result, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
1121     GNUNET_assert (0 != slen);
1122   }
1123 #else
1124   /* use broken version, insecure! */
1125   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("To be implemented: not secure at the moment, please read README\n"));
1126   slen = sprintf ((char*) sdata_buf, "FIXME-this is not key material");
1127 #endif
1128   gcry_sexp_release (data);
1129
1130   /* finally, get a string of the resulting S-expression and hash it to generate the key material */
1131   GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
1132   return GNUNET_OK;
1133 }
1134
1135
1136 /* end of crypto_ecc.c */