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