1 /* export.c - Export keys in the OpenPGP defined format.
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2010 Free Software Foundation, Inc.
4 * Copyright (C) 1998-2016 Werner Koch
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <http://www.gnu.org/licenses/>.
39 #include "call-agent.h"
41 /* An object to keep track of subkeys. */
44 struct subkey_list_s *next;
47 typedef struct subkey_list_s *subkey_list_t;
50 /* An object to track statistics for export operations. */
53 ulong count; /* Number of processed keys. */
54 ulong secret_count; /* Number of secret keys seen. */
55 ulong exported; /* Number of actual exported keys. */
59 /* Local prototypes. */
60 static int do_export (ctrl_t ctrl, strlist_t users, int secret,
61 unsigned int options, export_stats_t stats);
62 static int do_export_stream (ctrl_t ctrl, iobuf_t out,
63 strlist_t users, int secret,
64 kbnode_t *keyblock_out, unsigned int options,
65 export_stats_t stats, int *any);
70 /* Option parser for export options. See parse_options fro
73 parse_export_options(char *str,unsigned int *options,int noisy)
75 struct parse_options export_opts[]=
77 {"export-local-sigs",EXPORT_LOCAL_SIGS,NULL,
78 N_("export signatures that are marked as local-only")},
79 {"export-attributes",EXPORT_ATTRIBUTES,NULL,
80 N_("export attribute user IDs (generally photo IDs)")},
81 {"export-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,
82 N_("export revocation keys marked as \"sensitive\"")},
83 {"export-clean",EXPORT_CLEAN,NULL,
84 N_("remove unusable parts from key during export")},
85 {"export-minimal",EXPORT_MINIMAL|EXPORT_CLEAN,NULL,
86 N_("remove as much as possible from key during export")},
87 /* Aliases for backward compatibility */
88 {"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
89 {"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
90 {"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
92 {"export-unusable-sigs",0,NULL,NULL},
93 {"export-clean-sigs",0,NULL,NULL},
94 {"export-clean-uids",0,NULL,NULL},
96 /* add tags for include revoked and disabled? */
99 return parse_options(str,options,export_opts,noisy);
103 /* Create a new export stats object initialized to zero. On error
104 returns NULL and sets ERRNO. */
106 export_new_stats (void)
108 export_stats_t stats;
110 return xtrycalloc (1, sizeof *stats);
114 /* Release an export stats object. */
116 export_release_stats (export_stats_t stats)
122 /* Print export statistics using the status interface. */
124 export_print_stats (export_stats_t stats)
129 if (is_status_enabled ())
133 snprintf (buf, sizeof buf, "%lu %lu %lu",
137 write_status_text (STATUS_EXPORT_RES, buf);
143 * Export public keys (to stdout or to --output FILE).
145 * Depending on opt.armor the output is armored. OPTIONS are defined
146 * in main.h. If USERS is NULL, all keys will be exported. STATS is
147 * either an export stats object for update or NULL.
149 * This function is the core of "gpg --export".
152 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
153 export_stats_t stats)
155 return do_export (ctrl, users, 0, options, stats);
160 * Export secret keys (to stdout or to --output FILE).
162 * Depending on opt.armor the output is armored. If USERS is NULL,
163 * all secret keys will be exported. STATS is either an export stats
164 * object for update or NULL.
166 * This function is the core of "gpg --export-secret-keys".
169 export_seckeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
171 return do_export (ctrl, users, 1, 0, stats);
176 * Export secret sub keys (to stdout or to --output FILE).
178 * This is the same as export_seckeys but replaces the primary key by
179 * a stub key. Depending on opt.armor the output is armored. If
180 * USERS is NULL, all secret subkeys will be exported. STATS is
181 * either an export stats object for update or NULL.
183 * This function is the core of "gpg --export-secret-subkeys".
186 export_secsubkeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
188 return do_export (ctrl, users, 2, 0, stats);
193 * Export a single key into a memory buffer. STATS is either an
194 * export stats object for update or NULL.
197 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
198 export_stats_t stats,
199 kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
211 if (!add_to_strlist_try (&helplist, keyspec))
212 return gpg_error_from_syserror ();
214 iobuf = iobuf_temp ();
215 err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
218 err = gpg_error (GPG_ERR_NOT_FOUND);
224 iobuf_flush_temp (iobuf);
225 src = iobuf_get_temp_buffer (iobuf);
226 datalen = iobuf_get_temp_length (iobuf);
228 err = gpg_error (GPG_ERR_NO_PUBKEY);
229 else if (!(*r_data = xtrymalloc (datalen)))
230 err = gpg_error_from_syserror ();
233 memcpy (*r_data, src, datalen);
234 *r_datalen = datalen;
238 free_strlist (helplist);
239 if (err && *r_keyblock)
241 release_kbnode (*r_keyblock);
248 /* Export the keys identified by the list of strings in USERS. If
249 Secret is false public keys will be exported. With secret true
250 secret keys will be exported; in this case 1 means the entire
251 secret keyblock and 2 only the subkeys. OPTIONS are the export
254 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
255 export_stats_t stats)
259 armor_filter_context_t *afx = NULL;
260 compress_filter_context_t zfx;
262 memset( &zfx, 0, sizeof zfx);
264 rc = open_outfile (-1, NULL, 0, !!secret, &out );
270 afx = new_armor_context ();
271 afx->what = secret? 5 : 1;
272 push_armor_filter (afx, out);
275 rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
281 release_armor_context (afx);
287 /* Release an entire subkey list. */
289 release_subkey_list (subkey_list_t list)
293 subkey_list_t tmp = list->next;;
300 /* Returns true if NODE is a subkey and contained in LIST. */
302 subkey_in_list_p (subkey_list_t list, KBNODE node)
304 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
305 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
309 keyid_from_pk (node->pkt->pkt.public_key, kid);
311 for (; list; list = list->next)
312 if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
318 /* Allocate a new subkey list item from NODE. */
320 new_subkey_list_item (KBNODE node)
322 subkey_list_t list = xcalloc (1, sizeof *list);
324 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
325 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
326 keyid_from_pk (node->pkt->pkt.public_key, list->kid);
332 /* Helper function to check whether the subkey at NODE actually
333 matches the description at DESC. The function returns true if the
334 key under question has been specified by an exact specification
335 (keyID or fingerprint) and does match the one at NODE. It is
336 assumed that the packet at NODE is either a public or secret
339 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
342 byte fpr[MAX_FINGERPRINT_LEN];
348 case KEYDB_SEARCH_MODE_SHORT_KID:
349 case KEYDB_SEARCH_MODE_LONG_KID:
350 keyid_from_pk (node->pkt->pkt.public_key, kid);
353 case KEYDB_SEARCH_MODE_FPR16:
354 case KEYDB_SEARCH_MODE_FPR20:
355 case KEYDB_SEARCH_MODE_FPR:
356 fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
365 case KEYDB_SEARCH_MODE_SHORT_KID:
366 if (desc->u.kid[1] == kid[1])
370 case KEYDB_SEARCH_MODE_LONG_KID:
371 if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
375 case KEYDB_SEARCH_MODE_FPR16:
376 if (!memcmp (desc->u.fpr, fpr, 16))
380 case KEYDB_SEARCH_MODE_FPR20:
381 case KEYDB_SEARCH_MODE_FPR:
382 if (!memcmp (desc->u.fpr, fpr, 20))
394 /* Return a canonicalized public key algoithms. This is used to
395 compare different flavors of algorithms (e.g. ELG and ELG_E are
396 considered the same). */
397 static enum gcry_pk_algos
398 canon_pk_algo (enum gcry_pk_algos algo)
404 case GCRY_PK_RSA_S: return GCRY_PK_RSA;
406 case GCRY_PK_ELG_E: return GCRY_PK_ELG;
409 case GCRY_PK_ECDH: return GCRY_PK_ECC;
410 default: return algo;
415 /* Use the key transfer format given in S_PGP to create the secinfo
416 structure in PK and change the parameter array in PK to include the
417 secret parameters. */
419 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
422 gcry_sexp_t top_list;
423 gcry_sexp_t list = NULL;
429 int is_v4, is_protected;
430 enum gcry_pk_algos pk_algo;
431 int protect_algo = 0;
440 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
442 struct seckey_info *ski;
444 /* gcry_log_debugsxp ("transferkey", s_pgp); */
445 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
449 list = gcry_sexp_find_token (top_list, "version", 0);
452 value = gcry_sexp_nth_data (list, 1, &valuelen);
453 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
455 is_v4 = (value[0] == '4');
457 gcry_sexp_release (list);
458 list = gcry_sexp_find_token (top_list, "protection", 0);
461 value = gcry_sexp_nth_data (list, 1, &valuelen);
464 if (valuelen == 4 && !memcmp (value, "sha1", 4))
466 else if (valuelen == 3 && !memcmp (value, "sum", 3))
468 else if (valuelen == 4 && !memcmp (value, "none", 4))
474 string = gcry_sexp_nth_string (list, 2);
477 protect_algo = gcry_cipher_map_name (string);
480 value = gcry_sexp_nth_data (list, 3, &valuelen);
481 if (!value || !valuelen || valuelen > sizeof iv)
483 memcpy (iv, value, valuelen);
486 string = gcry_sexp_nth_string (list, 4);
489 s2k_mode = strtol (string, NULL, 10);
492 string = gcry_sexp_nth_string (list, 5);
495 s2k_algo = gcry_md_map_name (string);
498 value = gcry_sexp_nth_data (list, 6, &valuelen);
499 if (!value || !valuelen || valuelen > sizeof s2k_salt)
501 memcpy (s2k_salt, value, valuelen);
503 string = gcry_sexp_nth_string (list, 7);
506 s2k_count = strtoul (string, NULL, 10);
510 /* Parse the gcrypt PK algo and check that it is okay. */
511 gcry_sexp_release (list);
512 list = gcry_sexp_find_token (top_list, "algo", 0);
515 string = gcry_sexp_nth_string (list, 1);
518 pk_algo = gcry_pk_map_name (string);
519 xfree (string); string = NULL;
520 if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
521 || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
522 || !npkey || npkey >= nskey)
525 /* Check that the pubkey algo matches the one from the public key. */
526 switch (canon_pk_algo (pk_algo))
529 if (!is_RSA (pk->pubkey_algo))
530 pk_algo = 0; /* Does not match. */
533 if (!is_DSA (pk->pubkey_algo))
534 pk_algo = 0; /* Does not match. */
537 if (!is_ELGAMAL (pk->pubkey_algo))
538 pk_algo = 0; /* Does not match. */
541 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
543 else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
545 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
548 pk_algo = 0; /* Does not match. */
549 /* For ECC we do not have the domain parameters thus fix our info. */
554 pk_algo = 0; /* Oops. */
559 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
563 /* This check has to go after the ecc adjustments. */
564 if (nskey > PUBKEY_MAX_NSKEY)
567 /* Parse the key parameters. */
568 gcry_sexp_release (list);
569 list = gcry_sexp_find_token (top_list, "skey", 0);
576 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
577 if (!value && skeyidx >= npkey)
580 /* Check for too many parameters. Note that depending on the
581 protection mode and version number we may see less than NSKEY
582 (but at least NPKEY+1) parameters. */
585 if (skeyidx >= DIM (skey)-1)
588 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
590 is_enc = (value[0] == 'e');
591 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
592 if (!value || !valuelen)
596 void *p = xtrymalloc (valuelen);
599 memcpy (p, value, valuelen);
600 skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
606 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
607 value, valuelen, NULL))
612 skey[skeyidx++] = NULL;
614 gcry_sexp_release (list); list = NULL;
616 /* We have no need for the CSUM value thus we don't parse it. */
617 /* list = gcry_sexp_find_token (top_list, "csum", 0); */
620 /* string = gcry_sexp_nth_string (list, 1); */
622 /* goto bad_seckey; */
623 /* desired_csum = strtoul (string, NULL, 10); */
624 /* xfree (string); */
627 /* desired_csum = 0; */
628 /* gcry_sexp_release (list); list = NULL; */
630 /* Get the curve name if any, */
631 list = gcry_sexp_find_token (top_list, "curve", 0);
634 curve = gcry_sexp_nth_string (list, 1);
635 gcry_sexp_release (list); list = NULL;
638 gcry_sexp_release (top_list); top_list = NULL;
640 /* log_debug ("XXX is_v4=%d\n", is_v4); */
641 /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
642 /* log_debug ("XXX is_protected=%d\n", is_protected); */
643 /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
644 /* log_printhex ("XXX iv", iv, ivlen); */
645 /* log_debug ("XXX ivlen=%d\n", ivlen); */
646 /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
647 /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
648 /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
649 /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
650 /* for (idx=0; skey[idx]; idx++) */
652 /* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
653 /* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
657 /* unsigned int nbits; */
658 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
659 /* log_printhex (NULL, p, (nbits+7)/8); */
662 /* gcry_mpi_dump (skey[idx]); */
663 /* log_printf ("\n"); */
666 if (!is_v4 || is_protected != 2 )
668 /* We only support the v4 format and a SHA-1 checksum. */
669 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
673 /* We need to change the received parameters for ECC algorithms.
674 The transfer format has the curve name and the parameters
675 separate. We put them all into the SKEY array. */
676 if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
680 /* Assert that all required parameters are available. We also
681 check that the array does not contain more parameters than
682 needed (this was used by some beta versions of 2.1. */
683 if (!curve || !skey[0] || !skey[1] || skey[2])
685 err = gpg_error (GPG_ERR_INTERNAL);
689 oidstr = openpgp_curve_to_oid (curve, NULL);
692 log_error ("no OID known for curve '%s'\n", curve);
693 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
696 /* Put the curve's OID into into the MPI array. This requires
697 that we shift Q and D. For ECDH also insert the KDF parms. */
702 skey[2] = gcry_mpi_copy (pk->pkey[2]);
711 err = openpgp_oid_from_str (oidstr, skey + 0);
714 /* Fixup the NPKEY and NSKEY to match OpenPGP reality. */
718 /* for (idx=0; skey[idx]; idx++) */
720 /* log_info ("YYY skey[%d]:", idx); */
721 /* if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
724 /* unsigned int nbits; */
725 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
726 /* log_printhex (NULL, p, (nbits+7)/8); */
729 /* gcry_mpi_dump (skey[idx]); */
730 /* log_printf ("\n"); */
734 /* Do some sanity checks. */
737 /* We expect an already encoded S2K count. */
738 err = gpg_error (GPG_ERR_INV_DATA);
741 err = openpgp_cipher_test_algo (protect_algo);
744 err = openpgp_md_test_algo (s2k_algo);
748 /* Check that the public key parameters match. Note that since
749 Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly. */
750 for (idx=0; idx < npkey; idx++)
751 if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
753 err = gpg_error (GPG_ERR_BAD_PUBKEY);
757 /* Check that the first secret key parameter in SKEY is encrypted
758 and that there are no more secret key parameters. The latter is
759 guaranteed by the v4 packet format. */
760 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
762 if (npkey+1 < DIM (skey) && skey[npkey+1])
765 /* Check that the secret key parameters in PK are all set to NULL. */
766 for (idx=npkey; idx < nskey; idx++)
770 /* Now build the protection info. */
771 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
774 err = gpg_error_from_syserror ();
778 ski->is_protected = 1;
780 ski->algo = protect_algo;
781 ski->s2k.mode = s2k_mode;
782 ski->s2k.hash_algo = s2k_algo;
783 log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
784 memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
785 ski->s2k.count = s2k_count;
786 log_assert (ivlen <= sizeof ski->iv);
787 memcpy (ski->iv, iv, ivlen);
790 /* Store the protected secret key parameter. */
791 pk->pkey[npkey] = skey[npkey];
798 gcry_sexp_release (list);
799 gcry_sexp_release (top_list);
800 for (idx=0; idx < skeyidx; idx++)
801 gcry_mpi_release (skey[idx]);
805 err = gpg_error (GPG_ERR_BAD_SECKEY);
809 err = gpg_error (GPG_ERR_ENOMEM);
814 /* Print an "EXPORTED" status line. PK is the primary public key. */
816 print_status_exported (PKT_public_key *pk)
820 if (!is_status_enabled ())
823 hexfpr = hexfingerprint (pk, NULL, 0);
824 write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
830 * Receive a secret key from agent specified by HEXGRIP.
832 * Since the key data from agant is encrypted, decrypt it by CIPHERHD.
833 * Then, parse the decrypted key data in transfer format, and put
834 * secret papameters into PK.
836 * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
839 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
840 char **cache_nonce_addr, const char *hexgrip,
844 unsigned char *wrappedkey = NULL;
845 size_t wrappedkeylen;
846 unsigned char *key = NULL;
847 size_t keylen, realkeylen;
852 log_info ("key %s: asking agent for the secret parts\n", hexgrip);
854 prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
855 err = agent_export_key (ctrl, hexgrip, prompt, cache_nonce_addr,
856 &wrappedkey, &wrappedkeylen);
861 if (wrappedkeylen < 24)
863 err = gpg_error (GPG_ERR_INV_LENGTH);
866 keylen = wrappedkeylen - 8;
867 key = xtrymalloc_secure (keylen);
870 err = gpg_error_from_syserror ();
873 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
876 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
878 goto unwraperror; /* Invalid csexp. */
880 err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
883 err = transfer_format_to_openpgp (s_skey, pk);
884 gcry_sexp_release (s_skey);
892 log_error ("key %s: error receiving key from agent:"
893 " %s%s\n", hexgrip, gpg_strerror (err),
894 gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
901 /* Export the keys identified by the list of strings in USERS to the
902 stream OUT. If Secret is false public keys will be exported. With
903 secret true secret keys will be exported; in this case 1 means the
904 entire secret keyblock and 2 only the subkeys. OPTIONS are the
905 export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
906 code is zero, a pointer to the first keyblock found and exported
907 will be stored at this address; no other keyblocks are exported in
908 this case. The caller must free the returned keyblock. If any
909 key has been exported true is stored at ANY. */
911 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
912 kbnode_t *keyblock_out, unsigned int options,
913 export_stats_t stats, int *any)
917 KBNODE keyblock = NULL;
919 size_t ndesc, descindex;
920 KEYDB_SEARCH_DESC *desc = NULL;
921 subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
924 gcry_cipher_hd_t cipherhd = NULL;
925 char *cache_nonce = NULL;
926 struct export_stats_s dummystats;
932 kdbhd = keydb_new ();
934 return gpg_error_from_syserror ();
936 /* For the DANE format override the options. */
937 if ((options & EXPORT_DANE_FORMAT))
938 options = (EXPORT_DANE_FORMAT | EXPORT_MINIMAL | EXPORT_CLEAN);
944 desc = xcalloc (ndesc, sizeof *desc);
945 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
949 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
951 desc = xmalloc ( ndesc * sizeof *desc);
953 for (ndesc=0, sl=users; sl; sl = sl->next)
955 if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
958 log_error (_("key \"%s\" not found: %s\n"),
959 sl->d, gpg_strerror (err));
962 keydb_disable_caching (kdbhd); /* We are looping the search. */
964 /* It would be nice to see which of the given users did actually
965 match one in the keyring. To implement this we need to have
966 a found flag for each entry in desc. To set this flag we
967 must check all those entries after a match to mark all
968 matched one - currently we stop at the first match. To do
969 this we need an extra flag to enable this feature. */
972 #ifdef ENABLE_SELINUX_HACKS
975 log_error (_("exporting secret keys not allowed\n"));
976 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
981 /* For secret key export we need to setup a decryption context. */
987 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
990 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
994 /* Prepare a cipher context. */
995 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
996 GCRY_CIPHER_MODE_AESWRAP, 0);
998 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1001 log_error ("error setting up an encryption context: %s\n",
1002 gpg_strerror (err));
1011 int skip_until_subkey = 0;
1015 err = keydb_search (kdbhd, desc, ndesc, &descindex);
1017 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1021 /* Read the keyblock. */
1022 release_kbnode (keyblock);
1024 err = keydb_get_keyblock (kdbhd, &keyblock);
1027 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1031 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1034 log_error ("public key packet not found in keyblock - skipped\n");
1038 setup_main_keyids (keyblock); /* gpg_format_keydesc needs it. */
1039 pk = node->pkt->pkt.public_key;
1040 keyid_from_pk (pk, keyid);
1042 /* If a secret key export is required we need to check whether
1043 we have a secret key at all and if so create the seckey_info
1047 if (agent_probe_any_secret_key (ctrl, keyblock))
1048 continue; /* No secret key (neither primary nor subkey). */
1050 /* No v3 keys with GNU mode 1001. */
1051 if (secret == 2 && pk->version == 3)
1053 log_info (_("key %s: PGP 2.x style key - skipped\n"),
1058 /* The agent does not yet allow to export v3 packets. It is
1059 actually questionable whether we should allow them at
1061 if (pk->version == 3)
1063 log_info ("key %s: PGP 2.x style key (v3) export "
1064 "not yet supported - skipped\n", keystr (keyid));
1067 stats->secret_count++;
1070 /* Always do the cleaning on the public key part if requested.
1071 Note that we don't yet set this option if we are exporting
1072 secret keys. Note that both export-clean and export-minimal
1073 only apply to UID sigs (0x10, 0x11, 0x12, and 0x13). A
1074 designated revocation is never stripped, even with
1075 export-minimal set. */
1076 if ((options & EXPORT_CLEAN))
1077 clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1080 xfree (cache_nonce);
1082 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1084 if (skip_until_subkey)
1086 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1087 skip_until_subkey = 0;
1092 /* We used to use comment packets, but not any longer. In
1093 case we still have comments on a key, strip them here
1094 before we call build_packet(). */
1095 if (node->pkt->pkttype == PKT_COMMENT)
1098 /* Make sure that ring_trust packets never get exported. */
1099 if (node->pkt->pkttype == PKT_RING_TRUST)
1102 /* If exact is set, then we only export what was requested
1103 (plus the primary key, if the user didn't specifically
1105 if (desc[descindex].exact
1106 && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1108 if (!exact_subkey_match_p (desc+descindex, node))
1110 /* Before skipping this subkey, check whether any
1111 other description wants an exact match on a
1112 subkey and include that subkey into the output
1113 too. Need to add this subkey to a list so that
1114 it won't get processed a second time.
1116 So the first step here is to check that list and
1117 skip in any case if the key is in that list.
1119 We need this whole mess because the import
1120 function of GnuPG < 2.1 is not able to merge
1121 secret keys and thus it is useless to output them
1122 as two separate keys and have import merge them. */
1123 if (subkey_in_list_p (subkey_list, node))
1124 skip_until_subkey = 1; /* Already processed this one. */
1129 for (j=0; j < ndesc; j++)
1130 if (j != descindex && desc[j].exact
1131 && exact_subkey_match_p (desc+j, node))
1134 skip_until_subkey = 1; /* No other one matching. */
1138 if(skip_until_subkey)
1141 /* Mark this one as processed. */
1143 subkey_list_t tmp = new_subkey_list_item (node);
1144 tmp->next = subkey_list;
1149 if (node->pkt->pkttype == PKT_SIGNATURE)
1151 /* Do not export packets which are marked as not
1153 if (!(options&EXPORT_LOCAL_SIGS)
1154 && !node->pkt->pkt.signature->flags.exportable)
1155 continue; /* not exportable */
1157 /* Do not export packets with a "sensitive" revocation
1158 key unless the user wants us to. Note that we do
1159 export these when issuing the actual revocation
1161 if (!(options&EXPORT_SENSITIVE_REVKEYS)
1162 && node->pkt->pkt.signature->revkey)
1166 for (i=0;i<node->pkt->pkt.signature->numrevkeys;i++)
1167 if ( (node->pkt->pkt.signature->revkey[i].class & 0x40))
1170 if (i < node->pkt->pkt.signature->numrevkeys)
1175 /* Don't export attribs? */
1176 if (!(options&EXPORT_ATTRIBUTES)
1177 && node->pkt->pkttype == PKT_USER_ID
1178 && node->pkt->pkt.user_id->attrib_data )
1180 /* Skip until we get to something that is not an attrib
1181 or a signature on an attrib */
1182 while (kbctx->next && kbctx->next->pkt->pkttype==PKT_SIGNATURE)
1183 kbctx = kbctx->next;
1188 if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1189 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1191 u32 subkidbuf[2], *subkid;
1192 char *hexgrip, *serialno;
1194 pk = node->pkt->pkt.public_key;
1195 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1199 keyid_from_pk (pk, subkidbuf);
1203 if (pk->seckey_info)
1205 log_error ("key %s: oops: seckey_info already set"
1206 " - skipped\n", keystr_with_sub (keyid, subkid));
1207 skip_until_subkey = 1;
1211 err = hexkeygrip_from_pk (pk, &hexgrip);
1214 log_error ("key %s: error computing keygrip: %s"
1215 " - skipped\n", keystr_with_sub (keyid, subkid),
1216 gpg_strerror (err));
1217 skip_until_subkey = 1;
1222 if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1224 /* We are asked not to export the secret parts of
1225 the primary key. Make up an error code to create
1227 err = GPG_ERR_NOT_FOUND;
1231 err = agent_get_keyinfo (ctrl, hexgrip, &serialno);
1233 if ((!err && serialno)
1234 && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1236 /* It does not make sense to export a key with its
1237 primary key on card using a non-key stub. Thus
1238 we skip those keys when used with
1239 --export-secret-subkeys. */
1240 log_info (_("key %s: key material on-card - skipped\n"),
1241 keystr_with_sub (keyid, subkid));
1242 skip_until_subkey = 1;
1244 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1245 || (!err && serialno))
1247 /* Create a key stub. */
1248 struct seckey_info *ski;
1251 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1254 err = gpg_error_from_syserror ();
1259 ski->is_protected = 1;
1261 ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
1264 ski->s2k.mode = 1002; /* GNU-divert-to-card. */
1265 for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1266 ski->ivlen++, s += 2)
1267 ski->iv[ski->ivlen] = xtoi_2 (s);
1270 err = build_packet (out, node->pkt);
1271 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1274 print_status_exported (node->pkt->pkt.public_key);
1279 err = receive_seckey_from_agent (ctrl, cipherhd, &cache_nonce,
1283 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1285 skip_until_subkey = 1;
1290 err = build_packet (out, node->pkt);
1291 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1294 print_status_exported (node->pkt->pkt.public_key);
1300 log_error ("key %s: error getting keyinfo from agent: %s"
1301 " - skipped\n", keystr_with_sub (keyid, subkid),
1302 gpg_strerror (err));
1303 skip_until_subkey = 1;
1307 xfree (pk->seckey_info);
1308 pk->seckey_info = NULL;
1313 err = build_packet (out, node->pkt);
1314 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1317 print_status_exported (node->pkt->pkt.public_key);
1324 log_error ("build_packet(%d) failed: %s\n",
1325 node->pkt->pkttype, gpg_strerror (err));
1329 if (!skip_until_subkey)
1335 *keyblock_out = keyblock;
1339 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1343 gcry_cipher_close (cipherhd);
1344 release_subkey_list (subkey_list);
1346 keydb_release (kdbhd);
1347 if (err || !keyblock_out)
1348 release_kbnode( keyblock );
1349 xfree (cache_nonce);
1351 log_info(_("WARNING: nothing exported\n"));
1359 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
1362 gpg_error_t err = 0;
1363 unsigned char nbuf[4];
1368 ulongtobuf (nbuf, (ulong)strlen (identifier));
1369 put_membuf (mb, nbuf, 4);
1370 put_membuf_str (mb, identifier);
1371 if (!strncmp (identifier, "ecdsa-sha2-", 11))
1373 ulongtobuf (nbuf, (ulong)strlen (identifier+11));
1374 put_membuf (mb, nbuf, 4);
1375 put_membuf_str (mb, identifier+11);
1377 va_start (arg_ptr, identifier);
1378 while ((a = va_arg (arg_ptr, gcry_mpi_t)))
1380 err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
1383 if (!strcmp (identifier, "ssh-ed25519")
1384 && buflen > 5 && buf[4] == 0x40)
1386 /* We need to strip our 0x40 prefix. */
1387 put_membuf (mb, "\x00\x00\x00\x20", 4);
1388 put_membuf (mb, buf+5, buflen-5);
1391 put_membuf (mb, buf, buflen);
1398 /* Export the key identified by USERID in the SSH public key format.
1399 The function exports the latest subkey with Authentication
1400 capability unless the '!' suffix is used to export a specific
1403 export_ssh_key (ctrl_t ctrl, const char *userid)
1406 kbnode_t keyblock = NULL;
1407 KEYDB_SEARCH_DESC desc;
1409 u32 curtime = make_timestamp ();
1410 kbnode_t latest_key, node;
1412 const char *identifier;
1414 estream_t fp = NULL;
1415 struct b64state b64_state;
1416 const char *fname = "-";
1418 init_membuf (&mb, 4096);
1420 /* We need to know whether the key has been specified using the
1421 exact syntax ('!' suffix). Thus we need to run a
1422 classify_user_id on our own. */
1423 err = classify_user_id (userid, &desc, 1);
1425 /* Get the public key. */
1428 getkey_ctx_t getkeyctx;
1430 err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
1432 0 /* Only usable keys or given exact. */,
1433 1 /* No AKL lookup. */);
1436 err = getkey_next (getkeyctx, NULL, NULL);
1438 err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
1439 else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
1442 getkey_end (getkeyctx);
1446 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
1450 /* The finish_lookup code in getkey.c does not handle auth keys,
1451 thus we have to duplicate the code here to find the latest
1452 subkey. However, if the key has been found using an exact match
1453 ('!' notation) we use that key without any further checks and
1454 even allow the use of the primary key. */
1457 for (node = keyblock; node; node = node->next)
1459 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1460 || node->pkt->pkttype == PKT_PUBLIC_KEY)
1461 && node->pkt->pkt.public_key->flags.exact)
1469 for (node = keyblock; node; node = node->next)
1471 if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
1474 pk = node->pkt->pkt.public_key;
1476 log_debug ("\tchecking subkey %08lX\n",
1477 (ulong) keyid_from_pk (pk, NULL));
1478 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
1481 log_debug ("\tsubkey not usable for authentication\n");
1484 if (!pk->flags.valid)
1487 log_debug ("\tsubkey not valid\n");
1490 if (pk->flags.revoked)
1493 log_debug ("\tsubkey has been revoked\n");
1496 if (pk->has_expired)
1499 log_debug ("\tsubkey has expired\n");
1502 if (pk->timestamp > curtime && !opt.ignore_valid_from)
1505 log_debug ("\tsubkey not yet valid\n");
1509 log_debug ("\tsubkey might be fine\n");
1510 /* In case a key has a timestamp of 0 set, we make sure that it
1511 is used. A better change would be to compare ">=" but that
1512 might also change the selected keys and is as such a more
1513 intrusive change. */
1514 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
1516 latest_date = pk->timestamp;
1524 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1525 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
1529 pk = latest_key->pkt->pkt.public_key;
1531 log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
1533 switch (pk->pubkey_algo)
1535 case PUBKEY_ALGO_DSA:
1536 identifier = "ssh-dss";
1537 err = key_to_sshblob (&mb, identifier,
1538 pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
1542 case PUBKEY_ALGO_RSA:
1543 case PUBKEY_ALGO_RSA_S:
1544 identifier = "ssh-rsa";
1545 err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
1548 case PUBKEY_ALGO_ECDSA:
1553 curveoid = openpgp_oid_to_str (pk->pkey[0]);
1555 err = gpg_error_from_syserror ();
1556 else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
1557 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1560 if (!strcmp (curve, "nistp256"))
1561 identifier = "ecdsa-sha2-nistp256";
1562 else if (!strcmp (curve, "nistp384"))
1563 identifier = "ecdsa-sha2-nistp384";
1564 else if (!strcmp (curve, "nistp521"))
1565 identifier = "ecdsa-sha2-nistp521";
1570 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1572 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
1578 case PUBKEY_ALGO_EDDSA:
1579 if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
1580 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1583 identifier = "ssh-ed25519";
1584 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
1588 case PUBKEY_ALGO_ELGAMAL_E:
1589 case PUBKEY_ALGO_ELGAMAL:
1590 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1594 err = GPG_ERR_PUBKEY_ALGO;
1601 if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
1602 fp = es_fopen ((fname = opt.outfile), "w");
1607 err = gpg_error_from_syserror ();
1608 log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
1612 es_fprintf (fp, "%s ", identifier);
1613 err = b64enc_start_es (&b64_state, fp, "");
1620 blob = get_membuf (&mb, &bloblen);
1622 err = gpg_error_from_syserror ();
1624 err = b64enc_write (&b64_state, blob, bloblen);
1629 err = b64enc_finish (&b64_state);
1632 es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
1635 err = gpg_error_from_syserror ();
1639 err = gpg_error_from_syserror ();
1644 log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
1648 xfree (get_membuf (&mb, NULL));
1649 release_kbnode (keyblock);