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
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
37 #define HOSTKEY_LEN 2048
39 #define EXTRA_CHECKS ALLOW_EXTRA_CHECKS
43 * The private information of an RSA key pair.
44 * NOTE: this must match the definition in crypto_ksk.c and gnunet-rsa.c!
46 struct GNUNET_CRYPTO_RsaPrivateKey
49 * Libgcrypt S-expression for the ECC key.
55 * Log an error message at log-level 'level' that indicates
56 * a failure of the command 'cmd' with the message given
57 * by gcry_strerror(rc).
59 #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);
62 * If target != size, move target bytes to the
63 * end of the size-sized buffer and zero out the
64 * first target-size bytes.
66 * @param buf original buffer
67 * @param size number of bytes in the buffer
68 * @param target target size of the buffer
71 adjust (unsigned char *buf, size_t size, size_t target)
75 memmove (&buf[target - size], buf, size);
76 memset (buf, 0, target - size);
82 * Free memory occupied by hostkey
83 * @param hostkey pointer to the memory to free
86 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
88 gcry_sexp_release (hostkey->sexp);
89 GNUNET_free (hostkey);
94 * Extract values from an S-expression.
96 * @param array where to store the result(s)
97 * @param sexp S-expression to parse
98 * @param topname top-level name in the S-expression that is of interest
99 * @param elems names of the elements to extract
100 * @return 0 on success
103 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
112 list = gcry_sexp_find_token (sexp, topname, 0);
115 l2 = gcry_sexp_cadr (list);
116 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);
153 * Extract the public key of the host.
154 * @param priv the private key
155 * @param pub where to write the public key
158 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
160 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
167 rc = key_from_sexp (skey, priv->sexp, "public-key", "ne");
169 rc = key_from_sexp (skey, priv->sexp, "private-key", "ne");
171 rc = key_from_sexp (skey, priv->sexp, "rsa", "ne");
172 GNUNET_assert (0 == rc);
174 htons (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
175 sizeof (pub->padding));
176 pub->sizen = htons (GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
178 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
180 gcry_mpi_print (GCRYMPI_FMT_USG, &pub->key[0], size, &size,
182 adjust (&pub->key[0], size, GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
183 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
185 gcry_mpi_print (GCRYMPI_FMT_USG,
187 [GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
189 adjust (&pub->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH], size,
190 GNUNET_CRYPTO_RSA_KEY_LENGTH -
191 GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH);
192 gcry_mpi_release (skey[0]);
193 gcry_mpi_release (skey[1]);
198 * Convert a public key to a string.
200 * @param pub key to convert
201 * @return string representing 'pub'
204 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
207 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
211 keylen += 5 - keylen % 5;
213 pubkeybuf = GNUNET_malloc (keylen + 1);
214 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
215 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
220 GNUNET_free (pubkeybuf);
229 * Convert a string representing a public key to a public key.
231 * @param enc encoded public key
232 * @param enclen number of bytes in enc (without 0-terminator)
233 * @param pub where to store the public key
234 * @return GNUNET_OK on success
237 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
239 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
241 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
244 keylen += 5 - keylen % 5;
246 if (enclen != keylen)
247 return GNUNET_SYSERR;
249 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
250 (unsigned char*) pub,
251 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
252 return GNUNET_SYSERR;
253 if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
254 (ntohs (pub->padding) != 0) ||
255 (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
256 return GNUNET_SYSERR;
262 * Internal: publicKey => RSA-Key.
264 * Note that the return type is not actually a private
265 * key but rather an sexpression for the public key!
267 static struct GNUNET_CRYPTO_RsaPrivateKey *
268 public2PrivateKey (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
271 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
279 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
280 (ntohs (publicKey->len) !=
281 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
282 sizeof (publicKey->padding)))
287 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
288 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size);
291 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
294 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
295 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
296 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
300 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
301 gcry_mpi_release (n);
304 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
306 gcry_mpi_release (n);
307 gcry_mpi_release (e);
310 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
313 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
320 * Encode the private key in a format suitable for
321 * storing it into a file.
322 * @returns encoding of the private key.
323 * The first 4 bytes give the size of the array, as usual.
325 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
326 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
328 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
337 if (gcry_pk_testkey (hostkey->sexp))
344 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
345 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
347 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
349 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
351 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
353 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
355 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
356 GNUNET_assert (0 == rc);
357 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
358 for (i = 0; i < 6; i++)
363 gcry_mpi_aprint (GCRYMPI_FMT_USG,
364 (unsigned char **) &pbu[i], &sizes[i],
374 GNUNET_assert (size < 65536);
375 retval = GNUNET_malloc (size);
376 retval->len = htons (size);
378 retval->sizen = htons (sizes[0]);
379 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
381 retval->sizee = htons (sizes[1]);
382 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
384 retval->sized = htons (sizes[2]);
385 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
388 retval->sizep = htons (sizes[4]);
389 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
391 retval->sizeq = htons (sizes[3]);
392 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
394 retval->sizedmp1 = htons (0);
395 retval->sizedmq1 = htons (0);
396 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
397 for (i = 0; i < 6; i++)
400 gcry_mpi_release (pkv[i]);
409 * Decode the private key from the file-format back
410 * to the "normal", internal format.
412 * @param buf the buffer where the private key data is stored
413 * @param len the length of the data in 'buffer'
415 struct GNUNET_CRYPTO_RsaPrivateKey *
416 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
418 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
419 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
420 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
422 gcry_mpi_t n, e, d, p, q, u;
428 enc_len = ntohs (encoding->len);
433 size = ntohs (encoding->sizen);
434 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
435 &((const unsigned char *) (&encoding[1]))[pos], size,
437 pos += ntohs (encoding->sizen);
440 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
443 size = ntohs (encoding->sizee);
444 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
445 &((const unsigned char *) (&encoding[1]))[pos], size,
447 pos += ntohs (encoding->sizee);
450 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
451 gcry_mpi_release (n);
454 size = ntohs (encoding->sized);
455 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
456 &((const unsigned char *) (&encoding[1]))[pos], size,
458 pos += ntohs (encoding->sized);
461 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
462 gcry_mpi_release (n);
463 gcry_mpi_release (e);
467 size = ntohs (encoding->sizep);
470 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
471 &((const unsigned char *) (&encoding[1]))[pos], size,
473 pos += ntohs (encoding->sizep);
476 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
477 gcry_mpi_release (n);
478 gcry_mpi_release (e);
479 gcry_mpi_release (d);
485 size = ntohs (encoding->sizeq);
488 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
489 &((const unsigned char *) (&encoding[1]))[pos], size,
491 pos += ntohs (encoding->sizeq);
494 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
495 gcry_mpi_release (n);
496 gcry_mpi_release (e);
497 gcry_mpi_release (d);
499 gcry_mpi_release (q);
505 pos += ntohs (encoding->sizedmp1);
506 pos += ntohs (encoding->sizedmq1);
508 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
511 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
512 &((const unsigned char *) (&encoding[1]))[pos], size,
516 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
517 gcry_mpi_release (n);
518 gcry_mpi_release (e);
519 gcry_mpi_release (d);
521 gcry_mpi_release (p);
523 gcry_mpi_release (q);
530 if ((p != NULL) && (q != NULL) && (u != NULL))
532 rc = gcry_sexp_build (&res, &size, /* erroff */
533 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
538 if ((p != NULL) && (q != NULL))
540 rc = gcry_sexp_build (&res, &size, /* erroff */
541 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
546 rc = gcry_sexp_build (&res, &size, /* erroff */
547 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
550 gcry_mpi_release (n);
551 gcry_mpi_release (e);
552 gcry_mpi_release (d);
554 gcry_mpi_release (p);
556 gcry_mpi_release (q);
558 gcry_mpi_release (u);
561 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
563 if (gcry_pk_testkey (res))
565 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
569 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
576 * Create a new private key. Caller must free return value.
578 * @return fresh private key
580 static struct GNUNET_CRYPTO_RsaPrivateKey *
583 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
585 gcry_sexp_t s_keyparam;
588 gcry_sexp_build (&s_keyparam, NULL,
589 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
591 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
592 gcry_sexp_release (s_keyparam);
594 GNUNET_assert (0 == gcry_pk_testkey (s_key));
596 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
603 * Try to read the private key from the given file.
605 * @param filename file to read the key from
606 * @return NULL on error
608 static struct GNUNET_CRYPTO_RsaPrivateKey *
609 try_read_key (const char *filename)
611 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
612 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
613 struct GNUNET_DISK_FileHandle *fd;
617 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
620 /* hostkey file exists already, read it! */
621 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
622 GNUNET_DISK_PERM_NONE)))
624 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
627 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
629 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
630 (void) GNUNET_DISK_file_close (fd);
635 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
640 LOG (GNUNET_ERROR_TYPE_ERROR,
641 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
643 (unsigned long long) fs);
644 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
645 if (0 != UNLINK (filename))
646 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
650 enc = GNUNET_malloc (fs);
651 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
652 len = ntohs (enc->len);
655 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
657 LOG (GNUNET_ERROR_TYPE_ERROR,
658 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
660 (unsigned long long) fs);
661 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
662 if (0 != UNLINK (filename))
663 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
669 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
675 * Wait for a short time (we're trying to lock a file or want
676 * to give another process a shot at finishing a disk write, etc.).
677 * Sleeps for 100ms (as that should be long enough for virtually all
678 * modern systems to context switch and allow another process to do
684 struct GNUNET_TIME_Relative timeout;
686 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
687 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
692 * Create a new private key by reading it from a file. If the
693 * files does not exist, create a new key and write it to the
694 * file. Caller must free return value. Note that this function
695 * can not guarantee that another process might not be trying
696 * the same operation on the same file at the same time.
697 * If the contents of the file
698 * are invalid the old file is deleted and a fresh key is
701 * @return new private key, NULL on error (for example,
704 struct GNUNET_CRYPTO_RsaPrivateKey *
705 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
707 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
708 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
710 struct GNUNET_DISK_FileHandle *fd;
714 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
715 struct GNUNET_PeerIdentity pid;
717 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
719 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
721 fd = GNUNET_DISK_file_open (filename,
722 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
723 | GNUNET_DISK_OPEN_FAILIFEXISTS,
724 GNUNET_DISK_PERM_USER_READ |
725 GNUNET_DISK_PERM_USER_WRITE);
730 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
732 /* must exist but not be accessible, fail for good! */
733 if (0 != ACCESS (filename, R_OK))
734 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
736 GNUNET_break (0); /* what is going on!? */
741 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
747 GNUNET_DISK_file_lock (fd, 0,
748 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
755 LOG (GNUNET_ERROR_TYPE_ERROR,
756 _("Could not acquire lock on file `%s': %s...\n"), filename,
760 LOG (GNUNET_ERROR_TYPE_INFO,
761 _("Creating a new private key. This may take a while.\n"));
762 ret = rsa_key_create ();
763 GNUNET_assert (ret != NULL);
764 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
765 GNUNET_assert (enc != NULL);
766 GNUNET_assert (ntohs (enc->len) ==
767 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
770 GNUNET_DISK_file_sync (fd);
772 GNUNET_DISK_file_unlock (fd, 0,
773 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
774 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
775 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
776 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
777 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
778 LOG (GNUNET_ERROR_TYPE_INFO,
779 _("I am host `%s'. Stored new private key in `%s'.\n"),
780 GNUNET_i2s (&pid), filename);
783 /* hostkey file exists already, read it! */
784 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
785 GNUNET_DISK_PERM_NONE);
788 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
795 GNUNET_DISK_file_lock (fd, 0,
796 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
802 LOG (GNUNET_ERROR_TYPE_ERROR,
803 _("Could not acquire lock on file `%s': %s...\n"), filename,
805 LOG (GNUNET_ERROR_TYPE_ERROR,
807 ("This may be ok if someone is currently generating a hostkey.\n"));
812 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
814 /* eh, what!? File we opened is now gone!? */
815 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
817 GNUNET_DISK_file_unlock (fd, 0,
818 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
819 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
820 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
824 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
826 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
828 /* maybe we got the read lock before the hostkey generating
829 * process had a chance to get the write lock; give it up! */
831 GNUNET_DISK_file_unlock (fd, 0,
832 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
833 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
836 LOG (GNUNET_ERROR_TYPE_ERROR,
838 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
839 filename, (unsigned int) fs,
840 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
841 LOG (GNUNET_ERROR_TYPE_ERROR,
843 ("This may be ok if someone is currently generating a hostkey.\n"));
845 short_wait (); /* wait a bit longer! */
850 enc = GNUNET_malloc (fs);
851 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
852 len = ntohs (enc->len);
855 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
857 LOG (GNUNET_ERROR_TYPE_ERROR,
858 _("File `%s' does not contain a valid private key. Deleting it.\n"),
860 if (0 != UNLINK (filename))
862 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
867 GNUNET_DISK_file_unlock (fd, 0,
868 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
869 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
870 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
873 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
874 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
875 LOG (GNUNET_ERROR_TYPE_INFO,
876 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
884 * Handle to cancel private key generation and state for the
885 * key generation operation.
887 struct GNUNET_CRYPTO_RsaKeyGenerationContext
891 * Continuation to call upon completion.
893 GNUNET_CRYPTO_RsaKeyCallback cont;
896 * Closure for 'cont'.
906 * Handle to the helper process which does the key generation.
908 struct GNUNET_OS_Process *gnunet_rsa;
911 * Handle to 'stdout' of gnunet-rsa. We 'read' on stdout to detect
912 * process termination (instead of messing with SIGCHLD).
914 struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
917 * Location where we store the private key if it already existed.
918 * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
921 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
924 * Task reading from 'gnunet_rsa_out' to wait for process termination.
926 GNUNET_SCHEDULER_TaskIdentifier read_task;
932 * Task called upon shutdown or process termination of 'gnunet-rsa' during
933 * RSA key generation. Check where we are and perform the appropriate
936 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
937 * @param tc scheduler context
940 check_key_generation_completion (void *cls,
941 const struct GNUNET_SCHEDULER_TaskContext *tc)
943 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
944 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
946 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
947 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
949 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
950 GNUNET_CRYPTO_rsa_key_create_stop (gc);
953 GNUNET_assert (GNUNET_OK ==
954 GNUNET_OS_process_wait (gc->gnunet_rsa));
955 GNUNET_OS_process_destroy (gc->gnunet_rsa);
956 gc->gnunet_rsa = NULL;
957 if (NULL == (pk = try_read_key (gc->filename)))
960 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
961 GNUNET_CRYPTO_rsa_key_create_stop (gc);
964 gc->cont (gc->cont_cls, pk, NULL);
965 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
966 GNUNET_free (gc->filename);
972 * Return the private RSA key which already existed on disk
973 * (asynchronously) to the caller.
975 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
976 * @param tc scheduler context (unused)
979 async_return_key (void *cls,
980 const struct GNUNET_SCHEDULER_TaskContext *tc)
982 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
984 gc->cont (gc->cont_cls,
992 * Create a new private key by reading it from a file. If the files
993 * does not exist, create a new key and write it to the file. If the
994 * contents of the file are invalid the old file is deleted and a
995 * fresh key is created.
997 * @param filename name of file to use for storage
998 * @param cont function to call when done (or on errors)
999 * @param cont_cls closure for 'cont'
1000 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1002 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1003 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1004 GNUNET_CRYPTO_RsaKeyCallback cont,
1007 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1008 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1009 const char *weak_random;
1011 if (NULL != (pk = try_read_key (filename)))
1013 /* quick happy ending: key already exists! */
1014 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1017 gc->cont_cls = cont_cls;
1018 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1022 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1023 gc->filename = GNUNET_strdup (filename);
1025 gc->cont_cls = cont_cls;
1026 gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1030 if (NULL == gc->gnunet_rsa_out)
1032 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1033 GNUNET_free (gc->filename);
1039 GNUNET_CRYPTO_random_is_weak ())
1041 gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1042 GNUNET_OS_INHERIT_STD_ERR,
1050 if (NULL == gc->gnunet_rsa)
1052 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1053 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1054 GNUNET_free (gc->filename);
1058 GNUNET_assert (GNUNET_OK ==
1059 GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1060 GNUNET_DISK_PIPE_END_WRITE));
1061 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1062 GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1063 GNUNET_DISK_PIPE_END_READ),
1064 &check_key_generation_completion,
1071 * Abort RSA key generation.
1073 * @param gc key generation context to abort
1076 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1078 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1080 GNUNET_SCHEDULER_cancel (gc->read_task);
1081 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1083 if (NULL != gc->gnunet_rsa)
1085 (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1086 GNUNET_break (GNUNET_OK ==
1087 GNUNET_OS_process_wait (gc->gnunet_rsa));
1088 GNUNET_OS_process_destroy (gc->gnunet_rsa);
1089 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1092 if (NULL != gc->filename)
1094 if (0 != UNLINK (gc->filename))
1095 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1096 GNUNET_free (gc->filename);
1099 GNUNET_CRYPTO_rsa_key_free (gc->pk);
1105 * Setup a hostkey file for a peer given the name of the
1106 * configuration file (!). This function is used so that
1107 * at a later point code can be certain that reading a
1108 * hostkey is fast (for example in time-dependent testcases).
1110 * @param cfg_name name of the configuration file to use
1113 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name)
1115 struct GNUNET_CONFIGURATION_Handle *cfg;
1116 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1119 cfg = GNUNET_CONFIGURATION_create ();
1120 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1122 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1124 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1126 GNUNET_CRYPTO_rsa_key_free (pk);
1129 GNUNET_CONFIGURATION_destroy (cfg);
1134 * Encrypt a block with the public key of another host that uses the
1137 * @param block the block to encrypt
1138 * @param size the size of block
1139 * @param publicKey the encoded public key used to encrypt
1140 * @param target where to store the encrypted block
1141 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1144 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1145 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1147 struct GNUNET_CRYPTO_RsaEncryptedData *target)
1151 struct GNUNET_CRYPTO_RsaPrivateKey *pubkey;
1157 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1158 pubkey = public2PrivateKey (publicKey);
1160 return GNUNET_SYSERR;
1163 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1165 gcry_sexp_build (&data, &erroff,
1166 "(data (flags pkcs1)(value %m))", val));
1167 gcry_mpi_release (val);
1168 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, pubkey->sexp));
1169 gcry_sexp_release (data);
1170 GNUNET_CRYPTO_rsa_key_free (pubkey);
1172 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1173 gcry_sexp_release (result);
1174 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1176 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1177 isize, &isize, rval));
1178 gcry_mpi_release (rval);
1179 adjust (&target->encoding[0], isize,
1180 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1186 * Decrypt a given block with the hostkey.
1188 * @param key the key with which to decrypt this block
1189 * @param block the data to decrypt, encoded as returned by encrypt
1190 * @param result pointer to a location where the result can be stored
1191 * @param max the maximum number of bits to store for the result, if
1192 * the decrypted block is bigger, an error is returned
1193 * @return the size of the decrypted block, -1 on error
1196 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1197 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1198 void *result, size_t max)
1200 gcry_sexp_t resultsexp;
1205 unsigned char *endp;
1209 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1211 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1213 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1216 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1218 gcry_mpi_release (val);
1219 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1220 gcry_sexp_release (data);
1221 /* resultsexp has format "(value %m)" */
1222 GNUNET_assert (NULL !=
1223 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1224 gcry_sexp_release (resultsexp);
1225 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1226 size = max + HOSTKEY_LEN / 8;
1227 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1228 gcry_mpi_release (val);
1230 endp += (size - max);
1232 memcpy (result, endp, size);
1239 * Sign a given block.
1241 * @param key private key to use for the signing
1242 * @param purpose what to sign (size, purpose)
1243 * @param sig where to write the signature
1244 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1247 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1248 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1249 struct GNUNET_CRYPTO_RsaSignature *sig)
1255 struct GNUNET_HashCode hc;
1259 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1260 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1261 bufSize = strlen (FORMATSTRING) + 1;
1262 buff = GNUNET_malloc (bufSize);
1263 memcpy (buff, FORMATSTRING, bufSize);
1267 ("0123456789012345678901234567890123456789012345678901234567890123))")
1268 - 1], &hc, sizeof (struct GNUNET_HashCode));
1269 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1271 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1272 gcry_sexp_release (data);
1273 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1274 gcry_sexp_release (result);
1275 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1277 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1279 gcry_mpi_release (rval);
1280 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1288 * @param purpose what is the purpose that the signature should have?
1289 * @param validate block to validate (size, purpose, data)
1290 * @param sig signature that is being validated
1291 * @param publicKey public key of the signer
1292 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1295 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1296 const struct GNUNET_CRYPTO_RsaSignaturePurpose
1298 const struct GNUNET_CRYPTO_RsaSignature *sig,
1299 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1303 gcry_sexp_t sigdata;
1306 struct GNUNET_CRYPTO_RsaPrivateKey *hostkey;
1307 struct GNUNET_HashCode hc;
1313 if (purpose != ntohl (validate->purpose))
1314 return GNUNET_SYSERR; /* purpose mismatch */
1315 GNUNET_CRYPTO_hash (validate, ntohl (validate->size), &hc);
1316 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1318 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1319 (const unsigned char *) sig, size, &size));
1321 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1323 gcry_mpi_release (val);
1324 bufSize = strlen (FORMATSTRING) + 1;
1325 buff = GNUNET_malloc (bufSize);
1326 memcpy (buff, FORMATSTRING, bufSize);
1328 [strlen (FORMATSTRING) -
1330 ("0123456789012345678901234567890123456789012345678901234567890123))")],
1331 &hc, sizeof (struct GNUNET_HashCode));
1332 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1334 hostkey = public2PrivateKey (publicKey);
1335 if (hostkey == NULL)
1337 gcry_sexp_release (data);
1338 gcry_sexp_release (sigdata);
1339 return GNUNET_SYSERR;
1341 rc = gcry_pk_verify (sigdata, data, hostkey->sexp);
1342 GNUNET_CRYPTO_rsa_key_free (hostkey);
1343 gcry_sexp_release (data);
1344 gcry_sexp_release (sigdata);
1347 LOG (GNUNET_ERROR_TYPE_WARNING,
1348 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1349 __LINE__, gcry_strerror (rc));
1350 return GNUNET_SYSERR;
1356 /* end of crypto_rsa.c */