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 RSA private key.
84 * @param key pointer to the memory to free
87 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key)
89 gcry_sexp_release (key->sexp);
95 * Extract values from an S-expression.
97 * @param array where to store the result(s)
98 * @param sexp S-expression to parse
99 * @param topname top-level name in the S-expression that is of interest
100 * @param elems names of the elements to extract
101 * @return 0 on success
104 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
113 if (! (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 if (! (l2 = gcry_sexp_find_token (list, s, 1)))
125 for (i = 0; i < idx; i++)
127 gcry_free (array[i]);
130 gcry_sexp_release (list);
131 return 3; /* required parameter not found */
133 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
134 gcry_sexp_release (l2);
137 for (i = 0; i < idx; i++)
139 gcry_free (array[i]);
142 gcry_sexp_release (list);
143 return 4; /* required parameter is invalid */
146 gcry_sexp_release (list);
152 * 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 * Convert the given public key from the network format to the
263 * S-expression that can be used by libgcrypt.
265 * @param publicKey public key to decode
266 * @return NULL on error
269 decode_public_key (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
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 if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size)))
289 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
292 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
293 if (0 != (rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
294 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
297 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
298 gcry_mpi_release (n);
301 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
303 gcry_mpi_release (n);
304 gcry_mpi_release (e);
307 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
315 * Encode the private key in a format suitable for
316 * storing it into a file.
318 * @returns encoding of the private key.
319 * The first 4 bytes give the size of the array, as usual.
321 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
322 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
324 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
333 if (gcry_pk_testkey (hostkey->sexp))
340 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
341 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
343 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
345 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
347 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
349 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
351 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
352 GNUNET_assert (0 == rc);
353 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
354 for (i = 0; i < 6; i++)
359 gcry_mpi_aprint (GCRYMPI_FMT_USG,
360 (unsigned char **) &pbu[i], &sizes[i],
370 GNUNET_assert (size < 65536);
371 retval = GNUNET_malloc (size);
372 retval->len = htons (size);
374 retval->sizen = htons (sizes[0]);
375 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
377 retval->sizee = htons (sizes[1]);
378 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
380 retval->sized = htons (sizes[2]);
381 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
384 retval->sizep = htons (sizes[4]);
385 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
387 retval->sizeq = htons (sizes[3]);
388 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
390 retval->sizedmp1 = htons (0);
391 retval->sizedmq1 = htons (0);
392 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
393 for (i = 0; i < 6; i++)
396 gcry_mpi_release (pkv[i]);
405 * Decode the private key from the file-format back
406 * to the "normal", internal format.
408 * @param buf the buffer where the private key data is stored
409 * @param len the length of the data in 'buffer'
410 * @return NULL on error
412 struct GNUNET_CRYPTO_RsaPrivateKey *
413 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
415 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
416 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
417 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
431 enc_len = ntohs (encoding->len);
436 size = ntohs (encoding->sizen);
437 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
438 &((const unsigned char *) (&encoding[1]))[pos], size,
440 pos += ntohs (encoding->sizen);
443 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
446 size = ntohs (encoding->sizee);
447 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
448 &((const unsigned char *) (&encoding[1]))[pos], size,
450 pos += ntohs (encoding->sizee);
453 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
454 gcry_mpi_release (n);
457 size = ntohs (encoding->sized);
458 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
459 &((const unsigned char *) (&encoding[1]))[pos], size,
461 pos += ntohs (encoding->sized);
464 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
465 gcry_mpi_release (n);
466 gcry_mpi_release (e);
470 size = ntohs (encoding->sizep);
473 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
474 &((const unsigned char *) (&encoding[1]))[pos], size,
476 pos += ntohs (encoding->sizep);
479 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
480 gcry_mpi_release (n);
481 gcry_mpi_release (e);
482 gcry_mpi_release (d);
488 size = ntohs (encoding->sizeq);
491 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
492 &((const unsigned char *) (&encoding[1]))[pos], size,
494 pos += ntohs (encoding->sizeq);
497 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
498 gcry_mpi_release (n);
499 gcry_mpi_release (e);
500 gcry_mpi_release (d);
502 gcry_mpi_release (q);
508 pos += ntohs (encoding->sizedmp1);
509 pos += ntohs (encoding->sizedmq1);
511 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
514 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
515 &((const unsigned char *) (&encoding[1]))[pos], size,
519 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
520 gcry_mpi_release (n);
521 gcry_mpi_release (e);
522 gcry_mpi_release (d);
524 gcry_mpi_release (p);
526 gcry_mpi_release (q);
533 if ((NULL != p) && (NULL != q) && (NULL != u))
535 rc = gcry_sexp_build (&res, &erroff,
536 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
541 if ((NULL != p) && (NULL != q))
543 rc = gcry_sexp_build (&res, &erroff,
544 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
549 rc = gcry_sexp_build (&res, &erroff,
550 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
553 gcry_mpi_release (n);
554 gcry_mpi_release (e);
555 gcry_mpi_release (d);
557 gcry_mpi_release (p);
559 gcry_mpi_release (q);
561 gcry_mpi_release (u);
564 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
566 if (0 != (rc = gcry_pk_testkey (res)))
568 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
572 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
579 * Create a new private key. Caller must free return value.
581 * @return fresh private key
583 static struct GNUNET_CRYPTO_RsaPrivateKey *
586 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
588 gcry_sexp_t s_keyparam;
591 gcry_sexp_build (&s_keyparam, NULL,
592 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
594 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
595 gcry_sexp_release (s_keyparam);
597 GNUNET_assert (0 == gcry_pk_testkey (s_key));
599 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
606 * Try to read the private key from the given file.
608 * @param filename file to read the key from
609 * @return NULL on error
611 static struct GNUNET_CRYPTO_RsaPrivateKey *
612 try_read_key (const char *filename)
614 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
615 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
616 struct GNUNET_DISK_FileHandle *fd;
620 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
623 /* hostkey file exists already, read it! */
624 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
625 GNUNET_DISK_PERM_NONE)))
627 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
630 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
632 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
633 (void) GNUNET_DISK_file_close (fd);
638 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
643 LOG (GNUNET_ERROR_TYPE_ERROR,
644 _("File `%s' does not contain a valid private key (too long, %llu bytes). Deleting it.\n"),
646 (unsigned long long) fs);
647 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
648 if (0 != UNLINK (filename))
649 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
653 enc = GNUNET_malloc (fs);
654 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
655 len = ntohs (enc->len);
658 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
660 LOG (GNUNET_ERROR_TYPE_ERROR,
661 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
663 (unsigned long long) fs);
664 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
665 if (0 != UNLINK (filename))
666 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
672 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
678 * Wait for a short time (we're trying to lock a file or want
679 * to give another process a shot at finishing a disk write, etc.).
680 * Sleeps for 100ms (as that should be long enough for virtually all
681 * modern systems to context switch and allow another process to do
687 struct GNUNET_TIME_Relative timeout;
689 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
690 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
695 * Create a new private key by reading it from a file. If the
696 * files does not exist, create a new key and write it to the
697 * file. Caller must free return value. Note that this function
698 * can not guarantee that another process might not be trying
699 * the same operation on the same file at the same time.
700 * If the contents of the file
701 * are invalid the old file is deleted and a fresh key is
704 * @return new private key, NULL on error (for example,
707 struct GNUNET_CRYPTO_RsaPrivateKey *
708 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
710 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
711 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
713 struct GNUNET_DISK_FileHandle *fd;
717 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
718 struct GNUNET_PeerIdentity pid;
720 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
722 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
724 fd = GNUNET_DISK_file_open (filename,
725 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
726 | GNUNET_DISK_OPEN_FAILIFEXISTS,
727 GNUNET_DISK_PERM_USER_READ |
728 GNUNET_DISK_PERM_USER_WRITE);
733 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
735 /* must exist but not be accessible, fail for good! */
736 if (0 != ACCESS (filename, R_OK))
737 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
739 GNUNET_break (0); /* what is going on!? */
744 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
750 GNUNET_DISK_file_lock (fd, 0,
751 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
758 LOG (GNUNET_ERROR_TYPE_ERROR,
759 _("Could not acquire lock on file `%s': %s...\n"), filename,
763 LOG (GNUNET_ERROR_TYPE_INFO,
764 _("Creating a new private key. This may take a while.\n"));
765 ret = rsa_key_create ();
766 GNUNET_assert (ret != NULL);
767 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
768 GNUNET_assert (enc != NULL);
769 GNUNET_assert (ntohs (enc->len) ==
770 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
773 GNUNET_DISK_file_sync (fd);
775 GNUNET_DISK_file_unlock (fd, 0,
776 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
777 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
778 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
779 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
780 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
781 LOG (GNUNET_ERROR_TYPE_INFO,
782 _("I am host `%s'. Stored new private key in `%s'.\n"),
783 GNUNET_i2s (&pid), filename);
786 /* hostkey file exists already, read it! */
787 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
788 GNUNET_DISK_PERM_NONE);
791 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
798 GNUNET_DISK_file_lock (fd, 0,
799 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
805 LOG (GNUNET_ERROR_TYPE_ERROR,
806 _("Could not acquire lock on file `%s': %s...\n"), filename,
808 LOG (GNUNET_ERROR_TYPE_ERROR,
810 ("This may be ok if someone is currently generating a hostkey.\n"));
815 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
817 /* eh, what!? File we opened is now gone!? */
818 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
820 GNUNET_DISK_file_unlock (fd, 0,
821 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
822 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
823 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
827 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
829 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
831 /* maybe we got the read lock before the hostkey generating
832 * process had a chance to get the write lock; give it up! */
834 GNUNET_DISK_file_unlock (fd, 0,
835 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
836 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
839 LOG (GNUNET_ERROR_TYPE_ERROR,
841 ("When trying to read hostkey file `%s' I found %u bytes but I need at least %u.\n"),
842 filename, (unsigned int) fs,
843 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
844 LOG (GNUNET_ERROR_TYPE_ERROR,
846 ("This may be ok if someone is currently generating a hostkey.\n"));
848 short_wait (); /* wait a bit longer! */
853 enc = GNUNET_malloc (fs);
854 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
855 len = ntohs (enc->len);
858 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
860 LOG (GNUNET_ERROR_TYPE_ERROR,
861 _("File `%s' does not contain a valid private key. Deleting it.\n"),
863 if (0 != UNLINK (filename))
865 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", filename);
870 GNUNET_DISK_file_unlock (fd, 0,
871 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
872 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
873 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
876 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
877 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
878 LOG (GNUNET_ERROR_TYPE_INFO,
879 _("I am host `%s'. Read private key from `%s'.\n"), GNUNET_i2s (&pid),
887 * Handle to cancel private key generation and state for the
888 * key generation operation.
890 struct GNUNET_CRYPTO_RsaKeyGenerationContext
894 * Continuation to call upon completion.
896 GNUNET_CRYPTO_RsaKeyCallback cont;
899 * Closure for 'cont'.
909 * Handle to the helper process which does the key generation.
911 struct GNUNET_OS_Process *gnunet_rsa;
914 * Handle to 'stdout' of gnunet-rsa. We 'read' on stdout to detect
915 * process termination (instead of messing with SIGCHLD).
917 struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
920 * Location where we store the private key if it already existed.
921 * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
924 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
927 * Task reading from 'gnunet_rsa_out' to wait for process termination.
929 GNUNET_SCHEDULER_TaskIdentifier read_task;
935 * Task called upon shutdown or process termination of 'gnunet-rsa' during
936 * RSA key generation. Check where we are and perform the appropriate
939 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
940 * @param tc scheduler context
943 check_key_generation_completion (void *cls,
944 const struct GNUNET_SCHEDULER_TaskContext *tc)
946 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
947 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
949 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
950 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
952 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
953 GNUNET_CRYPTO_rsa_key_create_stop (gc);
956 GNUNET_assert (GNUNET_OK ==
957 GNUNET_OS_process_wait (gc->gnunet_rsa));
958 GNUNET_OS_process_destroy (gc->gnunet_rsa);
959 gc->gnunet_rsa = NULL;
960 if (NULL == (pk = try_read_key (gc->filename)))
963 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
964 GNUNET_CRYPTO_rsa_key_create_stop (gc);
967 gc->cont (gc->cont_cls, pk, NULL);
968 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
969 GNUNET_free (gc->filename);
975 * Return the private RSA key which already existed on disk
976 * (asynchronously) to the caller.
978 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
979 * @param tc scheduler context (unused)
982 async_return_key (void *cls,
983 const struct GNUNET_SCHEDULER_TaskContext *tc)
985 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
987 gc->cont (gc->cont_cls,
995 * Create a new private key by reading it from a file. If the files
996 * does not exist, create a new key and write it to the file. If the
997 * contents of the file are invalid the old file is deleted and a
998 * fresh key is created.
1000 * @param filename name of file to use for storage
1001 * @param cont function to call when done (or on errors)
1002 * @param cont_cls closure for 'cont'
1003 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1005 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1006 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1007 GNUNET_CRYPTO_RsaKeyCallback cont,
1010 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1011 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1012 const char *weak_random;
1014 if (NULL != (pk = try_read_key (filename)))
1016 /* quick happy ending: key already exists! */
1017 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1020 gc->cont_cls = cont_cls;
1021 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1025 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1026 gc->filename = GNUNET_strdup (filename);
1028 gc->cont_cls = cont_cls;
1029 gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1033 if (NULL == gc->gnunet_rsa_out)
1035 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1036 GNUNET_free (gc->filename);
1042 GNUNET_CRYPTO_random_is_weak ())
1044 gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1045 GNUNET_OS_INHERIT_STD_ERR,
1053 if (NULL == gc->gnunet_rsa)
1055 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1056 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1057 GNUNET_free (gc->filename);
1061 GNUNET_assert (GNUNET_OK ==
1062 GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1063 GNUNET_DISK_PIPE_END_WRITE));
1064 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1065 GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1066 GNUNET_DISK_PIPE_END_READ),
1067 &check_key_generation_completion,
1074 * Abort RSA key generation.
1076 * @param gc key generation context to abort
1079 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1081 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1083 GNUNET_SCHEDULER_cancel (gc->read_task);
1084 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1086 if (NULL != gc->gnunet_rsa)
1088 (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1089 GNUNET_break (GNUNET_OK ==
1090 GNUNET_OS_process_wait (gc->gnunet_rsa));
1091 GNUNET_OS_process_destroy (gc->gnunet_rsa);
1092 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1095 if (NULL != gc->filename)
1097 if (0 != UNLINK (gc->filename))
1098 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1099 GNUNET_free (gc->filename);
1102 GNUNET_CRYPTO_rsa_key_free (gc->pk);
1108 * Setup a hostkey file for a peer given the name of the
1109 * configuration file (!). This function is used so that
1110 * at a later point code can be certain that reading a
1111 * hostkey is fast (for example in time-dependent testcases).
1113 * @param cfg_name name of the configuration file to use
1116 GNUNET_CRYPTO_rsa_setup_hostkey (const char *cfg_name)
1118 struct GNUNET_CONFIGURATION_Handle *cfg;
1119 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1122 cfg = GNUNET_CONFIGURATION_create ();
1123 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1125 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1127 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1129 GNUNET_CRYPTO_rsa_key_free (pk);
1132 GNUNET_CONFIGURATION_destroy (cfg);
1137 * Encrypt a block with the public key of another host that uses the
1140 * @param block the block to encrypt
1141 * @param size the size of block
1142 * @param publicKey the encoded public key used to encrypt
1143 * @param target where to store the encrypted block
1144 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1147 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1148 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1150 struct GNUNET_CRYPTO_RsaEncryptedData *target)
1160 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1161 if (! (psexp = decode_public_key (publicKey)))
1162 return GNUNET_SYSERR;
1165 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1167 gcry_sexp_build (&data, &erroff,
1168 "(data (flags pkcs1)(value %m))", val));
1169 gcry_mpi_release (val);
1170 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, psexp));
1171 gcry_sexp_release (data);
1172 gcry_sexp_release (psexp);
1173 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "a"));
1174 gcry_sexp_release (result);
1175 isize = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1177 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) target,
1178 isize, &isize, rval));
1179 gcry_mpi_release (rval);
1180 adjust (&target->encoding[0], isize,
1181 sizeof (struct GNUNET_CRYPTO_RsaEncryptedData));
1187 * Decrypt a given block with the hostkey.
1189 * @param key the key with which to decrypt this block
1190 * @param block the data to decrypt, encoded as returned by encrypt
1191 * @param result pointer to a location where the result can be stored
1192 * @param max the maximum number of bits to store for the result, if
1193 * the decrypted block is bigger, an error is returned
1194 * @return the size of the decrypted block, -1 on error
1197 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey * key,
1198 const struct GNUNET_CRYPTO_RsaEncryptedData * block,
1199 void *result, size_t max)
1201 gcry_sexp_t resultsexp;
1206 unsigned char *endp;
1210 GNUNET_assert (0 == gcry_pk_testkey (key->sexp));
1212 size = sizeof (struct GNUNET_CRYPTO_RsaEncryptedData);
1214 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, &block->encoding[0],
1217 gcry_sexp_build (&data, &erroff, "(enc-val(flags)(rsa(a %m)))",
1219 gcry_mpi_release (val);
1220 GNUNET_assert (0 == gcry_pk_decrypt (&resultsexp, data, key->sexp));
1221 gcry_sexp_release (data);
1222 /* resultsexp has format "(value %m)" */
1223 GNUNET_assert (NULL !=
1224 (val = gcry_sexp_nth_mpi (resultsexp, 1, GCRYMPI_FMT_USG)));
1225 gcry_sexp_release (resultsexp);
1226 tmp = GNUNET_malloc (max + HOSTKEY_LEN / 8);
1227 size = max + HOSTKEY_LEN / 8;
1228 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG, tmp, size, &size, val));
1229 gcry_mpi_release (val);
1231 endp += (size - max);
1233 memcpy (result, endp, size);
1240 * Convert the data specified in the given purpose argument to an
1241 * S-expression suitable for signature operations.
1243 * @param purpose data to convert
1244 * @return converted s-expression
1247 data_to_pkcs1 (const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose)
1249 struct GNUNET_HashCode hc;
1253 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1254 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1255 bufSize = strlen (FORMATSTRING) + 1;
1259 memcpy (buff, FORMATSTRING, bufSize);
1263 ("0123456789012345678901234567890123456789012345678901234567890123))")
1264 - 1], &hc, sizeof (struct GNUNET_HashCode));
1265 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1273 * Sign a given block.
1275 * @param key private key to use for the signing
1276 * @param purpose what to sign (size, purpose)
1277 * @param sig where to write the signature
1278 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1281 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1282 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1283 struct GNUNET_CRYPTO_RsaSignature *sig)
1290 data = data_to_pkcs1 (purpose);
1291 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1292 gcry_sexp_release (data);
1293 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1294 gcry_sexp_release (result);
1295 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1297 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1299 gcry_mpi_release (rval);
1300 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1308 * @param purpose what is the purpose that the signature should have?
1309 * @param validate block to validate (size, purpose, data)
1310 * @param sig signature that is being validated
1311 * @param publicKey public key of the signer
1312 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1315 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1316 const struct GNUNET_CRYPTO_RsaSignaturePurpose
1318 const struct GNUNET_CRYPTO_RsaSignature *sig,
1319 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1323 gcry_sexp_t sigdata;
1330 if (purpose != ntohl (validate->purpose))
1331 return GNUNET_SYSERR; /* purpose mismatch */
1332 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1334 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1335 (const unsigned char *) sig, size, &size));
1337 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1339 gcry_mpi_release (val);
1340 data = data_to_pkcs1 (validate);
1341 if (! (psexp = decode_public_key (publicKey)))
1343 gcry_sexp_release (data);
1344 gcry_sexp_release (sigdata);
1345 return GNUNET_SYSERR;
1347 rc = gcry_pk_verify (sigdata, data, psexp);
1348 gcry_sexp_release (psexp);
1349 gcry_sexp_release (data);
1350 gcry_sexp_release (sigdata);
1353 LOG (GNUNET_ERROR_TYPE_WARNING,
1354 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1355 __LINE__, gcry_strerror (rc));
1356 return GNUNET_SYSERR;
1362 /* end of crypto_rsa.c */