2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file util/crypto_rsa.c
23 * @brief public key cryptography (RSA) with libgcrypt
24 * @author Christian Grothoff
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.
36 #include "gnunet_common.h"
37 #include "gnunet_util_lib.h"
39 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
47 * The private information of an RSA key pair.
48 * NOTE: this must match the definition in crypto_ksk.c and gnunet-rsa.c!
50 struct GNUNET_CRYPTO_RsaPrivateKey
56 #define HOSTKEY_LEN 2048
58 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
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).
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);
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.
74 adjust (unsigned char *buf, size_t size, size_t target)
78 memmove (&buf[target - size], buf, size);
79 memset (buf, 0, target - size);
85 * Free memory occupied by hostkey
86 * @param hostkey pointer to the memory to free
89 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
91 gcry_sexp_release (hostkey->sexp);
92 GNUNET_free (hostkey);
100 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
103 gcry_sexp_t list, l2;
107 list = gcry_sexp_find_token (sexp, topname, 0);
112 l2 = gcry_sexp_cadr (list);
113 gcry_sexp_release (list);
121 for (s = elems; *s; s++, idx++)
123 l2 = gcry_sexp_find_token (list, s, 1);
126 for (i = 0; i < idx; i++)
128 gcry_free (array[i]);
131 gcry_sexp_release (list);
132 return 3; /* required parameter not found */
134 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
135 gcry_sexp_release (l2);
138 for (i = 0; i < idx; i++)
140 gcry_free (array[i]);
143 gcry_sexp_release (list);
144 return 4; /* required parameter is invalid */
147 gcry_sexp_release (list);
152 * Extract the public key of the host.
153 * @param priv the private key
154 * @param pub where to write the public key
157 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
159 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
166 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
168 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
170 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
171 GNUNET_assert (0 == rc);
173 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
174 sizeof (pub->padding));
175 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
177 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
179 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
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;
184 gcry_mpi_print (GCRYMPI_FMT_USG,
186 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
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]);
197 * Convert a public key to a string.
199 * @param pub key to convert
200 * @return string representing 'pub'
203 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
206 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
210 keylen += 5 - keylen % 5;
212 pubkeybuf = GNUNET_malloc (keylen + 1);
213 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
214 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
219 GNUNET_free (pubkeybuf);
228 * Convert a string representing a public key to a public key.
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
236 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
238 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
240 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
243 keylen += 5 - keylen % 5;
245 if (enclen != keylen)
246 return GNUNET_SYSERR;
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;
261 * Internal: publicKey => RSA-Key.
263 * Note that the return type is not actually a private
264 * key but rather an sexpression for the public key!
266 static struct GNUNET_CRYPTO_RsaPrivateKey *
267 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
270 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
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)))
286 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
287 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
290 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
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],
299 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
300 gcry_mpi_release (n);
303 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
305 gcry_mpi_release (n);
306 gcry_mpi_release (e);
309 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
312 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
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.
324 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
325 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
327 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
336 if (gcry_pk_testkey (hostkey->sexp))
343 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
344 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
346 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
348 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
350 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
352 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
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++)
362 gcry_mpi_aprint (GCRYMPI_FMT_USG,
363 (unsigned char **) &pbu[i], &sizes[i],
373 GNUNET_assert (size < 65536);
374 retval = GNUNET_malloc (size);
375 retval->len = htons (size);
377 retval->sizen = htons (sizes[0]);
378 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
380 retval->sizee = htons (sizes[1]);
381 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
383 retval->sized = htons (sizes[2]);
384 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
387 retval->sizep = htons (sizes[4]);
388 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
390 retval->sizeq = htons (sizes[3]);
391 memcpy (&((char *) (&retval[1]))[i], pbu[3], 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++)
399 gcry_mpi_release (pkv[i]);
408 * Decode the private key from the file-format back
409 * to the "normal", internal format.
411 * @param buf the buffer where the private key data is stored
412 * @param len the length of the data in 'buffer'
414 struct GNUNET_CRYPTO_RsaPrivateKey *
415 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
417 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
418 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
419 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
421 gcry_mpi_t n, e, d, p, q, u;
427 enc_len = ntohs (encoding->len);
432 size = ntohs (encoding->sizen);
433 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
434 &((const unsigned char *) (&encoding[1]))[pos], size,
436 pos += ntohs (encoding->sizen);
439 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
442 size = ntohs (encoding->sizee);
443 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
444 &((const unsigned char *) (&encoding[1]))[pos], size,
446 pos += ntohs (encoding->sizee);
449 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
450 gcry_mpi_release (n);
453 size = ntohs (encoding->sized);
454 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
455 &((const unsigned char *) (&encoding[1]))[pos], size,
457 pos += ntohs (encoding->sized);
460 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
461 gcry_mpi_release (n);
462 gcry_mpi_release (e);
466 size = ntohs (encoding->sizep);
469 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
470 &((const unsigned char *) (&encoding[1]))[pos], size,
472 pos += ntohs (encoding->sizep);
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);
484 size = ntohs (encoding->sizeq);
487 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
488 &((const unsigned char *) (&encoding[1]))[pos], size,
490 pos += ntohs (encoding->sizeq);
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);
498 gcry_mpi_release (q);
504 pos += ntohs (encoding->sizedmp1);
505 pos += ntohs (encoding->sizedmq1);
507 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
510 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
511 &((const unsigned char *) (&encoding[1]))[pos], size,
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);
520 gcry_mpi_release (p);
522 gcry_mpi_release (q);
529 if ((p != NULL) && (q != NULL) && (u != NULL))
531 rc = gcry_sexp_build (&res, &size, /* erroff */
532 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
537 if ((p != NULL) && (q != NULL))
539 rc = gcry_sexp_build (&res, &size, /* erroff */
540 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
545 rc = gcry_sexp_build (&res, &size, /* erroff */
546 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
549 gcry_mpi_release (n);
550 gcry_mpi_release (e);
551 gcry_mpi_release (d);
553 gcry_mpi_release (p);
555 gcry_mpi_release (q);
557 gcry_mpi_release (u);
560 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
562 if (gcry_pk_testkey (res))
564 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
568 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
575 * Create a new private key. Caller must free return value.
577 * @return fresh private key
579 static struct GNUNET_CRYPTO_RsaPrivateKey *
582 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
584 gcry_sexp_t s_keyparam;
587 gcry_sexp_build (&s_keyparam, NULL,
588 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
590 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
591 gcry_sexp_release (s_keyparam);
593 GNUNET_assert (0 == gcry_pk_testkey (s_key));
595 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
602 * Try to read the private key from the given file.
604 * @param filename file to read the key from
605 * @return NULL on error
607 static struct GNUNET_CRYPTO_RsaPrivateKey *
608 try_read_key (const char *filename)
610 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
611 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
612 struct GNUNET_DISK_FileHandle *fd;
616 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
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)))
623 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
626 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
628 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
629 (void) GNUNET_DISK_file_close (fd);
634 LOG (GNUNET_ERROR_TYPE_ERROR,
635 _("File `%s' does not contain a valid private key. Deleting it.\n"),
637 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
638 if (0 != UNLINK (filename))
639 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
643 enc = GNUNET_malloc (fs);
644 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
645 len = ntohs (enc->len);
648 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
650 LOG (GNUNET_ERROR_TYPE_ERROR,
651 _("File `%s' does not contain a valid private key. Deleting it.\n"),
653 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
654 if (0 != UNLINK (filename))
655 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
661 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
667 * Create a new private key by reading it from a file. If the
668 * files does not exist, create a new key and write it to the
669 * file. Caller must free return value. Note that this function
670 * can not guarantee that another process might not be trying
671 * the same operation on the same file at the same time.
672 * If the contents of the file
673 * are invalid the old file is deleted and a fresh key is
676 * @return new private key, NULL on error (for example,
679 struct GNUNET_CRYPTO_RsaPrivateKey *
680 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
682 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
683 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
685 struct GNUNET_DISK_FileHandle *fd;
689 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
690 struct GNUNET_PeerIdentity pid;
692 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
694 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
696 fd = GNUNET_DISK_file_open (filename,
697 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
698 | GNUNET_DISK_OPEN_FAILIFEXISTS,
699 GNUNET_DISK_PERM_USER_READ |
700 GNUNET_DISK_PERM_USER_WRITE);
705 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
707 /* must exist but not be accessible, fail for good! */
708 if (0 != ACCESS (filename, R_OK))
709 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
711 GNUNET_break (0); /* what is going on!? */
716 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
722 GNUNET_DISK_file_lock (fd, 0,
723 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
730 LOG (GNUNET_ERROR_TYPE_ERROR,
731 _("Could not acquire lock on file `%s': %s...\n"), filename,
735 LOG (GNUNET_ERROR_TYPE_INFO,
736 _("Creating a new private key. This may take a while.\n"));
737 ret = rsa_key_create ();
738 GNUNET_assert (ret != NULL);
739 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
740 GNUNET_assert (enc != NULL);
741 GNUNET_assert (ntohs (enc->len) ==
742 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
745 GNUNET_DISK_file_sync (fd);
747 GNUNET_DISK_file_unlock (fd, 0,
748 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
749 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
750 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
751 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
752 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
753 LOG (GNUNET_ERROR_TYPE_INFO,
754 _("I am host `%s'. Stored new private key in `%s'.\n"),
755 GNUNET_i2s (&pid), filename);
758 /* hostkey file exists already, read it! */
759 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
760 GNUNET_DISK_PERM_NONE);
763 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
770 GNUNET_DISK_file_lock (fd, 0,
771 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
777 LOG (GNUNET_ERROR_TYPE_ERROR,
778 _("Could not acquire lock on file `%s': %s...\n"), filename,
780 LOG (GNUNET_ERROR_TYPE_ERROR,
782 ("This may be ok if someone is currently generating a hostkey.\n"));
787 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
789 /* eh, what!? File we opened is now gone!? */
790 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
792 GNUNET_DISK_file_unlock (fd, 0,
793 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
794 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
795 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
799 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
801 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
803 /* maybe we got the read lock before the hostkey generating
804 * process had a chance to get the write lock; give it up! */
806 GNUNET_DISK_file_unlock (fd, 0,
807 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
808 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
811 LOG (GNUNET_ERROR_TYPE_ERROR,
813 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
814 filename, (unsigned int) fs,
815 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
816 LOG (GNUNET_ERROR_TYPE_ERROR,
818 ("This may be ok if someone is currently generating a hostkey.\n"));
820 sleep (2); /* wait a bit longer! */
825 enc = GNUNET_malloc (fs);
826 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
827 len = ntohs (enc->len);
830 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
832 LOG (GNUNET_ERROR_TYPE_ERROR,
833 _("File `%s' does not contain a valid private key. Deleting it.\n"),
835 if (0 != UNLINK (filename))
837 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
842 GNUNET_DISK_file_unlock (fd, 0,
843 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
844 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
845 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
848 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
849 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
850 LOG (GNUNET_ERROR_TYPE_INFO,
851 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
859 * Handle to cancel private key generation and state for the
860 * key generation operation.
862 struct GNUNET_CRYPTO_RsaKeyGenerationContext
866 * Continuation to call upon completion.
868 GNUNET_CRYPTO_RsaKeyCallback cont;
871 * Closure for 'cont'.
881 * Handle to the helper process which does the key generation.
883 struct GNUNET_OS_Process *gnunet_rsa;
886 * Handle to 'stdout' of gnunet-rsa. We 'read' on stdout to detect
887 * process termination (instead of messing with SIGCHLD).
889 struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
892 * Location where we store the private key if it already existed.
893 * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
896 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
899 * Task reading from 'gnunet_rsa_out' to wait for process termination.
901 GNUNET_SCHEDULER_TaskIdentifier read_task;
907 * Task called upon shutdown or process termination of 'gnunet-rsa' during
908 * RSA key generation. Check where we are and perform the appropriate
911 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
912 * @param tc scheduler context
915 check_key_generation_completion (void *cls,
916 const struct GNUNET_SCHEDULER_TaskContext *tc)
918 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
919 enum GNUNET_OS_ProcessStatusType type;
921 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
923 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
924 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
926 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
927 GNUNET_CRYPTO_rsa_key_create_stop (gc);
931 GNUNET_OS_process_status (gc->gnunet_rsa,
935 gc->cont (gc->cont_cls, NULL, _("internal error"));
936 GNUNET_CRYPTO_rsa_key_create_stop (gc);
939 GNUNET_OS_process_destroy (gc->gnunet_rsa);
940 gc->gnunet_rsa = NULL;
941 if ( (GNUNET_OS_PROCESS_EXITED != type) ||
944 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
945 GNUNET_CRYPTO_rsa_key_create_stop (gc);
948 if (NULL == (pk = try_read_key (gc->filename)))
951 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
952 GNUNET_CRYPTO_rsa_key_create_stop (gc);
955 gc->cont (gc->cont_cls, pk, NULL);
956 GNUNET_free (gc->filename);
962 * Return the private RSA key which already existed on disk
963 * (asynchronously) to the caller.
965 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
966 * @param tc scheduler context (unused)
969 async_return_key (void *cls,
970 const struct GNUNET_SCHEDULER_TaskContext *tc)
972 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
974 gc->cont (gc->cont_cls,
982 * Create a new private key by reading it from a file. If the files
983 * does not exist, create a new key and write it to the file. If the
984 * contents of the file are invalid the old file is deleted and a
985 * fresh key is created.
987 * @param filename name of file to use for storage
988 * @param cont function to call when done (or on errors)
989 * @param cont_cls closure for 'cont'
990 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
992 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
993 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
994 GNUNET_CRYPTO_RsaKeyCallback cont,
997 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
998 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1000 if (NULL != (pk = try_read_key (filename)))
1002 /* quick happy ending: key already exists! */
1003 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1006 gc->cont_cls = cont_cls;
1007 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1011 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1012 gc->filename = GNUNET_strdup (filename);
1014 gc->cont_cls = cont_cls;
1015 gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1019 if (NULL == gc->gnunet_rsa_out)
1021 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1022 GNUNET_free (gc->filename);
1026 gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1027 GNUNET_OS_INHERIT_STD_ERR,
1034 if (NULL == gc->gnunet_rsa)
1036 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1037 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1038 GNUNET_free (gc->filename);
1042 GNUNET_assert (GNUNET_OK ==
1043 GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1044 GNUNET_DISK_PIPE_END_WRITE));
1045 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1046 GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1047 GNUNET_DISK_PIPE_END_READ),
1048 &check_key_generation_completion,
1055 * Abort RSA key generation.
1057 * @param gc key generation context to abort
1060 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1062 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1064 GNUNET_SCHEDULER_cancel (gc->read_task);
1065 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1067 if (NULL != gc->gnunet_rsa)
1069 (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1070 GNUNET_break (GNUNET_OK ==
1071 GNUNET_OS_process_wait (gc->gnunet_rsa));
1072 GNUNET_OS_process_destroy (gc->gnunet_rsa);
1073 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1076 if (NULL != gc->filename)
1078 if (0 != UNLINK (gc->filename))
1079 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1080 GNUNET_free (gc->filename);
1083 GNUNET_CRYPTO_rsa_key_free (gc->pk);
1089 * Setup a hostkey file for a peer given the name of the
1090 * configuration file (!). This function is used so that
1091 * at a later point code can be certain that reading a
1092 * hostkey is fast (for example in time-dependent testcases).
1094 * @param cfg_name name of the configuration file to use
1097 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
1099 struct GNUNET_CONFIGURATION_Handle *cfg;
1100 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1103 cfg = GNUNET_CONFIGURATION_create ();
1104 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1106 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1108 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1110 GNUNET_CRYPTO_rsa_key_free (pk);
1113 GNUNET_CONFIGURATION_destroy (cfg);
1118 * Encrypt a block with the public key of another host that uses the
1121 * @param block the block to encrypt
1122 * @param size the size of block
1123 * @param publicKey the encoded public key used to encrypt
1124 * @param target where to store the encrypted block
1125 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1128 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1129 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1131 struct GNUNET_CRYPTO_RsaEncryptedData *target)
1135 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
1141 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1142 pubkey = public2PrivateKey (publicKey);
1144 return GNUNET_SYSERR;
1147 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1149 gcry_sexp_build (&data, &erroff,
1150 "(data (flags pkcs1)(value %m))", val));
1151 gcry_mpi_release (val);
1152 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
1153 gcry_sexp_release (data);
1154 GNUNET_CRYPTO_rsa_key_free (pubkey);
1156 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1157 gcry_sexp_release (result);
1158 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1160 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1161 isize, &isize, rval));
1162 gcry_mpi_release (rval);
1163 adjust (&target->encoding[0], isize,
1164 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1170 * Decrypt a given block with the hostkey.
1172 * @param key the key with which to decrypt this block
1173 * @param block the data to decrypt, encoded as returned by encrypt
1174 * @param result pointer to a location where the result can be stored
1175 * @param max the maximum number of bits to store for the result, if
1176 * the decrypted block is bigger, an error is returned
1177 * @return the size of the decrypted block, -1 on error
1180 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1181 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1182 void *result, size_t max)
1184 gcry_sexp_t resultsexp;
1189 unsigned char *endp;
1193 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1195 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1197 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1200 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1202 gcry_mpi_release (val);
1203 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1204 gcry_sexp_release (data);
1205 /* resultsexp has format "(value %m)" */
1206 GNUNET_assert (NULL !=
1207 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1208 gcry_sexp_release (resultsexp);
1209 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1210 size = max + HOSTKEY_LEN / 8;
1211 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1212 gcry_mpi_release (val);
1214 endp += (size - max);
1216 memcpy (result, endp, size);
1223 * Sign a given block.
1225 * @param key private key to use for the signing
1226 * @param purpose what to sign (size, purpose)
1227 * @param sig where to write the signature
1228 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1231 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1232 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1233 struct GNUNET_CRYPTO_RsaSignature *sig)
1239 struct GNUNET_HashCode hc;
1243 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1244 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1245 bufSize = strlen (FORMATSTRING) + 1;
1246 buff = GNUNET_malloc (bufSize);
1247 memcpy (buff, FORMATSTRING, bufSize);
1251 ("0123456789012345678901234567890123456789012345678901234567890123))")
1252 - 1], &hc, sizeof (struct GNUNET_HashCode));
1253 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1255 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1256 gcry_sexp_release (data);
1257 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1258 gcry_sexp_release (result);
1259 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1261 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1263 gcry_mpi_release (rval);
1264 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1272 * @param purpose what is the purpose that the signature should have?
1273 * @param validate block to validate (size, purpose, data)
1274 * @param sig signature that is being validated
1275 * @param publicKey public key of the signer
1276 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1279 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1280 const struct GNUNET_CRYPTO_RsaSignaturePurpose
1282 const struct GNUNET_CRYPTO_RsaSignature *sig,
1283 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1287 gcry_sexp_t sigdata;
1290 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
1291 struct GNUNET_HashCode hc;
1297 if (purpose != ntohl (validate->purpose))
1298 return GNUNET_SYSERR; /* purpose mismatch */
1299 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
1300 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1302 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1303 (const unsigned char *) sig, size, &size));
1305 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1307 gcry_mpi_release (val);
1308 bufSize = strlen (FORMATSTRING) + 1;
1309 buff = GNUNET_malloc (bufSize);
1310 memcpy (buff, FORMATSTRING, bufSize);
1312 [strlen (FORMATSTRING) -
1314 ("0123456789012345678901234567890123456789012345678901234567890123))")],
1315 &hc, sizeof (struct GNUNET_HashCode));
1316 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1318 hostkey = public2PrivateKey (publicKey);
1319 if (hostkey == NULL)
1321 gcry_sexp_release (data);
1322 gcry_sexp_release (sigdata);
1323 return GNUNET_SYSERR;
1325 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1326 GNUNET_CRYPTO_rsa_key_free (hostkey);
1327 gcry_sexp_release (data);
1328 gcry_sexp_release (sigdata);
1331 LOG (GNUNET_ERROR_TYPE_WARNING,
1332 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1333 __LINE__, gcry_strerror (rc));
1334 return GNUNET_SYSERR;
1340 /* end of crypto_rsa.c */