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