-renaming
[oweals/gnunet.git] / src / util / crypto_rsa.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 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_rsa.c
23  * @brief public key cryptography (RSA) with libgcrypt
24  * @author Christian Grothoff
25  *
26  * Note that the code locks often needlessly on the gcrypt-locking api.
27  * One would think that simple MPI operations should not require locking
28  * (since only global operations on the random pool must be locked,
29  * strictly speaking).  But libgcrypt does sometimes require locking in
30  * unexpected places, so the safe solution is to always lock even if it
31  * is not required.  The performance impact is minimal anyway.
32  */
33
34 #include "platform.h"
35 #include <gcrypt.h>
36 #include "gnunet_common.h"
37 #include "gnunet_crypto_lib.h"
38 #include "gnunet_disk_lib.h"
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45
46 /**
47  * The private information of an RSA key pair.
48  * NOTE: this must match the definition in crypto_ksk.c
49  */
50 struct GNUNET_CRYPTO_RsaPrivateKey
51 {
52   gcry_sexp_t sexp;
53 };
54
55
56 #define HOSTKEY_LEN 2048
57
58 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
59
60
61 /**
62  * Log an error message at log-level 'level' that indicates
63  * a failure of the command 'cmd' with the message given
64  * by gcry_strerror(rc).
65  */
66 #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);
67
68 /**
69  * If target != size, move target bytes to the
70  * end of the size-sized buffer and zero out the
71  * first target-size bytes.
72  */
73 static void
74 adjust (unsigned char *buf, size_t size, size_t target)
75 {
76   if (size < target)
77   {
78     memmove (&buf[target - size], buf, size);
79     memset (buf, 0, target - size);
80   }
81 }
82
83 /**
84  * Create a new private key. Caller must free return value.
85  *
86  * @return fresh private key
87  */
88 struct GNUNET_CRYPTO_RsaPrivateKey *
89 GNUNET_CRYPTO_rsa_key_create ()
90 {
91   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
92   gcry_sexp_t s_key;
93   gcry_sexp_t s_keyparam;
94
95   GNUNET_assert (0 ==
96                  gcry_sexp_build (&s_keyparam, NULL,
97                                   "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
98                                   HOSTKEY_LEN));
99   GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
100   gcry_sexp_release (s_keyparam);
101 #if EXTRA_CHECKS
102   GNUNET_assert (0 == gcry_pk_testkey (s_key));
103 #endif
104   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
105   ret->sexp = s_key;
106   return ret;
107 }
108
109 /**
110  * Free memory occupied by hostkey
111  * @param hostkey pointer to the memory to free
112  */
113 void
114 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
115 {
116   gcry_sexp_release (hostkey->sexp);
117   GNUNET_free (hostkey);
118 }
119
120 static int
121 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
122                const char *elems)
123 {
124   gcry_sexp_t list, l2;
125   const char *s;
126   int i, idx;
127
128   list = gcry_sexp_find_token (sexp, topname, 0);
129   if (!list)
130   {
131     return 1;
132   }
133   l2 = gcry_sexp_cadr (list);
134   gcry_sexp_release (list);
135   list = l2;
136   if (!list)
137   {
138     return 2;
139   }
140
141   idx = 0;
142   for (s = elems; *s; s++, idx++)
143   {
144     l2 = gcry_sexp_find_token (list, s, 1);
145     if (!l2)
146     {
147       for (i = 0; i < idx; i++)
148       {
149         gcry_free (array[i]);
150         array[i] = NULL;
151       }
152       gcry_sexp_release (list);
153       return 3;                 /* required parameter not found */
154     }
155     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
156     gcry_sexp_release (l2);
157     if (!array[idx])
158     {
159       for (i = 0; i < idx; i++)
160       {
161         gcry_free (array[i]);
162         array[i] = NULL;
163       }
164       gcry_sexp_release (list);
165       return 4;                 /* required parameter is invalid */
166     }
167   }
168   gcry_sexp_release (list);
169   return 0;
170 }
171
172 /**
173  * Extract the public key of the host.
174  * @param priv the private key
175  * @param pub where to write the public key
176  */
177 void
178 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
179                                   *priv,
180                                   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
181                                   *pub)
182 {
183   gcry_mpi_t skey[2];
184   size_t size;
185   int rc;
186
187   rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
188   if (rc)
189     rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
190   if (rc)
191     rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
192   GNUNET_assert (0 == rc);
193   pub->len =
194       htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
195              sizeof (pub->padding));
196   pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
197   pub->padding = 0;
198   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
199   GNUNET_assert (0 ==
200                  gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
201                                  skey[0]));
202   adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
203   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
204   GNUNET_assert (0 ==
205                  gcry_mpi_print (GCRYMPI_FMT_USG,
206                                  &pub->key
207                                  [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
208                                  &size, skey[1]));
209   adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
210           GNUNET_CRYPTO_RSA_KEY_LENGTH -
211           GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
212   gcry_mpi_release (skey[0]);
213   gcry_mpi_release (skey[1]);
214 }
215
216
217 /**
218  * Convert a public key to a string.
219  *
220  * @param pub key to convert
221  * @return string representing  'pub'
222  */
223 char *
224 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
225 {
226   char *pubkeybuf;
227   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
228   char *end;
229
230   if (keylen % 5 > 0)
231     keylen += 5 - keylen % 5;
232   keylen /= 5;
233   pubkeybuf = GNUNET_malloc (keylen + 1);
234   end = GNUNET_STRINGS_data_to_string ((unsigned char *) &pub, 
235                                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), 
236                                       pubkeybuf, 
237                                       keylen);
238   if (NULL == end)
239     {
240       GNUNET_free (pubkeybuf);
241       return NULL;
242     }
243   *end = '\0';
244   return pubkeybuf;
245 }
246
247
248 /**
249  * Convert a string representing a public key to a public key.
250  *
251  * @param enc encoded public key
252  * @param enclen number of bytes in enc (without 0-terminator)
253  * @param pub where to store the public key
254  * @return GNUNET_OK on success
255  */
256 int
257 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
258                                           size_t enclen,
259                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
260 {
261   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
262
263   if (keylen % 5 > 0)
264     keylen += 5 - keylen % 5;
265   keylen /= 5;
266   if (enclen != keylen)
267     return GNUNET_SYSERR;
268
269   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
270                                                  (unsigned char*) pub,
271                                                  sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
272     return GNUNET_SYSERR;
273   if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
274        (ntohs (pub->padding) != 0) ||
275        (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
276     return GNUNET_SYSERR;
277   return GNUNET_OK;
278 }
279
280
281 /**
282  * Internal: publicKey => RSA-Key.
283  *
284  * Note that the return type is not actually a private
285  * key but rather an sexpression for the public key!
286  */
287 static struct GNUNET_CRYPTO_RsaPrivateKey *
288 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
289                    *publicKey)
290 {
291   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
292   gcry_sexp_t result;
293   gcry_mpi_t n;
294   gcry_mpi_t e;
295   size_t size;
296   size_t erroff;
297   int rc;
298
299   if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
300       (ntohs (publicKey->len) !=
301        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
302        sizeof (publicKey->padding)))
303   {
304     GNUNET_break (0);
305     return NULL;
306   }
307   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
308   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
309   if (rc)
310   {
311     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
312     return NULL;
313   }
314   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
315   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
316                       &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
317                       size, &size);
318   if (rc)
319   {
320     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
321     gcry_mpi_release (n);
322     return NULL;
323   }
324   rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
325                         e);
326   gcry_mpi_release (n);
327   gcry_mpi_release (e);
328   if (rc)
329   {
330     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
331     return NULL;
332   }
333   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
334   ret->sexp = result;
335   return ret;
336 }
337
338
339 /**
340  * Encode the private key in a format suitable for
341  * storing it into a file.
342  * @returns encoding of the private key.
343  *    The first 4 bytes give the size of the array, as usual.
344  */
345 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
346 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
347 {
348   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
349   gcry_mpi_t pkv[6];
350   void *pbu[6];
351   size_t sizes[6];
352   int rc;
353   int i;
354   int size;
355
356 #if EXTRA_CHECKS
357   if (gcry_pk_testkey (hostkey->sexp))
358   {
359     GNUNET_break (0);
360     return NULL;
361   }
362 #endif
363
364   memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
365   rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
366   if (rc)
367     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
368   if (rc)
369     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
370   if (rc)
371     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
372   if (rc)
373     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
374   if (rc)
375     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
376   GNUNET_assert (0 == rc);
377   size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
378   for (i = 0; i < 6; i++)
379   {
380     if (pkv[i] != NULL)
381     {
382       GNUNET_assert (0 ==
383                      gcry_mpi_aprint (GCRYMPI_FMT_USG,
384                                       (unsigned char **) &pbu[i], &sizes[i],
385                                       pkv[i]));
386       size += sizes[i];
387     }
388     else
389     {
390       pbu[i] = NULL;
391       sizes[i] = 0;
392     }
393   }
394   GNUNET_assert (size < 65536);
395   retval = GNUNET_malloc (size);
396   retval->len = htons (size);
397   i = 0;
398   retval->sizen = htons (sizes[0]);
399   memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
400   i += sizes[0];
401   retval->sizee = htons (sizes[1]);
402   memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
403   i += sizes[1];
404   retval->sized = htons (sizes[2]);
405   memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
406   i += sizes[2];
407   /* swap p and q! */
408   retval->sizep = htons (sizes[4]);
409   memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
410   i += sizes[4];
411   retval->sizeq = htons (sizes[3]);
412   memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
413   i += sizes[3];
414   retval->sizedmp1 = htons (0);
415   retval->sizedmq1 = htons (0);
416   memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
417   for (i = 0; i < 6; i++)
418   {
419     if (pkv[i] != NULL)
420       gcry_mpi_release (pkv[i]);
421     if (pbu[i] != NULL)
422       free (pbu[i]);
423   }
424   return retval;
425 }
426
427
428 /**
429  * Decode the private key from the file-format back
430  * to the "normal", internal format.
431  *
432  * @param buf the buffer where the private key data is stored
433  * @param len the length of the data in 'buffer'
434  */
435 struct GNUNET_CRYPTO_RsaPrivateKey *
436 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
437 {
438   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
439   const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
440       (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
441   gcry_sexp_t res;
442   gcry_mpi_t n, e, d, p, q, u;
443   int rc;
444   size_t size;
445   int pos;
446   uint16_t enc_len;
447
448   enc_len = ntohs (encoding->len);
449   if (len != enc_len)
450     return NULL;
451
452   pos = 0;
453   size = ntohs (encoding->sizen);
454   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
455                       &((const unsigned char *) (&encoding[1]))[pos], size,
456                       &size);
457   pos += ntohs (encoding->sizen);
458   if (rc)
459   {
460     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
461     return NULL;
462   }
463   size = ntohs (encoding->sizee);
464   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
465                       &((const unsigned char *) (&encoding[1]))[pos], size,
466                       &size);
467   pos += ntohs (encoding->sizee);
468   if (rc)
469   {
470     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
471     gcry_mpi_release (n);
472     return NULL;
473   }
474   size = ntohs (encoding->sized);
475   rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
476                       &((const unsigned char *) (&encoding[1]))[pos], size,
477                       &size);
478   pos += ntohs (encoding->sized);
479   if (rc)
480   {
481     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
482     gcry_mpi_release (n);
483     gcry_mpi_release (e);
484     return NULL;
485   }
486   /* swap p and q! */
487   size = ntohs (encoding->sizep);
488   if (size > 0)
489   {
490     rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
491                         &((const unsigned char *) (&encoding[1]))[pos], size,
492                         &size);
493     pos += ntohs (encoding->sizep);
494     if (rc)
495     {
496       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
497       gcry_mpi_release (n);
498       gcry_mpi_release (e);
499       gcry_mpi_release (d);
500       return NULL;
501     }
502   }
503   else
504     q = NULL;
505   size = ntohs (encoding->sizeq);
506   if (size > 0)
507   {
508     rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
509                         &((const unsigned char *) (&encoding[1]))[pos], size,
510                         &size);
511     pos += ntohs (encoding->sizeq);
512     if (rc)
513     {
514       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
515       gcry_mpi_release (n);
516       gcry_mpi_release (e);
517       gcry_mpi_release (d);
518       if (q != NULL)
519         gcry_mpi_release (q);
520       return NULL;
521     }
522   }
523   else
524     p = NULL;
525   pos += ntohs (encoding->sizedmp1);
526   pos += ntohs (encoding->sizedmq1);
527   size =
528       ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
529   if (size > 0)
530   {
531     rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
532                         &((const unsigned char *) (&encoding[1]))[pos], size,
533                         &size);
534     if (rc)
535     {
536       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
537       gcry_mpi_release (n);
538       gcry_mpi_release (e);
539       gcry_mpi_release (d);
540       if (p != NULL)
541         gcry_mpi_release (p);
542       if (q != NULL)
543         gcry_mpi_release (q);
544       return NULL;
545     }
546   }
547   else
548     u = NULL;
549
550   if ((p != NULL) && (q != NULL) && (u != NULL))
551   {
552     rc = gcry_sexp_build (&res, &size,  /* erroff */
553                           "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
554                           n, e, d, p, q, u);
555   }
556   else
557   {
558     if ((p != NULL) && (q != NULL))
559     {
560       rc = gcry_sexp_build (&res, &size,        /* erroff */
561                             "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
562                             n, e, d, p, q);
563     }
564     else
565     {
566       rc = gcry_sexp_build (&res, &size,        /* erroff */
567                             "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
568     }
569   }
570   gcry_mpi_release (n);
571   gcry_mpi_release (e);
572   gcry_mpi_release (d);
573   if (p != NULL)
574     gcry_mpi_release (p);
575   if (q != NULL)
576     gcry_mpi_release (q);
577   if (u != NULL)
578     gcry_mpi_release (u);
579
580   if (rc)
581     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
582 #if EXTRA_CHECKS
583   if (gcry_pk_testkey (res))
584   {
585     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
586     return NULL;
587   }
588 #endif
589   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
590   ret->sexp = res;
591   return ret;
592 }
593
594
595 /**
596  * Create a new private key by reading it from a file.  If the
597  * files does not exist, create a new key and write it to the
598  * file.  Caller must free return value.  Note that this function
599  * can not guarantee that another process might not be trying
600  * the same operation on the same file at the same time.
601  * If the contents of the file
602  * are invalid the old file is deleted and a fresh key is
603  * created.
604  *
605  * @return new private key, NULL on error (for example,
606  *   permission denied)
607  */
608 struct GNUNET_CRYPTO_RsaPrivateKey *
609 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
610 {
611   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
612   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
613   uint16_t len;
614   struct GNUNET_DISK_FileHandle *fd;
615   unsigned int cnt;
616   int ec;
617   uint64_t fs;
618   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
619   struct GNUNET_PeerIdentity pid;
620
621   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
622     return NULL;
623   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
624   {
625     fd = GNUNET_DISK_file_open (filename,
626                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
627                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
628                                 GNUNET_DISK_PERM_USER_READ |
629                                 GNUNET_DISK_PERM_USER_WRITE);
630     if (NULL == fd)
631     {
632       if (errno == EEXIST)
633       {
634         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
635         {
636           /* must exist but not be accessible, fail for good! */
637           if (0 != ACCESS (filename, R_OK))
638             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
639           else
640             GNUNET_break (0);   /* what is going on!? */
641           return NULL;
642         }
643         continue;
644       }
645       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
646       return NULL;
647     }
648     cnt = 0;
649
650     while (GNUNET_YES !=
651            GNUNET_DISK_file_lock (fd, 0,
652                                   sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
653                                   GNUNET_YES))
654     {
655       sleep (1);
656       if (0 == ++cnt % 10)
657       {
658         ec = errno;
659         LOG (GNUNET_ERROR_TYPE_ERROR,
660              _("Could not aquire lock on file `%s': %s...\n"), filename,
661              STRERROR (ec));
662       }
663     }
664     LOG (GNUNET_ERROR_TYPE_INFO,
665          _("Creating a new private key.  This may take a while.\n"));
666     ret = GNUNET_CRYPTO_rsa_key_create ();
667     GNUNET_assert (ret != NULL);
668     enc = GNUNET_CRYPTO_rsa_encode_key (ret);
669     GNUNET_assert (enc != NULL);
670     GNUNET_assert (ntohs (enc->len) ==
671                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
672     GNUNET_free (enc);
673
674     GNUNET_DISK_file_sync (fd);
675     if (GNUNET_YES !=
676         GNUNET_DISK_file_unlock (fd, 0,
677                                  sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
678       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
679     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
680     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
681     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
682     LOG (GNUNET_ERROR_TYPE_INFO,
683          _("I am host `%s'.  Stored new private key in `%s'.\n"),
684          GNUNET_i2s (&pid), filename);
685     return ret;
686   }
687   /* hostkey file exists already, read it! */
688   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
689                               GNUNET_DISK_PERM_NONE);
690   if (NULL == fd)
691   {
692     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
693     return NULL;
694   }
695   cnt = 0;
696   while (1)
697   {
698     if (GNUNET_YES !=
699         GNUNET_DISK_file_lock (fd, 0,
700                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
701                                GNUNET_NO))
702     {
703       if (0 == ++cnt % 60)
704       {
705         ec = errno;
706         LOG (GNUNET_ERROR_TYPE_ERROR,
707              _("Could not aquire lock on file `%s': %s...\n"), filename,
708              STRERROR (ec));
709         LOG (GNUNET_ERROR_TYPE_ERROR,
710              _
711              ("This may be ok if someone is currently generating a hostkey.\n"));
712       }
713       sleep (1);
714       continue;
715     }
716     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
717     {
718       /* eh, what!? File we opened is now gone!? */
719       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
720       if (GNUNET_YES !=
721           GNUNET_DISK_file_unlock (fd, 0,
722                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
723         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
724       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
725
726       return NULL;
727     }
728     if (GNUNET_YES != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES))
729       fs = 0;
730     if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
731     {
732       /* maybe we got the read lock before the hostkey generating
733        * process had a chance to get the write lock; give it up! */
734       if (GNUNET_YES !=
735           GNUNET_DISK_file_unlock (fd, 0,
736                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
737         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
738       if (0 == ++cnt % 10)
739       {
740         LOG (GNUNET_ERROR_TYPE_ERROR,
741              _
742              ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
743              filename, (unsigned int) fs,
744              (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
745         LOG (GNUNET_ERROR_TYPE_ERROR,
746              _
747              ("This may be ok if someone is currently generating a hostkey.\n"));
748       }
749       sleep (2);                /* wait a bit longer! */
750       continue;
751     }
752     break;
753   }
754   enc = GNUNET_malloc (fs);
755   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
756   len = ntohs (enc->len);
757   ret = NULL;
758   if ((len != fs) ||
759       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
760   {
761     LOG (GNUNET_ERROR_TYPE_ERROR,
762          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
763          filename);
764     if (0 != UNLINK (filename))
765     {
766       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
767     }
768   }
769   GNUNET_free (enc);
770   if (GNUNET_YES !=
771       GNUNET_DISK_file_unlock (fd, 0,
772                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
773     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
774   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
775   if (ret != NULL)
776   {
777     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
778     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
779     LOG (GNUNET_ERROR_TYPE_INFO,
780          _("I am host `%s'.  Read private key from `%s'.\n"), GNUNET_i2s (&pid),
781          filename);
782   }
783   return ret;
784 }
785
786
787 /**
788  * Setup a hostkey file for a peer given the name of the
789  * configuration file (!).  This function is used so that
790  * at a later point code can be certain that reading a
791  * hostkey is fast (for example in time-dependent testcases).
792  *
793  * @param cfg_name name of the configuration file to use
794  */
795 void
796 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
797 {
798   struct GNUNET_CONFIGURATION_Handle *cfg;
799   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
800   char *fn;
801
802   cfg = GNUNET_CONFIGURATION_create ();
803   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
804   if (GNUNET_OK == 
805       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
806   {
807     pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
808     if (NULL != pk)
809       GNUNET_CRYPTO_rsa_key_free (pk);
810   }
811   GNUNET_CONFIGURATION_destroy (cfg);
812 }
813
814
815 /**
816  * Encrypt a block with the public key of another host that uses the
817  * same cipher.
818  *
819  * @param block the block to encrypt
820  * @param size the size of block
821  * @param publicKey the encoded public key used to encrypt
822  * @param target where to store the encrypted block
823  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
824  */
825 int
826 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
827                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
828                            *publicKey,
829                            struct GNUNET_CRYPTO_RsaEncryptedData *target)
830 {
831   gcry_sexp_t result;
832   gcry_sexp_t data;
833   struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
834   gcry_mpi_t val;
835   gcry_mpi_t rval;
836   size_t isize;
837   size_t erroff;
838
839   GNUNET_assert (size <= sizeof (GNUNET_HashCode));
840   pubkey = public2PrivateKey (publicKey);
841   if (pubkey == NULL)
842     return GNUNET_SYSERR;
843   isize = size;
844   GNUNET_assert (0 ==
845                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
846   GNUNET_assert (0 ==
847                  gcry_sexp_build (&data, &erroff,
848                                   "(data (flags pkcs1)(value %m))", val));
849   gcry_mpi_release (val);
850   GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
851   gcry_sexp_release (data);
852   GNUNET_CRYPTO_rsa_key_free (pubkey);
853
854   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
855   gcry_sexp_release (result);
856   isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
857   GNUNET_assert (0 ==
858                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
859                                  isize, &isize, rval));
860   gcry_mpi_release (rval);
861   adjust (&target->encoding[0], isize,
862           sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
863   return GNUNET_OK;
864 }
865
866
867 /**
868  * Decrypt a given block with the hostkey.
869  *
870  * @param key the key with which to decrypt this block
871  * @param block the data to decrypt, encoded as returned by encrypt
872  * @param result pointer to a location where the result can be stored
873  * @param max the maximum number of bits to store for the result, if
874  *        the decrypted block is bigger, an error is returned
875  * @return the size of the decrypted block, -1 on error
876  */
877 ssize_t
878 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
879                            const struct GNUNET_CRYPTO_RsaEncryptedData * block,
880                            void *result, size_t max)
881 {
882   gcry_sexp_t resultsexp;
883   gcry_sexp_t data;
884   size_t erroff;
885   size_t size;
886   gcry_mpi_t val;
887   unsigned char *endp;
888   unsigned char *tmp;
889
890 #if EXTRA_CHECKS
891   GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
892 #endif
893   size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
894   GNUNET_assert (0 ==
895                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
896                                 size, &size));
897   GNUNET_assert (0 ==
898                  gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
899                                   val));
900   gcry_mpi_release (val);
901   GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
902   gcry_sexp_release (data);
903   /* resultsexp has format "(value %m)" */
904   GNUNET_assert (NULL !=
905                  (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
906   gcry_sexp_release (resultsexp);
907   tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
908   size = max + HOSTKEY_LEN / 8;
909   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
910   gcry_mpi_release (val);
911   endp = tmp;
912   endp += (size - max);
913   size = max;
914   memcpy (result, endp, size);
915   GNUNET_free (tmp);
916   return size;
917 }
918
919
920 /**
921  * Sign a given block.
922  *
923  * @param key private key to use for the signing
924  * @param purpose what to sign (size, purpose)
925  * @param sig where to write the signature
926  * @return GNUNET_SYSERR on error, GNUNET_OK on success
927  */
928 int
929 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
930                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
931                         struct GNUNET_CRYPTO_RsaSignature *sig)
932 {
933   gcry_sexp_t result;
934   gcry_sexp_t data;
935   size_t ssize;
936   gcry_mpi_t rval;
937   GNUNET_HashCode hc;
938   char *buff;
939   int bufSize;
940
941   GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
942 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
943   bufSize = strlen (FORMATSTRING) + 1;
944   buff = GNUNET_malloc (bufSize);
945   memcpy (buff, FORMATSTRING, bufSize);
946   memcpy (&buff
947           [bufSize -
948            strlen
949            ("0123456789012345678901234567890123456789012345678901234567890123))")
950            - 1], &hc, sizeof (GNUNET_HashCode));
951   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
952   GNUNET_free (buff);
953   GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
954   gcry_sexp_release (data);
955   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
956   gcry_sexp_release (result);
957   ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
958   GNUNET_assert (0 ==
959                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
960                                  &ssize, rval));
961   gcry_mpi_release (rval);
962   adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
963   return GNUNET_OK;
964 }
965
966
967 /**
968  * Verify signature.
969  *
970  * @param purpose what is the purpose that the signature should have?
971  * @param validate block to validate (size, purpose, data)
972  * @param sig signature that is being validated
973  * @param publicKey public key of the signer
974  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
975  */
976 int
977 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
978                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
979                           *validate,
980                           const struct GNUNET_CRYPTO_RsaSignature *sig,
981                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
982                           *publicKey)
983 {
984   gcry_sexp_t data;
985   gcry_sexp_t sigdata;
986   size_t size;
987   gcry_mpi_t val;
988   struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
989   GNUNET_HashCode hc;
990   char *buff;
991   int bufSize;
992   size_t erroff;
993   int rc;
994
995   if (purpose != ntohl (validate->purpose))
996     return GNUNET_SYSERR;       /* purpose mismatch */
997   GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
998   size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
999   GNUNET_assert (0 ==
1000                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1001                                 (const unsigned char *) sig, size, &size));
1002   GNUNET_assert (0 ==
1003                  gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1004                                   val));
1005   gcry_mpi_release (val);
1006   bufSize = strlen (FORMATSTRING) + 1;
1007   buff = GNUNET_malloc (bufSize);
1008   memcpy (buff, FORMATSTRING, bufSize);
1009   memcpy (&buff
1010           [strlen (FORMATSTRING) -
1011            strlen
1012            ("0123456789012345678901234567890123456789012345678901234567890123))")],
1013           &hc, sizeof (GNUNET_HashCode));
1014   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1015   GNUNET_free (buff);
1016   hostkey = public2PrivateKey (publicKey);
1017   if (hostkey == NULL)
1018   {
1019     gcry_sexp_release (data);
1020     gcry_sexp_release (sigdata);
1021     return GNUNET_SYSERR;
1022   }
1023   rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1024   GNUNET_CRYPTO_rsa_key_free (hostkey);
1025   gcry_sexp_release (data);
1026   gcry_sexp_release (sigdata);
1027   if (rc)
1028   {
1029     LOG (GNUNET_ERROR_TYPE_WARNING,
1030          _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1031          __LINE__, gcry_strerror (rc));
1032     return GNUNET_SYSERR;
1033   }
1034   return GNUNET_OK;
1035 }
1036
1037
1038 /* end of crypto_rsa.c */