-add identity service to standard build
[oweals/gnunet.git] / src / util / crypto_ecc.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012, 2013 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-256"
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                                                   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 #if EXTRA_CHECKS
267   if (0 != (rc = gcry_pk_testkey (result)))
268   {
269     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
270     gcry_sexp_release (result);
271     return NULL;
272   }
273 #endif
274   return result;
275 }
276
277
278 /**
279  * Encode the private key in a format suitable for
280  * storing it into a file.
281  *
282  * @param key key to encode
283  * @return encoding of the private key.
284  *    The first 4 bytes give the size of the array, as usual.
285  */
286 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
287 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key)
288 {
289   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *retval;
290   char buf[65536];
291   uint16_t be;
292   size_t size;
293
294 #if EXTRA_CHECKS
295   if (0 != gcry_pk_testkey (key->sexp))
296   {
297     GNUNET_break (0);
298     return NULL;
299   }
300 #endif
301   size = gcry_sexp_sprint (key->sexp, 
302                            GCRYSEXP_FMT_DEFAULT,
303                            &buf[2], sizeof (buf) - sizeof (uint16_t));
304   if (0 == size)
305   {
306     GNUNET_break (0);
307     return NULL;
308   }
309   GNUNET_assert (size < 65536 - sizeof (uint16_t));
310   be = htons ((uint16_t) size + (sizeof (be)));
311   memcpy (buf, &be, sizeof (be));
312   size += sizeof (be);
313   retval = GNUNET_malloc (size);
314   memcpy (retval, buf, size);
315   return retval;
316 }
317
318
319 /**
320  * Decode the private key from the file-format back
321  * to the "normal", internal format.
322  *
323  * @param buf the buffer where the private key data is stored
324  * @param len the length of the data in 'buffer'
325  * @param validate GNUNET_YES to validate that the key is well-formed,
326  *                 GNUNET_NO if the key comes from a totally trusted source 
327  *                 and validation is considered too expensive
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                               int validate)
334 {
335   struct GNUNET_CRYPTO_EccPrivateKey *ret;
336   uint16_t be;
337   gcry_sexp_t sexp;
338   int rc;
339   size_t erroff;
340
341   if (len < sizeof (uint16_t)) 
342     return NULL;
343   memcpy (&be, buf, sizeof (be));
344   if (len < ntohs (be))
345     return NULL;
346   len = ntohs (be);
347   if (0 != (rc = gcry_sexp_sscan (&sexp,
348                                   &erroff,
349                                   &buf[2],
350                                   len - sizeof (uint16_t))))
351   {
352     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_scan", rc);
353     return NULL;
354   }  
355   if ( (GNUNET_YES == validate) &&
356        (0 != (rc = gcry_pk_testkey (sexp))) )
357   {
358     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
359     return NULL;
360   }
361   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
362   ret->sexp = sexp;
363   return ret;
364 }
365
366
367 /**
368  * Create a new private key. Caller must free return value.
369  *
370  * @return fresh private key
371  */
372 struct GNUNET_CRYPTO_EccPrivateKey *
373 GNUNET_CRYPTO_ecc_key_create ()
374 {
375   struct GNUNET_CRYPTO_EccPrivateKey *ret;
376   gcry_sexp_t s_key;
377   gcry_sexp_t s_keyparam;
378   int rc;
379
380   if (0 != (rc = gcry_sexp_build (&s_keyparam, NULL,
381                                   "(genkey(ecdsa(curve \"" CURVE "\")))")))
382   {
383     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
384     return NULL;
385   }
386   if (0 != (rc = gcry_pk_genkey (&s_key, s_keyparam)))
387   {
388     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
389     gcry_sexp_release (s_keyparam);
390     return NULL;
391   }
392   gcry_sexp_release (s_keyparam);
393 #if EXTRA_CHECKS
394   if (0 != (rc = gcry_pk_testkey (s_key)))
395   {
396     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
397     gcry_sexp_release (s_key);
398     return NULL;
399   }
400 #endif
401   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_EccPrivateKey));
402   ret->sexp = s_key;
403   return ret;
404 }
405
406
407 /**
408  * Wait for a short time (we're trying to lock a file or want
409  * to give another process a shot at finishing a disk write, etc.).
410  * Sleeps for 100ms (as that should be long enough for virtually all
411  * modern systems to context switch and allow another process to do
412  * some 'real' work).
413  */
414 static void
415 short_wait ()
416 {
417   struct GNUNET_TIME_Relative timeout;
418
419   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
420   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
421 }
422
423
424 /**
425  * Create a new private key by reading it from a file.  If the
426  * files does not exist, create a new key and write it to the
427  * file.  Caller must free return value.  Note that this function
428  * can not guarantee that another process might not be trying
429  * the same operation on the same file at the same time.
430  * If the contents of the file
431  * are invalid the old file is deleted and a fresh key is
432  * created.
433  *
434  * @param filename name of file to use to store the key
435  * @return new private key, NULL on error (for example,
436  *   permission denied)
437  */
438 struct GNUNET_CRYPTO_EccPrivateKey *
439 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename)
440 {
441   struct GNUNET_CRYPTO_EccPrivateKey *ret;
442   struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *enc;
443   uint16_t len;
444   struct GNUNET_DISK_FileHandle *fd;
445   unsigned int cnt;
446   int ec;
447   uint64_t fs;
448   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded pub;
449   struct GNUNET_PeerIdentity pid;
450
451   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
452     return NULL;
453   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
454   {
455     fd = GNUNET_DISK_file_open (filename,
456                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
457                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
458                                 GNUNET_DISK_PERM_USER_READ |
459                                 GNUNET_DISK_PERM_USER_WRITE);
460     if (NULL == fd)
461     {
462       if (errno == EEXIST)
463       {
464         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
465         {
466           /* must exist but not be accessible, fail for good! */
467           if (0 != ACCESS (filename, R_OK))
468             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
469           else
470             GNUNET_break (0);   /* what is going on!? */
471           return NULL;
472         }
473         continue;
474       }
475       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
476       return NULL;
477     }
478     cnt = 0;
479
480     while (GNUNET_YES !=
481            GNUNET_DISK_file_lock (fd, 0,
482                                   sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
483                                   GNUNET_YES))
484     {
485       short_wait ();
486       if (0 == ++cnt % 10)
487       {
488         ec = errno;
489         LOG (GNUNET_ERROR_TYPE_ERROR,
490              _("Could not acquire lock on file `%s': %s...\n"), filename,
491              STRERROR (ec));
492       }
493     }
494     LOG (GNUNET_ERROR_TYPE_INFO,
495          _("Creating a new private key.  This may take a while.\n"));
496     ret = GNUNET_CRYPTO_ecc_key_create ();
497     GNUNET_assert (ret != NULL);
498     enc = GNUNET_CRYPTO_ecc_encode_key (ret);
499     GNUNET_assert (enc != NULL);
500     GNUNET_assert (ntohs (enc->size) ==
501                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->size)));
502     GNUNET_free (enc);
503
504     GNUNET_DISK_file_sync (fd);
505     if (GNUNET_YES !=
506         GNUNET_DISK_file_unlock (fd, 0,
507                                  sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
508       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
509     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
510     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
511     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
512     return ret;
513   }
514   /* key file exists already, read it! */
515   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
516                               GNUNET_DISK_PERM_NONE);
517   if (NULL == fd)
518   {
519     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
520     return NULL;
521   }
522   cnt = 0;
523   while (1)
524   {
525     if (GNUNET_YES !=
526         GNUNET_DISK_file_lock (fd, 0,
527                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded),
528                                GNUNET_NO))
529     {
530       if (0 == ++cnt % 60)
531       {
532         ec = errno;
533         LOG (GNUNET_ERROR_TYPE_ERROR,
534              _("Could not acquire lock on file `%s': %s...\n"), filename,
535              STRERROR (ec));
536         LOG (GNUNET_ERROR_TYPE_ERROR,
537              _
538              ("This may be ok if someone is currently generating a private key.\n"));
539       }
540       short_wait ();
541       continue;
542     }
543     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
544     {
545       /* eh, what!? File we opened is now gone!? */
546       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
547       if (GNUNET_YES !=
548           GNUNET_DISK_file_unlock (fd, 0,
549                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
550         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
551       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
552
553       return NULL;
554     }
555     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
556       fs = 0;
557     if (fs < sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded))
558     {
559       /* maybe we got the read lock before the key generating
560        * process had a chance to get the write lock; give it up! */
561       if (GNUNET_YES !=
562           GNUNET_DISK_file_unlock (fd, 0,
563                                    sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
564         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
565       if (0 == ++cnt % 10)
566       {
567         LOG (GNUNET_ERROR_TYPE_ERROR,
568              _
569              ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
570              filename, (unsigned int) fs,
571              (unsigned int) sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded));
572         LOG (GNUNET_ERROR_TYPE_ERROR,
573              _
574              ("This may be ok if someone is currently generating a key.\n"));
575       }
576       short_wait ();                /* wait a bit longer! */
577       continue;
578     }
579     break;
580   }
581   enc = GNUNET_malloc (fs);
582   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
583   len = ntohs (enc->size);
584   ret = NULL;
585   if ((len > fs) ||
586       (NULL == (ret = GNUNET_CRYPTO_ecc_decode_key ((char *) enc, len, GNUNET_YES))))
587   {
588     LOG (GNUNET_ERROR_TYPE_ERROR,
589          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
590          filename);
591     if (0 != UNLINK (filename))
592     {
593       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
594     }
595   }
596   GNUNET_free (enc);
597   if (GNUNET_YES !=
598       GNUNET_DISK_file_unlock (fd, 0,
599                                sizeof (struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded)))
600     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
601   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
602   if (ret != NULL)
603   {
604     GNUNET_CRYPTO_ecc_key_get_public (ret, &pub);
605     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
606   }
607   return ret;
608 }
609
610
611 /**
612  * Create a new private key by reading our peer's key from
613  * the file specified in the configuration.
614  *
615  * @return new private key, NULL on error (for example,
616  *   permission denied)
617  */
618 struct GNUNET_CRYPTO_EccPrivateKey *
619 GNUNET_CRYPTO_ecc_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg)
620 {
621   struct GNUNET_CRYPTO_EccPrivateKey *pk;
622   char *fn;
623
624   if (GNUNET_OK != 
625       GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn))
626     return NULL;
627   pk = GNUNET_CRYPTO_ecc_key_create_from_file (fn);
628   GNUNET_free (fn);
629   return pk;
630 }
631
632
633 /**
634  * Setup a key file for a peer given the name of the
635  * configuration file (!).  This function is used so that
636  * at a later point code can be certain that reading a
637  * key is fast (for example in time-dependent testcases).
638  *
639  * @param cfg_name name of the configuration file to use
640  */
641 void
642 GNUNET_CRYPTO_ecc_setup_key (const char *cfg_name)
643 {
644   struct GNUNET_CONFIGURATION_Handle *cfg;
645   struct GNUNET_CRYPTO_EccPrivateKey *pk;
646
647   cfg = GNUNET_CONFIGURATION_create ();
648   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
649   pk = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg);
650   if (NULL != pk)
651     GNUNET_CRYPTO_ecc_key_free (pk);
652   GNUNET_CONFIGURATION_destroy (cfg);
653 }
654
655
656 /**
657  * Retrieve the identity of the host's peer.
658  *
659  * @param cfg configuration to use
660  * @param dst pointer to where to write the peer identity
661  * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
662  *         could not be retrieved
663  */
664 int
665 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
666                                  struct GNUNET_PeerIdentity *dst)
667 {
668   struct GNUNET_CRYPTO_EccPrivateKey *my_private_key;
669   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded my_public_key;
670
671   if (NULL == (my_private_key = GNUNET_CRYPTO_ecc_key_create_from_configuration (cfg)))
672   {
673     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
674                 _("Could not load peer's private key\n"));
675     return GNUNET_SYSERR;
676   }
677   GNUNET_CRYPTO_ecc_key_get_public (my_private_key, &my_public_key);
678   GNUNET_CRYPTO_ecc_key_free (my_private_key);
679   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &dst->hashPubKey);
680   return GNUNET_OK;
681 }
682
683
684 /**
685  * Convert the data specified in the given purpose argument to an
686  * S-expression suitable for signature operations.
687  *
688  * @param purpose data to convert
689  * @return converted s-expression
690  */
691 static gcry_sexp_t
692 data_to_pkcs1 (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
693 {
694   struct GNUNET_CRYPTO_ShortHashCode hc;
695   size_t bufSize;
696   gcry_sexp_t data;
697
698   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
699 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
700   bufSize = strlen (FORMATSTRING) + 1;
701   {
702     char buff[bufSize];
703
704     memcpy (buff, FORMATSTRING, bufSize);
705     memcpy (&buff
706             [bufSize -
707              strlen
708              ("01234567890123456789012345678901))")
709              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
710     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
711   }
712 #undef FORMATSTRING
713   return data;
714 }
715
716
717 /**
718  * Sign a given block.
719  *
720  * @param key private key to use for the signing
721  * @param purpose what to sign (size, purpose)
722  * @param sig where to write the signature
723  * @return GNUNET_SYSERR on error, GNUNET_OK on success
724  */
725 int
726 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
727                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
728                         struct GNUNET_CRYPTO_EccSignature *sig)
729 {
730   gcry_sexp_t result;
731   gcry_sexp_t data;
732   size_t ssize;
733   int rc;
734
735   data = data_to_pkcs1 (purpose);
736   if (0 != (rc = gcry_pk_sign (&result, data, key->sexp)))
737   {
738     LOG (GNUNET_ERROR_TYPE_WARNING,
739          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
740          __LINE__, gcry_strerror (rc));
741     gcry_sexp_release (data);
742     return GNUNET_SYSERR;
743   }
744   gcry_sexp_release (data);
745   ssize = gcry_sexp_sprint (result, 
746                             GCRYSEXP_FMT_DEFAULT,
747                             sig->sexpr,
748                             GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH);
749   if (0 == ssize)
750   {
751     GNUNET_break (0);
752     return GNUNET_SYSERR;
753   }
754   sig->size = htons ((uint16_t) (ssize + sizeof (uint16_t)));
755   /* padd with zeros */
756   memset (&sig->sexpr[ssize], 0, GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - ssize);
757   gcry_sexp_release (result);
758   return GNUNET_OK;
759 }
760
761
762 /**
763  * Verify signature.
764  *
765  * @param purpose what is the purpose that the signature should have?
766  * @param validate block to validate (size, purpose, data)
767  * @param sig signature that is being validated
768  * @param publicKey public key of the signer
769  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
770  */
771 int
772 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
773                           const struct GNUNET_CRYPTO_EccSignaturePurpose
774                           *validate,
775                           const struct GNUNET_CRYPTO_EccSignature *sig,
776                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
777                           *publicKey)
778 {
779   gcry_sexp_t data;
780   gcry_sexp_t sigdata;
781   size_t size;
782   gcry_sexp_t psexp;
783   size_t erroff;
784   int rc;
785
786   if (purpose != ntohl (validate->purpose))
787     return GNUNET_SYSERR;       /* purpose mismatch */
788   size = ntohs (sig->size);
789   if ( (size < sizeof (uint16_t)) ||
790        (size > GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH - sizeof (uint16_t)) )
791     return GNUNET_SYSERR; /* size out of range */
792   data = data_to_pkcs1 (validate);
793   GNUNET_assert (0 ==
794                  gcry_sexp_sscan (&sigdata, &erroff, 
795                                   sig->sexpr, size - sizeof (uint16_t)));
796   if (! (psexp = decode_public_key (publicKey)))
797   {
798     gcry_sexp_release (data);
799     gcry_sexp_release (sigdata);
800     return GNUNET_SYSERR;
801   }
802   rc = gcry_pk_verify (sigdata, data, psexp);
803   gcry_sexp_release (psexp);
804   gcry_sexp_release (data);
805   gcry_sexp_release (sigdata);
806   if (0 != rc)
807   {
808     LOG (GNUNET_ERROR_TYPE_WARNING,
809          _("ECC signature verification failed at %s:%d: %s\n"), __FILE__,
810          __LINE__, gcry_strerror (rc));
811     return GNUNET_SYSERR;
812   }
813   return GNUNET_OK;
814 }
815
816
817 /**
818  * Derive key material from a public and a private ECC key.
819  *
820  * @param key private key to use for the ECDH (x)
821  * @param pub public key to use for the ECDY (yG)
822  * @param key_material where to write the key material (xyG)
823  * @return GNUNET_SYSERR on error, GNUNET_OK on success
824  */
825 int
826 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
827                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
828                         struct GNUNET_HashCode *key_material)
829
830   size_t slen;
831   size_t erroff;
832   int rc;
833   unsigned char sdata_buf[2048]; /* big enough to print dh-shared-secret as S-expression */
834   gcry_mpi_point_t result;
835   gcry_mpi_point_t q;
836   gcry_mpi_t d;
837   gcry_ctx_t ctx;
838   gcry_sexp_t psexp;
839   gcry_mpi_t result_x;
840   gcry_mpi_t result_y;
841
842   /* first, extract the q = dP value from the public key */
843   if (! (psexp = decode_public_key (pub)))
844     return GNUNET_SYSERR;
845   if (0 != (rc = gcry_mpi_ec_new (&ctx, psexp, NULL)))
846   {
847     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
848     return GNUNET_SYSERR;
849   }
850   gcry_sexp_release (psexp);
851   q = gcry_mpi_ec_get_point ("q", ctx, 0);
852   gcry_ctx_release (ctx);
853
854   /* second, extract the d value from our private key */
855   rc = key_from_sexp (&d, key->sexp, "private-key", "d");
856   if (rc)
857     rc = key_from_sexp (&d, key->sexp, "ecc", "d");
858   if (0 != rc)
859   {
860     GNUNET_break (0);
861     gcry_mpi_point_release (q);
862     return GNUNET_SYSERR;
863   }
864
865   /* create a new context for definitively the correct curve;
866      theoretically the 'public_key' might not use the right curve */
867   if (0 != (rc = gcry_mpi_ec_new (&ctx, NULL, "NIST P-256")))
868   {
869     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_ec_new", rc);  /* erroff gives more info */
870     gcry_mpi_release (d);
871     gcry_mpi_point_release (q);
872     return GNUNET_SYSERR;
873   }
874
875   /* then call the 'multiply' function, to compute the product */
876   GNUNET_assert (NULL != ctx);
877   result = gcry_mpi_point_new (0);
878   gcry_mpi_ec_mul (result, d, q, ctx);
879   gcry_mpi_point_release (q);
880   gcry_mpi_release (d);
881
882   /* finally, convert point to string for hashing */
883   result_x = gcry_mpi_new (256);
884   result_y = gcry_mpi_new (256);
885   if (gcry_mpi_ec_get_affine (result_x, result_y, result, ctx))
886   {
887     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
888     gcry_mpi_point_release (result);
889     gcry_ctx_release (ctx);
890     return GNUNET_SYSERR;
891   }
892   gcry_mpi_point_release (result);
893   gcry_ctx_release (ctx);
894   if (0 != (rc = gcry_sexp_build (&psexp, &erroff, 
895                                   "(dh-shared-secret (x %m)(y %m))",
896                                   result_x,
897                                   result_y)))
898   {
899     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
900     gcry_mpi_release (result_x);
901     gcry_mpi_release (result_y);
902     return GNUNET_SYSERR;
903   }
904   gcry_mpi_release (result_x);
905   gcry_mpi_release (result_y);
906   slen = gcry_sexp_sprint (psexp, GCRYSEXP_FMT_DEFAULT, sdata_buf, sizeof (sdata_buf));
907   GNUNET_assert (0 != slen);
908   gcry_sexp_release (psexp);
909   /* finally, get a string of the resulting S-expression and hash it to generate the key material */
910   GNUNET_CRYPTO_hash (sdata_buf, slen, key_material);
911   return GNUNET_OK;
912 }
913
914
915 /* end of crypto_ecc.c */