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