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