fixing #1551/#2503
[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_util_lib.h"
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40
41 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
42
43 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
44
45
46 /**
47  * The private information of an RSA key pair.
48  * NOTE: this must match the definition in crypto_ksk.c and gnunet-rsa.c!
49  */
50 struct GNUNET_CRYPTO_RsaPrivateKey
51 {
52   gcry_sexp_t sexp;
53 };
54
55
56 #define HOSTKEY_LEN 2048
57
58 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
59
60
61 /**
62  * Log an error message at log-level 'level' that indicates
63  * a failure of the command 'cmd' with the message given
64  * by gcry_strerror(rc).
65  */
66 #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);
67
68 /**
69  * If target != size, move target bytes to the
70  * end of the size-sized buffer and zero out the
71  * first target-size bytes.
72  */
73 static void
74 adjust (unsigned char *buf, size_t size, size_t target)
75 {
76   if (size < target)
77   {
78     memmove (&buf[target - size], buf, size);
79     memset (buf, 0, target - size);
80   }
81 }
82
83
84 /**
85  * Free memory occupied by hostkey
86  * @param hostkey pointer to the memory to free
87  */
88 void
89 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
90 {
91   gcry_sexp_release (hostkey->sexp);
92   GNUNET_free (hostkey);
93 }
94
95
96 /**
97  * FIXME: document!
98  */
99 static int
100 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
101                const char *elems)
102 {
103   gcry_sexp_t list, l2;
104   const char *s;
105   int i, idx;
106
107   list = gcry_sexp_find_token (sexp, topname, 0);
108   if (!list)
109   {
110     return 1;
111   }
112   l2 = gcry_sexp_cadr (list);
113   gcry_sexp_release (list);
114   list = l2;
115   if (!list)
116   {
117     return 2;
118   }
119
120   idx = 0;
121   for (s = elems; *s; s++, idx++)
122   {
123     l2 = gcry_sexp_find_token (list, s, 1);
124     if (!l2)
125     {
126       for (i = 0; i < idx; i++)
127       {
128         gcry_free (array[i]);
129         array[i] = NULL;
130       }
131       gcry_sexp_release (list);
132       return 3;                 /* required parameter not found */
133     }
134     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
135     gcry_sexp_release (l2);
136     if (!array[idx])
137     {
138       for (i = 0; i < idx; i++)
139       {
140         gcry_free (array[i]);
141         array[i] = NULL;
142       }
143       gcry_sexp_release (list);
144       return 4;                 /* required parameter is invalid */
145     }
146   }
147   gcry_sexp_release (list);
148   return 0;
149 }
150
151 /**
152  * Extract the public key of the host.
153  * @param priv the private key
154  * @param pub where to write the public key
155  */
156 void
157 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
158                                   *priv,
159                                   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
160                                   *pub)
161 {
162   gcry_mpi_t skey[2];
163   size_t size;
164   int rc;
165
166   rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
167   if (rc)
168     rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
169   if (rc)
170     rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
171   GNUNET_assert (0 == rc);
172   pub->len =
173       htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
174              sizeof (pub->padding));
175   pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
176   pub->padding = 0;
177   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
178   GNUNET_assert (0 ==
179                  gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
180                                  skey[0]));
181   adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
182   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
183   GNUNET_assert (0 ==
184                  gcry_mpi_print (GCRYMPI_FMT_USG,
185                                  &pub->key
186                                  [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
187                                  &size, skey[1]));
188   adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
189           GNUNET_CRYPTO_RSA_KEY_LENGTH -
190           GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
191   gcry_mpi_release (skey[0]);
192   gcry_mpi_release (skey[1]);
193 }
194
195
196 /**
197  * Convert a public key to a string.
198  *
199  * @param pub key to convert
200  * @return string representing  'pub'
201  */
202 char *
203 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
204 {
205   char *pubkeybuf;
206   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
207   char *end;
208
209   if (keylen % 5 > 0)
210     keylen += 5 - keylen % 5;
211   keylen /= 5;
212   pubkeybuf = GNUNET_malloc (keylen + 1);
213   end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 
214                                        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), 
215                                        pubkeybuf, 
216                                        keylen);
217   if (NULL == end)
218   {
219     GNUNET_free (pubkeybuf);
220     return NULL;
221   }
222   *end = '\0';
223   return pubkeybuf;
224 }
225
226
227 /**
228  * Convert a string representing a public key to a public key.
229  *
230  * @param enc encoded public key
231  * @param enclen number of bytes in enc (without 0-terminator)
232  * @param pub where to store the public key
233  * @return GNUNET_OK on success
234  */
235 int
236 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
237                                           size_t enclen,
238                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
239 {
240   size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
241
242   if (keylen % 5 > 0)
243     keylen += 5 - keylen % 5;
244   keylen /= 5;
245   if (enclen != keylen)
246     return GNUNET_SYSERR;
247
248   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
249                                                  (unsigned char*) pub,
250                                                  sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
251     return GNUNET_SYSERR;
252   if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
253        (ntohs (pub->padding) != 0) ||
254        (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
255     return GNUNET_SYSERR;
256   return GNUNET_OK;
257 }
258
259
260 /**
261  * Internal: publicKey => RSA-Key.
262  *
263  * Note that the return type is not actually a private
264  * key but rather an sexpression for the public key!
265  */
266 static struct GNUNET_CRYPTO_RsaPrivateKey *
267 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
268                    *publicKey)
269 {
270   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
271   gcry_sexp_t result;
272   gcry_mpi_t n;
273   gcry_mpi_t e;
274   size_t size;
275   size_t erroff;
276   int rc;
277
278   if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
279       (ntohs (publicKey->len) !=
280        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
281        sizeof (publicKey->padding)))
282   {
283     GNUNET_break (0);
284     return NULL;
285   }
286   size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
287   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
288   if (rc)
289   {
290     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
291     return NULL;
292   }
293   size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
294   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
295                       &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
296                       size, &size);
297   if (rc)
298   {
299     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
300     gcry_mpi_release (n);
301     return NULL;
302   }
303   rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
304                         e);
305   gcry_mpi_release (n);
306   gcry_mpi_release (e);
307   if (rc)
308   {
309     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);  /* erroff gives more info */
310     return NULL;
311   }
312   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
313   ret->sexp = result;
314   return ret;
315 }
316
317
318 /**
319  * Encode the private key in a format suitable for
320  * storing it into a file.
321  * @returns encoding of the private key.
322  *    The first 4 bytes give the size of the array, as usual.
323  */
324 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
325 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
326 {
327   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
328   gcry_mpi_t pkv[6];
329   void *pbu[6];
330   size_t sizes[6];
331   int rc;
332   int i;
333   int size;
334
335 #if EXTRA_CHECKS
336   if (gcry_pk_testkey (hostkey->sexp))
337   {
338     GNUNET_break (0);
339     return NULL;
340   }
341 #endif
342
343   memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
344   rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
345   if (rc)
346     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
347   if (rc)
348     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
349   if (rc)
350     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
351   if (rc)
352     rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
353   if (rc)
354     rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
355   GNUNET_assert (0 == rc);
356   size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
357   for (i = 0; i < 6; i++)
358   {
359     if (pkv[i] != NULL)
360     {
361       GNUNET_assert (0 ==
362                      gcry_mpi_aprint (GCRYMPI_FMT_USG,
363                                       (unsigned char **) &pbu[i], &sizes[i],
364                                       pkv[i]));
365       size += sizes[i];
366     }
367     else
368     {
369       pbu[i] = NULL;
370       sizes[i] = 0;
371     }
372   }
373   GNUNET_assert (size < 65536);
374   retval = GNUNET_malloc (size);
375   retval->len = htons (size);
376   i = 0;
377   retval->sizen = htons (sizes[0]);
378   memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
379   i += sizes[0];
380   retval->sizee = htons (sizes[1]);
381   memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
382   i += sizes[1];
383   retval->sized = htons (sizes[2]);
384   memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
385   i += sizes[2];
386   /* swap p and q! */
387   retval->sizep = htons (sizes[4]);
388   memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
389   i += sizes[4];
390   retval->sizeq = htons (sizes[3]);
391   memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
392   i += sizes[3];
393   retval->sizedmp1 = htons (0);
394   retval->sizedmq1 = htons (0);
395   memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
396   for (i = 0; i < 6; i++)
397   {
398     if (pkv[i] != NULL)
399       gcry_mpi_release (pkv[i]);
400     if (pbu[i] != NULL)
401       free (pbu[i]);
402   }
403   return retval;
404 }
405
406
407 /**
408  * Decode the private key from the file-format back
409  * to the "normal", internal format.
410  *
411  * @param buf the buffer where the private key data is stored
412  * @param len the length of the data in 'buffer'
413  */
414 struct GNUNET_CRYPTO_RsaPrivateKey *
415 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
416 {
417   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
418   const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
419       (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
420   gcry_sexp_t res;
421   gcry_mpi_t n, e, d, p, q, u;
422   int rc;
423   size_t size;
424   int pos;
425   uint16_t enc_len;
426
427   enc_len = ntohs (encoding->len);
428   if (len != enc_len)
429     return NULL;
430
431   pos = 0;
432   size = ntohs (encoding->sizen);
433   rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
434                       &((const unsigned char *) (&encoding[1]))[pos], size,
435                       &size);
436   pos += ntohs (encoding->sizen);
437   if (rc)
438   {
439     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
440     return NULL;
441   }
442   size = ntohs (encoding->sizee);
443   rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
444                       &((const unsigned char *) (&encoding[1]))[pos], size,
445                       &size);
446   pos += ntohs (encoding->sizee);
447   if (rc)
448   {
449     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
450     gcry_mpi_release (n);
451     return NULL;
452   }
453   size = ntohs (encoding->sized);
454   rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
455                       &((const unsigned char *) (&encoding[1]))[pos], size,
456                       &size);
457   pos += ntohs (encoding->sized);
458   if (rc)
459   {
460     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
461     gcry_mpi_release (n);
462     gcry_mpi_release (e);
463     return NULL;
464   }
465   /* swap p and q! */
466   size = ntohs (encoding->sizep);
467   if (size > 0)
468   {
469     rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
470                         &((const unsigned char *) (&encoding[1]))[pos], size,
471                         &size);
472     pos += ntohs (encoding->sizep);
473     if (rc)
474     {
475       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
476       gcry_mpi_release (n);
477       gcry_mpi_release (e);
478       gcry_mpi_release (d);
479       return NULL;
480     }
481   }
482   else
483     q = NULL;
484   size = ntohs (encoding->sizeq);
485   if (size > 0)
486   {
487     rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
488                         &((const unsigned char *) (&encoding[1]))[pos], size,
489                         &size);
490     pos += ntohs (encoding->sizeq);
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 (q != NULL)
498         gcry_mpi_release (q);
499       return NULL;
500     }
501   }
502   else
503     p = NULL;
504   pos += ntohs (encoding->sizedmp1);
505   pos += ntohs (encoding->sizedmq1);
506   size =
507       ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
508   if (size > 0)
509   {
510     rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
511                         &((const unsigned char *) (&encoding[1]))[pos], size,
512                         &size);
513     if (rc)
514     {
515       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
516       gcry_mpi_release (n);
517       gcry_mpi_release (e);
518       gcry_mpi_release (d);
519       if (p != NULL)
520         gcry_mpi_release (p);
521       if (q != NULL)
522         gcry_mpi_release (q);
523       return NULL;
524     }
525   }
526   else
527     u = NULL;
528
529   if ((p != NULL) && (q != NULL) && (u != NULL))
530   {
531     rc = gcry_sexp_build (&res, &size,  /* erroff */
532                           "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
533                           n, e, d, p, q, u);
534   }
535   else
536   {
537     if ((p != NULL) && (q != NULL))
538     {
539       rc = gcry_sexp_build (&res, &size,        /* erroff */
540                             "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
541                             n, e, d, p, q);
542     }
543     else
544     {
545       rc = gcry_sexp_build (&res, &size,        /* erroff */
546                             "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
547     }
548   }
549   gcry_mpi_release (n);
550   gcry_mpi_release (e);
551   gcry_mpi_release (d);
552   if (p != NULL)
553     gcry_mpi_release (p);
554   if (q != NULL)
555     gcry_mpi_release (q);
556   if (u != NULL)
557     gcry_mpi_release (u);
558
559   if (rc)
560     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
561 #if EXTRA_CHECKS
562   if (gcry_pk_testkey (res))
563   {
564     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
565     return NULL;
566   }
567 #endif
568   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
569   ret->sexp = res;
570   return ret;
571 }
572
573
574 /**
575  * Create a new private key. Caller must free return value.
576  *
577  * @return fresh private key
578  */
579 static struct GNUNET_CRYPTO_RsaPrivateKey *
580 rsa_key_create ()
581 {
582   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
583   gcry_sexp_t s_key;
584   gcry_sexp_t s_keyparam;
585
586   GNUNET_assert (0 ==
587                  gcry_sexp_build (&s_keyparam, NULL,
588                                   "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
589                                   HOSTKEY_LEN));
590   GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
591   gcry_sexp_release (s_keyparam);
592 #if EXTRA_CHECKS
593   GNUNET_assert (0 == gcry_pk_testkey (s_key));
594 #endif
595   ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
596   ret->sexp = s_key;
597   return ret;
598 }
599
600
601 /**
602  * Try to read the private key from the given file.
603  *
604  * @param filename file to read the key from
605  * @return NULL on error
606  */
607 static struct GNUNET_CRYPTO_RsaPrivateKey *
608 try_read_key (const char *filename)
609 {
610   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
611   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
612   struct GNUNET_DISK_FileHandle *fd;
613   OFF_T fs;
614   uint16_t len;
615
616   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
617     return NULL;
618
619   /* hostkey file exists already, read it! */
620   if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
621                                            GNUNET_DISK_PERM_NONE)))
622   {
623     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
624     return NULL;
625   }
626   if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
627   {
628     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
629     (void) GNUNET_DISK_file_close (fd);
630     return NULL;
631   }
632   if (0 == fs)
633   {
634     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
635     return NULL;
636   }
637   if (fs > UINT16_MAX)
638   {
639     LOG (GNUNET_ERROR_TYPE_ERROR,
640          _("File `%s' does not contain a valid private key (too long, %llu bytes).  Deleting it.\n"),   
641          filename,
642          (unsigned long long) fs);
643     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
644     if (0 != UNLINK (filename))    
645       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
646     return NULL;
647   }
648
649   enc = GNUNET_malloc (fs);
650   GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
651   len = ntohs (enc->len);
652   ret = NULL;
653   if ((len != fs) ||
654       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
655   {
656     LOG (GNUNET_ERROR_TYPE_ERROR,
657          _("File `%s' does not contain a valid private key (failed decode, %llu bytes).  Deleting it.\n"),
658          filename,
659          (unsigned long long) fs);
660     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
661     if (0 != UNLINK (filename))    
662       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
663     GNUNET_free (enc);
664     return NULL;
665   }
666   GNUNET_free (enc);
667
668   GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
669   return ret;  
670 }
671
672
673 /**
674  * Wait for a short time (we're trying to lock a file or want
675  * to give another process a shot at finishing a disk write, etc.).
676  * Sleeps for 100ms (as that should be long enough for virtually all
677  * modern systems to context switch and allow another process to do
678  * some 'real' work).
679  */
680 static void
681 short_wait ()
682 {
683   struct GNUNET_TIME_Relative timeout;
684
685   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
686   GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
687 }
688
689
690 /**
691  * Create a new private key by reading it from a file.  If the
692  * files does not exist, create a new key and write it to the
693  * file.  Caller must free return value.  Note that this function
694  * can not guarantee that another process might not be trying
695  * the same operation on the same file at the same time.
696  * If the contents of the file
697  * are invalid the old file is deleted and a fresh key is
698  * created.
699  *
700  * @return new private key, NULL on error (for example,
701  *   permission denied)
702  */
703 struct GNUNET_CRYPTO_RsaPrivateKey *
704 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
705 {
706   struct GNUNET_CRYPTO_RsaPrivateKey *ret;
707   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
708   uint16_t len;
709   struct GNUNET_DISK_FileHandle *fd;
710   unsigned int cnt;
711   int ec;
712   uint64_t fs;
713   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
714   struct GNUNET_PeerIdentity pid;
715
716   if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
717     return NULL;
718   while (GNUNET_YES != GNUNET_DISK_file_test (filename))
719   {
720     fd = GNUNET_DISK_file_open (filename,
721                                 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
722                                 | GNUNET_DISK_OPEN_FAILIFEXISTS,
723                                 GNUNET_DISK_PERM_USER_READ |
724                                 GNUNET_DISK_PERM_USER_WRITE);
725     if (NULL == fd)
726     {
727       if (errno == EEXIST)
728       {
729         if (GNUNET_YES != GNUNET_DISK_file_test (filename))
730         {
731           /* must exist but not be accessible, fail for good! */
732           if (0 != ACCESS (filename, R_OK))
733             LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
734           else
735             GNUNET_break (0);   /* what is going on!? */
736           return NULL;
737         }
738         continue;
739       }
740       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
741       return NULL;
742     }
743     cnt = 0;
744
745     while (GNUNET_YES !=
746            GNUNET_DISK_file_lock (fd, 0,
747                                   sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
748                                   GNUNET_YES))
749     {
750       short_wait (1);
751       if (0 == ++cnt % 10)
752       {
753         ec = errno;
754         LOG (GNUNET_ERROR_TYPE_ERROR,
755              _("Could not acquire lock on file `%s': %s...\n"), filename,
756              STRERROR (ec));
757       }
758     }
759     LOG (GNUNET_ERROR_TYPE_INFO,
760          _("Creating a new private key.  This may take a while.\n"));
761     ret = rsa_key_create ();
762     GNUNET_assert (ret != NULL);
763     enc = GNUNET_CRYPTO_rsa_encode_key (ret);
764     GNUNET_assert (enc != NULL);
765     GNUNET_assert (ntohs (enc->len) ==
766                    GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
767     GNUNET_free (enc);
768
769     GNUNET_DISK_file_sync (fd);
770     if (GNUNET_YES !=
771         GNUNET_DISK_file_unlock (fd, 0,
772                                  sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
773       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
774     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
775     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
776     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
777     LOG (GNUNET_ERROR_TYPE_INFO,
778          _("I am host `%s'.  Stored new private key in `%s'.\n"),
779          GNUNET_i2s (&pid), filename);
780     return ret;
781   }
782   /* hostkey file exists already, read it! */
783   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
784                               GNUNET_DISK_PERM_NONE);
785   if (NULL == fd)
786   {
787     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
788     return NULL;
789   }
790   cnt = 0;
791   while (1)
792   {
793     if (GNUNET_YES !=
794         GNUNET_DISK_file_lock (fd, 0,
795                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
796                                GNUNET_NO))
797     {
798       if (0 == ++cnt % 60)
799       {
800         ec = errno;
801         LOG (GNUNET_ERROR_TYPE_ERROR,
802              _("Could not acquire lock on file `%s': %s...\n"), filename,
803              STRERROR (ec));
804         LOG (GNUNET_ERROR_TYPE_ERROR,
805              _
806              ("This may be ok if someone is currently generating a hostkey.\n"));
807       }
808       short_wait (1);
809       continue;
810     }
811     if (GNUNET_YES != GNUNET_DISK_file_test (filename))
812     {
813       /* eh, what!? File we opened is now gone!? */
814       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
815       if (GNUNET_YES !=
816           GNUNET_DISK_file_unlock (fd, 0,
817                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
818         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
819       GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
820
821       return NULL;
822     }
823     if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
824       fs = 0;
825     if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
826     {
827       /* maybe we got the read lock before the hostkey generating
828        * process had a chance to get the write lock; give it up! */
829       if (GNUNET_YES !=
830           GNUNET_DISK_file_unlock (fd, 0,
831                                    sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
832         LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
833       if (0 == ++cnt % 10)
834       {
835         LOG (GNUNET_ERROR_TYPE_ERROR,
836              _
837              ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
838              filename, (unsigned int) fs,
839              (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
840         LOG (GNUNET_ERROR_TYPE_ERROR,
841              _
842              ("This may be ok if someone is currently generating a hostkey.\n"));
843       }
844       short_wait (1);                /* wait a bit longer! */
845       continue;
846     }
847     break;
848   }
849   enc = GNUNET_malloc (fs);
850   GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
851   len = ntohs (enc->len);
852   ret = NULL;
853   if ((len != fs) ||
854       (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
855   {
856     LOG (GNUNET_ERROR_TYPE_ERROR,
857          _("File `%s' does not contain a valid private key.  Deleting it.\n"),
858          filename);
859     if (0 != UNLINK (filename))
860     {
861       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
862     }
863   }
864   GNUNET_free (enc);
865   if (GNUNET_YES !=
866       GNUNET_DISK_file_unlock (fd, 0,
867                                sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
868     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
869   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
870   if (ret != NULL)
871   {
872     GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
873     GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
874     LOG (GNUNET_ERROR_TYPE_INFO,
875          _("I am host `%s'.  Read private key from `%s'.\n"), GNUNET_i2s (&pid),
876          filename);
877   }
878   return ret;
879 }
880
881
882 /**
883  * Handle to cancel private key generation and state for the
884  * key generation operation.
885  */
886 struct GNUNET_CRYPTO_RsaKeyGenerationContext
887 {
888   
889   /**
890    * Continuation to call upon completion.
891    */
892   GNUNET_CRYPTO_RsaKeyCallback cont;
893
894   /**
895    * Closure for 'cont'.
896    */
897   void *cont_cls;
898
899   /**
900    * Name of the file.
901    */
902   char *filename;
903
904   /**
905    * Handle to the helper process which does the key generation.
906    */ 
907   struct GNUNET_OS_Process *gnunet_rsa;
908   
909   /**
910    * Handle to 'stdout' of gnunet-rsa.  We 'read' on stdout to detect
911    * process termination (instead of messing with SIGCHLD).
912    */
913   struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
914
915   /**
916    * Location where we store the private key if it already existed.
917    * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
918    * not be used).
919    */
920   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
921   
922   /**
923    * Task reading from 'gnunet_rsa_out' to wait for process termination.
924    */
925   GNUNET_SCHEDULER_TaskIdentifier read_task;
926   
927 };
928
929
930 /**
931  * Task called upon shutdown or process termination of 'gnunet-rsa' during
932  * RSA key generation.  Check where we are and perform the appropriate
933  * action.
934  *
935  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
936  * @param tc scheduler context
937  */
938 static void
939 check_key_generation_completion (void *cls,
940                                  const struct GNUNET_SCHEDULER_TaskContext *tc)
941 {
942   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
943   enum GNUNET_OS_ProcessStatusType type;
944   unsigned long code;
945   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
946
947   gc->read_task = GNUNET_SCHEDULER_NO_TASK;
948   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
949   {
950     gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
951     GNUNET_CRYPTO_rsa_key_create_stop (gc);
952     return;
953   }
954   if (GNUNET_OK != 
955       GNUNET_OS_process_status (gc->gnunet_rsa,
956                                 &type, &code))
957   {
958     GNUNET_break (0);
959     gc->cont (gc->cont_cls, NULL, _("internal error"));
960     GNUNET_CRYPTO_rsa_key_create_stop (gc);
961     return;
962   }
963   GNUNET_OS_process_destroy (gc->gnunet_rsa);
964   gc->gnunet_rsa = NULL;
965   if ( (GNUNET_OS_PROCESS_EXITED != type) ||
966        (0 != code) )
967   {
968     gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
969     GNUNET_CRYPTO_rsa_key_create_stop (gc);
970     return;
971   }
972   if (NULL == (pk = try_read_key (gc->filename)))
973   {
974     GNUNET_break (0);
975     gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
976     GNUNET_CRYPTO_rsa_key_create_stop (gc);
977     return;
978   }
979   gc->cont (gc->cont_cls, pk, NULL);
980   GNUNET_free (gc->filename);
981   GNUNET_free (gc);
982 }
983
984
985 /**
986  * Return the private RSA key which already existed on disk
987  * (asynchronously) to the caller.
988  *
989  * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
990  * @param tc scheduler context (unused)
991  */
992 static void
993 async_return_key (void *cls,
994                   const struct GNUNET_SCHEDULER_TaskContext *tc)
995 {
996   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
997
998   gc->cont (gc->cont_cls,
999             gc->pk,
1000             NULL);
1001   GNUNET_free (gc);
1002 }
1003
1004
1005 /**
1006  * Create a new private key by reading it from a file.  If the files
1007  * does not exist, create a new key and write it to the file.  If the
1008  * contents of the file are invalid the old file is deleted and a
1009  * fresh key is created.
1010  *
1011  * @param filename name of file to use for storage
1012  * @param cont function to call when done (or on errors)
1013  * @param cont_cls closure for 'cont'
1014  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1015  */
1016 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1017 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1018                                     GNUNET_CRYPTO_RsaKeyCallback cont,
1019                                     void *cont_cls)
1020 {
1021   struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1022   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1023   const char *weak_random;
1024
1025   if (NULL != (pk = try_read_key (filename)))
1026   {
1027     /* quick happy ending: key already exists! */
1028     gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1029     gc->pk = pk;
1030     gc->cont = cont;
1031     gc->cont_cls = cont_cls;
1032     gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1033                                               gc);
1034     return gc;
1035   }
1036   gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1037   gc->filename = GNUNET_strdup (filename);
1038   gc->cont = cont;
1039   gc->cont_cls = cont_cls;
1040   gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1041                                          GNUNET_NO,
1042                                          GNUNET_NO,
1043                                          GNUNET_YES);
1044   if (NULL == gc->gnunet_rsa_out)
1045   {
1046     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1047     GNUNET_free (gc->filename);
1048     GNUNET_free (gc);
1049     return NULL;
1050   }
1051   weak_random = NULL;
1052   if (GNUNET_YES ==
1053       GNUNET_CRYPTO_random_is_weak ())
1054     weak_random = "-w";
1055   gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1056                                             GNUNET_OS_INHERIT_STD_ERR,
1057                                             NULL, 
1058                                             gc->gnunet_rsa_out,
1059                                             "gnunet-rsa",
1060                                             "gnunet-rsa",                                           
1061                                             gc->filename,
1062                                             weak_random,
1063                                             NULL);
1064   if (NULL == gc->gnunet_rsa)
1065   {
1066     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1067     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1068     GNUNET_free (gc->filename);
1069     GNUNET_free (gc);
1070     return NULL;
1071   }
1072   GNUNET_assert (GNUNET_OK ==
1073                  GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1074                                              GNUNET_DISK_PIPE_END_WRITE));
1075   gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1076                                                   GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1077                                                                            GNUNET_DISK_PIPE_END_READ),
1078                                                   &check_key_generation_completion,
1079                                                   gc);
1080   return gc;
1081 }
1082
1083
1084 /**
1085  * Abort RSA key generation.
1086  *
1087  * @param gc key generation context to abort
1088  */
1089 void
1090 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1091 {
1092   if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1093   {
1094     GNUNET_SCHEDULER_cancel (gc->read_task);
1095     gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1096   }
1097   if (NULL != gc->gnunet_rsa)
1098   {
1099     (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1100     GNUNET_break (GNUNET_OK ==
1101                   GNUNET_OS_process_wait (gc->gnunet_rsa));
1102     GNUNET_OS_process_destroy (gc->gnunet_rsa);
1103     GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1104   }
1105
1106   if (NULL != gc->filename)
1107   {
1108     if (0 != UNLINK (gc->filename))
1109       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1110     GNUNET_free (gc->filename);
1111   }
1112   if (NULL != gc->pk)
1113     GNUNET_CRYPTO_rsa_key_free (gc->pk);
1114   GNUNET_free (gc);
1115 }
1116
1117
1118 /**
1119  * Setup a hostkey file for a peer given the name of the
1120  * configuration file (!).  This function is used so that
1121  * at a later point code can be certain that reading a
1122  * hostkey is fast (for example in time-dependent testcases).
1123  *
1124  * @param cfg_name name of the configuration file to use
1125  */
1126 void
1127 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
1128 {
1129   struct GNUNET_CONFIGURATION_Handle *cfg;
1130   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1131   char *fn;
1132
1133   cfg = GNUNET_CONFIGURATION_create ();
1134   (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1135   if (GNUNET_OK == 
1136       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1137   {
1138     pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1139     if (NULL != pk)
1140       GNUNET_CRYPTO_rsa_key_free (pk);
1141     GNUNET_free (fn);
1142   }
1143   GNUNET_CONFIGURATION_destroy (cfg);
1144 }
1145
1146
1147 /**
1148  * Encrypt a block with the public key of another host that uses the
1149  * same cipher.
1150  *
1151  * @param block the block to encrypt
1152  * @param size the size of block
1153  * @param publicKey the encoded public key used to encrypt
1154  * @param target where to store the encrypted block
1155  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1156  */
1157 int
1158 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1159                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1160                            *publicKey,
1161                            struct GNUNET_CRYPTO_RsaEncryptedData *target)
1162 {
1163   gcry_sexp_t result;
1164   gcry_sexp_t data;
1165   struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
1166   gcry_mpi_t val;
1167   gcry_mpi_t rval;
1168   size_t isize;
1169   size_t erroff;
1170
1171   GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1172   pubkey = public2PrivateKey (publicKey);
1173   if (pubkey == NULL)
1174     return GNUNET_SYSERR;
1175   isize = size;
1176   GNUNET_assert (0 ==
1177                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1178   GNUNET_assert (0 ==
1179                  gcry_sexp_build (&data, &erroff,
1180                                   "(data (flags pkcs1)(value %m))", val));
1181   gcry_mpi_release (val);
1182   GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
1183   gcry_sexp_release (data);
1184   GNUNET_CRYPTO_rsa_key_free (pubkey);
1185
1186   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1187   gcry_sexp_release (result);
1188   isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1189   GNUNET_assert (0 ==
1190                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1191                                  isize, &isize, rval));
1192   gcry_mpi_release (rval);
1193   adjust (&target->encoding[0], isize,
1194           sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1195   return GNUNET_OK;
1196 }
1197
1198
1199 /**
1200  * Decrypt a given block with the hostkey.
1201  *
1202  * @param key the key with which to decrypt this block
1203  * @param block the data to decrypt, encoded as returned by encrypt
1204  * @param result pointer to a location where the result can be stored
1205  * @param max the maximum number of bits to store for the result, if
1206  *        the decrypted block is bigger, an error is returned
1207  * @return the size of the decrypted block, -1 on error
1208  */
1209 ssize_t
1210 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1211                            const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1212                            void *result, size_t max)
1213 {
1214   gcry_sexp_t resultsexp;
1215   gcry_sexp_t data;
1216   size_t erroff;
1217   size_t size;
1218   gcry_mpi_t val;
1219   unsigned char *endp;
1220   unsigned char *tmp;
1221
1222 #if EXTRA_CHECKS
1223   GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1224 #endif
1225   size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1226   GNUNET_assert (0 ==
1227                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1228                                 size, &size));
1229   GNUNET_assert (0 ==
1230                  gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1231                                   val));
1232   gcry_mpi_release (val);
1233   GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1234   gcry_sexp_release (data);
1235   /* resultsexp has format "(value %m)" */
1236   GNUNET_assert (NULL !=
1237                  (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1238   gcry_sexp_release (resultsexp);
1239   tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1240   size = max + HOSTKEY_LEN / 8;
1241   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1242   gcry_mpi_release (val);
1243   endp = tmp;
1244   endp += (size - max);
1245   size = max;
1246   memcpy (result, endp, size);
1247   GNUNET_free (tmp);
1248   return size;
1249 }
1250
1251
1252 /**
1253  * Sign a given block.
1254  *
1255  * @param key private key to use for the signing
1256  * @param purpose what to sign (size, purpose)
1257  * @param sig where to write the signature
1258  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1259  */
1260 int
1261 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1262                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1263                         struct GNUNET_CRYPTO_RsaSignature *sig)
1264 {
1265   gcry_sexp_t result;
1266   gcry_sexp_t data;
1267   size_t ssize;
1268   gcry_mpi_t rval;
1269   struct GNUNET_HashCode hc;
1270   char *buff;
1271   int bufSize;
1272
1273   GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1274 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1275   bufSize = strlen (FORMATSTRING) + 1;
1276   buff = GNUNET_malloc (bufSize);
1277   memcpy (buff, FORMATSTRING, bufSize);
1278   memcpy (&buff
1279           [bufSize -
1280            strlen
1281            ("0123456789012345678901234567890123456789012345678901234567890123))")
1282            - 1], &hc, sizeof (struct GNUNET_HashCode));
1283   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1284   GNUNET_free (buff);
1285   GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1286   gcry_sexp_release (data);
1287   GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1288   gcry_sexp_release (result);
1289   ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1290   GNUNET_assert (0 ==
1291                  gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1292                                  &ssize, rval));
1293   gcry_mpi_release (rval);
1294   adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1295   return GNUNET_OK;
1296 }
1297
1298
1299 /**
1300  * Verify signature.
1301  *
1302  * @param purpose what is the purpose that the signature should have?
1303  * @param validate block to validate (size, purpose, data)
1304  * @param sig signature that is being validated
1305  * @param publicKey public key of the signer
1306  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1307  */
1308 int
1309 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1310                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
1311                           *validate,
1312                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1313                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1314                           *publicKey)
1315 {
1316   gcry_sexp_t data;
1317   gcry_sexp_t sigdata;
1318   size_t size;
1319   gcry_mpi_t val;
1320   struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
1321   struct GNUNET_HashCode hc;
1322   char *buff;
1323   int bufSize;
1324   size_t erroff;
1325   int rc;
1326
1327   if (purpose != ntohl (validate->purpose))
1328     return GNUNET_SYSERR;       /* purpose mismatch */
1329   GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
1330   size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1331   GNUNET_assert (0 ==
1332                  gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1333                                 (const unsigned char *) sig, size, &size));
1334   GNUNET_assert (0 ==
1335                  gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1336                                   val));
1337   gcry_mpi_release (val);
1338   bufSize = strlen (FORMATSTRING) + 1;
1339   buff = GNUNET_malloc (bufSize);
1340   memcpy (buff, FORMATSTRING, bufSize);
1341   memcpy (&buff
1342           [strlen (FORMATSTRING) -
1343            strlen
1344            ("0123456789012345678901234567890123456789012345678901234567890123))")],
1345           &hc, sizeof (struct GNUNET_HashCode));
1346   GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1347   GNUNET_free (buff);
1348   hostkey = public2PrivateKey (publicKey);
1349   if (hostkey == NULL)
1350   {
1351     gcry_sexp_release (data);
1352     gcry_sexp_release (sigdata);
1353     return GNUNET_SYSERR;
1354   }
1355   rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1356   GNUNET_CRYPTO_rsa_key_free (hostkey);
1357   gcry_sexp_release (data);
1358   gcry_sexp_release (sigdata);
1359   if (rc)
1360   {
1361     LOG (GNUNET_ERROR_TYPE_WARNING,
1362          _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1363          __LINE__, gcry_strerror (rc));
1364     return GNUNET_SYSERR;
1365   }
1366   return GNUNET_OK;
1367 }
1368
1369
1370 /* end of crypto_rsa.c */