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