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 <https://www.gnu.org/licenses/>.
40 #include "mbox-util.h"
43 #include "call-agent.h"
45 /* An object to keep track of subkeys. */
48 struct subkey_list_s *next;
51 typedef struct subkey_list_s *subkey_list_t;
54 /* An object to track statistics for export operations. */
57 ulong count; /* Number of processed keys. */
58 ulong secret_count; /* Number of secret keys seen. */
59 ulong exported; /* Number of actual exported keys. */
63 /* A global variable to store the selector created from
64 * --export-filter keep-uid=EXPR.
65 * --export-filter drop-subkey=EXPR.
67 * FIXME: We should put this into the CTRL object but that requires a
68 * lot more changes right now.
70 static recsel_expr_t export_keep_uid;
71 static recsel_expr_t export_drop_subkey;
75 /* Local prototypes. */
76 static int do_export (ctrl_t ctrl, strlist_t users, int secret,
77 unsigned int options, export_stats_t stats);
78 static int do_export_stream (ctrl_t ctrl, iobuf_t out,
79 strlist_t users, int secret,
80 kbnode_t *keyblock_out, unsigned int options,
81 export_stats_t stats, int *any);
82 static gpg_error_t print_pka_or_dane_records
83 /**/ (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
84 const void *data, size_t datalen,
85 int print_pka, int print_dane);
89 cleanup_export_globals (void)
91 recsel_release (export_keep_uid);
92 export_keep_uid = NULL;
93 recsel_release (export_drop_subkey);
94 export_drop_subkey = NULL;
98 /* Option parser for export options. See parse_options fro
101 parse_export_options(char *str,unsigned int *options,int noisy)
103 struct parse_options export_opts[]=
105 {"export-local-sigs",EXPORT_LOCAL_SIGS,NULL,
106 N_("export signatures that are marked as local-only")},
107 {"export-attributes",EXPORT_ATTRIBUTES,NULL,
108 N_("export attribute user IDs (generally photo IDs)")},
109 {"export-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,
110 N_("export revocation keys marked as \"sensitive\"")},
111 {"export-clean",EXPORT_CLEAN,NULL,
112 N_("remove unusable parts from key during export")},
113 {"export-minimal",EXPORT_MINIMAL|EXPORT_CLEAN,NULL,
114 N_("remove as much as possible from key during export")},
116 {"export-pka", EXPORT_PKA_FORMAT, NULL, NULL },
117 {"export-dane", EXPORT_DANE_FORMAT, NULL, NULL },
119 {"backup", EXPORT_BACKUP, NULL,
120 N_("use the GnuPG key backup format")},
121 {"export-backup", EXPORT_BACKUP, NULL, NULL },
123 /* Aliases for backward compatibility */
124 {"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
125 {"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
126 {"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
128 {"export-unusable-sigs",0,NULL,NULL},
129 {"export-clean-sigs",0,NULL,NULL},
130 {"export-clean-uids",0,NULL,NULL},
132 /* add tags for include revoked and disabled? */
136 rc = parse_options (str, options, export_opts, noisy);
137 if (rc && (*options & EXPORT_BACKUP))
139 /* Alter other options we want or don't want for restore. */
140 *options |= (EXPORT_LOCAL_SIGS | EXPORT_ATTRIBUTES
141 | EXPORT_SENSITIVE_REVKEYS);
142 *options &= ~(EXPORT_CLEAN | EXPORT_MINIMAL
143 | EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT);
149 /* Parse and set an export filter from string. STRING has the format
150 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
151 * and after NAME are not allowed. If this function is called several
152 * times all expressions for the same NAME are concatenated.
153 * Supported filter names are:
155 * - keep-uid :: If the expression evaluates to true for a certain
156 * user ID packet, that packet and all it dependencies
157 * will be exported. The expression may use these
160 * - uid :: The entire user ID.
161 * - mbox :: The mail box part of the user ID.
162 * - primary :: Evaluate to true for the primary user ID.
164 * - drop-subkey :: If the expression evaluates to true for a subkey
165 * packet that subkey and all it dependencies will be
166 * remove from the keyblock. The expression may use these
169 * - secret :: 1 for a secret subkey, else 0.
170 * - key_algo :: Public key algorithm id
173 parse_and_set_export_filter (const char *string)
177 /* Auto register the cleanup function. */
178 register_mem_cleanup_func (cleanup_export_globals);
180 if (!strncmp (string, "keep-uid=", 9))
181 err = recsel_parse_expr (&export_keep_uid, string+9);
182 else if (!strncmp (string, "drop-subkey=", 12))
183 err = recsel_parse_expr (&export_drop_subkey, string+12);
185 err = gpg_error (GPG_ERR_INV_NAME);
191 /* Create a new export stats object initialized to zero. On error
192 returns NULL and sets ERRNO. */
194 export_new_stats (void)
196 export_stats_t stats;
198 return xtrycalloc (1, sizeof *stats);
202 /* Release an export stats object. */
204 export_release_stats (export_stats_t stats)
210 /* Print export statistics using the status interface. */
212 export_print_stats (export_stats_t stats)
217 if (is_status_enabled ())
221 snprintf (buf, sizeof buf, "%lu %lu %lu",
225 write_status_text (STATUS_EXPORT_RES, buf);
231 * Export public keys (to stdout or to --output FILE).
233 * Depending on opt.armor the output is armored. OPTIONS are defined
234 * in main.h. If USERS is NULL, all keys will be exported. STATS is
235 * either an export stats object for update or NULL.
237 * This function is the core of "gpg --export".
240 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
241 export_stats_t stats)
243 return do_export (ctrl, users, 0, options, stats);
248 * Export secret keys (to stdout or to --output FILE).
250 * Depending on opt.armor the output is armored. OPTIONS are defined
251 * in main.h. If USERS is NULL, all secret keys will be exported.
252 * STATS is either an export stats object for update or NULL.
254 * This function is the core of "gpg --export-secret-keys".
257 export_seckeys (ctrl_t ctrl, strlist_t users, unsigned int options,
258 export_stats_t stats)
260 return do_export (ctrl, users, 1, options, stats);
265 * Export secret sub keys (to stdout or to --output FILE).
267 * This is the same as export_seckeys but replaces the primary key by
268 * a stub key. Depending on opt.armor the output is armored. OPTIONS
269 * are defined in main.h. If USERS is NULL, all secret subkeys will
270 * be exported. STATS is either an export stats object for update or
273 * This function is the core of "gpg --export-secret-subkeys".
276 export_secsubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
277 export_stats_t stats)
279 return do_export (ctrl, users, 2, options, stats);
284 * Export a single key into a memory buffer. STATS is either an
285 * export stats object for update or NULL.
288 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
289 export_stats_t stats,
290 kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
302 if (!add_to_strlist_try (&helplist, keyspec))
303 return gpg_error_from_syserror ();
305 iobuf = iobuf_temp ();
306 err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
309 err = gpg_error (GPG_ERR_NOT_FOUND);
315 iobuf_flush_temp (iobuf);
316 src = iobuf_get_temp_buffer (iobuf);
317 datalen = iobuf_get_temp_length (iobuf);
319 err = gpg_error (GPG_ERR_NO_PUBKEY);
320 else if (!(*r_data = xtrymalloc (datalen)))
321 err = gpg_error_from_syserror ();
324 memcpy (*r_data, src, datalen);
325 *r_datalen = datalen;
329 free_strlist (helplist);
330 if (err && *r_keyblock)
332 release_kbnode (*r_keyblock);
339 /* Export the keys identified by the list of strings in USERS. If
340 Secret is false public keys will be exported. With secret true
341 secret keys will be exported; in this case 1 means the entire
342 secret keyblock and 2 only the subkeys. OPTIONS are the export
345 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
346 export_stats_t stats)
350 armor_filter_context_t *afx = NULL;
351 compress_filter_context_t zfx;
353 memset( &zfx, 0, sizeof zfx);
355 rc = open_outfile (-1, NULL, 0, !!secret, &out );
359 if ( opt.armor && !(options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)) )
361 afx = new_armor_context ();
362 afx->what = secret? 5 : 1;
363 push_armor_filter (afx, out);
366 rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
372 release_armor_context (afx);
378 /* Release an entire subkey list. */
380 release_subkey_list (subkey_list_t list)
384 subkey_list_t tmp = list->next;;
391 /* Returns true if NODE is a subkey and contained in LIST. */
393 subkey_in_list_p (subkey_list_t list, KBNODE node)
395 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
396 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
400 keyid_from_pk (node->pkt->pkt.public_key, kid);
402 for (; list; list = list->next)
403 if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
409 /* Allocate a new subkey list item from NODE. */
411 new_subkey_list_item (KBNODE node)
413 subkey_list_t list = xcalloc (1, sizeof *list);
415 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
416 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
417 keyid_from_pk (node->pkt->pkt.public_key, list->kid);
423 /* Helper function to check whether the subkey at NODE actually
424 matches the description at DESC. The function returns true if the
425 key under question has been specified by an exact specification
426 (keyID or fingerprint) and does match the one at NODE. It is
427 assumed that the packet at NODE is either a public or secret
430 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
433 byte fpr[MAX_FINGERPRINT_LEN];
439 case KEYDB_SEARCH_MODE_SHORT_KID:
440 case KEYDB_SEARCH_MODE_LONG_KID:
441 keyid_from_pk (node->pkt->pkt.public_key, kid);
444 case KEYDB_SEARCH_MODE_FPR16:
445 case KEYDB_SEARCH_MODE_FPR20:
446 case KEYDB_SEARCH_MODE_FPR:
447 fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
456 case KEYDB_SEARCH_MODE_SHORT_KID:
457 if (desc->u.kid[1] == kid[1])
461 case KEYDB_SEARCH_MODE_LONG_KID:
462 if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
466 case KEYDB_SEARCH_MODE_FPR16:
467 if (!memcmp (desc->u.fpr, fpr, 16))
471 case KEYDB_SEARCH_MODE_FPR20:
472 case KEYDB_SEARCH_MODE_FPR:
473 if (!memcmp (desc->u.fpr, fpr, 20))
485 /* Return an error if the key represented by the S-expression S_KEY
486 * and the OpenPGP key represented by PK do not use the same curve. */
488 match_curve_skey_pk (gcry_sexp_t s_key, PKT_public_key *pk)
490 gcry_sexp_t curve = NULL;
491 gcry_sexp_t flags = NULL;
492 char *curve_str = NULL;
494 const char *oidstr = NULL;
495 gcry_mpi_t curve_as_mpi = NULL;
500 if (!(pk->pubkey_algo==PUBKEY_ALGO_ECDH
501 || pk->pubkey_algo==PUBKEY_ALGO_ECDSA
502 || pk->pubkey_algo==PUBKEY_ALGO_EDDSA))
503 return gpg_error (GPG_ERR_PUBKEY_ALGO);
505 curve = gcry_sexp_find_token (s_key, "curve", 0);
508 log_error ("no reported curve\n");
509 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
511 curve_str = gcry_sexp_nth_string (curve, 1);
512 gcry_sexp_release (curve); curve = NULL;
515 log_error ("no curve name\n");
516 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
518 oidstr = openpgp_curve_to_oid (curve_str, NULL);
521 log_error ("no OID known for curve '%s'\n", curve_str);
523 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
526 err = openpgp_oid_from_str (oidstr, &curve_as_mpi);
529 if (gcry_mpi_cmp (pk->pkey[0], curve_as_mpi))
531 log_error ("curves do not match\n");
532 gcry_mpi_release (curve_as_mpi);
533 return gpg_error (GPG_ERR_INV_CURVE);
535 gcry_mpi_release (curve_as_mpi);
536 flags = gcry_sexp_find_token (s_key, "flags", 0);
539 for (idx = 1; idx < gcry_sexp_length (flags); idx++)
541 flag = gcry_sexp_nth_string (flags, idx);
542 if (flag && (strcmp ("eddsa", flag) == 0))
547 if (is_eddsa != (pk->pubkey_algo == PUBKEY_ALGO_EDDSA))
549 log_error ("disagreement about EdDSA\n");
550 err = gpg_error (GPG_ERR_INV_CURVE);
557 /* Return a canonicalized public key algoithms. This is used to
558 compare different flavors of algorithms (e.g. ELG and ELG_E are
559 considered the same). */
560 static enum gcry_pk_algos
561 canon_pk_algo (enum gcry_pk_algos algo)
567 case GCRY_PK_RSA_S: return GCRY_PK_RSA;
569 case GCRY_PK_ELG_E: return GCRY_PK_ELG;
572 case GCRY_PK_ECDH: return GCRY_PK_ECC;
573 default: return algo;
578 /* Take a cleartext dump of a secret key in PK and change the
579 * parameter array in PK to include the secret parameters. */
581 cleartext_secret_key_to_openpgp (gcry_sexp_t s_key, PKT_public_key *pk)
583 gpg_error_t err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
584 gcry_sexp_t top_list;
585 gcry_sexp_t key = NULL;
586 char *key_type = NULL;
587 enum gcry_pk_algos pk_algo;
588 struct seckey_info *ski;
590 gcry_mpi_t pub_params[10] = { NULL };
592 /* we look for a private-key, then the first element in it tells us
594 top_list = gcry_sexp_find_token (s_key, "private-key", 0);
597 if (gcry_sexp_length(top_list) != 2)
599 key = gcry_sexp_nth (top_list, 1);
602 key_type = gcry_sexp_nth_string(key, 0);
603 pk_algo = gcry_pk_map_name (key_type);
605 log_assert (!pk->seckey_info);
607 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
610 err = gpg_error_from_syserror ();
614 switch (canon_pk_algo (pk_algo))
617 if (!is_RSA (pk->pubkey_algo))
618 goto bad_pubkey_algo;
619 err = gcry_sexp_extract_param (key, NULL, "ne",
623 for (idx=0; idx < 2 && !err; idx++)
624 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
625 err = gpg_error (GPG_ERR_BAD_PUBKEY);
628 for (idx = 2; idx < 6 && !err; idx++)
630 gcry_mpi_release (pk->pkey[idx]);
631 pk->pkey[idx] = NULL;
633 err = gcry_sexp_extract_param (key, NULL, "dpqu",
642 for (idx = 2; idx < 6; idx++)
643 ski->csum += checksum_mpi (pk->pkey[idx]);
648 if (!is_DSA (pk->pubkey_algo))
649 goto bad_pubkey_algo;
650 err = gcry_sexp_extract_param (key, NULL, "pqgy",
656 for (idx=0; idx < 4 && !err; idx++)
657 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
658 err = gpg_error (GPG_ERR_BAD_PUBKEY);
661 gcry_mpi_release (pk->pkey[4]);
663 err = gcry_sexp_extract_param (key, NULL, "x",
668 ski->csum += checksum_mpi (pk->pkey[4]);
672 if (!is_ELGAMAL (pk->pubkey_algo))
673 goto bad_pubkey_algo;
674 err = gcry_sexp_extract_param (key, NULL, "pgy",
679 for (idx=0; idx < 3 && !err; idx++)
680 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
681 err = gpg_error (GPG_ERR_BAD_PUBKEY);
684 gcry_mpi_release (pk->pkey[3]);
686 err = gcry_sexp_extract_param (key, NULL, "x",
691 ski->csum += checksum_mpi (pk->pkey[3]);
695 err = match_curve_skey_pk (key, pk);
699 err = gcry_sexp_extract_param (key, NULL, "q",
702 if (!err && (gcry_mpi_cmp(pk->pkey[1], pub_params[0])))
703 err = gpg_error (GPG_ERR_BAD_PUBKEY);
706 if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
710 gcry_mpi_release (pk->pkey[sec_start]);
711 pk->pkey[sec_start] = NULL;
712 err = gcry_sexp_extract_param (key, NULL, "d",
713 &pk->pkey[sec_start],
718 ski->csum += checksum_mpi (pk->pkey[sec_start]);
722 pk->seckey_info = NULL;
724 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
729 gcry_sexp_release (top_list);
730 gcry_sexp_release (key);
731 gcry_free (key_type);
733 for (idx=0; idx < DIM(pub_params); idx++)
734 gcry_mpi_release (pub_params[idx]);
738 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
742 err = gpg_error (GPG_ERR_BAD_SECKEY);
747 /* Use the key transfer format given in S_PGP to create the secinfo
748 structure in PK and change the parameter array in PK to include the
749 secret parameters. */
751 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
754 gcry_sexp_t top_list;
755 gcry_sexp_t list = NULL;
761 int is_v4, is_protected;
762 enum gcry_pk_algos pk_algo;
763 int protect_algo = 0;
772 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
774 struct seckey_info *ski;
776 /* gcry_log_debugsxp ("transferkey", s_pgp); */
777 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
781 list = gcry_sexp_find_token (top_list, "version", 0);
784 value = gcry_sexp_nth_data (list, 1, &valuelen);
785 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
787 is_v4 = (value[0] == '4');
789 gcry_sexp_release (list);
790 list = gcry_sexp_find_token (top_list, "protection", 0);
793 value = gcry_sexp_nth_data (list, 1, &valuelen);
796 if (valuelen == 4 && !memcmp (value, "sha1", 4))
798 else if (valuelen == 3 && !memcmp (value, "sum", 3))
800 else if (valuelen == 4 && !memcmp (value, "none", 4))
806 string = gcry_sexp_nth_string (list, 2);
809 protect_algo = gcry_cipher_map_name (string);
812 value = gcry_sexp_nth_data (list, 3, &valuelen);
813 if (!value || !valuelen || valuelen > sizeof iv)
815 memcpy (iv, value, valuelen);
818 string = gcry_sexp_nth_string (list, 4);
821 s2k_mode = strtol (string, NULL, 10);
824 string = gcry_sexp_nth_string (list, 5);
827 s2k_algo = gcry_md_map_name (string);
830 value = gcry_sexp_nth_data (list, 6, &valuelen);
831 if (!value || !valuelen || valuelen > sizeof s2k_salt)
833 memcpy (s2k_salt, value, valuelen);
835 string = gcry_sexp_nth_string (list, 7);
838 s2k_count = strtoul (string, NULL, 10);
842 /* Parse the gcrypt PK algo and check that it is okay. */
843 gcry_sexp_release (list);
844 list = gcry_sexp_find_token (top_list, "algo", 0);
847 string = gcry_sexp_nth_string (list, 1);
850 pk_algo = gcry_pk_map_name (string);
851 xfree (string); string = NULL;
852 if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
853 || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
854 || !npkey || npkey >= nskey)
857 /* Check that the pubkey algo matches the one from the public key. */
858 switch (canon_pk_algo (pk_algo))
861 if (!is_RSA (pk->pubkey_algo))
862 pk_algo = 0; /* Does not match. */
865 if (!is_DSA (pk->pubkey_algo))
866 pk_algo = 0; /* Does not match. */
869 if (!is_ELGAMAL (pk->pubkey_algo))
870 pk_algo = 0; /* Does not match. */
873 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
875 else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
877 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
880 pk_algo = 0; /* Does not match. */
881 /* For ECC we do not have the domain parameters thus fix our info. */
886 pk_algo = 0; /* Oops. */
891 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
895 /* This check has to go after the ecc adjustments. */
896 if (nskey > PUBKEY_MAX_NSKEY)
899 /* Parse the key parameters. */
900 gcry_sexp_release (list);
901 list = gcry_sexp_find_token (top_list, "skey", 0);
908 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
909 if (!value && skeyidx >= npkey)
912 /* Check for too many parameters. Note that depending on the
913 protection mode and version number we may see less than NSKEY
914 (but at least NPKEY+1) parameters. */
917 if (skeyidx >= DIM (skey)-1)
920 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
922 is_enc = (value[0] == 'e');
923 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
924 if (!value || !valuelen)
928 void *p = xtrymalloc (valuelen);
931 memcpy (p, value, valuelen);
932 skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
938 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
939 value, valuelen, NULL))
944 skey[skeyidx++] = NULL;
946 gcry_sexp_release (list); list = NULL;
948 /* We have no need for the CSUM value thus we don't parse it. */
949 /* list = gcry_sexp_find_token (top_list, "csum", 0); */
952 /* string = gcry_sexp_nth_string (list, 1); */
954 /* goto bad_seckey; */
955 /* desired_csum = strtoul (string, NULL, 10); */
956 /* xfree (string); */
959 /* desired_csum = 0; */
960 /* gcry_sexp_release (list); list = NULL; */
962 /* Get the curve name if any, */
963 list = gcry_sexp_find_token (top_list, "curve", 0);
966 curve = gcry_sexp_nth_string (list, 1);
967 gcry_sexp_release (list); list = NULL;
970 gcry_sexp_release (top_list); top_list = NULL;
972 /* log_debug ("XXX is_v4=%d\n", is_v4); */
973 /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
974 /* log_debug ("XXX is_protected=%d\n", is_protected); */
975 /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
976 /* log_printhex ("XXX iv", iv, ivlen); */
977 /* log_debug ("XXX ivlen=%d\n", ivlen); */
978 /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
979 /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
980 /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
981 /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
982 /* for (idx=0; skey[idx]; idx++) */
984 /* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
985 /* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
989 /* unsigned int nbits; */
990 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
991 /* log_printhex (NULL, p, (nbits+7)/8); */
994 /* gcry_mpi_dump (skey[idx]); */
995 /* log_printf ("\n"); */
998 if (!is_v4 || is_protected != 2 )
1000 /* We only support the v4 format and a SHA-1 checksum. */
1001 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1005 /* We need to change the received parameters for ECC algorithms.
1006 The transfer format has the curve name and the parameters
1007 separate. We put them all into the SKEY array. */
1008 if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
1012 /* Assert that all required parameters are available. We also
1013 check that the array does not contain more parameters than
1014 needed (this was used by some beta versions of 2.1. */
1015 if (!curve || !skey[0] || !skey[1] || skey[2])
1017 err = gpg_error (GPG_ERR_INTERNAL);
1021 oidstr = openpgp_curve_to_oid (curve, NULL);
1024 log_error ("no OID known for curve '%s'\n", curve);
1025 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1028 /* Put the curve's OID into into the MPI array. This requires
1029 that we shift Q and D. For ECDH also insert the KDF parms. */
1034 skey[2] = gcry_mpi_copy (pk->pkey[2]);
1043 err = openpgp_oid_from_str (oidstr, skey + 0);
1046 /* Fixup the NPKEY and NSKEY to match OpenPGP reality. */
1047 npkey = 2 + is_ecdh;
1048 nskey = 3 + is_ecdh;
1050 /* for (idx=0; skey[idx]; idx++) */
1052 /* log_info ("YYY skey[%d]:", idx); */
1053 /* if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
1056 /* unsigned int nbits; */
1057 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
1058 /* log_printhex (NULL, p, (nbits+7)/8); */
1061 /* gcry_mpi_dump (skey[idx]); */
1062 /* log_printf ("\n"); */
1066 /* Do some sanity checks. */
1067 if (s2k_count > 255)
1069 /* We expect an already encoded S2K count. */
1070 err = gpg_error (GPG_ERR_INV_DATA);
1073 err = openpgp_cipher_test_algo (protect_algo);
1076 err = openpgp_md_test_algo (s2k_algo);
1080 /* Check that the public key parameters match. Note that since
1081 Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly. */
1082 for (idx=0; idx < npkey; idx++)
1083 if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
1085 err = gpg_error (GPG_ERR_BAD_PUBKEY);
1089 /* Check that the first secret key parameter in SKEY is encrypted
1090 and that there are no more secret key parameters. The latter is
1091 guaranteed by the v4 packet format. */
1092 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
1094 if (npkey+1 < DIM (skey) && skey[npkey+1])
1097 /* Check that the secret key parameters in PK are all set to NULL. */
1098 for (idx=npkey; idx < nskey; idx++)
1102 /* Now build the protection info. */
1103 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1106 err = gpg_error_from_syserror ();
1110 ski->is_protected = 1;
1112 ski->algo = protect_algo;
1113 ski->s2k.mode = s2k_mode;
1114 ski->s2k.hash_algo = s2k_algo;
1115 log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
1116 memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
1117 ski->s2k.count = s2k_count;
1118 log_assert (ivlen <= sizeof ski->iv);
1119 memcpy (ski->iv, iv, ivlen);
1122 /* Store the protected secret key parameter. */
1123 pk->pkey[npkey] = skey[npkey];
1130 gcry_sexp_release (list);
1131 gcry_sexp_release (top_list);
1132 for (idx=0; idx < skeyidx; idx++)
1133 gcry_mpi_release (skey[idx]);
1137 err = gpg_error (GPG_ERR_BAD_SECKEY);
1141 err = gpg_error (GPG_ERR_ENOMEM);
1146 /* Print an "EXPORTED" status line. PK is the primary public key. */
1148 print_status_exported (PKT_public_key *pk)
1152 if (!is_status_enabled ())
1155 hexfpr = hexfingerprint (pk, NULL, 0);
1156 write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
1162 * Receive a secret key from agent specified by HEXGRIP.
1164 * Since the key data from the agent is encrypted, decrypt it using
1165 * CIPHERHD context. Then, parse the decrypted key data into transfer
1166 * format, and put secret parameters into PK.
1168 * If CLEARTEXT is 0, store the secret key material
1169 * passphrase-protected. Otherwise, store secret key material in the
1172 * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
1175 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
1177 char **cache_nonce_addr, const char *hexgrip,
1180 gpg_error_t err = 0;
1181 unsigned char *wrappedkey = NULL;
1182 size_t wrappedkeylen;
1183 unsigned char *key = NULL;
1184 size_t keylen, realkeylen;
1189 log_info ("key %s: asking agent for the secret parts\n", hexgrip);
1191 prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
1192 err = agent_export_key (ctrl, hexgrip, prompt, !cleartext, cache_nonce_addr,
1193 &wrappedkey, &wrappedkeylen);
1198 if (wrappedkeylen < 24)
1200 err = gpg_error (GPG_ERR_INV_LENGTH);
1203 keylen = wrappedkeylen - 8;
1204 key = xtrymalloc_secure (keylen);
1207 err = gpg_error_from_syserror ();
1210 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
1213 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
1215 goto unwraperror; /* Invalid csexp. */
1217 err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
1221 err = cleartext_secret_key_to_openpgp (s_skey, pk);
1223 err = transfer_format_to_openpgp (s_skey, pk);
1224 gcry_sexp_release (s_skey);
1232 log_error ("key %s: error receiving key from agent:"
1233 " %s%s\n", hexgrip, gpg_strerror (err),
1234 gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
1235 "":_(" - skipped"));
1241 /* Write KEYBLOCK either to stdout or to the file set with the
1242 * --output option. This is a simplified version of do_export_stream
1243 * which supports only a few export options. */
1245 write_keyblock_to_output (kbnode_t keyblock, int with_armor,
1246 unsigned int options)
1252 armor_filter_context_t *afx = NULL;
1253 iobuf_t out_help = NULL;
1254 PKT_public_key *pk = NULL;
1256 fname = opt.outfile? opt.outfile : "-";
1257 if (is_secured_filename (fname) )
1258 return gpg_error (GPG_ERR_EPERM);
1260 out = iobuf_create (fname, 0);
1263 err = gpg_error_from_syserror ();
1264 log_error(_("can't create '%s': %s\n"), fname, gpg_strerror (err));
1268 log_info (_("writing to '%s'\n"), iobuf_get_fname_nonnull (out));
1270 if ((options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)))
1273 out_help = iobuf_temp ();
1278 afx = new_armor_context ();
1280 push_armor_filter (afx, out);
1283 for (node = keyblock; node; node = node->next)
1285 if (is_deleted_kbnode (node) || node->pkt->pkttype == PKT_RING_TRUST)
1287 if (!pk && (node->pkt->pkttype == PKT_PUBLIC_KEY
1288 || node->pkt->pkttype == PKT_SECRET_KEY))
1289 pk = node->pkt->pkt.public_key;
1291 err = build_packet (out_help? out_help : out, node->pkt);
1294 log_error ("build_packet(%d) failed: %s\n",
1295 node->pkt->pkttype, gpg_strerror (err) );
1306 iobuf_flush_temp (out_help);
1307 data = iobuf_get_temp_buffer (out_help);
1308 datalen = iobuf_get_temp_length (out_help);
1310 err = print_pka_or_dane_records (out,
1311 keyblock, pk, data, datalen,
1312 (options & EXPORT_PKA_FORMAT),
1313 (options & EXPORT_DANE_FORMAT));
1321 iobuf_cancel (out_help);
1322 release_armor_context (afx);
1328 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1329 * marked and thus the caller should call commit_kbnode afterwards.
1330 * KEYBLOCK must not have any blocks marked as deleted.
1333 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1337 for (node = keyblock->next; node; node = node->next )
1339 if (node->pkt->pkttype == PKT_USER_ID)
1341 if (!recsel_select (selector, impex_filter_getval, node))
1343 /* log_debug ("keep-uid: deleting '%s'\n", */
1344 /* node->pkt->pkt.user_id->name); */
1345 /* The UID packet and all following packets up to the
1346 * next UID or a subkey. */
1347 delete_kbnode (node);
1349 && node->next->pkt->pkttype != PKT_USER_ID
1350 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1351 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1353 delete_kbnode (node->next);
1356 /* log_debug ("keep-uid: keeping '%s'\n", */
1357 /* node->pkt->pkt.user_id->name); */
1364 * Apply the drop-subkey filter to the keyblock. The deleted nodes are
1365 * marked and thus the caller should call commit_kbnode afterwards.
1366 * KEYBLOCK must not have any blocks marked as deleted.
1369 apply_drop_subkey_filter (kbnode_t keyblock, recsel_expr_t selector)
1373 for (node = keyblock->next; node; node = node->next )
1375 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1376 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1378 if (recsel_select (selector, impex_filter_getval, node))
1380 log_debug ("drop-subkey: deleting a key\n");
1381 /* The subkey packet and all following packets up to the
1383 delete_kbnode (node);
1385 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1386 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1388 delete_kbnode (node->next);
1395 /* Print DANE or PKA records for all user IDs in KEYBLOCK to OUT. The
1396 * data for the record is taken from (DATA,DATELEN). PK is the public
1397 * key packet with the primary key. */
1399 print_pka_or_dane_records (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
1400 const void *data, size_t datalen,
1401 int print_pka, int print_dane)
1403 gpg_error_t err = 0;
1404 kbnode_t kbctx, node;
1412 estream_t fp = NULL;
1413 char *hexdata = NULL;
1416 hexfpr = hexfingerprint (pk, NULL, 0);
1417 hexdata = bin2hex (data, datalen, NULL);
1420 err = gpg_error_from_syserror ();
1423 ascii_strlwr (hexdata);
1424 fp = es_fopenmem (0, "rw,samethread");
1427 err = gpg_error_from_syserror ();
1431 for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1433 if (node->pkt->pkttype != PKT_USER_ID)
1435 uid = node->pkt->pkt.user_id;
1437 if (uid->is_expired || uid->is_revoked)
1441 mbox = mailbox_from_userid (uid->name);
1445 domain = strchr (mbox, '@');
1450 es_fprintf (fp, "$ORIGIN _pka.%s.\n; %s\n; ", domain, hexfpr);
1451 print_utf8_buffer (fp, uid->name, uid->len);
1453 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
1455 hash = zb32_encode (hashbuf, 8*20);
1458 err = gpg_error_from_syserror ();
1461 len = strlen (hexfpr)/2;
1462 es_fprintf (fp, "%s TYPE37 \\# %u 0006 0000 00 %02X %s\n\n",
1463 hash, 6 + len, len, hexfpr);
1466 if (print_dane && hexdata)
1468 es_fprintf (fp, "$ORIGIN _openpgpkey.%s.\n; %s\n; ", domain, hexfpr);
1469 print_utf8_buffer (fp, uid->name, uid->len);
1471 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
1473 hash = bin2hex (hashbuf, 28, NULL);
1476 err = gpg_error_from_syserror ();
1479 ascii_strlwr (hash);
1480 len = strlen (hexdata)/2;
1481 es_fprintf (fp, "%s TYPE61 \\# %u (\n", hash, len);
1482 for (s = hexdata; ;)
1484 es_fprintf (fp, "\t%.64s\n", s);
1485 if (strlen (s) < 64)
1489 es_fputs ("\t)\n\n", fp);
1493 /* Make sure it is a string and write it. */
1498 if (es_fclose_snatch (fp, &vp, NULL))
1500 err = gpg_error_from_syserror ();
1504 iobuf_writestr (out, vp);
1519 /* Helper for do_export_stream which writes one keyblock to OUT. */
1521 do_export_one_keyblock (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
1522 iobuf_t out, int secret, unsigned int options,
1523 export_stats_t stats, int *any,
1524 KEYDB_SEARCH_DESC *desc, size_t ndesc,
1525 size_t descindex, gcry_cipher_hd_t cipherhd)
1528 char *cache_nonce = NULL;
1529 subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
1530 int skip_until_subkey = 0;
1532 char *hexgrip = NULL;
1533 char *serialno = NULL;
1535 u32 subkidbuf[2], *subkid;
1536 kbnode_t kbctx, node;
1538 /* NB: walk_kbnode skips packets marked as deleted. */
1539 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1541 if (skip_until_subkey)
1543 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1544 skip_until_subkey = 0;
1549 /* We used to use comment packets, but not any longer. In
1550 * case we still have comments on a key, strip them here
1551 * before we call build_packet(). */
1552 if (node->pkt->pkttype == PKT_COMMENT)
1555 /* Make sure that ring_trust packets are only exported in backup
1557 if (node->pkt->pkttype == PKT_RING_TRUST && !(options & EXPORT_BACKUP))
1560 /* If exact is set, then we only export what was requested
1561 * (plus the primary key, if the user didn't specifically
1563 if (desc[descindex].exact && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1565 if (!exact_subkey_match_p (desc+descindex, node))
1567 /* Before skipping this subkey, check whether any
1568 * other description wants an exact match on a
1569 * subkey and include that subkey into the output
1570 * too. Need to add this subkey to a list so that
1571 * it won't get processed a second time.
1573 * So the first step here is to check that list and
1574 * skip in any case if the key is in that list.
1576 * We need this whole mess because the import
1577 * function of GnuPG < 2.1 is not able to merge
1578 * secret keys and thus it is useless to output them
1579 * as two separate keys and have import merge them.
1581 if (subkey_in_list_p (subkey_list, node))
1582 skip_until_subkey = 1; /* Already processed this one. */
1587 for (j=0; j < ndesc; j++)
1588 if (j != descindex && desc[j].exact
1589 && exact_subkey_match_p (desc+j, node))
1592 skip_until_subkey = 1; /* No other one matching. */
1596 if (skip_until_subkey)
1599 /* Mark this one as processed. */
1601 subkey_list_t tmp = new_subkey_list_item (node);
1602 tmp->next = subkey_list;
1607 if (node->pkt->pkttype == PKT_SIGNATURE)
1609 /* Do not export packets which are marked as not
1611 if (!(options & EXPORT_LOCAL_SIGS)
1612 && !node->pkt->pkt.signature->flags.exportable)
1613 continue; /* not exportable */
1615 /* Do not export packets with a "sensitive" revocation key
1616 * unless the user wants us to. Note that we do export
1617 * these when issuing the actual revocation (see revoke.c). */
1618 if (!(options & EXPORT_SENSITIVE_REVKEYS)
1619 && node->pkt->pkt.signature->revkey)
1623 for (i = 0; i < node->pkt->pkt.signature->numrevkeys; i++)
1624 if ((node->pkt->pkt.signature->revkey[i].class & 0x40))
1626 if (i < node->pkt->pkt.signature->numrevkeys)
1631 /* Don't export attribs? */
1632 if (!(options & EXPORT_ATTRIBUTES)
1633 && node->pkt->pkttype == PKT_USER_ID
1634 && node->pkt->pkt.user_id->attrib_data)
1636 /* Skip until we get to something that is not an attrib or a
1637 * signature on an attrib. */
1638 while (kbctx->next && kbctx->next->pkt->pkttype == PKT_SIGNATURE)
1639 kbctx = kbctx->next;
1644 if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1645 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1647 pk = node->pkt->pkt.public_key;
1648 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1652 keyid_from_pk (pk, subkidbuf);
1656 if (pk->seckey_info)
1658 log_error ("key %s: oops: seckey_info already set"
1659 " - skipped\n", keystr_with_sub (keyid, subkid));
1660 skip_until_subkey = 1;
1665 err = hexkeygrip_from_pk (pk, &hexgrip);
1668 log_error ("key %s: error computing keygrip: %s"
1669 " - skipped\n", keystr_with_sub (keyid, subkid),
1670 gpg_strerror (err));
1671 skip_until_subkey = 1;
1678 if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1680 /* We are asked not to export the secret parts of the
1681 * primary key. Make up an error code to create the
1683 err = GPG_ERR_NOT_FOUND;
1686 err = agent_get_keyinfo (ctrl, hexgrip, &serialno, &cleartext);
1688 if ((!err && serialno)
1689 && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1691 /* It does not make sense to export a key with its
1692 * primary key on card using a non-key stub. Thus we
1693 * skip those keys when used with --export-secret-subkeys. */
1694 log_info (_("key %s: key material on-card - skipped\n"),
1695 keystr_with_sub (keyid, subkid));
1696 skip_until_subkey = 1;
1698 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1699 || (!err && serialno))
1701 /* Create a key stub. */
1702 struct seckey_info *ski;
1705 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1708 err = gpg_error_from_syserror ();
1712 ski->is_protected = 1;
1714 ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
1717 ski->s2k.mode = 1002; /* GNU-divert-to-card. */
1718 for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1719 ski->ivlen++, s += 2)
1720 ski->iv[ski->ivlen] = xtoi_2 (s);
1723 err = build_packet (out, node->pkt);
1724 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1727 print_status_exported (node->pkt->pkt.public_key);
1732 err = receive_seckey_from_agent (ctrl, cipherhd,
1733 cleartext, &cache_nonce,
1737 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1739 skip_until_subkey = 1;
1744 err = build_packet (out, node->pkt);
1745 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1748 print_status_exported (node->pkt->pkt.public_key);
1754 log_error ("key %s: error getting keyinfo from agent: %s"
1755 " - skipped\n", keystr_with_sub (keyid, subkid),
1756 gpg_strerror (err));
1757 skip_until_subkey = 1;
1761 xfree (pk->seckey_info);
1762 pk->seckey_info = NULL;
1765 for (i = pubkey_get_npkey (pk->pubkey_algo);
1766 i < pubkey_get_nskey (pk->pubkey_algo); i++)
1768 gcry_mpi_release (pk->pkey[i]);
1773 else /* Not secret or common packets. */
1775 err = build_packet (out, node->pkt);
1776 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1779 print_status_exported (node->pkt->pkt.public_key);
1785 log_error ("build_packet(%d) failed: %s\n",
1786 node->pkt->pkttype, gpg_strerror (err));
1790 if (!skip_until_subkey)
1795 release_subkey_list (subkey_list);
1798 xfree (cache_nonce);
1803 /* Export the keys identified by the list of strings in USERS to the
1804 stream OUT. If SECRET is false public keys will be exported. With
1805 secret true secret keys will be exported; in this case 1 means the
1806 entire secret keyblock and 2 only the subkeys. OPTIONS are the
1807 export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
1808 code is zero, a pointer to the first keyblock found and exported
1809 will be stored at this address; no other keyblocks are exported in
1810 this case. The caller must free the returned keyblock. If any
1811 key has been exported true is stored at ANY. */
1813 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
1814 kbnode_t *keyblock_out, unsigned int options,
1815 export_stats_t stats, int *any)
1817 gpg_error_t err = 0;
1819 kbnode_t keyblock = NULL;
1821 size_t ndesc, descindex;
1822 KEYDB_SEARCH_DESC *desc = NULL;
1825 gcry_cipher_hd_t cipherhd = NULL;
1826 struct export_stats_s dummystats;
1827 iobuf_t out_help = NULL;
1830 stats = &dummystats;
1833 kdbhd = keydb_new ();
1835 return gpg_error_from_syserror ();
1837 /* For the PKA and DANE format open a helper iobuf and for DANE
1838 * enforce some options. */
1839 if ((options & (EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT)))
1841 out_help = iobuf_temp ();
1842 if ((options & EXPORT_DANE_FORMAT))
1843 options |= EXPORT_MINIMAL | EXPORT_CLEAN;
1849 desc = xcalloc (ndesc, sizeof *desc);
1850 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1854 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1856 desc = xmalloc ( ndesc * sizeof *desc);
1858 for (ndesc=0, sl=users; sl; sl = sl->next)
1860 if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
1863 log_error (_("key \"%s\" not found: %s\n"),
1864 sl->d, gpg_strerror (err));
1867 keydb_disable_caching (kdbhd); /* We are looping the search. */
1869 /* It would be nice to see which of the given users did actually
1870 match one in the keyring. To implement this we need to have
1871 a found flag for each entry in desc. To set this flag we
1872 must check all those entries after a match to mark all
1873 matched one - currently we stop at the first match. To do
1874 this we need an extra flag to enable this feature. */
1877 #ifdef ENABLE_SELINUX_HACKS
1880 log_error (_("exporting secret keys not allowed\n"));
1881 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1886 /* For secret key export we need to setup a decryption context. */
1892 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
1895 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1899 /* Prepare a cipher context. */
1900 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1901 GCRY_CIPHER_MODE_AESWRAP, 0);
1903 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1906 log_error ("error setting up an encryption context: %s\n",
1907 gpg_strerror (err));
1919 err = keydb_search (kdbhd, desc, ndesc, &descindex);
1921 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1925 /* Read the keyblock. */
1926 release_kbnode (keyblock);
1928 err = keydb_get_keyblock (kdbhd, &keyblock);
1931 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1935 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1938 log_error ("public key packet not found in keyblock - skipped\n");
1942 setup_main_keyids (keyblock); /* gpg_format_keydesc needs it. */
1943 pk = node->pkt->pkt.public_key;
1944 keyid_from_pk (pk, keyid);
1946 /* If a secret key export is required we need to check whether
1947 we have a secret key at all and if so create the seckey_info
1951 if (agent_probe_any_secret_key (ctrl, keyblock))
1952 continue; /* No secret key (neither primary nor subkey). */
1954 /* No v3 keys with GNU mode 1001. */
1955 if (secret == 2 && pk->version == 3)
1957 log_info (_("key %s: PGP 2.x style key - skipped\n"),
1962 /* The agent does not yet allow export of v3 packets. It is
1963 actually questionable whether we should allow them at
1965 if (pk->version == 3)
1967 log_info ("key %s: PGP 2.x style key (v3) export "
1968 "not yet supported - skipped\n", keystr (keyid));
1971 stats->secret_count++;
1974 /* Always do the cleaning on the public key part if requested.
1975 * Note that both export-clean and export-minimal only apply to
1976 * UID sigs (0x10, 0x11, 0x12, and 0x13). A designated
1977 * revocation is never stripped, even with export-minimal set. */
1978 if ((options & EXPORT_CLEAN))
1979 clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1981 if (export_keep_uid)
1983 commit_kbnode (&keyblock);
1984 apply_keep_uid_filter (keyblock, export_keep_uid);
1985 commit_kbnode (&keyblock);
1988 if (export_drop_subkey)
1990 commit_kbnode (&keyblock);
1991 apply_drop_subkey_filter (keyblock, export_drop_subkey);
1992 commit_kbnode (&keyblock);
1996 err = do_export_one_keyblock (ctrl, keyblock, keyid,
1997 out_help? out_help : out,
1998 secret, options, stats, any,
1999 desc, ndesc, descindex, cipherhd);
2005 *keyblock_out = keyblock;
2011 /* We want to write PKA or DANE records. OUT_HELP has the
2012 * keyblock and we print a record for each uid to OUT. */
2016 iobuf_flush_temp (out_help);
2017 data = iobuf_get_temp_buffer (out_help);
2018 datalen = iobuf_get_temp_length (out_help);
2020 err = print_pka_or_dane_records (out,
2021 keyblock, pk, data, datalen,
2022 (options & EXPORT_PKA_FORMAT),
2023 (options & EXPORT_DANE_FORMAT));
2027 iobuf_close (out_help);
2028 out_help = iobuf_temp ();
2032 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2036 iobuf_cancel (out_help);
2037 gcry_cipher_close (cipherhd);
2039 keydb_release (kdbhd);
2040 if (err || !keyblock_out)
2041 release_kbnode( keyblock );
2043 log_info(_("WARNING: nothing exported\n"));
2051 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
2054 gpg_error_t err = 0;
2055 unsigned char nbuf[4];
2060 ulongtobuf (nbuf, (ulong)strlen (identifier));
2061 put_membuf (mb, nbuf, 4);
2062 put_membuf_str (mb, identifier);
2063 if (!strncmp (identifier, "ecdsa-sha2-", 11))
2065 ulongtobuf (nbuf, (ulong)strlen (identifier+11));
2066 put_membuf (mb, nbuf, 4);
2067 put_membuf_str (mb, identifier+11);
2069 va_start (arg_ptr, identifier);
2070 while ((a = va_arg (arg_ptr, gcry_mpi_t)))
2072 err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
2075 if (!strcmp (identifier, "ssh-ed25519")
2076 && buflen > 5 && buf[4] == 0x40)
2078 /* We need to strip our 0x40 prefix. */
2079 put_membuf (mb, "\x00\x00\x00\x20", 4);
2080 put_membuf (mb, buf+5, buflen-5);
2083 put_membuf (mb, buf, buflen);
2090 /* Export the key identified by USERID in the SSH public key format.
2091 The function exports the latest subkey with Authentication
2092 capability unless the '!' suffix is used to export a specific
2095 export_ssh_key (ctrl_t ctrl, const char *userid)
2098 kbnode_t keyblock = NULL;
2099 KEYDB_SEARCH_DESC desc;
2101 u32 curtime = make_timestamp ();
2102 kbnode_t latest_key, node;
2104 const char *identifier;
2106 estream_t fp = NULL;
2107 struct b64state b64_state;
2108 const char *fname = "-";
2110 init_membuf (&mb, 4096);
2112 /* We need to know whether the key has been specified using the
2113 exact syntax ('!' suffix). Thus we need to run a
2114 classify_user_id on our own. */
2115 err = classify_user_id (userid, &desc, 1);
2117 /* Get the public key. */
2120 getkey_ctx_t getkeyctx;
2122 err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
2124 0 /* Only usable keys or given exact. */,
2125 1 /* No AKL lookup. */);
2128 err = getkey_next (getkeyctx, NULL, NULL);
2130 err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2131 else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
2134 getkey_end (getkeyctx);
2138 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2142 /* The finish_lookup code in getkey.c does not handle auth keys,
2143 thus we have to duplicate the code here to find the latest
2144 subkey. However, if the key has been found using an exact match
2145 ('!' notation) we use that key without any further checks and
2146 even allow the use of the primary key. */
2149 for (node = keyblock; node; node = node->next)
2151 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2152 || node->pkt->pkttype == PKT_PUBLIC_KEY)
2153 && node->pkt->pkt.public_key->flags.exact)
2161 for (node = keyblock; node; node = node->next)
2163 if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2166 pk = node->pkt->pkt.public_key;
2168 log_debug ("\tchecking subkey %08lX\n",
2169 (ulong) keyid_from_pk (pk, NULL));
2170 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2173 log_debug ("\tsubkey not usable for authentication\n");
2176 if (!pk->flags.valid)
2179 log_debug ("\tsubkey not valid\n");
2182 if (pk->flags.revoked)
2185 log_debug ("\tsubkey has been revoked\n");
2188 if (pk->has_expired)
2191 log_debug ("\tsubkey has expired\n");
2194 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2197 log_debug ("\tsubkey not yet valid\n");
2201 log_debug ("\tsubkey might be fine\n");
2202 /* In case a key has a timestamp of 0 set, we make sure that it
2203 is used. A better change would be to compare ">=" but that
2204 might also change the selected keys and is as such a more
2205 intrusive change. */
2206 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2208 latest_date = pk->timestamp;
2213 /* If no subkey was suitable check the primary key. */
2215 && (node = keyblock) && node->pkt->pkttype == PKT_PUBLIC_KEY)
2217 pk = node->pkt->pkt.public_key;
2219 log_debug ("\tchecking primary key %08lX\n",
2220 (ulong) keyid_from_pk (pk, NULL));
2221 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2224 log_debug ("\tprimary key not usable for authentication\n");
2226 else if (!pk->flags.valid)
2229 log_debug ("\tprimary key not valid\n");
2231 else if (pk->flags.revoked)
2234 log_debug ("\tprimary key has been revoked\n");
2236 else if (pk->has_expired)
2239 log_debug ("\tprimary key has expired\n");
2241 else if (pk->timestamp > curtime && !opt.ignore_valid_from)
2244 log_debug ("\tprimary key not yet valid\n");
2249 log_debug ("\tprimary key is fine\n");
2250 latest_date = pk->timestamp;
2258 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2259 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2263 pk = latest_key->pkt->pkt.public_key;
2265 log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
2267 switch (pk->pubkey_algo)
2269 case PUBKEY_ALGO_DSA:
2270 identifier = "ssh-dss";
2271 err = key_to_sshblob (&mb, identifier,
2272 pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
2276 case PUBKEY_ALGO_RSA:
2277 case PUBKEY_ALGO_RSA_S:
2278 identifier = "ssh-rsa";
2279 err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
2282 case PUBKEY_ALGO_ECDSA:
2287 curveoid = openpgp_oid_to_str (pk->pkey[0]);
2289 err = gpg_error_from_syserror ();
2290 else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
2291 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2294 if (!strcmp (curve, "nistp256"))
2295 identifier = "ecdsa-sha2-nistp256";
2296 else if (!strcmp (curve, "nistp384"))
2297 identifier = "ecdsa-sha2-nistp384";
2298 else if (!strcmp (curve, "nistp521"))
2299 identifier = "ecdsa-sha2-nistp521";
2304 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2306 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2312 case PUBKEY_ALGO_EDDSA:
2313 if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
2314 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2317 identifier = "ssh-ed25519";
2318 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2322 case PUBKEY_ALGO_ELGAMAL_E:
2323 case PUBKEY_ALGO_ELGAMAL:
2324 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2328 err = GPG_ERR_PUBKEY_ALGO;
2335 if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
2336 fp = es_fopen ((fname = opt.outfile), "w");
2341 err = gpg_error_from_syserror ();
2342 log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
2346 es_fprintf (fp, "%s ", identifier);
2347 err = b64enc_start_es (&b64_state, fp, "");
2354 blob = get_membuf (&mb, &bloblen);
2356 err = gpg_error_from_syserror ();
2358 err = b64enc_write (&b64_state, blob, bloblen);
2363 err = b64enc_finish (&b64_state);
2366 es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
2369 err = gpg_error_from_syserror ();
2373 err = gpg_error_from_syserror ();
2378 log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
2382 xfree (get_membuf (&mb, NULL));
2383 release_kbnode (keyblock);