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 * Get hash of the public key that corresponds to a private key.
200 * @param key RSA private key
201 * @param id buffer for hash of the public key
204 GNUNET_CRYPTO_rsa_get_public_key_hash (struct GNUNET_CRYPTO_RsaPrivateKey *key,
205 struct GNUNET_HashCode *id)
207 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
208 GNUNET_CRYPTO_rsa_key_get_public (key, &pk);
209 GNUNET_CRYPTO_hash (&pk, sizeof (pk), id);
214 * Convert a public key to a string.
216 * @param pub key to convert
217 * @return string representing 'pub'
220 GNUNET_CRYPTO_rsa_public_key_to_string (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
223 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
227 keylen += 5 - keylen % 5;
229 pubkeybuf = GNUNET_malloc (keylen + 1);
230 end = GNUNET_STRINGS_data_to_string ((unsigned char *) pub,
231 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
236 GNUNET_free (pubkeybuf);
245 * Convert a string representing a public key to a public key.
247 * @param enc encoded public key
248 * @param enclen number of bytes in enc (without 0-terminator)
249 * @param pub where to store the public key
250 * @return GNUNET_OK on success
253 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc,
255 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub)
257 size_t keylen = (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) * 8;
260 keylen += 5 - keylen % 5;
262 if (enclen != keylen)
263 return GNUNET_SYSERR;
265 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (enc, enclen,
266 (unsigned char*) pub,
267 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)))
268 return GNUNET_SYSERR;
269 if ( (ntohs (pub->len) != sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded)) ||
270 (ntohs (pub->padding) != 0) ||
271 (ntohs (pub->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) )
272 return GNUNET_SYSERR;
278 * Convert the given public key from the network format to the
279 * S-expression that can be used by libgcrypt.
281 * @param publicKey public key to decode
282 * @return NULL on error
285 decode_public_key (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
294 if ((ntohs (publicKey->sizen) != GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH) ||
295 (ntohs (publicKey->len) !=
296 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) -
297 sizeof (publicKey->padding)))
302 size = GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
303 if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG, &publicKey->key[0], size, &size)))
305 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
308 size = GNUNET_CRYPTO_RSA_KEY_LENGTH - GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH;
309 if (0 != (rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
310 &publicKey->key[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH],
313 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
314 gcry_mpi_release (n);
317 rc = gcry_sexp_build (&result, &erroff, "(public-key(rsa(n %m)(e %m)))", n,
319 gcry_mpi_release (n);
320 gcry_mpi_release (e);
323 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); /* erroff gives more info */
331 * Encode the private key in a format suitable for
332 * storing it into a file.
334 * @return encoding of the private key.
335 * The first 4 bytes give the size of the array, as usual.
337 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
338 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey)
340 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *retval;
349 if (gcry_pk_testkey (hostkey->sexp))
356 memset (pkv, 0, sizeof (gcry_mpi_t) * 6);
357 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpqu");
359 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpqu");
361 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "nedpq");
363 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "nedpq");
365 rc = key_from_sexp (pkv, hostkey->sexp, "private-key", "ned");
367 rc = key_from_sexp (pkv, hostkey->sexp, "rsa", "ned");
368 GNUNET_assert (0 == rc);
369 size = sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded);
370 for (i = 0; i < 6; i++)
375 gcry_mpi_aprint (GCRYMPI_FMT_USG,
376 (unsigned char **) &pbu[i], &sizes[i],
386 GNUNET_assert (size < 65536);
387 retval = GNUNET_malloc (size);
388 retval->len = htons (size);
390 retval->sizen = htons (sizes[0]);
391 memcpy (&((char *) (&retval[1]))[i], pbu[0], sizes[0]);
393 retval->sizee = htons (sizes[1]);
394 memcpy (&((char *) (&retval[1]))[i], pbu[1], sizes[1]);
396 retval->sized = htons (sizes[2]);
397 memcpy (&((char *) (&retval[1]))[i], pbu[2], sizes[2]);
400 retval->sizep = htons (sizes[4]);
401 memcpy (&((char *) (&retval[1]))[i], pbu[4], sizes[4]);
403 retval->sizeq = htons (sizes[3]);
404 memcpy (&((char *) (&retval[1]))[i], pbu[3], sizes[3]);
406 retval->sizedmp1 = htons (0);
407 retval->sizedmq1 = htons (0);
408 memcpy (&((char *) (&retval[1]))[i], pbu[5], sizes[5]);
409 for (i = 0; i < 6; i++)
412 gcry_mpi_release (pkv[i]);
421 * Decode the private key from the file-format back
422 * to the "normal", internal format.
424 * @param buf the buffer where the private key data is stored
425 * @param len the length of the data in 'buffer'
426 * @return NULL on error
428 struct GNUNET_CRYPTO_RsaPrivateKey *
429 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len)
431 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
432 const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *encoding =
433 (const struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *) buf;
447 enc_len = ntohs (encoding->len);
452 size = ntohs (encoding->sizen);
453 rc = gcry_mpi_scan (&n, GCRYMPI_FMT_USG,
454 &((const unsigned char *) (&encoding[1]))[pos], size,
456 pos += ntohs (encoding->sizen);
459 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
462 size = ntohs (encoding->sizee);
463 rc = gcry_mpi_scan (&e, GCRYMPI_FMT_USG,
464 &((const unsigned char *) (&encoding[1]))[pos], size,
466 pos += ntohs (encoding->sizee);
469 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
470 gcry_mpi_release (n);
473 size = ntohs (encoding->sized);
474 rc = gcry_mpi_scan (&d, GCRYMPI_FMT_USG,
475 &((const unsigned char *) (&encoding[1]))[pos], size,
477 pos += ntohs (encoding->sized);
480 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
481 gcry_mpi_release (n);
482 gcry_mpi_release (e);
486 size = ntohs (encoding->sizep);
489 rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
490 &((const unsigned char *) (&encoding[1]))[pos], size,
492 pos += ntohs (encoding->sizep);
495 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
496 gcry_mpi_release (n);
497 gcry_mpi_release (e);
498 gcry_mpi_release (d);
504 size = ntohs (encoding->sizeq);
507 rc = gcry_mpi_scan (&p, GCRYMPI_FMT_USG,
508 &((const unsigned char *) (&encoding[1]))[pos], size,
510 pos += ntohs (encoding->sizeq);
513 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
514 gcry_mpi_release (n);
515 gcry_mpi_release (e);
516 gcry_mpi_release (d);
518 gcry_mpi_release (q);
524 pos += ntohs (encoding->sizedmp1);
525 pos += ntohs (encoding->sizedmq1);
527 ntohs (encoding->len) - sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded) - pos;
530 rc = gcry_mpi_scan (&u, GCRYMPI_FMT_USG,
531 &((const unsigned char *) (&encoding[1]))[pos], size,
535 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
536 gcry_mpi_release (n);
537 gcry_mpi_release (e);
538 gcry_mpi_release (d);
540 gcry_mpi_release (p);
542 gcry_mpi_release (q);
549 if ((NULL != p) && (NULL != q) && (NULL != u))
551 rc = gcry_sexp_build (&res, &erroff,
552 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)(u %m)))",
557 if ((NULL != p) && (NULL != q))
559 rc = gcry_sexp_build (&res, &erroff,
560 "(private-key(rsa(n %m)(e %m)(d %m)(p %m)(q %m)))",
565 rc = gcry_sexp_build (&res, &erroff,
566 "(private-key(rsa(n %m)(e %m)(d %m)))", n, e, d);
569 gcry_mpi_release (n);
570 gcry_mpi_release (e);
571 gcry_mpi_release (d);
573 gcry_mpi_release (p);
575 gcry_mpi_release (q);
577 gcry_mpi_release (u);
580 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
582 if (0 != (rc = gcry_pk_testkey (res)))
584 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
588 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
595 * Create a new private key. Caller must free return value.
597 * @return fresh private key
599 static struct GNUNET_CRYPTO_RsaPrivateKey *
602 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
604 gcry_sexp_t s_keyparam;
607 gcry_sexp_build (&s_keyparam, NULL,
608 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
610 GNUNET_assert (0 == gcry_pk_genkey (&s_key, s_keyparam));
611 gcry_sexp_release (s_keyparam);
613 GNUNET_assert (0 == gcry_pk_testkey (s_key));
615 ret = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPrivateKey));
622 * Try to read the private key from the given file.
624 * @param filename file to read the key from
625 * @return NULL on error
627 static struct GNUNET_CRYPTO_RsaPrivateKey *
628 try_read_key (const char *filename)
630 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
631 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
632 struct GNUNET_DISK_FileHandle *fd;
636 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
639 /* hostkey file exists already, read it! */
640 if (NULL == (fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
641 GNUNET_DISK_PERM_NONE)))
643 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
646 if (GNUNET_OK != (GNUNET_DISK_file_handle_size (fd, &fs)))
648 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "stat", filename);
649 (void) GNUNET_DISK_file_close (fd);
654 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
659 LOG (GNUNET_ERROR_TYPE_ERROR,
660 _("File `%s' does not contain a valid private key (too long, %llu bytes). Renaming it.\n"),
662 (unsigned long long) fs);
663 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
664 GNUNET_DISK_file_backup (filename);
668 enc = GNUNET_malloc (fs);
669 GNUNET_break (fs == GNUNET_DISK_file_read (fd, enc, fs));
670 len = ntohs (enc->len);
673 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
675 LOG (GNUNET_ERROR_TYPE_ERROR,
676 _("File `%s' does not contain a valid private key (failed decode, %llu bytes). Deleting it.\n"),
678 (unsigned long long) fs);
679 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
680 GNUNET_DISK_file_backup (filename);
686 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fd));
692 * Wait for a short time (we're trying to lock a file or want
693 * to give another process a shot at finishing a disk write, etc.).
694 * Sleeps for 100ms (as that should be long enough for virtually all
695 * modern systems to context switch and allow another process to do
701 struct GNUNET_TIME_Relative timeout;
703 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
704 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
709 * Create a new private key by reading it from a file. If the
710 * files does not exist, create a new key and write it to the
711 * file. Caller must free return value. Note that this function
712 * can not guarantee that another process might not be trying
713 * the same operation on the same file at the same time.
714 * If the contents of the file
715 * are invalid the old file is deleted and a fresh key is
718 * @return new private key, NULL on error (for example,
721 struct GNUNET_CRYPTO_RsaPrivateKey *
722 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename)
724 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
725 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
727 struct GNUNET_DISK_FileHandle *fd;
731 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
732 struct GNUNET_PeerIdentity pid;
734 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename))
736 while (GNUNET_YES != GNUNET_DISK_file_test (filename))
738 fd = GNUNET_DISK_file_open (filename,
739 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE
740 | GNUNET_DISK_OPEN_FAILIFEXISTS,
741 GNUNET_DISK_PERM_USER_READ |
742 GNUNET_DISK_PERM_USER_WRITE);
747 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
749 /* must exist but not be accessible, fail for good! */
750 if (0 != ACCESS (filename, R_OK))
751 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
753 GNUNET_break (0); /* what is going on!? */
758 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
764 GNUNET_DISK_file_lock (fd, 0,
765 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
772 LOG (GNUNET_ERROR_TYPE_ERROR,
773 _("Could not acquire lock on file `%s': %s...\n"), filename,
777 LOG (GNUNET_ERROR_TYPE_INFO,
778 _("Creating a new private key. This may take a while.\n"));
779 ret = rsa_key_create ();
780 GNUNET_assert (ret != NULL);
781 enc = GNUNET_CRYPTO_rsa_encode_key (ret);
782 GNUNET_assert (enc != NULL);
783 GNUNET_assert (ntohs (enc->len) ==
784 GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
787 GNUNET_DISK_file_sync (fd);
789 GNUNET_DISK_file_unlock (fd, 0,
790 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
791 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
792 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
793 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
794 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
797 /* hostkey file exists already, read it! */
798 fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_READ,
799 GNUNET_DISK_PERM_NONE);
802 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
809 GNUNET_DISK_file_lock (fd, 0,
810 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded),
816 LOG (GNUNET_ERROR_TYPE_ERROR,
817 _("Could not acquire lock on file `%s': %s...\n"), filename,
819 LOG (GNUNET_ERROR_TYPE_ERROR,
821 ("This may be ok if someone is currently generating a private key.\n"));
826 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
828 /* eh, what!? File we opened is now gone!? */
829 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
831 GNUNET_DISK_file_unlock (fd, 0,
832 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
833 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
834 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
838 if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES))
840 if (fs < sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded))
842 /* maybe we got the read lock before the key generating
843 * process had a chance to get the write lock; give it up! */
845 GNUNET_DISK_file_unlock (fd, 0,
846 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
847 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
850 LOG (GNUNET_ERROR_TYPE_ERROR,
852 ("When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
853 filename, (unsigned int) fs,
854 (unsigned int) sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded));
855 LOG (GNUNET_ERROR_TYPE_ERROR,
857 ("This may be ok if someone is currently generating a private key.\n"));
859 short_wait (); /* wait a bit longer! */
864 enc = GNUNET_malloc (fs);
865 GNUNET_assert (fs == GNUNET_DISK_file_read (fd, enc, fs));
866 len = ntohs (enc->len);
869 (NULL == (ret = GNUNET_CRYPTO_rsa_decode_key ((char *) enc, len))))
871 LOG (GNUNET_ERROR_TYPE_ERROR,
872 _("File `%s' does not contain a valid private key. Deleting it.\n"),
874 GNUNET_DISK_file_backup (filename);
878 GNUNET_DISK_file_unlock (fd, 0,
879 sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
880 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
881 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
884 GNUNET_CRYPTO_rsa_key_get_public (ret, &pub);
885 GNUNET_CRYPTO_hash (&pub, sizeof (pub), &pid.hashPubKey);
892 * Handle to cancel private key generation and state for the
893 * key generation operation.
895 struct GNUNET_CRYPTO_RsaKeyGenerationContext
899 * Continuation to call upon completion.
901 GNUNET_CRYPTO_RsaKeyCallback cont;
904 * Closure for 'cont'.
914 * Handle to the helper process which does the key generation.
916 struct GNUNET_OS_Process *gnunet_rsa;
919 * Handle to 'stdout' of gnunet-rsa. We 'read' on stdout to detect
920 * process termination (instead of messing with SIGCHLD).
922 struct GNUNET_DISK_PipeHandle *gnunet_rsa_out;
925 * Location where we store the private key if it already existed.
926 * (if this is used, 'filename', 'gnunet_rsa' and 'gnunet_rsa_out' will
929 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
932 * Task reading from 'gnunet_rsa_out' to wait for process termination.
934 GNUNET_SCHEDULER_TaskIdentifier read_task;
940 * Task called upon shutdown or process termination of 'gnunet-rsa' during
941 * RSA key generation. Check where we are and perform the appropriate
944 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
945 * @param tc scheduler context
948 check_key_generation_completion (void *cls,
949 const struct GNUNET_SCHEDULER_TaskContext *tc)
951 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
952 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
954 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
955 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
957 gc->cont (gc->cont_cls, NULL, _("interrupted by shutdown"));
958 GNUNET_CRYPTO_rsa_key_create_stop (gc);
961 GNUNET_assert (GNUNET_OK ==
962 GNUNET_OS_process_wait (gc->gnunet_rsa));
963 GNUNET_OS_process_destroy (gc->gnunet_rsa);
964 gc->gnunet_rsa = NULL;
965 if (NULL == (pk = try_read_key (gc->filename)))
968 gc->cont (gc->cont_cls, NULL, _("gnunet-rsa failed"));
969 GNUNET_CRYPTO_rsa_key_create_stop (gc);
972 gc->cont (gc->cont_cls, pk, NULL);
973 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
974 GNUNET_free (gc->filename);
980 * Return the private RSA key which already existed on disk
981 * (asynchronously) to the caller.
983 * @param cls the 'struct GNUNET_CRYPTO_RsaKeyGenerationContext'
984 * @param tc scheduler context (unused)
987 async_return_key (void *cls,
988 const struct GNUNET_SCHEDULER_TaskContext *tc)
990 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc = cls;
992 gc->cont (gc->cont_cls,
1000 * Create a new private key by reading it from a file. If the files
1001 * does not exist, create a new key and write it to the file. If the
1002 * contents of the file are invalid the old file is deleted and a
1003 * fresh key is created.
1005 * @param filename name of file to use for storage
1006 * @param cont function to call when done (or on errors)
1007 * @param cont_cls closure for 'cont'
1008 * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1010 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1011 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1012 GNUNET_CRYPTO_RsaKeyCallback cont,
1015 struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc;
1016 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1018 if (NULL != (pk = try_read_key (filename)))
1020 /* quick happy ending: key already exists! */
1021 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1024 gc->cont_cls = cont_cls;
1025 gc->read_task = GNUNET_SCHEDULER_add_now (&async_return_key,
1029 gc = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaKeyGenerationContext));
1030 gc->filename = GNUNET_strdup (filename);
1032 gc->cont_cls = cont_cls;
1033 gc->gnunet_rsa_out = GNUNET_DISK_pipe (GNUNET_NO,
1037 if (NULL == gc->gnunet_rsa_out)
1039 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "pipe");
1040 GNUNET_free (gc->filename);
1044 gc->gnunet_rsa = GNUNET_OS_start_process (GNUNET_NO,
1045 GNUNET_OS_INHERIT_STD_ERR,
1052 if (NULL == gc->gnunet_rsa)
1054 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fork");
1055 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1056 GNUNET_free (gc->filename);
1060 GNUNET_assert (GNUNET_OK ==
1061 GNUNET_DISK_pipe_close_end (gc->gnunet_rsa_out,
1062 GNUNET_DISK_PIPE_END_WRITE));
1063 gc->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1064 GNUNET_DISK_pipe_handle (gc->gnunet_rsa_out,
1065 GNUNET_DISK_PIPE_END_READ),
1066 &check_key_generation_completion,
1073 * Abort RSA key generation.
1075 * @param gc key generation context to abort
1078 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc)
1080 if (GNUNET_SCHEDULER_NO_TASK != gc->read_task)
1082 GNUNET_SCHEDULER_cancel (gc->read_task);
1083 gc->read_task = GNUNET_SCHEDULER_NO_TASK;
1085 if (NULL != gc->gnunet_rsa)
1087 (void) GNUNET_OS_process_kill (gc->gnunet_rsa, SIGKILL);
1088 GNUNET_break (GNUNET_OK ==
1089 GNUNET_OS_process_wait (gc->gnunet_rsa));
1090 GNUNET_OS_process_destroy (gc->gnunet_rsa);
1091 GNUNET_DISK_pipe_close (gc->gnunet_rsa_out);
1094 if (NULL != gc->filename)
1096 if (0 != UNLINK (gc->filename))
1097 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", gc->filename);
1098 GNUNET_free (gc->filename);
1101 GNUNET_CRYPTO_rsa_key_free (gc->pk);
1107 * Setup a key file for a peer given the name of the
1108 * configuration file (!). This function is used so that
1109 * at a later point code can be certain that reading a
1110 * key is fast (for example in time-dependent testcases).
1112 * @param cfg_name name of the configuration file to use
1115 GNUNET_CRYPTO_rsa_setup_hostkey (const char *cfg_name)
1117 struct GNUNET_CONFIGURATION_Handle *cfg;
1118 struct GNUNET_CRYPTO_RsaPrivateKey *pk;
1121 cfg = GNUNET_CONFIGURATION_create ();
1122 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name);
1124 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY", &fn))
1126 pk = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
1128 GNUNET_CRYPTO_rsa_key_free (pk);
1131 GNUNET_CONFIGURATION_destroy (cfg);
1136 * Encrypt a block with the public key of another host that uses the
1139 * @param block the block to encrypt
1140 * @param size the size of block
1141 * @param publicKey the encoded public key used to encrypt
1142 * @param target where to store the encrypted block
1143 * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1146 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1147 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1149 struct GNUNET_CRYPTO_RsaEncryptedData *target)
1159 GNUNET_assert (size <= sizeof (struct GNUNET_HashCode));
1160 if (! (psexp = decode_public_key (publicKey)))
1161 return GNUNET_SYSERR;
1164 gcry_mpi_scan (&val, GCRYMPI_FMT_USG, block, isize, &isize));
1166 gcry_sexp_build (&data, &erroff,
1167 "(data (flags pkcs1)(value %m))", val));
1168 gcry_mpi_release (val);
1169 GNUNET_assert (0 == gcry_pk_encrypt (&result, data, psexp));
1170 gcry_sexp_release (data);
1171 gcry_sexp_release (psexp);
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 key.
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 * Convert the data specified in the given purpose argument to an
1240 * S-expression suitable for signature operations.
1242 * @param purpose data to convert
1243 * @return converted s-expression
1246 data_to_pkcs1 (const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose)
1248 struct GNUNET_HashCode hc;
1252 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc);
1253 #define FORMATSTRING "(4:data(5:flags5:pkcs1)(4:hash6:sha51264:0123456789012345678901234567890123456789012345678901234567890123))"
1254 bufSize = strlen (FORMATSTRING) + 1;
1258 memcpy (buff, FORMATSTRING, bufSize);
1262 ("0123456789012345678901234567890123456789012345678901234567890123))")
1263 - 1], &hc, sizeof (struct GNUNET_HashCode));
1264 GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1272 * Sign a given block.
1274 * @param key private key to use for the signing
1275 * @param purpose what to sign (size, purpose)
1276 * @param sig where to write the signature
1277 * @return GNUNET_SYSERR on error, GNUNET_OK on success
1280 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1281 const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1282 struct GNUNET_CRYPTO_RsaSignature *sig)
1289 data = data_to_pkcs1 (purpose);
1290 GNUNET_assert (0 == gcry_pk_sign (&result, data, key->sexp));
1291 gcry_sexp_release (data);
1292 GNUNET_assert (0 == key_from_sexp (&rval, result, "rsa", "s"));
1293 gcry_sexp_release (result);
1294 ssize = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1296 gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) sig, ssize,
1298 gcry_mpi_release (rval);
1299 adjust (sig->sig, ssize, sizeof (struct GNUNET_CRYPTO_RsaSignature));
1307 * @param purpose what is the purpose that the signature should have?
1308 * @param validate block to validate (size, purpose, data)
1309 * @param sig signature that is being validated
1310 * @param publicKey public key of the signer
1311 * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1314 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1315 const struct GNUNET_CRYPTO_RsaSignaturePurpose
1317 const struct GNUNET_CRYPTO_RsaSignature *sig,
1318 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1322 gcry_sexp_t sigdata;
1329 if (purpose != ntohl (validate->purpose))
1330 return GNUNET_SYSERR; /* purpose mismatch */
1331 size = sizeof (struct GNUNET_CRYPTO_RsaSignature);
1333 gcry_mpi_scan (&val, GCRYMPI_FMT_USG,
1334 (const unsigned char *) sig, size, &size));
1336 gcry_sexp_build (&sigdata, &erroff, "(sig-val(rsa(s %m)))",
1338 gcry_mpi_release (val);
1339 data = data_to_pkcs1 (validate);
1340 if (! (psexp = decode_public_key (publicKey)))
1342 gcry_sexp_release (data);
1343 gcry_sexp_release (sigdata);
1344 return GNUNET_SYSERR;
1346 rc = gcry_pk_verify (sigdata, data, psexp);
1347 gcry_sexp_release (psexp);
1348 gcry_sexp_release (data);
1349 gcry_sexp_release (sigdata);
1352 LOG (GNUNET_ERROR_TYPE_WARNING,
1353 _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1354 __LINE__, gcry_strerror (rc));
1355 return GNUNET_SYSERR;
1361 /* end of crypto_rsa.c */