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