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