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 /* Aliases for backward compatibility */
120 {"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
121 {"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
122 {"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
124 {"export-unusable-sigs",0,NULL,NULL},
125 {"export-clean-sigs",0,NULL,NULL},
126 {"export-clean-uids",0,NULL,NULL},
128 /* add tags for include revoked and disabled? */
131 return parse_options(str,options,export_opts,noisy);
135 /* Parse and set an export filter from string. STRING has the format
136 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
137 * and after NAME are not allowed. If this function is called several
138 * times all expressions for the same NAME are concatenated.
139 * Supported filter names are:
141 * - keep-uid :: If the expression evaluates to true for a certain
142 * user ID packet, that packet and all it dependencies
143 * will be exported. The expression may use these
146 * - uid :: The entire user ID.
147 * - mbox :: The mail box part of the user ID.
148 * - primary :: Evaluate to true for the primary user ID.
150 * - drop-subkey :: If the expression evaluates to true for a subkey
151 * packet that subkey and all it dependencies will be
152 * remove from the keyblock. The expression may use these
155 * - secret :: 1 for a secret subkey, else 0.
156 * - key_algo :: Public key algorithm id
159 parse_and_set_export_filter (const char *string)
163 /* Auto register the cleanup function. */
164 register_mem_cleanup_func (cleanup_export_globals);
166 if (!strncmp (string, "keep-uid=", 9))
167 err = recsel_parse_expr (&export_keep_uid, string+9);
168 else if (!strncmp (string, "drop-subkey=", 12))
169 err = recsel_parse_expr (&export_drop_subkey, string+12);
171 err = gpg_error (GPG_ERR_INV_NAME);
177 /* Create a new export stats object initialized to zero. On error
178 returns NULL and sets ERRNO. */
180 export_new_stats (void)
182 export_stats_t stats;
184 return xtrycalloc (1, sizeof *stats);
188 /* Release an export stats object. */
190 export_release_stats (export_stats_t stats)
196 /* Print export statistics using the status interface. */
198 export_print_stats (export_stats_t stats)
203 if (is_status_enabled ())
207 snprintf (buf, sizeof buf, "%lu %lu %lu",
211 write_status_text (STATUS_EXPORT_RES, buf);
217 * Export public keys (to stdout or to --output FILE).
219 * Depending on opt.armor the output is armored. OPTIONS are defined
220 * in main.h. If USERS is NULL, all keys will be exported. STATS is
221 * either an export stats object for update or NULL.
223 * This function is the core of "gpg --export".
226 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
227 export_stats_t stats)
229 return do_export (ctrl, users, 0, options, stats);
234 * Export secret keys (to stdout or to --output FILE).
236 * Depending on opt.armor the output is armored. If USERS is NULL,
237 * all secret keys will be exported. STATS is either an export stats
238 * object for update or NULL.
240 * This function is the core of "gpg --export-secret-keys".
243 export_seckeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
245 return do_export (ctrl, users, 1, 0, stats);
250 * Export secret sub keys (to stdout or to --output FILE).
252 * This is the same as export_seckeys but replaces the primary key by
253 * a stub key. Depending on opt.armor the output is armored. If
254 * USERS is NULL, all secret subkeys will be exported. STATS is
255 * either an export stats object for update or NULL.
257 * This function is the core of "gpg --export-secret-subkeys".
260 export_secsubkeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
262 return do_export (ctrl, users, 2, 0, stats);
267 * Export a single key into a memory buffer. STATS is either an
268 * export stats object for update or NULL.
271 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
272 export_stats_t stats,
273 kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
285 if (!add_to_strlist_try (&helplist, keyspec))
286 return gpg_error_from_syserror ();
288 iobuf = iobuf_temp ();
289 err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
292 err = gpg_error (GPG_ERR_NOT_FOUND);
298 iobuf_flush_temp (iobuf);
299 src = iobuf_get_temp_buffer (iobuf);
300 datalen = iobuf_get_temp_length (iobuf);
302 err = gpg_error (GPG_ERR_NO_PUBKEY);
303 else if (!(*r_data = xtrymalloc (datalen)))
304 err = gpg_error_from_syserror ();
307 memcpy (*r_data, src, datalen);
308 *r_datalen = datalen;
312 free_strlist (helplist);
313 if (err && *r_keyblock)
315 release_kbnode (*r_keyblock);
322 /* Export the keys identified by the list of strings in USERS. If
323 Secret is false public keys will be exported. With secret true
324 secret keys will be exported; in this case 1 means the entire
325 secret keyblock and 2 only the subkeys. OPTIONS are the export
328 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
329 export_stats_t stats)
333 armor_filter_context_t *afx = NULL;
334 compress_filter_context_t zfx;
336 memset( &zfx, 0, sizeof zfx);
338 rc = open_outfile (-1, NULL, 0, !!secret, &out );
342 if ( opt.armor && !(options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)) )
344 afx = new_armor_context ();
345 afx->what = secret? 5 : 1;
346 push_armor_filter (afx, out);
349 rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
355 release_armor_context (afx);
361 /* Release an entire subkey list. */
363 release_subkey_list (subkey_list_t list)
367 subkey_list_t tmp = list->next;;
374 /* Returns true if NODE is a subkey and contained in LIST. */
376 subkey_in_list_p (subkey_list_t list, KBNODE node)
378 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
379 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
383 keyid_from_pk (node->pkt->pkt.public_key, kid);
385 for (; list; list = list->next)
386 if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
392 /* Allocate a new subkey list item from NODE. */
394 new_subkey_list_item (KBNODE node)
396 subkey_list_t list = xcalloc (1, sizeof *list);
398 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
399 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
400 keyid_from_pk (node->pkt->pkt.public_key, list->kid);
406 /* Helper function to check whether the subkey at NODE actually
407 matches the description at DESC. The function returns true if the
408 key under question has been specified by an exact specification
409 (keyID or fingerprint) and does match the one at NODE. It is
410 assumed that the packet at NODE is either a public or secret
413 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
416 byte fpr[MAX_FINGERPRINT_LEN];
422 case KEYDB_SEARCH_MODE_SHORT_KID:
423 case KEYDB_SEARCH_MODE_LONG_KID:
424 keyid_from_pk (node->pkt->pkt.public_key, kid);
427 case KEYDB_SEARCH_MODE_FPR16:
428 case KEYDB_SEARCH_MODE_FPR20:
429 case KEYDB_SEARCH_MODE_FPR:
430 fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
439 case KEYDB_SEARCH_MODE_SHORT_KID:
440 if (desc->u.kid[1] == kid[1])
444 case KEYDB_SEARCH_MODE_LONG_KID:
445 if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
449 case KEYDB_SEARCH_MODE_FPR16:
450 if (!memcmp (desc->u.fpr, fpr, 16))
454 case KEYDB_SEARCH_MODE_FPR20:
455 case KEYDB_SEARCH_MODE_FPR:
456 if (!memcmp (desc->u.fpr, fpr, 20))
468 /* Return an error if the key represented by the S-expression S_KEY
469 * and the OpenPGP key represented by PK do not use the same curve. */
471 match_curve_skey_pk (gcry_sexp_t s_key, PKT_public_key *pk)
473 gcry_sexp_t curve = NULL;
474 gcry_sexp_t flags = NULL;
475 char *curve_str = NULL;
477 const char *oidstr = NULL;
478 gcry_mpi_t curve_as_mpi = NULL;
483 if (!(pk->pubkey_algo==PUBKEY_ALGO_ECDH
484 || pk->pubkey_algo==PUBKEY_ALGO_ECDSA
485 || pk->pubkey_algo==PUBKEY_ALGO_EDDSA))
486 return gpg_error (GPG_ERR_PUBKEY_ALGO);
488 curve = gcry_sexp_find_token (s_key, "curve", 0);
491 log_error ("no reported curve\n");
492 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
494 curve_str = gcry_sexp_nth_string (curve, 1);
495 gcry_sexp_release (curve); curve = NULL;
498 log_error ("no curve name\n");
499 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
501 oidstr = openpgp_curve_to_oid (curve_str, NULL);
504 log_error ("no OID known for curve '%s'\n", curve_str);
506 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
509 err = openpgp_oid_from_str (oidstr, &curve_as_mpi);
512 if (gcry_mpi_cmp (pk->pkey[0], curve_as_mpi))
514 log_error ("curves do not match\n");
515 gcry_mpi_release (curve_as_mpi);
516 return gpg_error (GPG_ERR_INV_CURVE);
518 gcry_mpi_release (curve_as_mpi);
519 flags = gcry_sexp_find_token (s_key, "flags", 0);
522 for (idx = 1; idx < gcry_sexp_length (flags); idx++)
524 flag = gcry_sexp_nth_string (flags, idx);
525 if (flag && (strcmp ("eddsa", flag) == 0))
530 if (is_eddsa != (pk->pubkey_algo == PUBKEY_ALGO_EDDSA))
532 log_error ("disagreement about EdDSA\n");
533 err = gpg_error (GPG_ERR_INV_CURVE);
540 /* Return a canonicalized public key algoithms. This is used to
541 compare different flavors of algorithms (e.g. ELG and ELG_E are
542 considered the same). */
543 static enum gcry_pk_algos
544 canon_pk_algo (enum gcry_pk_algos algo)
550 case GCRY_PK_RSA_S: return GCRY_PK_RSA;
552 case GCRY_PK_ELG_E: return GCRY_PK_ELG;
555 case GCRY_PK_ECDH: return GCRY_PK_ECC;
556 default: return algo;
561 /* Take a cleartext dump of a secret key in PK and change the
562 * parameter array in PK to include the secret parameters. */
564 cleartext_secret_key_to_openpgp (gcry_sexp_t s_key, PKT_public_key *pk)
566 gpg_error_t err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
567 gcry_sexp_t top_list;
568 gcry_sexp_t key = NULL;
569 char *key_type = NULL;
570 enum gcry_pk_algos pk_algo;
571 struct seckey_info *ski;
573 gcry_mpi_t pub_params[10] = { NULL };
575 /* we look for a private-key, then the first element in it tells us
577 top_list = gcry_sexp_find_token (s_key, "private-key", 0);
580 if (gcry_sexp_length(top_list) != 2)
582 key = gcry_sexp_nth (top_list, 1);
585 key_type = gcry_sexp_nth_string(key, 0);
586 pk_algo = gcry_pk_map_name (key_type);
588 log_assert (!pk->seckey_info);
590 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
593 err = gpg_error_from_syserror ();
597 switch (canon_pk_algo (pk_algo))
600 if (!is_RSA (pk->pubkey_algo))
601 goto bad_pubkey_algo;
602 err = gcry_sexp_extract_param (key, NULL, "ne",
606 for (idx=0; idx < 2 && !err; idx++)
607 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
608 err = gpg_error (GPG_ERR_BAD_PUBKEY);
611 for (idx = 2; idx < 6 && !err; idx++)
613 gcry_mpi_release (pk->pkey[idx]);
614 pk->pkey[idx] = NULL;
616 err = gcry_sexp_extract_param (key, NULL, "dpqu",
625 for (idx = 2; idx < 6; idx++)
626 ski->csum += checksum_mpi (pk->pkey[idx]);
631 if (!is_DSA (pk->pubkey_algo))
632 goto bad_pubkey_algo;
633 err = gcry_sexp_extract_param (key, NULL, "pqgy",
639 for (idx=0; idx < 4 && !err; idx++)
640 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
641 err = gpg_error (GPG_ERR_BAD_PUBKEY);
644 gcry_mpi_release (pk->pkey[4]);
646 err = gcry_sexp_extract_param (key, NULL, "x",
651 ski->csum += checksum_mpi (pk->pkey[4]);
655 if (!is_ELGAMAL (pk->pubkey_algo))
656 goto bad_pubkey_algo;
657 err = gcry_sexp_extract_param (key, NULL, "pgy",
662 for (idx=0; idx < 3 && !err; idx++)
663 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
664 err = gpg_error (GPG_ERR_BAD_PUBKEY);
667 gcry_mpi_release (pk->pkey[3]);
669 err = gcry_sexp_extract_param (key, NULL, "x",
674 ski->csum += checksum_mpi (pk->pkey[3]);
678 err = match_curve_skey_pk (key, pk);
682 err = gcry_sexp_extract_param (key, NULL, "q",
685 if (!err && (gcry_mpi_cmp(pk->pkey[1], pub_params[0])))
686 err = gpg_error (GPG_ERR_BAD_PUBKEY);
689 if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
693 gcry_mpi_release (pk->pkey[sec_start]);
694 pk->pkey[sec_start] = NULL;
695 err = gcry_sexp_extract_param (key, NULL, "d",
696 &pk->pkey[sec_start],
701 ski->csum += checksum_mpi (pk->pkey[sec_start]);
705 pk->seckey_info = NULL;
707 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
712 gcry_sexp_release (top_list);
713 gcry_sexp_release (key);
714 gcry_free (key_type);
716 for (idx=0; idx < DIM(pub_params); idx++)
717 gcry_mpi_release (pub_params[idx]);
721 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
725 err = gpg_error (GPG_ERR_BAD_SECKEY);
730 /* Use the key transfer format given in S_PGP to create the secinfo
731 structure in PK and change the parameter array in PK to include the
732 secret parameters. */
734 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
737 gcry_sexp_t top_list;
738 gcry_sexp_t list = NULL;
744 int is_v4, is_protected;
745 enum gcry_pk_algos pk_algo;
746 int protect_algo = 0;
755 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
757 struct seckey_info *ski;
759 /* gcry_log_debugsxp ("transferkey", s_pgp); */
760 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
764 list = gcry_sexp_find_token (top_list, "version", 0);
767 value = gcry_sexp_nth_data (list, 1, &valuelen);
768 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
770 is_v4 = (value[0] == '4');
772 gcry_sexp_release (list);
773 list = gcry_sexp_find_token (top_list, "protection", 0);
776 value = gcry_sexp_nth_data (list, 1, &valuelen);
779 if (valuelen == 4 && !memcmp (value, "sha1", 4))
781 else if (valuelen == 3 && !memcmp (value, "sum", 3))
783 else if (valuelen == 4 && !memcmp (value, "none", 4))
789 string = gcry_sexp_nth_string (list, 2);
792 protect_algo = gcry_cipher_map_name (string);
795 value = gcry_sexp_nth_data (list, 3, &valuelen);
796 if (!value || !valuelen || valuelen > sizeof iv)
798 memcpy (iv, value, valuelen);
801 string = gcry_sexp_nth_string (list, 4);
804 s2k_mode = strtol (string, NULL, 10);
807 string = gcry_sexp_nth_string (list, 5);
810 s2k_algo = gcry_md_map_name (string);
813 value = gcry_sexp_nth_data (list, 6, &valuelen);
814 if (!value || !valuelen || valuelen > sizeof s2k_salt)
816 memcpy (s2k_salt, value, valuelen);
818 string = gcry_sexp_nth_string (list, 7);
821 s2k_count = strtoul (string, NULL, 10);
825 /* Parse the gcrypt PK algo and check that it is okay. */
826 gcry_sexp_release (list);
827 list = gcry_sexp_find_token (top_list, "algo", 0);
830 string = gcry_sexp_nth_string (list, 1);
833 pk_algo = gcry_pk_map_name (string);
834 xfree (string); string = NULL;
835 if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
836 || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
837 || !npkey || npkey >= nskey)
840 /* Check that the pubkey algo matches the one from the public key. */
841 switch (canon_pk_algo (pk_algo))
844 if (!is_RSA (pk->pubkey_algo))
845 pk_algo = 0; /* Does not match. */
848 if (!is_DSA (pk->pubkey_algo))
849 pk_algo = 0; /* Does not match. */
852 if (!is_ELGAMAL (pk->pubkey_algo))
853 pk_algo = 0; /* Does not match. */
856 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
858 else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
860 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
863 pk_algo = 0; /* Does not match. */
864 /* For ECC we do not have the domain parameters thus fix our info. */
869 pk_algo = 0; /* Oops. */
874 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
878 /* This check has to go after the ecc adjustments. */
879 if (nskey > PUBKEY_MAX_NSKEY)
882 /* Parse the key parameters. */
883 gcry_sexp_release (list);
884 list = gcry_sexp_find_token (top_list, "skey", 0);
891 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
892 if (!value && skeyidx >= npkey)
895 /* Check for too many parameters. Note that depending on the
896 protection mode and version number we may see less than NSKEY
897 (but at least NPKEY+1) parameters. */
900 if (skeyidx >= DIM (skey)-1)
903 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
905 is_enc = (value[0] == 'e');
906 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
907 if (!value || !valuelen)
911 void *p = xtrymalloc (valuelen);
914 memcpy (p, value, valuelen);
915 skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
921 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
922 value, valuelen, NULL))
927 skey[skeyidx++] = NULL;
929 gcry_sexp_release (list); list = NULL;
931 /* We have no need for the CSUM value thus we don't parse it. */
932 /* list = gcry_sexp_find_token (top_list, "csum", 0); */
935 /* string = gcry_sexp_nth_string (list, 1); */
937 /* goto bad_seckey; */
938 /* desired_csum = strtoul (string, NULL, 10); */
939 /* xfree (string); */
942 /* desired_csum = 0; */
943 /* gcry_sexp_release (list); list = NULL; */
945 /* Get the curve name if any, */
946 list = gcry_sexp_find_token (top_list, "curve", 0);
949 curve = gcry_sexp_nth_string (list, 1);
950 gcry_sexp_release (list); list = NULL;
953 gcry_sexp_release (top_list); top_list = NULL;
955 /* log_debug ("XXX is_v4=%d\n", is_v4); */
956 /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
957 /* log_debug ("XXX is_protected=%d\n", is_protected); */
958 /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
959 /* log_printhex ("XXX iv", iv, ivlen); */
960 /* log_debug ("XXX ivlen=%d\n", ivlen); */
961 /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
962 /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
963 /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
964 /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
965 /* for (idx=0; skey[idx]; idx++) */
967 /* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
968 /* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
972 /* unsigned int nbits; */
973 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
974 /* log_printhex (NULL, p, (nbits+7)/8); */
977 /* gcry_mpi_dump (skey[idx]); */
978 /* log_printf ("\n"); */
981 if (!is_v4 || is_protected != 2 )
983 /* We only support the v4 format and a SHA-1 checksum. */
984 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
988 /* We need to change the received parameters for ECC algorithms.
989 The transfer format has the curve name and the parameters
990 separate. We put them all into the SKEY array. */
991 if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
995 /* Assert that all required parameters are available. We also
996 check that the array does not contain more parameters than
997 needed (this was used by some beta versions of 2.1. */
998 if (!curve || !skey[0] || !skey[1] || skey[2])
1000 err = gpg_error (GPG_ERR_INTERNAL);
1004 oidstr = openpgp_curve_to_oid (curve, NULL);
1007 log_error ("no OID known for curve '%s'\n", curve);
1008 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1011 /* Put the curve's OID into into the MPI array. This requires
1012 that we shift Q and D. For ECDH also insert the KDF parms. */
1017 skey[2] = gcry_mpi_copy (pk->pkey[2]);
1026 err = openpgp_oid_from_str (oidstr, skey + 0);
1029 /* Fixup the NPKEY and NSKEY to match OpenPGP reality. */
1030 npkey = 2 + is_ecdh;
1031 nskey = 3 + is_ecdh;
1033 /* for (idx=0; skey[idx]; idx++) */
1035 /* log_info ("YYY skey[%d]:", idx); */
1036 /* if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
1039 /* unsigned int nbits; */
1040 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
1041 /* log_printhex (NULL, p, (nbits+7)/8); */
1044 /* gcry_mpi_dump (skey[idx]); */
1045 /* log_printf ("\n"); */
1049 /* Do some sanity checks. */
1050 if (s2k_count > 255)
1052 /* We expect an already encoded S2K count. */
1053 err = gpg_error (GPG_ERR_INV_DATA);
1056 err = openpgp_cipher_test_algo (protect_algo);
1059 err = openpgp_md_test_algo (s2k_algo);
1063 /* Check that the public key parameters match. Note that since
1064 Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly. */
1065 for (idx=0; idx < npkey; idx++)
1066 if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
1068 err = gpg_error (GPG_ERR_BAD_PUBKEY);
1072 /* Check that the first secret key parameter in SKEY is encrypted
1073 and that there are no more secret key parameters. The latter is
1074 guaranteed by the v4 packet format. */
1075 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
1077 if (npkey+1 < DIM (skey) && skey[npkey+1])
1080 /* Check that the secret key parameters in PK are all set to NULL. */
1081 for (idx=npkey; idx < nskey; idx++)
1085 /* Now build the protection info. */
1086 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1089 err = gpg_error_from_syserror ();
1093 ski->is_protected = 1;
1095 ski->algo = protect_algo;
1096 ski->s2k.mode = s2k_mode;
1097 ski->s2k.hash_algo = s2k_algo;
1098 log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
1099 memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
1100 ski->s2k.count = s2k_count;
1101 log_assert (ivlen <= sizeof ski->iv);
1102 memcpy (ski->iv, iv, ivlen);
1105 /* Store the protected secret key parameter. */
1106 pk->pkey[npkey] = skey[npkey];
1113 gcry_sexp_release (list);
1114 gcry_sexp_release (top_list);
1115 for (idx=0; idx < skeyidx; idx++)
1116 gcry_mpi_release (skey[idx]);
1120 err = gpg_error (GPG_ERR_BAD_SECKEY);
1124 err = gpg_error (GPG_ERR_ENOMEM);
1129 /* Print an "EXPORTED" status line. PK is the primary public key. */
1131 print_status_exported (PKT_public_key *pk)
1135 if (!is_status_enabled ())
1138 hexfpr = hexfingerprint (pk, NULL, 0);
1139 write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
1145 * Receive a secret key from agent specified by HEXGRIP.
1147 * Since the key data from the agent is encrypted, decrypt it using
1148 * CIPHERHD context. Then, parse the decrypted key data into transfer
1149 * format, and put secret parameters into PK.
1151 * If CLEARTEXT is 0, store the secret key material
1152 * passphrase-protected. Otherwise, store secret key material in the
1155 * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
1158 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
1160 char **cache_nonce_addr, const char *hexgrip,
1163 gpg_error_t err = 0;
1164 unsigned char *wrappedkey = NULL;
1165 size_t wrappedkeylen;
1166 unsigned char *key = NULL;
1167 size_t keylen, realkeylen;
1172 log_info ("key %s: asking agent for the secret parts\n", hexgrip);
1174 prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
1175 err = agent_export_key (ctrl, hexgrip, prompt, !cleartext, cache_nonce_addr,
1176 &wrappedkey, &wrappedkeylen);
1181 if (wrappedkeylen < 24)
1183 err = gpg_error (GPG_ERR_INV_LENGTH);
1186 keylen = wrappedkeylen - 8;
1187 key = xtrymalloc_secure (keylen);
1190 err = gpg_error_from_syserror ();
1193 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
1196 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
1198 goto unwraperror; /* Invalid csexp. */
1200 err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
1204 err = cleartext_secret_key_to_openpgp (s_skey, pk);
1206 err = transfer_format_to_openpgp (s_skey, pk);
1207 gcry_sexp_release (s_skey);
1215 log_error ("key %s: error receiving key from agent:"
1216 " %s%s\n", hexgrip, gpg_strerror (err),
1217 gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
1218 "":_(" - skipped"));
1224 /* Write KEYBLOCK either to stdout or to the file set with the
1225 * --output option. This is a simplified version of do_export_stream
1226 * which supports only a few export options. */
1228 write_keyblock_to_output (kbnode_t keyblock, int with_armor,
1229 unsigned int options)
1235 armor_filter_context_t *afx = NULL;
1236 iobuf_t out_help = NULL;
1237 PKT_public_key *pk = NULL;
1239 fname = opt.outfile? opt.outfile : "-";
1240 if (is_secured_filename (fname) )
1241 return gpg_error (GPG_ERR_EPERM);
1243 out = iobuf_create (fname, 0);
1246 err = gpg_error_from_syserror ();
1247 log_error(_("can't create '%s': %s\n"), fname, gpg_strerror (err));
1251 log_info (_("writing to '%s'\n"), iobuf_get_fname_nonnull (out));
1253 if ((options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)))
1256 out_help = iobuf_temp ();
1261 afx = new_armor_context ();
1263 push_armor_filter (afx, out);
1266 for (node = keyblock; node; node = node->next)
1268 if (is_deleted_kbnode (node) || node->pkt->pkttype == PKT_RING_TRUST)
1270 if (!pk && (node->pkt->pkttype == PKT_PUBLIC_KEY
1271 || node->pkt->pkttype == PKT_SECRET_KEY))
1272 pk = node->pkt->pkt.public_key;
1274 err = build_packet (out_help? out_help : out, node->pkt);
1277 log_error ("build_packet(%d) failed: %s\n",
1278 node->pkt->pkttype, gpg_strerror (err) );
1289 iobuf_flush_temp (out_help);
1290 data = iobuf_get_temp_buffer (out_help);
1291 datalen = iobuf_get_temp_length (out_help);
1293 err = print_pka_or_dane_records (out,
1294 keyblock, pk, data, datalen,
1295 (options & EXPORT_PKA_FORMAT),
1296 (options & EXPORT_DANE_FORMAT));
1304 iobuf_cancel (out_help);
1305 release_armor_context (afx);
1311 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1312 * marked and thus the caller should call commit_kbnode afterwards.
1313 * KEYBLOCK must not have any blocks marked as deleted.
1316 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1320 for (node = keyblock->next; node; node = node->next )
1322 if (node->pkt->pkttype == PKT_USER_ID)
1324 if (!recsel_select (selector, impex_filter_getval, node))
1326 /* log_debug ("keep-uid: deleting '%s'\n", */
1327 /* node->pkt->pkt.user_id->name); */
1328 /* The UID packet and all following packets up to the
1329 * next UID or a subkey. */
1330 delete_kbnode (node);
1332 && node->next->pkt->pkttype != PKT_USER_ID
1333 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1334 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1336 delete_kbnode (node->next);
1339 /* log_debug ("keep-uid: keeping '%s'\n", */
1340 /* node->pkt->pkt.user_id->name); */
1347 * Apply the drop-subkey filter to the keyblock. The deleted nodes are
1348 * marked and thus the caller should call commit_kbnode afterwards.
1349 * KEYBLOCK must not have any blocks marked as deleted.
1352 apply_drop_subkey_filter (kbnode_t keyblock, recsel_expr_t selector)
1356 for (node = keyblock->next; node; node = node->next )
1358 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1359 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1361 if (recsel_select (selector, impex_filter_getval, node))
1363 log_debug ("drop-subkey: deleting a key\n");
1364 /* The subkey packet and all following packets up to the
1366 delete_kbnode (node);
1368 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1369 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1371 delete_kbnode (node->next);
1378 /* Print DANE or PKA records for all user IDs in KEYBLOCK to OUT. The
1379 * data for the record is taken from (DATA,DATELEN). PK is the public
1380 * key packet with the primary key. */
1382 print_pka_or_dane_records (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
1383 const void *data, size_t datalen,
1384 int print_pka, int print_dane)
1386 gpg_error_t err = 0;
1387 kbnode_t kbctx, node;
1395 estream_t fp = NULL;
1396 char *hexdata = NULL;
1399 hexfpr = hexfingerprint (pk, NULL, 0);
1400 hexdata = bin2hex (data, datalen, NULL);
1403 err = gpg_error_from_syserror ();
1406 ascii_strlwr (hexdata);
1407 fp = es_fopenmem (0, "rw,samethread");
1410 err = gpg_error_from_syserror ();
1414 for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1416 if (node->pkt->pkttype != PKT_USER_ID)
1418 uid = node->pkt->pkt.user_id;
1420 if (uid->is_expired || uid->is_revoked)
1424 mbox = mailbox_from_userid (uid->name);
1428 domain = strchr (mbox, '@');
1433 es_fprintf (fp, "$ORIGIN _pka.%s.\n; %s\n; ", domain, hexfpr);
1434 print_utf8_buffer (fp, uid->name, uid->len);
1436 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
1438 hash = zb32_encode (hashbuf, 8*20);
1441 err = gpg_error_from_syserror ();
1444 len = strlen (hexfpr)/2;
1445 es_fprintf (fp, "%s TYPE37 \\# %u 0006 0000 00 %02X %s\n\n",
1446 hash, 6 + len, len, hexfpr);
1449 if (print_dane && hexdata)
1451 es_fprintf (fp, "$ORIGIN _openpgpkey.%s.\n; %s\n; ", domain, hexfpr);
1452 print_utf8_buffer (fp, uid->name, uid->len);
1454 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
1456 hash = bin2hex (hashbuf, 28, NULL);
1459 err = gpg_error_from_syserror ();
1462 ascii_strlwr (hash);
1463 len = strlen (hexdata)/2;
1464 es_fprintf (fp, "%s TYPE61 \\# %u (\n", hash, len);
1465 for (s = hexdata; ;)
1467 es_fprintf (fp, "\t%.64s\n", s);
1468 if (strlen (s) < 64)
1472 es_fputs ("\t)\n\n", fp);
1476 /* Make sure it is a string and write it. */
1481 if (es_fclose_snatch (fp, &vp, NULL))
1483 err = gpg_error_from_syserror ();
1487 iobuf_writestr (out, vp);
1502 /* Helper for do_export_stream which writes one keyblock to OUT. */
1504 do_export_one_keyblock (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
1505 iobuf_t out, int secret, unsigned int options,
1506 export_stats_t stats, int *any,
1507 KEYDB_SEARCH_DESC *desc, size_t ndesc,
1508 size_t descindex, gcry_cipher_hd_t cipherhd)
1511 char *cache_nonce = NULL;
1512 subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
1513 int skip_until_subkey = 0;
1515 char *hexgrip = NULL;
1516 char *serialno = NULL;
1518 u32 subkidbuf[2], *subkid;
1519 kbnode_t kbctx, node;
1521 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1523 if (skip_until_subkey)
1525 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1526 skip_until_subkey = 0;
1531 /* We used to use comment packets, but not any longer. In
1532 * case we still have comments on a key, strip them here
1533 * before we call build_packet(). */
1534 if (node->pkt->pkttype == PKT_COMMENT)
1537 /* Make sure that ring_trust packets never get exported. */
1538 if (node->pkt->pkttype == PKT_RING_TRUST)
1541 /* If exact is set, then we only export what was requested
1542 * (plus the primary key, if the user didn't specifically
1544 if (desc[descindex].exact && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1546 if (!exact_subkey_match_p (desc+descindex, node))
1548 /* Before skipping this subkey, check whether any
1549 * other description wants an exact match on a
1550 * subkey and include that subkey into the output
1551 * too. Need to add this subkey to a list so that
1552 * it won't get processed a second time.
1554 * So the first step here is to check that list and
1555 * skip in any case if the key is in that list.
1557 * We need this whole mess because the import
1558 * function of GnuPG < 2.1 is not able to merge
1559 * secret keys and thus it is useless to output them
1560 * as two separate keys and have import merge them.
1562 if (subkey_in_list_p (subkey_list, node))
1563 skip_until_subkey = 1; /* Already processed this one. */
1568 for (j=0; j < ndesc; j++)
1569 if (j != descindex && desc[j].exact
1570 && exact_subkey_match_p (desc+j, node))
1573 skip_until_subkey = 1; /* No other one matching. */
1577 if (skip_until_subkey)
1580 /* Mark this one as processed. */
1582 subkey_list_t tmp = new_subkey_list_item (node);
1583 tmp->next = subkey_list;
1588 if (node->pkt->pkttype == PKT_SIGNATURE)
1590 /* Do not export packets which are marked as not
1592 if (!(options & EXPORT_LOCAL_SIGS)
1593 && !node->pkt->pkt.signature->flags.exportable)
1594 continue; /* not exportable */
1596 /* Do not export packets with a "sensitive" revocation key
1597 * unless the user wants us to. Note that we do export
1598 * these when issuing the actual revocation (see revoke.c). */
1599 if (!(options & EXPORT_SENSITIVE_REVKEYS)
1600 && node->pkt->pkt.signature->revkey)
1604 for (i = 0; i < node->pkt->pkt.signature->numrevkeys; i++)
1605 if ((node->pkt->pkt.signature->revkey[i].class & 0x40))
1607 if (i < node->pkt->pkt.signature->numrevkeys)
1612 /* Don't export attribs? */
1613 if (!(options & EXPORT_ATTRIBUTES)
1614 && node->pkt->pkttype == PKT_USER_ID
1615 && node->pkt->pkt.user_id->attrib_data)
1617 /* Skip until we get to something that is not an attrib or a
1618 * signature on an attrib. */
1619 while (kbctx->next && kbctx->next->pkt->pkttype == PKT_SIGNATURE)
1620 kbctx = kbctx->next;
1625 if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1626 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1628 pk = node->pkt->pkt.public_key;
1629 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1633 keyid_from_pk (pk, subkidbuf);
1637 if (pk->seckey_info)
1639 log_error ("key %s: oops: seckey_info already set"
1640 " - skipped\n", keystr_with_sub (keyid, subkid));
1641 skip_until_subkey = 1;
1646 err = hexkeygrip_from_pk (pk, &hexgrip);
1649 log_error ("key %s: error computing keygrip: %s"
1650 " - skipped\n", keystr_with_sub (keyid, subkid),
1651 gpg_strerror (err));
1652 skip_until_subkey = 1;
1659 if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1661 /* We are asked not to export the secret parts of the
1662 * primary key. Make up an error code to create the
1664 err = GPG_ERR_NOT_FOUND;
1667 err = agent_get_keyinfo (ctrl, hexgrip, &serialno, &cleartext);
1669 if ((!err && serialno)
1670 && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1672 /* It does not make sense to export a key with its
1673 * primary key on card using a non-key stub. Thus we
1674 * skip those keys when used with --export-secret-subkeys. */
1675 log_info (_("key %s: key material on-card - skipped\n"),
1676 keystr_with_sub (keyid, subkid));
1677 skip_until_subkey = 1;
1679 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1680 || (!err && serialno))
1682 /* Create a key stub. */
1683 struct seckey_info *ski;
1686 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1689 err = gpg_error_from_syserror ();
1693 ski->is_protected = 1;
1695 ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
1698 ski->s2k.mode = 1002; /* GNU-divert-to-card. */
1699 for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1700 ski->ivlen++, s += 2)
1701 ski->iv[ski->ivlen] = xtoi_2 (s);
1704 err = build_packet (out, node->pkt);
1705 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1708 print_status_exported (node->pkt->pkt.public_key);
1713 err = receive_seckey_from_agent (ctrl, cipherhd,
1714 cleartext, &cache_nonce,
1718 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1720 skip_until_subkey = 1;
1725 err = build_packet (out, node->pkt);
1726 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1729 print_status_exported (node->pkt->pkt.public_key);
1735 log_error ("key %s: error getting keyinfo from agent: %s"
1736 " - skipped\n", keystr_with_sub (keyid, subkid),
1737 gpg_strerror (err));
1738 skip_until_subkey = 1;
1742 xfree (pk->seckey_info);
1743 pk->seckey_info = NULL;
1746 for (i = pubkey_get_npkey (pk->pubkey_algo);
1747 i < pubkey_get_nskey (pk->pubkey_algo); i++)
1749 gcry_mpi_release (pk->pkey[i]);
1754 else /* Not secret or common packets. */
1756 err = build_packet (out, node->pkt);
1757 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1760 print_status_exported (node->pkt->pkt.public_key);
1766 log_error ("build_packet(%d) failed: %s\n",
1767 node->pkt->pkttype, gpg_strerror (err));
1771 if (!skip_until_subkey)
1776 release_subkey_list (subkey_list);
1779 xfree (cache_nonce);
1784 /* Export the keys identified by the list of strings in USERS to the
1785 stream OUT. If SECRET is false public keys will be exported. With
1786 secret true secret keys will be exported; in this case 1 means the
1787 entire secret keyblock and 2 only the subkeys. OPTIONS are the
1788 export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
1789 code is zero, a pointer to the first keyblock found and exported
1790 will be stored at this address; no other keyblocks are exported in
1791 this case. The caller must free the returned keyblock. If any
1792 key has been exported true is stored at ANY. */
1794 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
1795 kbnode_t *keyblock_out, unsigned int options,
1796 export_stats_t stats, int *any)
1798 gpg_error_t err = 0;
1800 kbnode_t keyblock = NULL;
1802 size_t ndesc, descindex;
1803 KEYDB_SEARCH_DESC *desc = NULL;
1806 gcry_cipher_hd_t cipherhd = NULL;
1807 struct export_stats_s dummystats;
1808 iobuf_t out_help = NULL;
1811 stats = &dummystats;
1814 kdbhd = keydb_new ();
1816 return gpg_error_from_syserror ();
1818 /* For the PKA and DANE format open a helper iobuf and for DANE
1819 * enforce some options. */
1820 if ((options & (EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT)))
1822 out_help = iobuf_temp ();
1823 if ((options & EXPORT_DANE_FORMAT))
1824 options |= EXPORT_MINIMAL | EXPORT_CLEAN;
1830 desc = xcalloc (ndesc, sizeof *desc);
1831 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1835 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1837 desc = xmalloc ( ndesc * sizeof *desc);
1839 for (ndesc=0, sl=users; sl; sl = sl->next)
1841 if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
1844 log_error (_("key \"%s\" not found: %s\n"),
1845 sl->d, gpg_strerror (err));
1848 keydb_disable_caching (kdbhd); /* We are looping the search. */
1850 /* It would be nice to see which of the given users did actually
1851 match one in the keyring. To implement this we need to have
1852 a found flag for each entry in desc. To set this flag we
1853 must check all those entries after a match to mark all
1854 matched one - currently we stop at the first match. To do
1855 this we need an extra flag to enable this feature. */
1858 #ifdef ENABLE_SELINUX_HACKS
1861 log_error (_("exporting secret keys not allowed\n"));
1862 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1867 /* For secret key export we need to setup a decryption context. */
1873 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
1876 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1880 /* Prepare a cipher context. */
1881 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1882 GCRY_CIPHER_MODE_AESWRAP, 0);
1884 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1887 log_error ("error setting up an encryption context: %s\n",
1888 gpg_strerror (err));
1900 err = keydb_search (kdbhd, desc, ndesc, &descindex);
1902 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1906 /* Read the keyblock. */
1907 release_kbnode (keyblock);
1909 err = keydb_get_keyblock (kdbhd, &keyblock);
1912 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1916 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1919 log_error ("public key packet not found in keyblock - skipped\n");
1923 setup_main_keyids (keyblock); /* gpg_format_keydesc needs it. */
1924 pk = node->pkt->pkt.public_key;
1925 keyid_from_pk (pk, keyid);
1927 /* If a secret key export is required we need to check whether
1928 we have a secret key at all and if so create the seckey_info
1932 if (agent_probe_any_secret_key (ctrl, keyblock))
1933 continue; /* No secret key (neither primary nor subkey). */
1935 /* No v3 keys with GNU mode 1001. */
1936 if (secret == 2 && pk->version == 3)
1938 log_info (_("key %s: PGP 2.x style key - skipped\n"),
1943 /* The agent does not yet allow export of v3 packets. It is
1944 actually questionable whether we should allow them at
1946 if (pk->version == 3)
1948 log_info ("key %s: PGP 2.x style key (v3) export "
1949 "not yet supported - skipped\n", keystr (keyid));
1952 stats->secret_count++;
1955 /* Always do the cleaning on the public key part if requested.
1956 Note that we don't yet set this option if we are exporting
1957 secret keys. Note that both export-clean and export-minimal
1958 only apply to UID sigs (0x10, 0x11, 0x12, and 0x13). A
1959 designated revocation is never stripped, even with
1960 export-minimal set. */
1961 if ((options & EXPORT_CLEAN))
1962 clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1964 if (export_keep_uid)
1966 commit_kbnode (&keyblock);
1967 apply_keep_uid_filter (keyblock, export_keep_uid);
1968 commit_kbnode (&keyblock);
1971 if (export_drop_subkey)
1973 commit_kbnode (&keyblock);
1974 apply_drop_subkey_filter (keyblock, export_drop_subkey);
1975 commit_kbnode (&keyblock);
1979 err = do_export_one_keyblock (ctrl, keyblock, keyid,
1980 out_help? out_help : out,
1981 secret, options, stats, any,
1982 desc, ndesc, descindex, cipherhd);
1988 *keyblock_out = keyblock;
1994 /* We want to write PKA or DANE records. OUT_HELP has the
1995 * keyblock and we print a record for each uid to OUT. */
1999 iobuf_flush_temp (out_help);
2000 data = iobuf_get_temp_buffer (out_help);
2001 datalen = iobuf_get_temp_length (out_help);
2003 err = print_pka_or_dane_records (out,
2004 keyblock, pk, data, datalen,
2005 (options & EXPORT_PKA_FORMAT),
2006 (options & EXPORT_DANE_FORMAT));
2010 iobuf_close (out_help);
2011 out_help = iobuf_temp ();
2015 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2019 iobuf_cancel (out_help);
2020 gcry_cipher_close (cipherhd);
2022 keydb_release (kdbhd);
2023 if (err || !keyblock_out)
2024 release_kbnode( keyblock );
2026 log_info(_("WARNING: nothing exported\n"));
2034 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
2037 gpg_error_t err = 0;
2038 unsigned char nbuf[4];
2043 ulongtobuf (nbuf, (ulong)strlen (identifier));
2044 put_membuf (mb, nbuf, 4);
2045 put_membuf_str (mb, identifier);
2046 if (!strncmp (identifier, "ecdsa-sha2-", 11))
2048 ulongtobuf (nbuf, (ulong)strlen (identifier+11));
2049 put_membuf (mb, nbuf, 4);
2050 put_membuf_str (mb, identifier+11);
2052 va_start (arg_ptr, identifier);
2053 while ((a = va_arg (arg_ptr, gcry_mpi_t)))
2055 err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
2058 if (!strcmp (identifier, "ssh-ed25519")
2059 && buflen > 5 && buf[4] == 0x40)
2061 /* We need to strip our 0x40 prefix. */
2062 put_membuf (mb, "\x00\x00\x00\x20", 4);
2063 put_membuf (mb, buf+5, buflen-5);
2066 put_membuf (mb, buf, buflen);
2073 /* Export the key identified by USERID in the SSH public key format.
2074 The function exports the latest subkey with Authentication
2075 capability unless the '!' suffix is used to export a specific
2078 export_ssh_key (ctrl_t ctrl, const char *userid)
2081 kbnode_t keyblock = NULL;
2082 KEYDB_SEARCH_DESC desc;
2084 u32 curtime = make_timestamp ();
2085 kbnode_t latest_key, node;
2087 const char *identifier;
2089 estream_t fp = NULL;
2090 struct b64state b64_state;
2091 const char *fname = "-";
2093 init_membuf (&mb, 4096);
2095 /* We need to know whether the key has been specified using the
2096 exact syntax ('!' suffix). Thus we need to run a
2097 classify_user_id on our own. */
2098 err = classify_user_id (userid, &desc, 1);
2100 /* Get the public key. */
2103 getkey_ctx_t getkeyctx;
2105 err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
2107 0 /* Only usable keys or given exact. */,
2108 1 /* No AKL lookup. */);
2111 err = getkey_next (getkeyctx, NULL, NULL);
2113 err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2114 else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
2117 getkey_end (getkeyctx);
2121 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2125 /* The finish_lookup code in getkey.c does not handle auth keys,
2126 thus we have to duplicate the code here to find the latest
2127 subkey. However, if the key has been found using an exact match
2128 ('!' notation) we use that key without any further checks and
2129 even allow the use of the primary key. */
2132 for (node = keyblock; node; node = node->next)
2134 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2135 || node->pkt->pkttype == PKT_PUBLIC_KEY)
2136 && node->pkt->pkt.public_key->flags.exact)
2144 for (node = keyblock; node; node = node->next)
2146 if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2149 pk = node->pkt->pkt.public_key;
2151 log_debug ("\tchecking subkey %08lX\n",
2152 (ulong) keyid_from_pk (pk, NULL));
2153 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2156 log_debug ("\tsubkey not usable for authentication\n");
2159 if (!pk->flags.valid)
2162 log_debug ("\tsubkey not valid\n");
2165 if (pk->flags.revoked)
2168 log_debug ("\tsubkey has been revoked\n");
2171 if (pk->has_expired)
2174 log_debug ("\tsubkey has expired\n");
2177 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2180 log_debug ("\tsubkey not yet valid\n");
2184 log_debug ("\tsubkey might be fine\n");
2185 /* In case a key has a timestamp of 0 set, we make sure that it
2186 is used. A better change would be to compare ">=" but that
2187 might also change the selected keys and is as such a more
2188 intrusive change. */
2189 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2191 latest_date = pk->timestamp;
2199 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2200 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2204 pk = latest_key->pkt->pkt.public_key;
2206 log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
2208 switch (pk->pubkey_algo)
2210 case PUBKEY_ALGO_DSA:
2211 identifier = "ssh-dss";
2212 err = key_to_sshblob (&mb, identifier,
2213 pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
2217 case PUBKEY_ALGO_RSA:
2218 case PUBKEY_ALGO_RSA_S:
2219 identifier = "ssh-rsa";
2220 err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
2223 case PUBKEY_ALGO_ECDSA:
2228 curveoid = openpgp_oid_to_str (pk->pkey[0]);
2230 err = gpg_error_from_syserror ();
2231 else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
2232 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2235 if (!strcmp (curve, "nistp256"))
2236 identifier = "ecdsa-sha2-nistp256";
2237 else if (!strcmp (curve, "nistp384"))
2238 identifier = "ecdsa-sha2-nistp384";
2239 else if (!strcmp (curve, "nistp521"))
2240 identifier = "ecdsa-sha2-nistp521";
2245 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2247 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2253 case PUBKEY_ALGO_EDDSA:
2254 if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
2255 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2258 identifier = "ssh-ed25519";
2259 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2263 case PUBKEY_ALGO_ELGAMAL_E:
2264 case PUBKEY_ALGO_ELGAMAL:
2265 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2269 err = GPG_ERR_PUBKEY_ALGO;
2276 if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
2277 fp = es_fopen ((fname = opt.outfile), "w");
2282 err = gpg_error_from_syserror ();
2283 log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
2287 es_fprintf (fp, "%s ", identifier);
2288 err = b64enc_start_es (&b64_state, fp, "");
2295 blob = get_membuf (&mb, &bloblen);
2297 err = gpg_error_from_syserror ();
2299 err = b64enc_write (&b64_state, blob, bloblen);
2304 err = b64enc_finish (&b64_state);
2307 es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
2310 err = gpg_error_from_syserror ();
2314 err = gpg_error_from_syserror ();
2319 log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
2323 xfree (get_membuf (&mb, NULL));
2324 release_kbnode (keyblock);