1 /* cvt-openpgp.c - Convert an OpenPGP key to our internal format.
2 * Copyright (C) 1998-2002, 2006, 2009, 2010 Free Software Foundation, Inc.
3 * Copyright (C) 2013, 2014 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
29 #include "cvt-openpgp.h"
33 /* Helper to pass data via the callback to do_unprotect. */
34 struct try_do_unprotect_arg_s
56 /* Compute the keygrip from the public key and store it at GRIP. */
58 get_keygrip (int pubkey_algo, const char *curve, gcry_mpi_t *pkey,
62 gcry_sexp_t s_pkey = NULL;
67 err = gcry_sexp_build (&s_pkey, NULL,
68 "(public-key(dsa(p%m)(q%m)(g%m)(y%m)))",
69 pkey[0], pkey[1], pkey[2], pkey[3]);
73 err = gcry_sexp_build (&s_pkey, NULL,
74 "(public-key(elg(p%m)(g%m)(y%m)))",
75 pkey[0], pkey[1], pkey[2]);
79 err = gcry_sexp_build (&s_pkey, NULL,
80 "(public-key(rsa(n%m)(e%m)))", pkey[0], pkey[1]);
85 err = gpg_error (GPG_ERR_BAD_SECKEY);
90 if (!strcmp (curve, "Ed25519"))
91 format = "(public-key(ecc(curve %s)(flags eddsa)(q%m)))";
92 else if (!strcmp (curve, "Curve25519"))
93 format = "(public-key(ecc(curve %s)(flags djb-tweak)(q%m)))";
95 format = "(public-key(ecc(curve %s)(q%m)))";
97 err = gcry_sexp_build (&s_pkey, NULL, format, curve, pkey[0]);
102 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
106 if (!err && !gcry_pk_get_keygrip (s_pkey, grip))
107 err = gpg_error (GPG_ERR_INTERNAL);
109 gcry_sexp_release (s_pkey);
114 /* Convert a secret key given as algorithm id and an array of key
115 parameters into our s-expression based format. Note that
116 PUBKEY_ALGO has an gcrypt algorithm number. */
118 convert_secret_key (gcry_sexp_t *r_key, int pubkey_algo, gcry_mpi_t *skey,
122 gcry_sexp_t s_skey = NULL;
129 err = gcry_sexp_build (&s_skey, NULL,
130 "(private-key(dsa(p%m)(q%m)(g%m)(y%m)(x%m)))",
131 skey[0], skey[1], skey[2], skey[3], skey[4]);
136 err = gcry_sexp_build (&s_skey, NULL,
137 "(private-key(elg(p%m)(g%m)(y%m)(x%m)))",
138 skey[0], skey[1], skey[2], skey[3]);
145 err = gcry_sexp_build (&s_skey, NULL,
146 "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
147 skey[0], skey[1], skey[2], skey[3], skey[4],
153 err = gpg_error (GPG_ERR_BAD_SECKEY);
158 if (!strcmp (curve, "Ed25519"))
159 /* Do not store the OID as name but the real name and the
161 format = "(private-key(ecc(curve %s)(flags eddsa)(q%m)(d%m)))";
162 else if (!strcmp (curve, "Curve25519"))
163 format = "(private-key(ecc(curve %s)(flags djb-tweak)(q%m)(d%m)))";
165 format = "(private-key(ecc(curve %s)(q%m)(d%m)))";
167 err = gcry_sexp_build (&s_skey, NULL, format, curve, skey[0], skey[1]);
172 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
182 /* Convert a secret key given as algorithm id, an array of key
183 parameters, and an S-expression of the original OpenPGP transfer
184 key into our s-expression based format. This is a variant of
185 convert_secret_key which is used for the openpgp-native protection
186 mode. Note that PUBKEY_ALGO has an gcrypt algorithm number. */
188 convert_transfer_key (gcry_sexp_t *r_key, int pubkey_algo, gcry_mpi_t *skey,
189 const char *curve, gcry_sexp_t transfer_key)
192 gcry_sexp_t s_skey = NULL;
199 err = gcry_sexp_build
201 "(protected-private-key(dsa(p%m)(q%m)(g%m)(y%m)"
202 "(protected openpgp-native%S)))",
203 skey[0], skey[1], skey[2], skey[3], transfer_key);
207 err = gcry_sexp_build
209 "(protected-private-key(elg(p%m)(g%m)(y%m)"
210 "(protected openpgp-native%S)))",
211 skey[0], skey[1], skey[2], transfer_key);
216 err = gcry_sexp_build
218 "(protected-private-key(rsa(n%m)(e%m)"
219 "(protected openpgp-native%S)))",
220 skey[0], skey[1], transfer_key );
225 err = gpg_error (GPG_ERR_BAD_SECKEY);
230 if (!strcmp (curve, "Ed25519"))
231 /* Do not store the OID as name but the real name and the
233 format = "(protected-private-key(ecc(curve %s)(flags eddsa)(q%m)"
234 "(protected openpgp-native%S)))";
235 else if (!strcmp (curve, "Curve25519"))
236 format = "(protected-private-key(ecc(curve %s)(flags djb-tweak)(q%m)"
237 "(protected openpgp-native%S)))";
239 format = "(protected-private-key(ecc(curve %s)(q%m)"
240 "(protected openpgp-native%S)))";
242 err = gcry_sexp_build (&s_skey, NULL, format, curve, skey[0], transfer_key);
247 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
257 /* Hash the passphrase and set the key. */
259 hash_passphrase_and_set_key (const char *passphrase,
260 gcry_cipher_hd_t hd, int protect_algo,
261 int s2k_mode, int s2k_algo,
262 byte *s2k_salt, u32 s2k_count)
268 keylen = gcry_cipher_get_algo_keylen (protect_algo);
270 return gpg_error (GPG_ERR_INTERNAL);
272 key = xtrymalloc_secure (keylen);
274 return gpg_error_from_syserror ();
276 err = s2k_hash_passphrase (passphrase,
277 s2k_algo, s2k_mode, s2k_salt, s2k_count,
280 err = gcry_cipher_setkey (hd, key, keylen);
288 checksum (const unsigned char *p, unsigned int n)
298 /* Return the number of expected key parameters. */
300 get_npkey_nskey (int pubkey_algo, size_t *npkey, size_t *nskey)
304 case GCRY_PK_RSA: *npkey = 2; *nskey = 6; break;
305 case GCRY_PK_ELG: *npkey = 3; *nskey = 4; break;
306 case GCRY_PK_ELG_E: *npkey = 3; *nskey = 4; break;
307 case GCRY_PK_DSA: *npkey = 4; *nskey = 5; break;
308 case GCRY_PK_ECC: *npkey = 1; *nskey = 2; break;
309 default: *npkey = 0; *nskey = 0; break;
314 /* Helper for do_unprotect. PUBKEY_ALOGO is the gcrypt algo number.
315 On success R_NPKEY and R_NSKEY receive the number or parameters for
316 the algorithm PUBKEY_ALGO and R_SKEYLEN the used length of
319 prepare_unprotect (int pubkey_algo, gcry_mpi_t *skey, size_t skeysize,
321 unsigned int *r_npkey, unsigned int *r_nskey,
322 unsigned int *r_skeylen)
324 size_t npkey, nskey, skeylen;
327 /* Count the actual number of MPIs is in the array and set the
328 remainder to NULL for easier processing later on. */
329 for (skeylen = 0; skey[skeylen]; skeylen++)
331 for (i=skeylen; i < skeysize; i++)
334 /* Check some args. */
335 if (s2k_mode == 1001)
338 log_info (_("secret key parts are not available\n"));
339 return gpg_error (GPG_ERR_UNUSABLE_SECKEY);
342 if (gcry_pk_test_algo (pubkey_algo))
344 log_info (_("public key algorithm %d (%s) is not supported\n"),
345 pubkey_algo, gcry_pk_algo_name (pubkey_algo));
346 return gpg_error (GPG_ERR_PUBKEY_ALGO);
349 /* Get properties of the public key algorithm and do some
350 consistency checks. Note that we need at least NPKEY+1 elements
351 in the SKEY array. */
352 get_npkey_nskey (pubkey_algo, &npkey, &nskey);
353 if (!npkey || !nskey || npkey >= nskey)
354 return gpg_error (GPG_ERR_INTERNAL);
355 if (skeylen <= npkey)
356 return gpg_error (GPG_ERR_MISSING_VALUE);
357 if (nskey+1 >= skeysize)
358 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
360 /* Check that the public key parameters are all available and not
362 for (i=0; i < npkey; i++)
364 if (!skey[i] || gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_USER1))
365 return gpg_error (GPG_ERR_BAD_SECKEY);
373 *r_skeylen = skeylen;
378 /* Note that this function modifies SKEY. SKEYSIZE is the allocated
379 size of the array including the NULL item; this is used for a
380 bounds check. On success a converted key is stored at R_KEY. */
382 do_unprotect (const char *passphrase,
383 int pkt_version, int pubkey_algo, int is_protected,
384 const char *curve, gcry_mpi_t *skey, size_t skeysize,
385 int protect_algo, void *protect_iv, size_t protect_ivlen,
386 int s2k_mode, int s2k_algo, byte *s2k_salt, u32 s2k_count,
387 u16 desired_csum, gcry_sexp_t *r_key)
390 unsigned int npkey, nskey, skeylen;
391 gcry_cipher_hd_t cipher_hd = NULL;
399 err = prepare_unprotect (pubkey_algo, skey, skeysize, s2k_mode,
400 &npkey, &nskey, &skeylen);
404 /* Check whether SKEY is at all protected. If it is not protected
405 merely verify the checksum. */
409 for (i=npkey; i < nskey; i++)
411 if (!skey[i] || gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_USER1))
412 return gpg_error (GPG_ERR_BAD_SECKEY);
414 if (gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_OPAQUE))
417 const unsigned char *buffer;
418 buffer = gcry_mpi_get_opaque (skey[i], &nbits);
419 nbytes = (nbits+7)/8;
420 actual_csum += checksum (buffer, nbytes);
424 unsigned char *buffer;
426 err = gcry_mpi_aprint (GCRYMPI_FMT_PGP, &buffer, &nbytes,
429 actual_csum += checksum (buffer, nbytes);
436 if (actual_csum != desired_csum)
437 return gpg_error (GPG_ERR_CHECKSUM);
443 if (gcry_cipher_test_algo (protect_algo))
445 /* The algorithm numbers are Libgcrypt numbers but fortunately
446 the OpenPGP algorithm numbers map one-to-one to the Libgcrypt
448 log_info (_("protection algorithm %d (%s) is not supported\n"),
449 protect_algo, gnupg_cipher_algo_name (protect_algo));
450 return gpg_error (GPG_ERR_CIPHER_ALGO);
453 if (gcry_md_test_algo (s2k_algo))
455 log_info (_("protection hash algorithm %d (%s) is not supported\n"),
456 s2k_algo, gcry_md_algo_name (s2k_algo));
457 return gpg_error (GPG_ERR_DIGEST_ALGO);
460 err = gcry_cipher_open (&cipher_hd, protect_algo,
461 GCRY_CIPHER_MODE_CFB,
463 | (protect_algo >= 100 ?
464 0 : GCRY_CIPHER_ENABLE_SYNC)));
467 log_error ("failed to open cipher_algo %d: %s\n",
468 protect_algo, gpg_strerror (err));
472 err = hash_passphrase_and_set_key (passphrase, cipher_hd, protect_algo,
473 s2k_mode, s2k_algo, s2k_salt, s2k_count);
476 gcry_cipher_close (cipher_hd);
480 gcry_cipher_setiv (cipher_hd, protect_iv, protect_ivlen);
483 if (pkt_version >= 4)
486 unsigned int ndatabits;
487 const unsigned char *p;
491 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE ))
493 gcry_cipher_close (cipher_hd);
494 return gpg_error (GPG_ERR_BAD_SECKEY);
496 p = gcry_mpi_get_opaque (skey[npkey], &ndatabits);
497 ndata = (ndatabits+7)/8;
500 csum_pgp7 = buf16_to_u16 (p+ndata-2);
501 data = xtrymalloc_secure (ndata);
504 err = gpg_error_from_syserror ();
505 gcry_cipher_close (cipher_hd);
508 gcry_cipher_decrypt (cipher_hd, data, ndata, p, ndata);
511 if (is_protected == 2)
513 /* This is the new SHA1 checksum method to detect tampering
514 with the key as used by the Klima/Rosa attack. */
516 actual_csum = 1; /* Default to bad checksum. */
519 log_error ("not enough bytes for SHA-1 checksum\n");
524 if (gcry_md_open (&h, GCRY_MD_SHA1, 1))
525 BUG(); /* Algo not available. */
526 gcry_md_write (h, data, ndata - 20);
528 if (!memcmp (gcry_md_read (h, GCRY_MD_SHA1), data+ndata-20, 20))
529 actual_csum = 0; /* Digest does match. */
535 /* Old 16 bit checksum method. */
538 log_error ("not enough bytes for checksum\n");
540 actual_csum = 1; /* Mark checksum bad. */
544 desired_csum = buf16_to_u16 (data+ndata-2);
545 actual_csum = checksum (data, ndata-2);
546 if (desired_csum != actual_csum)
548 /* This is a PGP 7.0.0 workaround */
549 desired_csum = csum_pgp7; /* Take the encrypted one. */
554 /* Better check it here. Otherwise the gcry_mpi_scan would fail
555 because the length may have an arbitrary value. */
556 if (desired_csum == actual_csum)
558 for (i=npkey; i < nskey; i++ )
560 if (gcry_mpi_scan (&tmpmpi, GCRYMPI_FMT_PGP, p, ndata, &nbytes))
562 /* Checksum was okay, but not correctly decrypted. */
564 actual_csum = 1; /* Mark checksum bad. */
567 gcry_mpi_release (skey[i]);
574 assert (skeylen <= skeysize);
576 /* Note: at this point NDATA should be 2 for a simple
577 checksum or 20 for the sha1 digest. */
581 else /* Packet version <= 3. */
583 unsigned char *buffer;
585 for (i = npkey; i < nskey; i++)
587 const unsigned char *p;
589 unsigned int ndatabits;
591 if (!skey[i] || !gcry_mpi_get_flag (skey[i], GCRYMPI_FLAG_OPAQUE))
593 gcry_cipher_close (cipher_hd);
594 return gpg_error (GPG_ERR_BAD_SECKEY);
596 p = gcry_mpi_get_opaque (skey[i], &ndatabits);
597 ndata = (ndatabits+7)/8;
599 if (!(ndata >= 2) || !(ndata == (buf16_to_ushort (p) + 7)/8 + 2))
601 gcry_cipher_close (cipher_hd);
602 return gpg_error (GPG_ERR_BAD_SECKEY);
605 buffer = xtrymalloc_secure (ndata);
608 err = gpg_error_from_syserror ();
609 gcry_cipher_close (cipher_hd);
613 gcry_cipher_sync (cipher_hd);
616 gcry_cipher_decrypt (cipher_hd, buffer+2, ndata-2, p+2, ndata-2);
617 actual_csum += checksum (buffer, ndata);
618 err = gcry_mpi_scan (&tmpmpi, GCRYMPI_FMT_PGP, buffer, ndata, &ndata);
622 /* Checksum was okay, but not correctly decrypted. */
624 actual_csum = 1; /* Mark checksum bad. */
627 gcry_mpi_release (skey[i]);
631 gcry_cipher_close (cipher_hd);
633 /* Now let's see whether we have used the correct passphrase. */
634 if (actual_csum != desired_csum)
635 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
638 if (nskey != skeylen)
639 err = gpg_error (GPG_ERR_BAD_SECKEY);
641 err = convert_secret_key (r_key, pubkey_algo, skey, curve);
645 /* The checksum may fail, thus we also check the key itself. */
646 err = gcry_pk_testkey (*r_key);
649 gcry_sexp_release (*r_key);
651 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
658 /* Callback function to try the unprotection from the passphrase query
661 try_do_unprotect_cb (struct pin_entry_info_s *pi)
664 struct try_do_unprotect_arg_s *arg = pi->check_cb_arg;
666 err = do_unprotect (pi->pin,
668 arg->pubkey_algo, arg->is_protected,
670 arg->skey, arg->skeysize,
671 arg->protect_algo, arg->iv, arg->ivlen,
672 arg->s2k_mode, arg->s2k_algo,
673 arg->s2k_salt, arg->s2k_count,
674 arg->desired_csum, arg->r_key);
675 /* SKEY may be modified now, thus we need to re-compute SKEYIDX. */
676 for (arg->skeyidx = 0; (arg->skeyidx < arg->skeysize
677 && arg->skey[arg->skeyidx]); arg->skeyidx++)
683 /* See convert_from_openpgp for the core of the description. This
684 function adds an optional PASSPHRASE argument and uses this to
685 silently decrypt the key; CACHE_NONCE and R_PASSPHRASE must both be
686 NULL in this mode. */
688 convert_from_openpgp_main (ctrl_t ctrl, gcry_sexp_t s_pgp, int dontcare_exist,
689 unsigned char *grip, const char *prompt,
690 const char *cache_nonce, const char *passphrase,
691 unsigned char **r_key, char **r_passphrase)
696 gcry_sexp_t top_list;
697 gcry_sexp_t list = NULL;
702 int is_v4, is_protected;
704 int protect_algo = 0;
712 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
716 gcry_sexp_t s_skey = NULL;
720 *r_passphrase = NULL;
721 unattended = !r_passphrase;
722 from_native = (!cache_nonce && passphrase && !r_passphrase);
724 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
728 list = gcry_sexp_find_token (top_list, "version", 0);
731 value = gcry_sexp_nth_data (list, 1, &valuelen);
732 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
734 is_v4 = (value[0] == '4');
736 gcry_sexp_release (list);
737 list = gcry_sexp_find_token (top_list, "protection", 0);
740 value = gcry_sexp_nth_data (list, 1, &valuelen);
743 if (valuelen == 4 && !memcmp (value, "sha1", 4))
745 else if (valuelen == 3 && !memcmp (value, "sum", 3))
747 else if (valuelen == 4 && !memcmp (value, "none", 4))
754 string = gcry_sexp_nth_string (list, 2);
757 protect_algo = gcry_cipher_map_name (string);
760 value = gcry_sexp_nth_data (list, 3, &valuelen);
761 if (!value || !valuelen || valuelen > sizeof iv)
763 memcpy (iv, value, valuelen);
766 string = gcry_sexp_nth_string (list, 4);
769 s2k_mode = strtol (string, NULL, 10);
772 string = gcry_sexp_nth_string (list, 5);
775 s2k_algo = gcry_md_map_name (string);
778 value = gcry_sexp_nth_data (list, 6, &valuelen);
779 if (!value || !valuelen || valuelen > sizeof s2k_salt)
781 memcpy (s2k_salt, value, valuelen);
783 string = gcry_sexp_nth_string (list, 7);
786 s2k_count = strtoul (string, NULL, 10);
790 gcry_sexp_release (list);
791 list = gcry_sexp_find_token (top_list, "algo", 0);
794 string = gcry_sexp_nth_string (list, 1);
797 pubkey_algo = gcry_pk_map_name (string);
800 get_npkey_nskey (pubkey_algo, &npkey, &nskey);
801 if (!npkey || !nskey || npkey >= nskey)
804 if (npkey == 1) /* This is ECC */
806 gcry_sexp_release (list);
807 list = gcry_sexp_find_token (top_list, "curve", 0);
810 curve = gcry_sexp_nth_string (list, 1);
815 gcry_sexp_release (list);
816 list = gcry_sexp_find_token (top_list, "skey", 0);
823 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
824 if (!value && skeyidx >= npkey)
827 /* Check for too many parameters. Note that depending on the
828 protection mode and version number we may see less than NSKEY
829 (but at least NPKEY+1) parameters. */
832 if (skeyidx >= DIM (skey)-1)
835 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
837 is_enc = (value[0] == 'e');
838 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
839 if (!value || !valuelen)
843 /* Encrypted parameters need to be stored as opaque. */
844 skey[skeyidx] = gcry_mpi_set_opaque_copy (NULL, value, valuelen*8);
847 gcry_mpi_set_flag (skey[skeyidx], GCRYMPI_FLAG_USER1);
851 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
852 value, valuelen, NULL))
857 skey[skeyidx++] = NULL;
859 gcry_sexp_release (list);
860 list = gcry_sexp_find_token (top_list, "csum", 0);
863 string = gcry_sexp_nth_string (list, 1);
866 desired_csum = strtoul (string, NULL, 10);
873 gcry_sexp_release (list); list = NULL;
874 gcry_sexp_release (top_list); top_list = NULL;
877 log_debug ("XXX is_v4=%d\n", is_v4);
878 log_debug ("XXX pubkey_algo=%d\n", pubkey_algo);
879 log_debug ("XXX is_protected=%d\n", is_protected);
880 log_debug ("XXX protect_algo=%d\n", protect_algo);
881 log_printhex ("XXX iv", iv, ivlen);
882 log_debug ("XXX ivlen=%d\n", ivlen);
883 log_debug ("XXX s2k_mode=%d\n", s2k_mode);
884 log_debug ("XXX s2k_algo=%d\n", s2k_algo);
885 log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt);
886 log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count);
887 log_debug ("XXX curve='%s'\n", curve);
888 for (idx=0; skey[idx]; idx++)
889 gcry_log_debugmpi (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_USER1)
890 ? "skey(e)" : "skey(_)", skey[idx]);
893 err = get_keygrip (pubkey_algo, curve, skey, grip);
897 if (!dontcare_exist && !from_native && !agent_key_available (grip))
899 err = gpg_error (GPG_ERR_EEXIST);
903 if (unattended && !from_native)
905 err = prepare_unprotect (pubkey_algo, skey, DIM(skey), s2k_mode,
910 err = convert_transfer_key (&s_skey, pubkey_algo, skey, curve, s_pgp);
916 struct pin_entry_info_s *pi;
917 struct try_do_unprotect_arg_s pi_arg;
919 pi = xtrycalloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
921 return gpg_error_from_syserror ();
922 pi->max_length = MAX_PASSPHRASE_LEN + 1;
923 pi->min_digits = 0; /* We want a real passphrase. */
926 pi->check_cb = try_do_unprotect_cb;
927 pi->check_cb_arg = &pi_arg;
928 pi_arg.is_v4 = is_v4;
929 pi_arg.is_protected = is_protected;
930 pi_arg.pubkey_algo = pubkey_algo;
931 pi_arg.curve = curve;
932 pi_arg.protect_algo = protect_algo;
934 pi_arg.ivlen = ivlen;
935 pi_arg.s2k_mode = s2k_mode;
936 pi_arg.s2k_algo = s2k_algo;
937 pi_arg.s2k_salt = s2k_salt;
938 pi_arg.s2k_count = s2k_count;
939 pi_arg.desired_csum = desired_csum;
941 pi_arg.skeysize = DIM (skey);
942 pi_arg.skeyidx = skeyidx;
943 pi_arg.r_key = &s_skey;
945 err = gpg_error (GPG_ERR_BAD_PASSPHRASE);
948 err = try_do_unprotect_cb (pi);
950 else if (cache_nonce)
954 cache_value = agent_get_cache (cache_nonce, CACHE_MODE_NONCE);
957 if (strlen (cache_value) < pi->max_length)
958 strcpy (pi->pin, cache_value);
962 err = try_do_unprotect_cb (pi);
964 else if (from_native)
966 if (strlen (passphrase) < pi->max_length)
967 strcpy (pi->pin, passphrase);
968 err = try_do_unprotect_cb (pi);
970 if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE && !from_native)
971 err = agent_askpin (ctrl, prompt, NULL, NULL, pi, NULL, 0);
972 skeyidx = pi_arg.skeyidx;
973 if (!err && r_passphrase && is_protected)
975 *r_passphrase = xtrystrdup (pi->pin);
977 err = gpg_error_from_syserror ();
984 /* Save some memory and get rid of the SKEY array now. */
985 for (idx=0; idx < skeyidx; idx++)
986 gcry_mpi_release (skey[idx]);
989 /* Note that the padding is not required - we use it only because
990 that function allows us to create the result in secure memory. */
991 err = make_canon_sexp_pad (s_skey, 1, r_key, NULL);
995 gcry_sexp_release (s_skey);
996 gcry_sexp_release (list);
997 gcry_sexp_release (top_list);
998 for (idx=0; idx < skeyidx; idx++)
999 gcry_mpi_release (skey[idx]);
1000 if (err && r_passphrase)
1002 xfree (*r_passphrase);
1003 *r_passphrase = NULL;
1008 err = gpg_error (GPG_ERR_BAD_SECKEY);
1012 err = gpg_error (GPG_ERR_ENOMEM);
1018 /* Convert an OpenPGP transfer key into our internal format. Before
1019 asking for a passphrase we check whether the key already exists in
1020 our key storage. S_PGP is the OpenPGP key in transfer format. If
1021 CACHE_NONCE is given the passphrase will be looked up in the cache.
1022 On success R_KEY will receive a canonical encoded S-expression with
1023 the unprotected key in our internal format; the caller needs to
1024 release that memory. The passphrase used to decrypt the OpenPGP
1025 key will be returned at R_PASSPHRASE; the caller must release this
1026 passphrase. If R_PASSPHRASE is NULL the unattended conversion mode
1027 will be used which uses the openpgp-native protection format for
1028 the key. The keygrip will be stored at the 20 byte buffer pointed
1029 to by GRIP. On error NULL is stored at all return arguments. */
1031 convert_from_openpgp (ctrl_t ctrl, gcry_sexp_t s_pgp, int dontcare_exist,
1032 unsigned char *grip, const char *prompt,
1033 const char *cache_nonce,
1034 unsigned char **r_key, char **r_passphrase)
1036 return convert_from_openpgp_main (ctrl, s_pgp, dontcare_exist, grip, prompt,
1038 r_key, r_passphrase);
1041 /* This function is called by agent_unprotect to re-protect an
1042 openpgp-native protected private-key into the standard private-key
1043 protection format. */
1045 convert_from_openpgp_native (ctrl_t ctrl,
1046 gcry_sexp_t s_pgp, const char *passphrase,
1047 unsigned char **r_key)
1050 unsigned char grip[20];
1053 return gpg_error (GPG_ERR_INTERNAL);
1055 err = convert_from_openpgp_main (ctrl, s_pgp, 0, grip, NULL,
1059 /* On success try to re-write the key. */
1064 unsigned char *protectedkey = NULL;
1065 size_t protectedkeylen;
1067 if (!agent_protect (*r_key, passphrase,
1068 &protectedkey, &protectedkeylen,
1070 agent_write_private_key (grip, protectedkey, protectedkeylen, 1);
1071 xfree (protectedkey);
1075 /* Empty passphrase: write key without protection. */
1076 agent_write_private_key (grip,
1078 gcry_sexp_canon_len (*r_key, 0, NULL,NULL),
1087 /* Given an ARRAY of mpis with the key parameters, protect the secret
1088 parameters in that array and replace them by one opaque encoded
1089 mpi. NPKEY is the number of public key parameters and NSKEY is
1090 the number of secret key parameters (including the public ones).
1091 On success the array will have NPKEY+1 elements. */
1093 apply_protection (gcry_mpi_t *array, int npkey, int nskey,
1094 const char *passphrase,
1095 int protect_algo, void *protect_iv, size_t protect_ivlen,
1096 int s2k_mode, int s2k_algo, byte *s2k_salt, u32 s2k_count)
1100 gcry_cipher_hd_t cipherhd;
1101 unsigned char *bufarr[10];
1103 unsigned int nbits[10];
1105 unsigned char *p, *data;
1107 assert (npkey < nskey);
1108 assert (nskey < DIM (bufarr));
1110 /* Collect only the secret key parameters into BUFARR et al and
1111 compute the required size of the data buffer. */
1112 ndata = 20; /* Space for the SHA-1 checksum. */
1113 for (i = npkey, j = 0; i < nskey; i++, j++ )
1115 err = gcry_mpi_aprint (GCRYMPI_FMT_USG, bufarr+j, narr+j, array[i]);
1118 for (i = 0; i < j; i++)
1122 nbits[j] = gcry_mpi_get_nbits (array[i]);
1123 ndata += 2 + narr[j];
1126 /* Allocate data buffer and stuff it with the secret key parameters. */
1127 data = xtrymalloc_secure (ndata);
1130 err = gpg_error_from_syserror ();
1131 for (i = 0; i < (nskey-npkey); i++ )
1136 for (i = 0; i < (nskey-npkey); i++ )
1138 *p++ = nbits[i] >> 8 ;
1140 memcpy (p, bufarr[i], narr[i]);
1145 assert (p == data + ndata - 20);
1147 /* Append a hash of the secret key parameters. */
1148 gcry_md_hash_buffer (GCRY_MD_SHA1, p, data, ndata - 20);
1151 err = gcry_cipher_open (&cipherhd, protect_algo,
1152 GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_SECURE);
1154 err = hash_passphrase_and_set_key (passphrase, cipherhd, protect_algo,
1155 s2k_mode, s2k_algo, s2k_salt, s2k_count);
1157 err = gcry_cipher_setiv (cipherhd, protect_iv, protect_ivlen);
1159 err = gcry_cipher_encrypt (cipherhd, data, ndata, NULL, 0);
1160 gcry_cipher_close (cipherhd);
1167 /* Replace the secret key parameters in the array by one opaque value. */
1168 for (i = npkey; i < nskey; i++ )
1170 gcry_mpi_release (array[i]);
1173 array[npkey] = gcry_mpi_set_opaque (NULL, data, ndata*8);
1179 * Examining S_KEY in S-Expression and extract data.
1180 * When REQ_PRIVATE_KEY_DATA == 1, S_KEY's CAR should be 'private-key',
1181 * but it also allows shadowed or protected versions.
1182 * On success, it returns 0, otherwise error number.
1183 * R_ALGONAME is static string which is no need to free by caller.
1184 * R_NPKEY is pointer to number of public key data.
1185 * R_NSKEY is pointer to number of private key data.
1186 * R_ELEMS is static string which is no need to free by caller.
1187 * ARRAY contains public and private key data.
1188 * ARRAYSIZE is the allocated size of the array for cross-checking.
1189 * R_CURVE is pointer to S-Expression of the curve (can be NULL).
1190 * R_FLAGS is pointer to S-Expression of the flags (can be NULL).
1193 extract_private_key (gcry_sexp_t s_key, int req_private_key_data,
1194 const char **r_algoname, int *r_npkey, int *r_nskey,
1195 const char **r_elems,
1196 gcry_mpi_t *array, int arraysize,
1197 gcry_sexp_t *r_curve, gcry_sexp_t *r_flags)
1200 gcry_sexp_t list, l2;
1202 const char *algoname, *format;
1204 gcry_sexp_t curve = NULL;
1205 gcry_sexp_t flags = NULL;
1210 if (!req_private_key_data)
1212 list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1214 list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1216 list = gcry_sexp_find_token (s_key, "private-key", 0 );
1219 list = gcry_sexp_find_token (s_key, "private-key", 0);
1223 log_error ("invalid private key format\n");
1224 return gpg_error (GPG_ERR_BAD_SECKEY);
1227 l2 = gcry_sexp_cadr (list);
1228 gcry_sexp_release (list);
1230 name = gcry_sexp_nth_string (list, 0);
1233 gcry_sexp_release (list);
1234 return gpg_error (GPG_ERR_INV_OBJ); /* Invalid structure of object. */
1240 /* Map NAME to a name as used by Libgcrypt. We do not use the
1241 Libgcrypt function here because we need a lowercase name and
1242 require special treatment for some algorithms. */
1244 if (!strcmp (name, "rsa"))
1247 format = "ned?p?q?u?";
1250 err = gcry_sexp_extract_param (list, NULL, format,
1251 array+0, array+1, array+2, array+3,
1252 array+4, array+5, NULL);
1254 else if (!strcmp (name, "elg"))
1260 err = gcry_sexp_extract_param (list, NULL, format,
1261 array+0, array+1, array+2, array+3,
1264 else if (!strcmp (name, "dsa"))
1270 err = gcry_sexp_extract_param (list, NULL, format,
1271 array+0, array+1, array+2, array+3,
1274 else if (!strcmp (name, "ecc"))
1280 curve = gcry_sexp_find_token (list, "curve", 0);
1281 flags = gcry_sexp_find_token (list, "flags", 0);
1282 err = gcry_sexp_extract_param (list, NULL, format,
1283 array+0, array+1, NULL);
1287 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
1290 gcry_sexp_release (list);
1293 gcry_sexp_release (curve);
1294 gcry_sexp_release (flags);
1299 *r_algoname = algoname;
1312 /* Convert our key S_KEY into an OpenPGP key transfer format. On
1313 success a canonical encoded S-expression is stored at R_TRANSFERKEY
1314 and its length at R_TRANSFERKEYLEN; this S-expression is also
1315 padded to a multiple of 64 bits. */
1317 convert_to_openpgp (ctrl_t ctrl, gcry_sexp_t s_key, const char *passphrase,
1318 unsigned char **r_transferkey, size_t *r_transferkeylen)
1321 const char *algoname;
1323 gcry_mpi_t array[10];
1324 gcry_sexp_t curve = NULL;
1325 gcry_sexp_t flags = NULL;
1326 char protect_iv[16];
1328 unsigned long s2k_count;
1333 *r_transferkey = NULL;
1335 for (i=0; i < DIM (array); i++)
1338 err = extract_private_key (s_key, 1, &algoname, &npkey, &nskey, NULL,
1339 array, DIM (array), &curve, &flags);
1343 gcry_create_nonce (protect_iv, sizeof protect_iv);
1344 gcry_create_nonce (salt, sizeof salt);
1345 /* We need to use the encoded S2k count. It is not possible to
1346 encode it after it has been used because the encoding procedure
1347 may round the value up. */
1348 s2k_count = get_standard_s2k_count_rfc4880 ();
1349 err = apply_protection (array, npkey, nskey, passphrase,
1350 GCRY_CIPHER_AES, protect_iv, sizeof protect_iv,
1351 3, GCRY_MD_SHA1, salt, s2k_count);
1352 /* Turn it into the transfer key S-expression. Note that we always
1353 return a protected key. */
1358 void *format_args[10+2];
1360 gcry_sexp_t tmpsexp = NULL;
1362 snprintf (countbuf, sizeof countbuf, "%lu", s2k_count);
1364 init_membuf (&mbuf, 50);
1365 put_membuf_str (&mbuf, "(skey");
1366 for (i=j=0; i < npkey; i++)
1368 put_membuf_str (&mbuf, " _ %m");
1369 format_args[j++] = array + i;
1371 put_membuf_str (&mbuf, " e %m");
1372 format_args[j++] = array + npkey;
1373 put_membuf_str (&mbuf, ")\n");
1374 put_membuf (&mbuf, "", 1);
1378 char *format = get_membuf (&mbuf, NULL);
1380 err = gpg_error_from_syserror ();
1382 err = gcry_sexp_build_array (&tmpkey, NULL, format, format_args);
1386 err = gcry_sexp_build (&tmpsexp, NULL,
1387 "(openpgp-private-key\n"
1391 " (protection sha1 aes %b 1:3 sha1 %b %s))\n",
1395 (int)sizeof protect_iv, protect_iv,
1396 (int)sizeof salt, salt,
1398 gcry_sexp_release (tmpkey);
1400 err = make_canon_sexp_pad (tmpsexp, 0, r_transferkey, r_transferkeylen);
1401 gcry_sexp_release (tmpsexp);
1404 for (i=0; i < DIM (array); i++)
1405 gcry_mpi_release (array[i]);
1406 gcry_sexp_release (curve);
1407 gcry_sexp_release (flags);