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