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. If USERS is NULL,
251 * all secret keys will be exported. STATS is either an export stats
252 * 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, export_stats_t stats)
259 return do_export (ctrl, users, 1, 0, stats);
264 * Export secret sub keys (to stdout or to --output FILE).
266 * This is the same as export_seckeys but replaces the primary key by
267 * a stub key. Depending on opt.armor the output is armored. If
268 * USERS is NULL, all secret subkeys will be exported. STATS is
269 * either an export stats object for update or NULL.
271 * This function is the core of "gpg --export-secret-subkeys".
274 export_secsubkeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
276 return do_export (ctrl, users, 2, 0, stats);
281 * Export a single key into a memory buffer. STATS is either an
282 * export stats object for update or NULL.
285 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
286 export_stats_t stats,
287 kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
299 if (!add_to_strlist_try (&helplist, keyspec))
300 return gpg_error_from_syserror ();
302 iobuf = iobuf_temp ();
303 err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
306 err = gpg_error (GPG_ERR_NOT_FOUND);
312 iobuf_flush_temp (iobuf);
313 src = iobuf_get_temp_buffer (iobuf);
314 datalen = iobuf_get_temp_length (iobuf);
316 err = gpg_error (GPG_ERR_NO_PUBKEY);
317 else if (!(*r_data = xtrymalloc (datalen)))
318 err = gpg_error_from_syserror ();
321 memcpy (*r_data, src, datalen);
322 *r_datalen = datalen;
326 free_strlist (helplist);
327 if (err && *r_keyblock)
329 release_kbnode (*r_keyblock);
336 /* Export the keys identified by the list of strings in USERS. If
337 Secret is false public keys will be exported. With secret true
338 secret keys will be exported; in this case 1 means the entire
339 secret keyblock and 2 only the subkeys. OPTIONS are the export
342 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
343 export_stats_t stats)
347 armor_filter_context_t *afx = NULL;
348 compress_filter_context_t zfx;
350 memset( &zfx, 0, sizeof zfx);
352 rc = open_outfile (-1, NULL, 0, !!secret, &out );
356 if ( opt.armor && !(options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)) )
358 afx = new_armor_context ();
359 afx->what = secret? 5 : 1;
360 push_armor_filter (afx, out);
363 rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
369 release_armor_context (afx);
375 /* Release an entire subkey list. */
377 release_subkey_list (subkey_list_t list)
381 subkey_list_t tmp = list->next;;
388 /* Returns true if NODE is a subkey and contained in LIST. */
390 subkey_in_list_p (subkey_list_t list, KBNODE node)
392 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
393 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
397 keyid_from_pk (node->pkt->pkt.public_key, kid);
399 for (; list; list = list->next)
400 if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
406 /* Allocate a new subkey list item from NODE. */
408 new_subkey_list_item (KBNODE node)
410 subkey_list_t list = xcalloc (1, sizeof *list);
412 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
413 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
414 keyid_from_pk (node->pkt->pkt.public_key, list->kid);
420 /* Helper function to check whether the subkey at NODE actually
421 matches the description at DESC. The function returns true if the
422 key under question has been specified by an exact specification
423 (keyID or fingerprint) and does match the one at NODE. It is
424 assumed that the packet at NODE is either a public or secret
427 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
430 byte fpr[MAX_FINGERPRINT_LEN];
436 case KEYDB_SEARCH_MODE_SHORT_KID:
437 case KEYDB_SEARCH_MODE_LONG_KID:
438 keyid_from_pk (node->pkt->pkt.public_key, kid);
441 case KEYDB_SEARCH_MODE_FPR16:
442 case KEYDB_SEARCH_MODE_FPR20:
443 case KEYDB_SEARCH_MODE_FPR:
444 fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
453 case KEYDB_SEARCH_MODE_SHORT_KID:
454 if (desc->u.kid[1] == kid[1])
458 case KEYDB_SEARCH_MODE_LONG_KID:
459 if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
463 case KEYDB_SEARCH_MODE_FPR16:
464 if (!memcmp (desc->u.fpr, fpr, 16))
468 case KEYDB_SEARCH_MODE_FPR20:
469 case KEYDB_SEARCH_MODE_FPR:
470 if (!memcmp (desc->u.fpr, fpr, 20))
482 /* Return an error if the key represented by the S-expression S_KEY
483 * and the OpenPGP key represented by PK do not use the same curve. */
485 match_curve_skey_pk (gcry_sexp_t s_key, PKT_public_key *pk)
487 gcry_sexp_t curve = NULL;
488 gcry_sexp_t flags = NULL;
489 char *curve_str = NULL;
491 const char *oidstr = NULL;
492 gcry_mpi_t curve_as_mpi = NULL;
497 if (!(pk->pubkey_algo==PUBKEY_ALGO_ECDH
498 || pk->pubkey_algo==PUBKEY_ALGO_ECDSA
499 || pk->pubkey_algo==PUBKEY_ALGO_EDDSA))
500 return gpg_error (GPG_ERR_PUBKEY_ALGO);
502 curve = gcry_sexp_find_token (s_key, "curve", 0);
505 log_error ("no reported curve\n");
506 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
508 curve_str = gcry_sexp_nth_string (curve, 1);
509 gcry_sexp_release (curve); curve = NULL;
512 log_error ("no curve name\n");
513 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
515 oidstr = openpgp_curve_to_oid (curve_str, NULL);
518 log_error ("no OID known for curve '%s'\n", curve_str);
520 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
523 err = openpgp_oid_from_str (oidstr, &curve_as_mpi);
526 if (gcry_mpi_cmp (pk->pkey[0], curve_as_mpi))
528 log_error ("curves do not match\n");
529 gcry_mpi_release (curve_as_mpi);
530 return gpg_error (GPG_ERR_INV_CURVE);
532 gcry_mpi_release (curve_as_mpi);
533 flags = gcry_sexp_find_token (s_key, "flags", 0);
536 for (idx = 1; idx < gcry_sexp_length (flags); idx++)
538 flag = gcry_sexp_nth_string (flags, idx);
539 if (flag && (strcmp ("eddsa", flag) == 0))
544 if (is_eddsa != (pk->pubkey_algo == PUBKEY_ALGO_EDDSA))
546 log_error ("disagreement about EdDSA\n");
547 err = gpg_error (GPG_ERR_INV_CURVE);
554 /* Return a canonicalized public key algoithms. This is used to
555 compare different flavors of algorithms (e.g. ELG and ELG_E are
556 considered the same). */
557 static enum gcry_pk_algos
558 canon_pk_algo (enum gcry_pk_algos algo)
564 case GCRY_PK_RSA_S: return GCRY_PK_RSA;
566 case GCRY_PK_ELG_E: return GCRY_PK_ELG;
569 case GCRY_PK_ECDH: return GCRY_PK_ECC;
570 default: return algo;
575 /* Take a cleartext dump of a secret key in PK and change the
576 * parameter array in PK to include the secret parameters. */
578 cleartext_secret_key_to_openpgp (gcry_sexp_t s_key, PKT_public_key *pk)
580 gpg_error_t err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
581 gcry_sexp_t top_list;
582 gcry_sexp_t key = NULL;
583 char *key_type = NULL;
584 enum gcry_pk_algos pk_algo;
585 struct seckey_info *ski;
587 gcry_mpi_t pub_params[10] = { NULL };
589 /* we look for a private-key, then the first element in it tells us
591 top_list = gcry_sexp_find_token (s_key, "private-key", 0);
594 if (gcry_sexp_length(top_list) != 2)
596 key = gcry_sexp_nth (top_list, 1);
599 key_type = gcry_sexp_nth_string(key, 0);
600 pk_algo = gcry_pk_map_name (key_type);
602 log_assert (!pk->seckey_info);
604 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
607 err = gpg_error_from_syserror ();
611 switch (canon_pk_algo (pk_algo))
614 if (!is_RSA (pk->pubkey_algo))
615 goto bad_pubkey_algo;
616 err = gcry_sexp_extract_param (key, NULL, "ne",
620 for (idx=0; idx < 2 && !err; idx++)
621 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
622 err = gpg_error (GPG_ERR_BAD_PUBKEY);
625 for (idx = 2; idx < 6 && !err; idx++)
627 gcry_mpi_release (pk->pkey[idx]);
628 pk->pkey[idx] = NULL;
630 err = gcry_sexp_extract_param (key, NULL, "dpqu",
639 for (idx = 2; idx < 6; idx++)
640 ski->csum += checksum_mpi (pk->pkey[idx]);
645 if (!is_DSA (pk->pubkey_algo))
646 goto bad_pubkey_algo;
647 err = gcry_sexp_extract_param (key, NULL, "pqgy",
653 for (idx=0; idx < 4 && !err; idx++)
654 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
655 err = gpg_error (GPG_ERR_BAD_PUBKEY);
658 gcry_mpi_release (pk->pkey[4]);
660 err = gcry_sexp_extract_param (key, NULL, "x",
665 ski->csum += checksum_mpi (pk->pkey[4]);
669 if (!is_ELGAMAL (pk->pubkey_algo))
670 goto bad_pubkey_algo;
671 err = gcry_sexp_extract_param (key, NULL, "pgy",
676 for (idx=0; idx < 3 && !err; idx++)
677 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
678 err = gpg_error (GPG_ERR_BAD_PUBKEY);
681 gcry_mpi_release (pk->pkey[3]);
683 err = gcry_sexp_extract_param (key, NULL, "x",
688 ski->csum += checksum_mpi (pk->pkey[3]);
692 err = match_curve_skey_pk (key, pk);
696 err = gcry_sexp_extract_param (key, NULL, "q",
699 if (!err && (gcry_mpi_cmp(pk->pkey[1], pub_params[0])))
700 err = gpg_error (GPG_ERR_BAD_PUBKEY);
703 if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
707 gcry_mpi_release (pk->pkey[sec_start]);
708 pk->pkey[sec_start] = NULL;
709 err = gcry_sexp_extract_param (key, NULL, "d",
710 &pk->pkey[sec_start],
715 ski->csum += checksum_mpi (pk->pkey[sec_start]);
719 pk->seckey_info = NULL;
721 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
726 gcry_sexp_release (top_list);
727 gcry_sexp_release (key);
728 gcry_free (key_type);
730 for (idx=0; idx < DIM(pub_params); idx++)
731 gcry_mpi_release (pub_params[idx]);
735 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
739 err = gpg_error (GPG_ERR_BAD_SECKEY);
744 /* Use the key transfer format given in S_PGP to create the secinfo
745 structure in PK and change the parameter array in PK to include the
746 secret parameters. */
748 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
751 gcry_sexp_t top_list;
752 gcry_sexp_t list = NULL;
758 int is_v4, is_protected;
759 enum gcry_pk_algos pk_algo;
760 int protect_algo = 0;
769 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
771 struct seckey_info *ski;
773 /* gcry_log_debugsxp ("transferkey", s_pgp); */
774 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
778 list = gcry_sexp_find_token (top_list, "version", 0);
781 value = gcry_sexp_nth_data (list, 1, &valuelen);
782 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
784 is_v4 = (value[0] == '4');
786 gcry_sexp_release (list);
787 list = gcry_sexp_find_token (top_list, "protection", 0);
790 value = gcry_sexp_nth_data (list, 1, &valuelen);
793 if (valuelen == 4 && !memcmp (value, "sha1", 4))
795 else if (valuelen == 3 && !memcmp (value, "sum", 3))
797 else if (valuelen == 4 && !memcmp (value, "none", 4))
803 string = gcry_sexp_nth_string (list, 2);
806 protect_algo = gcry_cipher_map_name (string);
809 value = gcry_sexp_nth_data (list, 3, &valuelen);
810 if (!value || !valuelen || valuelen > sizeof iv)
812 memcpy (iv, value, valuelen);
815 string = gcry_sexp_nth_string (list, 4);
818 s2k_mode = strtol (string, NULL, 10);
821 string = gcry_sexp_nth_string (list, 5);
824 s2k_algo = gcry_md_map_name (string);
827 value = gcry_sexp_nth_data (list, 6, &valuelen);
828 if (!value || !valuelen || valuelen > sizeof s2k_salt)
830 memcpy (s2k_salt, value, valuelen);
832 string = gcry_sexp_nth_string (list, 7);
835 s2k_count = strtoul (string, NULL, 10);
839 /* Parse the gcrypt PK algo and check that it is okay. */
840 gcry_sexp_release (list);
841 list = gcry_sexp_find_token (top_list, "algo", 0);
844 string = gcry_sexp_nth_string (list, 1);
847 pk_algo = gcry_pk_map_name (string);
848 xfree (string); string = NULL;
849 if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
850 || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
851 || !npkey || npkey >= nskey)
854 /* Check that the pubkey algo matches the one from the public key. */
855 switch (canon_pk_algo (pk_algo))
858 if (!is_RSA (pk->pubkey_algo))
859 pk_algo = 0; /* Does not match. */
862 if (!is_DSA (pk->pubkey_algo))
863 pk_algo = 0; /* Does not match. */
866 if (!is_ELGAMAL (pk->pubkey_algo))
867 pk_algo = 0; /* Does not match. */
870 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
872 else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
874 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
877 pk_algo = 0; /* Does not match. */
878 /* For ECC we do not have the domain parameters thus fix our info. */
883 pk_algo = 0; /* Oops. */
888 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
892 /* This check has to go after the ecc adjustments. */
893 if (nskey > PUBKEY_MAX_NSKEY)
896 /* Parse the key parameters. */
897 gcry_sexp_release (list);
898 list = gcry_sexp_find_token (top_list, "skey", 0);
905 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
906 if (!value && skeyidx >= npkey)
909 /* Check for too many parameters. Note that depending on the
910 protection mode and version number we may see less than NSKEY
911 (but at least NPKEY+1) parameters. */
914 if (skeyidx >= DIM (skey)-1)
917 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
919 is_enc = (value[0] == 'e');
920 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
921 if (!value || !valuelen)
925 void *p = xtrymalloc (valuelen);
928 memcpy (p, value, valuelen);
929 skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
935 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
936 value, valuelen, NULL))
941 skey[skeyidx++] = NULL;
943 gcry_sexp_release (list); list = NULL;
945 /* We have no need for the CSUM value thus we don't parse it. */
946 /* list = gcry_sexp_find_token (top_list, "csum", 0); */
949 /* string = gcry_sexp_nth_string (list, 1); */
951 /* goto bad_seckey; */
952 /* desired_csum = strtoul (string, NULL, 10); */
953 /* xfree (string); */
956 /* desired_csum = 0; */
957 /* gcry_sexp_release (list); list = NULL; */
959 /* Get the curve name if any, */
960 list = gcry_sexp_find_token (top_list, "curve", 0);
963 curve = gcry_sexp_nth_string (list, 1);
964 gcry_sexp_release (list); list = NULL;
967 gcry_sexp_release (top_list); top_list = NULL;
969 /* log_debug ("XXX is_v4=%d\n", is_v4); */
970 /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
971 /* log_debug ("XXX is_protected=%d\n", is_protected); */
972 /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
973 /* log_printhex ("XXX iv", iv, ivlen); */
974 /* log_debug ("XXX ivlen=%d\n", ivlen); */
975 /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
976 /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
977 /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
978 /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
979 /* for (idx=0; skey[idx]; idx++) */
981 /* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
982 /* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
986 /* unsigned int nbits; */
987 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
988 /* log_printhex (NULL, p, (nbits+7)/8); */
991 /* gcry_mpi_dump (skey[idx]); */
992 /* log_printf ("\n"); */
995 if (!is_v4 || is_protected != 2 )
997 /* We only support the v4 format and a SHA-1 checksum. */
998 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1002 /* We need to change the received parameters for ECC algorithms.
1003 The transfer format has the curve name and the parameters
1004 separate. We put them all into the SKEY array. */
1005 if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
1009 /* Assert that all required parameters are available. We also
1010 check that the array does not contain more parameters than
1011 needed (this was used by some beta versions of 2.1. */
1012 if (!curve || !skey[0] || !skey[1] || skey[2])
1014 err = gpg_error (GPG_ERR_INTERNAL);
1018 oidstr = openpgp_curve_to_oid (curve, NULL);
1021 log_error ("no OID known for curve '%s'\n", curve);
1022 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1025 /* Put the curve's OID into into the MPI array. This requires
1026 that we shift Q and D. For ECDH also insert the KDF parms. */
1031 skey[2] = gcry_mpi_copy (pk->pkey[2]);
1040 err = openpgp_oid_from_str (oidstr, skey + 0);
1043 /* Fixup the NPKEY and NSKEY to match OpenPGP reality. */
1044 npkey = 2 + is_ecdh;
1045 nskey = 3 + is_ecdh;
1047 /* for (idx=0; skey[idx]; idx++) */
1049 /* log_info ("YYY skey[%d]:", idx); */
1050 /* if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
1053 /* unsigned int nbits; */
1054 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
1055 /* log_printhex (NULL, p, (nbits+7)/8); */
1058 /* gcry_mpi_dump (skey[idx]); */
1059 /* log_printf ("\n"); */
1063 /* Do some sanity checks. */
1064 if (s2k_count > 255)
1066 /* We expect an already encoded S2K count. */
1067 err = gpg_error (GPG_ERR_INV_DATA);
1070 err = openpgp_cipher_test_algo (protect_algo);
1073 err = openpgp_md_test_algo (s2k_algo);
1077 /* Check that the public key parameters match. Note that since
1078 Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly. */
1079 for (idx=0; idx < npkey; idx++)
1080 if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
1082 err = gpg_error (GPG_ERR_BAD_PUBKEY);
1086 /* Check that the first secret key parameter in SKEY is encrypted
1087 and that there are no more secret key parameters. The latter is
1088 guaranteed by the v4 packet format. */
1089 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
1091 if (npkey+1 < DIM (skey) && skey[npkey+1])
1094 /* Check that the secret key parameters in PK are all set to NULL. */
1095 for (idx=npkey; idx < nskey; idx++)
1099 /* Now build the protection info. */
1100 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1103 err = gpg_error_from_syserror ();
1107 ski->is_protected = 1;
1109 ski->algo = protect_algo;
1110 ski->s2k.mode = s2k_mode;
1111 ski->s2k.hash_algo = s2k_algo;
1112 log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
1113 memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
1114 ski->s2k.count = s2k_count;
1115 log_assert (ivlen <= sizeof ski->iv);
1116 memcpy (ski->iv, iv, ivlen);
1119 /* Store the protected secret key parameter. */
1120 pk->pkey[npkey] = skey[npkey];
1127 gcry_sexp_release (list);
1128 gcry_sexp_release (top_list);
1129 for (idx=0; idx < skeyidx; idx++)
1130 gcry_mpi_release (skey[idx]);
1134 err = gpg_error (GPG_ERR_BAD_SECKEY);
1138 err = gpg_error (GPG_ERR_ENOMEM);
1143 /* Print an "EXPORTED" status line. PK is the primary public key. */
1145 print_status_exported (PKT_public_key *pk)
1149 if (!is_status_enabled ())
1152 hexfpr = hexfingerprint (pk, NULL, 0);
1153 write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
1159 * Receive a secret key from agent specified by HEXGRIP.
1161 * Since the key data from the agent is encrypted, decrypt it using
1162 * CIPHERHD context. Then, parse the decrypted key data into transfer
1163 * format, and put secret parameters into PK.
1165 * If CLEARTEXT is 0, store the secret key material
1166 * passphrase-protected. Otherwise, store secret key material in the
1169 * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
1172 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
1174 char **cache_nonce_addr, const char *hexgrip,
1177 gpg_error_t err = 0;
1178 unsigned char *wrappedkey = NULL;
1179 size_t wrappedkeylen;
1180 unsigned char *key = NULL;
1181 size_t keylen, realkeylen;
1186 log_info ("key %s: asking agent for the secret parts\n", hexgrip);
1188 prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
1189 err = agent_export_key (ctrl, hexgrip, prompt, !cleartext, cache_nonce_addr,
1190 &wrappedkey, &wrappedkeylen);
1195 if (wrappedkeylen < 24)
1197 err = gpg_error (GPG_ERR_INV_LENGTH);
1200 keylen = wrappedkeylen - 8;
1201 key = xtrymalloc_secure (keylen);
1204 err = gpg_error_from_syserror ();
1207 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
1210 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
1212 goto unwraperror; /* Invalid csexp. */
1214 err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
1218 err = cleartext_secret_key_to_openpgp (s_skey, pk);
1220 err = transfer_format_to_openpgp (s_skey, pk);
1221 gcry_sexp_release (s_skey);
1229 log_error ("key %s: error receiving key from agent:"
1230 " %s%s\n", hexgrip, gpg_strerror (err),
1231 gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
1232 "":_(" - skipped"));
1238 /* Write KEYBLOCK either to stdout or to the file set with the
1239 * --output option. This is a simplified version of do_export_stream
1240 * which supports only a few export options. */
1242 write_keyblock_to_output (kbnode_t keyblock, int with_armor,
1243 unsigned int options)
1249 armor_filter_context_t *afx = NULL;
1250 iobuf_t out_help = NULL;
1251 PKT_public_key *pk = NULL;
1253 fname = opt.outfile? opt.outfile : "-";
1254 if (is_secured_filename (fname) )
1255 return gpg_error (GPG_ERR_EPERM);
1257 out = iobuf_create (fname, 0);
1260 err = gpg_error_from_syserror ();
1261 log_error(_("can't create '%s': %s\n"), fname, gpg_strerror (err));
1265 log_info (_("writing to '%s'\n"), iobuf_get_fname_nonnull (out));
1267 if ((options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)))
1270 out_help = iobuf_temp ();
1275 afx = new_armor_context ();
1277 push_armor_filter (afx, out);
1280 for (node = keyblock; node; node = node->next)
1282 if (is_deleted_kbnode (node) || node->pkt->pkttype == PKT_RING_TRUST)
1284 if (!pk && (node->pkt->pkttype == PKT_PUBLIC_KEY
1285 || node->pkt->pkttype == PKT_SECRET_KEY))
1286 pk = node->pkt->pkt.public_key;
1288 err = build_packet (out_help? out_help : out, node->pkt);
1291 log_error ("build_packet(%d) failed: %s\n",
1292 node->pkt->pkttype, gpg_strerror (err) );
1303 iobuf_flush_temp (out_help);
1304 data = iobuf_get_temp_buffer (out_help);
1305 datalen = iobuf_get_temp_length (out_help);
1307 err = print_pka_or_dane_records (out,
1308 keyblock, pk, data, datalen,
1309 (options & EXPORT_PKA_FORMAT),
1310 (options & EXPORT_DANE_FORMAT));
1318 iobuf_cancel (out_help);
1319 release_armor_context (afx);
1325 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1326 * marked and thus the caller should call commit_kbnode afterwards.
1327 * KEYBLOCK must not have any blocks marked as deleted.
1330 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1334 for (node = keyblock->next; node; node = node->next )
1336 if (node->pkt->pkttype == PKT_USER_ID)
1338 if (!recsel_select (selector, impex_filter_getval, node))
1340 /* log_debug ("keep-uid: deleting '%s'\n", */
1341 /* node->pkt->pkt.user_id->name); */
1342 /* The UID packet and all following packets up to the
1343 * next UID or a subkey. */
1344 delete_kbnode (node);
1346 && node->next->pkt->pkttype != PKT_USER_ID
1347 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1348 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1350 delete_kbnode (node->next);
1353 /* log_debug ("keep-uid: keeping '%s'\n", */
1354 /* node->pkt->pkt.user_id->name); */
1361 * Apply the drop-subkey filter to the keyblock. The deleted nodes are
1362 * marked and thus the caller should call commit_kbnode afterwards.
1363 * KEYBLOCK must not have any blocks marked as deleted.
1366 apply_drop_subkey_filter (kbnode_t keyblock, recsel_expr_t selector)
1370 for (node = keyblock->next; node; node = node->next )
1372 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1373 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1375 if (recsel_select (selector, impex_filter_getval, node))
1377 log_debug ("drop-subkey: deleting a key\n");
1378 /* The subkey packet and all following packets up to the
1380 delete_kbnode (node);
1382 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1383 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1385 delete_kbnode (node->next);
1392 /* Print DANE or PKA records for all user IDs in KEYBLOCK to OUT. The
1393 * data for the record is taken from (DATA,DATELEN). PK is the public
1394 * key packet with the primary key. */
1396 print_pka_or_dane_records (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
1397 const void *data, size_t datalen,
1398 int print_pka, int print_dane)
1400 gpg_error_t err = 0;
1401 kbnode_t kbctx, node;
1409 estream_t fp = NULL;
1410 char *hexdata = NULL;
1413 hexfpr = hexfingerprint (pk, NULL, 0);
1414 hexdata = bin2hex (data, datalen, NULL);
1417 err = gpg_error_from_syserror ();
1420 ascii_strlwr (hexdata);
1421 fp = es_fopenmem (0, "rw,samethread");
1424 err = gpg_error_from_syserror ();
1428 for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1430 if (node->pkt->pkttype != PKT_USER_ID)
1432 uid = node->pkt->pkt.user_id;
1434 if (uid->is_expired || uid->is_revoked)
1438 mbox = mailbox_from_userid (uid->name);
1442 domain = strchr (mbox, '@');
1447 es_fprintf (fp, "$ORIGIN _pka.%s.\n; %s\n; ", domain, hexfpr);
1448 print_utf8_buffer (fp, uid->name, uid->len);
1450 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
1452 hash = zb32_encode (hashbuf, 8*20);
1455 err = gpg_error_from_syserror ();
1458 len = strlen (hexfpr)/2;
1459 es_fprintf (fp, "%s TYPE37 \\# %u 0006 0000 00 %02X %s\n\n",
1460 hash, 6 + len, len, hexfpr);
1463 if (print_dane && hexdata)
1465 es_fprintf (fp, "$ORIGIN _openpgpkey.%s.\n; %s\n; ", domain, hexfpr);
1466 print_utf8_buffer (fp, uid->name, uid->len);
1468 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
1470 hash = bin2hex (hashbuf, 28, NULL);
1473 err = gpg_error_from_syserror ();
1476 ascii_strlwr (hash);
1477 len = strlen (hexdata)/2;
1478 es_fprintf (fp, "%s TYPE61 \\# %u (\n", hash, len);
1479 for (s = hexdata; ;)
1481 es_fprintf (fp, "\t%.64s\n", s);
1482 if (strlen (s) < 64)
1486 es_fputs ("\t)\n\n", fp);
1490 /* Make sure it is a string and write it. */
1495 if (es_fclose_snatch (fp, &vp, NULL))
1497 err = gpg_error_from_syserror ();
1501 iobuf_writestr (out, vp);
1516 /* Helper for do_export_stream which writes one keyblock to OUT. */
1518 do_export_one_keyblock (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
1519 iobuf_t out, int secret, unsigned int options,
1520 export_stats_t stats, int *any,
1521 KEYDB_SEARCH_DESC *desc, size_t ndesc,
1522 size_t descindex, gcry_cipher_hd_t cipherhd)
1525 char *cache_nonce = NULL;
1526 subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
1527 int skip_until_subkey = 0;
1529 char *hexgrip = NULL;
1530 char *serialno = NULL;
1532 u32 subkidbuf[2], *subkid;
1533 kbnode_t kbctx, node;
1535 /* NB: walk_kbnode skips packets marked as deleted. */
1536 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1538 if (skip_until_subkey)
1540 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1541 skip_until_subkey = 0;
1546 /* We used to use comment packets, but not any longer. In
1547 * case we still have comments on a key, strip them here
1548 * before we call build_packet(). */
1549 if (node->pkt->pkttype == PKT_COMMENT)
1552 /* Make sure that ring_trust packets are only exported in backup
1554 if (node->pkt->pkttype == PKT_RING_TRUST && !(options & EXPORT_BACKUP))
1557 /* If exact is set, then we only export what was requested
1558 * (plus the primary key, if the user didn't specifically
1560 if (desc[descindex].exact && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1562 if (!exact_subkey_match_p (desc+descindex, node))
1564 /* Before skipping this subkey, check whether any
1565 * other description wants an exact match on a
1566 * subkey and include that subkey into the output
1567 * too. Need to add this subkey to a list so that
1568 * it won't get processed a second time.
1570 * So the first step here is to check that list and
1571 * skip in any case if the key is in that list.
1573 * We need this whole mess because the import
1574 * function of GnuPG < 2.1 is not able to merge
1575 * secret keys and thus it is useless to output them
1576 * as two separate keys and have import merge them.
1578 if (subkey_in_list_p (subkey_list, node))
1579 skip_until_subkey = 1; /* Already processed this one. */
1584 for (j=0; j < ndesc; j++)
1585 if (j != descindex && desc[j].exact
1586 && exact_subkey_match_p (desc+j, node))
1589 skip_until_subkey = 1; /* No other one matching. */
1593 if (skip_until_subkey)
1596 /* Mark this one as processed. */
1598 subkey_list_t tmp = new_subkey_list_item (node);
1599 tmp->next = subkey_list;
1604 if (node->pkt->pkttype == PKT_SIGNATURE)
1606 /* Do not export packets which are marked as not
1608 if (!(options & EXPORT_LOCAL_SIGS)
1609 && !node->pkt->pkt.signature->flags.exportable)
1610 continue; /* not exportable */
1612 /* Do not export packets with a "sensitive" revocation key
1613 * unless the user wants us to. Note that we do export
1614 * these when issuing the actual revocation (see revoke.c). */
1615 if (!(options & EXPORT_SENSITIVE_REVKEYS)
1616 && node->pkt->pkt.signature->revkey)
1620 for (i = 0; i < node->pkt->pkt.signature->numrevkeys; i++)
1621 if ((node->pkt->pkt.signature->revkey[i].class & 0x40))
1623 if (i < node->pkt->pkt.signature->numrevkeys)
1628 /* Don't export attribs? */
1629 if (!(options & EXPORT_ATTRIBUTES)
1630 && node->pkt->pkttype == PKT_USER_ID
1631 && node->pkt->pkt.user_id->attrib_data)
1633 /* Skip until we get to something that is not an attrib or a
1634 * signature on an attrib. */
1635 while (kbctx->next && kbctx->next->pkt->pkttype == PKT_SIGNATURE)
1636 kbctx = kbctx->next;
1641 if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1642 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1644 pk = node->pkt->pkt.public_key;
1645 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1649 keyid_from_pk (pk, subkidbuf);
1653 if (pk->seckey_info)
1655 log_error ("key %s: oops: seckey_info already set"
1656 " - skipped\n", keystr_with_sub (keyid, subkid));
1657 skip_until_subkey = 1;
1662 err = hexkeygrip_from_pk (pk, &hexgrip);
1665 log_error ("key %s: error computing keygrip: %s"
1666 " - skipped\n", keystr_with_sub (keyid, subkid),
1667 gpg_strerror (err));
1668 skip_until_subkey = 1;
1675 if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1677 /* We are asked not to export the secret parts of the
1678 * primary key. Make up an error code to create the
1680 err = GPG_ERR_NOT_FOUND;
1683 err = agent_get_keyinfo (ctrl, hexgrip, &serialno, &cleartext);
1685 if ((!err && serialno)
1686 && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1688 /* It does not make sense to export a key with its
1689 * primary key on card using a non-key stub. Thus we
1690 * skip those keys when used with --export-secret-subkeys. */
1691 log_info (_("key %s: key material on-card - skipped\n"),
1692 keystr_with_sub (keyid, subkid));
1693 skip_until_subkey = 1;
1695 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1696 || (!err && serialno))
1698 /* Create a key stub. */
1699 struct seckey_info *ski;
1702 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1705 err = gpg_error_from_syserror ();
1709 ski->is_protected = 1;
1711 ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
1714 ski->s2k.mode = 1002; /* GNU-divert-to-card. */
1715 for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1716 ski->ivlen++, s += 2)
1717 ski->iv[ski->ivlen] = xtoi_2 (s);
1720 err = build_packet (out, node->pkt);
1721 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1724 print_status_exported (node->pkt->pkt.public_key);
1729 err = receive_seckey_from_agent (ctrl, cipherhd,
1730 cleartext, &cache_nonce,
1734 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1736 skip_until_subkey = 1;
1741 err = build_packet (out, node->pkt);
1742 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1745 print_status_exported (node->pkt->pkt.public_key);
1751 log_error ("key %s: error getting keyinfo from agent: %s"
1752 " - skipped\n", keystr_with_sub (keyid, subkid),
1753 gpg_strerror (err));
1754 skip_until_subkey = 1;
1758 xfree (pk->seckey_info);
1759 pk->seckey_info = NULL;
1762 for (i = pubkey_get_npkey (pk->pubkey_algo);
1763 i < pubkey_get_nskey (pk->pubkey_algo); i++)
1765 gcry_mpi_release (pk->pkey[i]);
1770 else /* Not secret or common packets. */
1772 err = build_packet (out, node->pkt);
1773 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1776 print_status_exported (node->pkt->pkt.public_key);
1782 log_error ("build_packet(%d) failed: %s\n",
1783 node->pkt->pkttype, gpg_strerror (err));
1787 if (!skip_until_subkey)
1792 release_subkey_list (subkey_list);
1795 xfree (cache_nonce);
1800 /* Export the keys identified by the list of strings in USERS to the
1801 stream OUT. If SECRET is false public keys will be exported. With
1802 secret true secret keys will be exported; in this case 1 means the
1803 entire secret keyblock and 2 only the subkeys. OPTIONS are the
1804 export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
1805 code is zero, a pointer to the first keyblock found and exported
1806 will be stored at this address; no other keyblocks are exported in
1807 this case. The caller must free the returned keyblock. If any
1808 key has been exported true is stored at ANY. */
1810 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
1811 kbnode_t *keyblock_out, unsigned int options,
1812 export_stats_t stats, int *any)
1814 gpg_error_t err = 0;
1816 kbnode_t keyblock = NULL;
1818 size_t ndesc, descindex;
1819 KEYDB_SEARCH_DESC *desc = NULL;
1822 gcry_cipher_hd_t cipherhd = NULL;
1823 struct export_stats_s dummystats;
1824 iobuf_t out_help = NULL;
1827 stats = &dummystats;
1830 kdbhd = keydb_new ();
1832 return gpg_error_from_syserror ();
1834 /* For the PKA and DANE format open a helper iobuf and for DANE
1835 * enforce some options. */
1836 if ((options & (EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT)))
1838 out_help = iobuf_temp ();
1839 if ((options & EXPORT_DANE_FORMAT))
1840 options |= EXPORT_MINIMAL | EXPORT_CLEAN;
1846 desc = xcalloc (ndesc, sizeof *desc);
1847 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1851 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1853 desc = xmalloc ( ndesc * sizeof *desc);
1855 for (ndesc=0, sl=users; sl; sl = sl->next)
1857 if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
1860 log_error (_("key \"%s\" not found: %s\n"),
1861 sl->d, gpg_strerror (err));
1864 keydb_disable_caching (kdbhd); /* We are looping the search. */
1866 /* It would be nice to see which of the given users did actually
1867 match one in the keyring. To implement this we need to have
1868 a found flag for each entry in desc. To set this flag we
1869 must check all those entries after a match to mark all
1870 matched one - currently we stop at the first match. To do
1871 this we need an extra flag to enable this feature. */
1874 #ifdef ENABLE_SELINUX_HACKS
1877 log_error (_("exporting secret keys not allowed\n"));
1878 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1883 /* For secret key export we need to setup a decryption context. */
1889 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
1892 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1896 /* Prepare a cipher context. */
1897 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1898 GCRY_CIPHER_MODE_AESWRAP, 0);
1900 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1903 log_error ("error setting up an encryption context: %s\n",
1904 gpg_strerror (err));
1916 err = keydb_search (kdbhd, desc, ndesc, &descindex);
1918 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1922 /* Read the keyblock. */
1923 release_kbnode (keyblock);
1925 err = keydb_get_keyblock (kdbhd, &keyblock);
1928 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1932 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1935 log_error ("public key packet not found in keyblock - skipped\n");
1939 setup_main_keyids (keyblock); /* gpg_format_keydesc needs it. */
1940 pk = node->pkt->pkt.public_key;
1941 keyid_from_pk (pk, keyid);
1943 /* If a secret key export is required we need to check whether
1944 we have a secret key at all and if so create the seckey_info
1948 if (agent_probe_any_secret_key (ctrl, keyblock))
1949 continue; /* No secret key (neither primary nor subkey). */
1951 /* No v3 keys with GNU mode 1001. */
1952 if (secret == 2 && pk->version == 3)
1954 log_info (_("key %s: PGP 2.x style key - skipped\n"),
1959 /* The agent does not yet allow export of v3 packets. It is
1960 actually questionable whether we should allow them at
1962 if (pk->version == 3)
1964 log_info ("key %s: PGP 2.x style key (v3) export "
1965 "not yet supported - skipped\n", keystr (keyid));
1968 stats->secret_count++;
1971 /* Always do the cleaning on the public key part if requested.
1972 Note that we don't yet set this option if we are exporting
1973 secret keys. Note that both export-clean and export-minimal
1974 only apply to UID sigs (0x10, 0x11, 0x12, and 0x13). A
1975 designated revocation is never stripped, even with
1976 export-minimal set. */
1977 if ((options & EXPORT_CLEAN))
1978 clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1980 if (export_keep_uid)
1982 commit_kbnode (&keyblock);
1983 apply_keep_uid_filter (keyblock, export_keep_uid);
1984 commit_kbnode (&keyblock);
1987 if (export_drop_subkey)
1989 commit_kbnode (&keyblock);
1990 apply_drop_subkey_filter (keyblock, export_drop_subkey);
1991 commit_kbnode (&keyblock);
1995 err = do_export_one_keyblock (ctrl, keyblock, keyid,
1996 out_help? out_help : out,
1997 secret, options, stats, any,
1998 desc, ndesc, descindex, cipherhd);
2004 *keyblock_out = keyblock;
2010 /* We want to write PKA or DANE records. OUT_HELP has the
2011 * keyblock and we print a record for each uid to OUT. */
2015 iobuf_flush_temp (out_help);
2016 data = iobuf_get_temp_buffer (out_help);
2017 datalen = iobuf_get_temp_length (out_help);
2019 err = print_pka_or_dane_records (out,
2020 keyblock, pk, data, datalen,
2021 (options & EXPORT_PKA_FORMAT),
2022 (options & EXPORT_DANE_FORMAT));
2026 iobuf_close (out_help);
2027 out_help = iobuf_temp ();
2031 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2035 iobuf_cancel (out_help);
2036 gcry_cipher_close (cipherhd);
2038 keydb_release (kdbhd);
2039 if (err || !keyblock_out)
2040 release_kbnode( keyblock );
2042 log_info(_("WARNING: nothing exported\n"));
2050 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
2053 gpg_error_t err = 0;
2054 unsigned char nbuf[4];
2059 ulongtobuf (nbuf, (ulong)strlen (identifier));
2060 put_membuf (mb, nbuf, 4);
2061 put_membuf_str (mb, identifier);
2062 if (!strncmp (identifier, "ecdsa-sha2-", 11))
2064 ulongtobuf (nbuf, (ulong)strlen (identifier+11));
2065 put_membuf (mb, nbuf, 4);
2066 put_membuf_str (mb, identifier+11);
2068 va_start (arg_ptr, identifier);
2069 while ((a = va_arg (arg_ptr, gcry_mpi_t)))
2071 err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
2074 if (!strcmp (identifier, "ssh-ed25519")
2075 && buflen > 5 && buf[4] == 0x40)
2077 /* We need to strip our 0x40 prefix. */
2078 put_membuf (mb, "\x00\x00\x00\x20", 4);
2079 put_membuf (mb, buf+5, buflen-5);
2082 put_membuf (mb, buf, buflen);
2089 /* Export the key identified by USERID in the SSH public key format.
2090 The function exports the latest subkey with Authentication
2091 capability unless the '!' suffix is used to export a specific
2094 export_ssh_key (ctrl_t ctrl, const char *userid)
2097 kbnode_t keyblock = NULL;
2098 KEYDB_SEARCH_DESC desc;
2100 u32 curtime = make_timestamp ();
2101 kbnode_t latest_key, node;
2103 const char *identifier;
2105 estream_t fp = NULL;
2106 struct b64state b64_state;
2107 const char *fname = "-";
2109 init_membuf (&mb, 4096);
2111 /* We need to know whether the key has been specified using the
2112 exact syntax ('!' suffix). Thus we need to run a
2113 classify_user_id on our own. */
2114 err = classify_user_id (userid, &desc, 1);
2116 /* Get the public key. */
2119 getkey_ctx_t getkeyctx;
2121 err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
2123 0 /* Only usable keys or given exact. */,
2124 1 /* No AKL lookup. */);
2127 err = getkey_next (getkeyctx, NULL, NULL);
2129 err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2130 else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
2133 getkey_end (getkeyctx);
2137 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2141 /* The finish_lookup code in getkey.c does not handle auth keys,
2142 thus we have to duplicate the code here to find the latest
2143 subkey. However, if the key has been found using an exact match
2144 ('!' notation) we use that key without any further checks and
2145 even allow the use of the primary key. */
2148 for (node = keyblock; node; node = node->next)
2150 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2151 || node->pkt->pkttype == PKT_PUBLIC_KEY)
2152 && node->pkt->pkt.public_key->flags.exact)
2160 for (node = keyblock; node; node = node->next)
2162 if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2165 pk = node->pkt->pkt.public_key;
2167 log_debug ("\tchecking subkey %08lX\n",
2168 (ulong) keyid_from_pk (pk, NULL));
2169 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2172 log_debug ("\tsubkey not usable for authentication\n");
2175 if (!pk->flags.valid)
2178 log_debug ("\tsubkey not valid\n");
2181 if (pk->flags.revoked)
2184 log_debug ("\tsubkey has been revoked\n");
2187 if (pk->has_expired)
2190 log_debug ("\tsubkey has expired\n");
2193 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2196 log_debug ("\tsubkey not yet valid\n");
2200 log_debug ("\tsubkey might be fine\n");
2201 /* In case a key has a timestamp of 0 set, we make sure that it
2202 is used. A better change would be to compare ">=" but that
2203 might also change the selected keys and is as such a more
2204 intrusive change. */
2205 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2207 latest_date = pk->timestamp;
2215 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2216 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2220 pk = latest_key->pkt->pkt.public_key;
2222 log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
2224 switch (pk->pubkey_algo)
2226 case PUBKEY_ALGO_DSA:
2227 identifier = "ssh-dss";
2228 err = key_to_sshblob (&mb, identifier,
2229 pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
2233 case PUBKEY_ALGO_RSA:
2234 case PUBKEY_ALGO_RSA_S:
2235 identifier = "ssh-rsa";
2236 err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
2239 case PUBKEY_ALGO_ECDSA:
2244 curveoid = openpgp_oid_to_str (pk->pkey[0]);
2246 err = gpg_error_from_syserror ();
2247 else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
2248 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2251 if (!strcmp (curve, "nistp256"))
2252 identifier = "ecdsa-sha2-nistp256";
2253 else if (!strcmp (curve, "nistp384"))
2254 identifier = "ecdsa-sha2-nistp384";
2255 else if (!strcmp (curve, "nistp521"))
2256 identifier = "ecdsa-sha2-nistp521";
2261 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2263 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2269 case PUBKEY_ALGO_EDDSA:
2270 if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
2271 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2274 identifier = "ssh-ed25519";
2275 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2279 case PUBKEY_ALGO_ELGAMAL_E:
2280 case PUBKEY_ALGO_ELGAMAL:
2281 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2285 err = GPG_ERR_PUBKEY_ALGO;
2292 if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
2293 fp = es_fopen ((fname = opt.outfile), "w");
2298 err = gpg_error_from_syserror ();
2299 log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
2303 es_fprintf (fp, "%s ", identifier);
2304 err = b64enc_start_es (&b64_state, fp, "");
2311 blob = get_membuf (&mb, &bloblen);
2313 err = gpg_error_from_syserror ();
2315 err = b64enc_write (&b64_state, blob, bloblen);
2320 err = b64enc_finish (&b64_state);
2323 es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
2326 err = gpg_error_from_syserror ();
2330 err = gpg_error_from_syserror ();
2335 log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
2339 xfree (get_membuf (&mb, NULL));
2340 release_kbnode (keyblock);