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/>.
31 #include "../common/status.h"
33 #include "../common/util.h"
35 #include "../common/i18n.h"
36 #include "../common/membuf.h"
37 #include "../common/host2net.h"
38 #include "../common/zb32.h"
39 #include "../common/recsel.h"
40 #include "../common/mbox-util.h"
41 #include "../common/init.h"
43 #include "call-agent.h"
45 /* An object to keep track of subkeys. */
48 struct subkey_list_s *next;
51 typedef struct subkey_list_s *subkey_list_t;
54 /* An object to track statistics for export operations. */
57 ulong count; /* Number of processed keys. */
58 ulong secret_count; /* Number of secret keys seen. */
59 ulong exported; /* Number of actual exported keys. */
63 /* A global variable to store the selector created from
64 * --export-filter keep-uid=EXPR.
65 * --export-filter drop-subkey=EXPR.
67 * FIXME: We should put this into the CTRL object but that requires a
68 * lot more changes right now.
70 static recsel_expr_t export_keep_uid;
71 static recsel_expr_t export_drop_subkey;
75 /* Local prototypes. */
76 static int do_export (ctrl_t ctrl, strlist_t users, int secret,
77 unsigned int options, export_stats_t stats);
78 static int do_export_stream (ctrl_t ctrl, iobuf_t out,
79 strlist_t users, int secret,
80 kbnode_t *keyblock_out, unsigned int options,
81 export_stats_t stats, int *any);
82 static gpg_error_t print_pka_or_dane_records
83 /**/ (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
84 const void *data, size_t datalen,
85 int print_pka, int print_dane);
89 cleanup_export_globals (void)
91 recsel_release (export_keep_uid);
92 export_keep_uid = NULL;
93 recsel_release (export_drop_subkey);
94 export_drop_subkey = NULL;
98 /* Option parser for export options. See parse_options fro
101 parse_export_options(char *str,unsigned int *options,int noisy)
103 struct parse_options export_opts[]=
105 {"export-local-sigs",EXPORT_LOCAL_SIGS,NULL,
106 N_("export signatures that are marked as local-only")},
107 {"export-attributes",EXPORT_ATTRIBUTES,NULL,
108 N_("export attribute user IDs (generally photo IDs)")},
109 {"export-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,
110 N_("export revocation keys marked as \"sensitive\"")},
111 {"export-clean",EXPORT_CLEAN,NULL,
112 N_("remove unusable parts from key during export")},
113 {"export-minimal",EXPORT_MINIMAL|EXPORT_CLEAN,NULL,
114 N_("remove as much as possible from key during export")},
116 {"export-pka", EXPORT_PKA_FORMAT, NULL, NULL },
117 {"export-dane", EXPORT_DANE_FORMAT, NULL, NULL },
119 {"backup", EXPORT_BACKUP, NULL,
120 N_("use the GnuPG key backup format")},
121 {"export-backup", EXPORT_BACKUP, NULL, NULL },
123 /* Aliases for backward compatibility */
124 {"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
125 {"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
126 {"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
128 {"export-unusable-sigs",0,NULL,NULL},
129 {"export-clean-sigs",0,NULL,NULL},
130 {"export-clean-uids",0,NULL,NULL},
132 /* add tags for include revoked and disabled? */
136 rc = parse_options (str, options, export_opts, noisy);
137 if (rc && (*options & EXPORT_BACKUP))
139 /* Alter other options we want or don't want for restore. */
140 *options |= (EXPORT_LOCAL_SIGS | EXPORT_ATTRIBUTES
141 | EXPORT_SENSITIVE_REVKEYS);
142 *options &= ~(EXPORT_CLEAN | EXPORT_MINIMAL
143 | EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT);
149 /* Parse and set an export filter from string. STRING has the format
150 * "NAME=EXPR" with NAME being the name of the filter. Spaces before
151 * and after NAME are not allowed. If this function is called several
152 * times all expressions for the same NAME are concatenated.
153 * Supported filter names are:
155 * - keep-uid :: If the expression evaluates to true for a certain
156 * user ID packet, that packet and all it dependencies
157 * will be exported. The expression may use these
160 * - uid :: The entire user ID.
161 * - mbox :: The mail box part of the user ID.
162 * - primary :: Evaluate to true for the primary user ID.
164 * - drop-subkey :: If the expression evaluates to true for a subkey
165 * packet that subkey and all it dependencies will be
166 * remove from the keyblock. The expression may use these
169 * - secret :: 1 for a secret subkey, else 0.
170 * - key_algo :: Public key algorithm id
173 parse_and_set_export_filter (const char *string)
177 /* Auto register the cleanup function. */
178 register_mem_cleanup_func (cleanup_export_globals);
180 if (!strncmp (string, "keep-uid=", 9))
181 err = recsel_parse_expr (&export_keep_uid, string+9);
182 else if (!strncmp (string, "drop-subkey=", 12))
183 err = recsel_parse_expr (&export_drop_subkey, string+12);
185 err = gpg_error (GPG_ERR_INV_NAME);
191 /* Create a new export stats object initialized to zero. On error
192 returns NULL and sets ERRNO. */
194 export_new_stats (void)
196 export_stats_t stats;
198 return xtrycalloc (1, sizeof *stats);
202 /* Release an export stats object. */
204 export_release_stats (export_stats_t stats)
210 /* Print export statistics using the status interface. */
212 export_print_stats (export_stats_t stats)
217 if (is_status_enabled ())
221 snprintf (buf, sizeof buf, "%lu %lu %lu",
225 write_status_text (STATUS_EXPORT_RES, buf);
231 * Export public keys (to stdout or to --output FILE).
233 * Depending on opt.armor the output is armored. OPTIONS are defined
234 * in main.h. If USERS is NULL, all keys will be exported. STATS is
235 * either an export stats object for update or NULL.
237 * This function is the core of "gpg --export".
240 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
241 export_stats_t stats)
243 return do_export (ctrl, users, 0, options, stats);
248 * Export secret keys (to stdout or to --output FILE).
250 * Depending on opt.armor the output is armored. OPTIONS are defined
251 * in main.h. If USERS is NULL, all secret keys will be exported.
252 * STATS is either an export stats object for update or NULL.
254 * This function is the core of "gpg --export-secret-keys".
257 export_seckeys (ctrl_t ctrl, strlist_t users, unsigned int options,
258 export_stats_t stats)
260 return do_export (ctrl, users, 1, options, stats);
265 * Export secret sub keys (to stdout or to --output FILE).
267 * This is the same as export_seckeys but replaces the primary key by
268 * a stub key. Depending on opt.armor the output is armored. OPTIONS
269 * are defined in main.h. If USERS is NULL, all secret subkeys will
270 * be exported. STATS is either an export stats object for update or
273 * This function is the core of "gpg --export-secret-subkeys".
276 export_secsubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
277 export_stats_t stats)
279 return do_export (ctrl, users, 2, options, stats);
284 * Export a single key into a memory buffer. STATS is either an
285 * export stats object for update or NULL.
288 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
289 export_stats_t stats,
290 kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
302 if (!add_to_strlist_try (&helplist, keyspec))
303 return gpg_error_from_syserror ();
305 iobuf = iobuf_temp ();
306 err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
309 err = gpg_error (GPG_ERR_NOT_FOUND);
315 iobuf_flush_temp (iobuf);
316 src = iobuf_get_temp_buffer (iobuf);
317 datalen = iobuf_get_temp_length (iobuf);
319 err = gpg_error (GPG_ERR_NO_PUBKEY);
320 else if (!(*r_data = xtrymalloc (datalen)))
321 err = gpg_error_from_syserror ();
324 memcpy (*r_data, src, datalen);
325 *r_datalen = datalen;
329 free_strlist (helplist);
330 if (err && *r_keyblock)
332 release_kbnode (*r_keyblock);
339 /* Export the keys identified by the list of strings in USERS. If
340 Secret is false public keys will be exported. With secret true
341 secret keys will be exported; in this case 1 means the entire
342 secret keyblock and 2 only the subkeys. OPTIONS are the export
345 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
346 export_stats_t stats)
350 armor_filter_context_t *afx = NULL;
351 compress_filter_context_t zfx;
353 memset( &zfx, 0, sizeof zfx);
355 rc = open_outfile (-1, NULL, 0, !!secret, &out );
359 if ( opt.armor && !(options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)) )
361 afx = new_armor_context ();
362 afx->what = secret? 5 : 1;
363 push_armor_filter (afx, out);
366 rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
372 release_armor_context (afx);
378 /* Release an entire subkey list. */
380 release_subkey_list (subkey_list_t list)
384 subkey_list_t tmp = list->next;;
391 /* Returns true if NODE is a subkey and contained in LIST. */
393 subkey_in_list_p (subkey_list_t list, KBNODE node)
395 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
396 || node->pkt->pkttype == PKT_SECRET_SUBKEY )
400 keyid_from_pk (node->pkt->pkt.public_key, kid);
402 for (; list; list = list->next)
403 if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
409 /* Allocate a new subkey list item from NODE. */
411 new_subkey_list_item (KBNODE node)
413 subkey_list_t list = xcalloc (1, sizeof *list);
415 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
416 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
417 keyid_from_pk (node->pkt->pkt.public_key, list->kid);
423 /* Helper function to check whether the subkey at NODE actually
424 matches the description at DESC. The function returns true if the
425 key under question has been specified by an exact specification
426 (keyID or fingerprint) and does match the one at NODE. It is
427 assumed that the packet at NODE is either a public or secret
430 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
433 byte fpr[MAX_FINGERPRINT_LEN];
439 case KEYDB_SEARCH_MODE_SHORT_KID:
440 case KEYDB_SEARCH_MODE_LONG_KID:
441 keyid_from_pk (node->pkt->pkt.public_key, kid);
444 case KEYDB_SEARCH_MODE_FPR16:
445 case KEYDB_SEARCH_MODE_FPR20:
446 case KEYDB_SEARCH_MODE_FPR:
447 fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
456 case KEYDB_SEARCH_MODE_SHORT_KID:
457 if (desc->u.kid[1] == kid[1])
461 case KEYDB_SEARCH_MODE_LONG_KID:
462 if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
466 case KEYDB_SEARCH_MODE_FPR16:
467 if (!memcmp (desc->u.fpr, fpr, 16))
471 case KEYDB_SEARCH_MODE_FPR20:
472 case KEYDB_SEARCH_MODE_FPR:
473 if (!memcmp (desc->u.fpr, fpr, 20))
485 /* Return an error if the key represented by the S-expression S_KEY
486 * and the OpenPGP key represented by PK do not use the same curve. */
488 match_curve_skey_pk (gcry_sexp_t s_key, PKT_public_key *pk)
490 gcry_sexp_t curve = NULL;
491 gcry_sexp_t flags = NULL;
492 char *curve_str = NULL;
494 const char *oidstr = NULL;
495 gcry_mpi_t curve_as_mpi = NULL;
500 if (!(pk->pubkey_algo==PUBKEY_ALGO_ECDH
501 || pk->pubkey_algo==PUBKEY_ALGO_ECDSA
502 || pk->pubkey_algo==PUBKEY_ALGO_EDDSA))
503 return gpg_error (GPG_ERR_PUBKEY_ALGO);
505 curve = gcry_sexp_find_token (s_key, "curve", 0);
508 log_error ("no reported curve\n");
509 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
511 curve_str = gcry_sexp_nth_string (curve, 1);
512 gcry_sexp_release (curve); curve = NULL;
515 log_error ("no curve name\n");
516 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
518 oidstr = openpgp_curve_to_oid (curve_str, NULL);
521 log_error ("no OID known for curve '%s'\n", curve_str);
523 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
526 err = openpgp_oid_from_str (oidstr, &curve_as_mpi);
529 if (gcry_mpi_cmp (pk->pkey[0], curve_as_mpi))
531 log_error ("curves do not match\n");
532 gcry_mpi_release (curve_as_mpi);
533 return gpg_error (GPG_ERR_INV_CURVE);
535 gcry_mpi_release (curve_as_mpi);
536 flags = gcry_sexp_find_token (s_key, "flags", 0);
539 for (idx = 1; idx < gcry_sexp_length (flags); idx++)
541 flag = gcry_sexp_nth_string (flags, idx);
542 if (flag && (strcmp ("eddsa", flag) == 0))
547 if (is_eddsa != (pk->pubkey_algo == PUBKEY_ALGO_EDDSA))
549 log_error ("disagreement about EdDSA\n");
550 err = gpg_error (GPG_ERR_INV_CURVE);
557 /* Return a canonicalized public key algoithms. This is used to
558 compare different flavors of algorithms (e.g. ELG and ELG_E are
559 considered the same). */
560 static enum gcry_pk_algos
561 canon_pk_algo (enum gcry_pk_algos algo)
567 case GCRY_PK_RSA_S: return GCRY_PK_RSA;
569 case GCRY_PK_ELG_E: return GCRY_PK_ELG;
572 case GCRY_PK_ECDH: return GCRY_PK_ECC;
573 default: return algo;
578 /* Take a cleartext dump of a secret key in PK and change the
579 * parameter array in PK to include the secret parameters. */
581 cleartext_secret_key_to_openpgp (gcry_sexp_t s_key, PKT_public_key *pk)
584 gcry_sexp_t top_list;
585 gcry_sexp_t key = NULL;
586 char *key_type = NULL;
587 enum gcry_pk_algos pk_algo;
588 struct seckey_info *ski;
590 gcry_mpi_t pub_params[10] = { NULL };
592 /* we look for a private-key, then the first element in it tells us
594 top_list = gcry_sexp_find_token (s_key, "private-key", 0);
597 if (gcry_sexp_length(top_list) != 2)
599 key = gcry_sexp_nth (top_list, 1);
602 key_type = gcry_sexp_nth_string(key, 0);
603 pk_algo = gcry_pk_map_name (key_type);
605 log_assert (!pk->seckey_info);
607 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
610 err = gpg_error_from_syserror ();
614 switch (canon_pk_algo (pk_algo))
617 if (!is_RSA (pk->pubkey_algo))
618 goto bad_pubkey_algo;
619 err = gcry_sexp_extract_param (key, NULL, "ne",
623 for (idx=0; idx < 2 && !err; idx++)
624 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
625 err = gpg_error (GPG_ERR_BAD_PUBKEY);
628 for (idx = 2; idx < 6 && !err; idx++)
630 gcry_mpi_release (pk->pkey[idx]);
631 pk->pkey[idx] = NULL;
633 err = gcry_sexp_extract_param (key, NULL, "dpqu",
642 for (idx = 2; idx < 6; idx++)
643 ski->csum += checksum_mpi (pk->pkey[idx]);
648 if (!is_DSA (pk->pubkey_algo))
649 goto bad_pubkey_algo;
650 err = gcry_sexp_extract_param (key, NULL, "pqgy",
656 for (idx=0; idx < 4 && !err; idx++)
657 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
658 err = gpg_error (GPG_ERR_BAD_PUBKEY);
661 gcry_mpi_release (pk->pkey[4]);
663 err = gcry_sexp_extract_param (key, NULL, "x",
668 ski->csum += checksum_mpi (pk->pkey[4]);
672 if (!is_ELGAMAL (pk->pubkey_algo))
673 goto bad_pubkey_algo;
674 err = gcry_sexp_extract_param (key, NULL, "pgy",
679 for (idx=0; idx < 3 && !err; idx++)
680 if (gcry_mpi_cmp(pk->pkey[idx], pub_params[idx]))
681 err = gpg_error (GPG_ERR_BAD_PUBKEY);
684 gcry_mpi_release (pk->pkey[3]);
686 err = gcry_sexp_extract_param (key, NULL, "x",
691 ski->csum += checksum_mpi (pk->pkey[3]);
695 err = match_curve_skey_pk (key, pk);
699 err = gcry_sexp_extract_param (key, NULL, "q",
702 if (!err && (gcry_mpi_cmp(pk->pkey[1], pub_params[0])))
703 err = gpg_error (GPG_ERR_BAD_PUBKEY);
706 if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
710 gcry_mpi_release (pk->pkey[sec_start]);
711 pk->pkey[sec_start] = NULL;
712 err = gcry_sexp_extract_param (key, NULL, "d",
713 &pk->pkey[sec_start],
718 ski->csum += checksum_mpi (pk->pkey[sec_start]);
722 pk->seckey_info = NULL;
724 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
729 gcry_sexp_release (top_list);
730 gcry_sexp_release (key);
731 gcry_free (key_type);
733 for (idx=0; idx < DIM(pub_params); idx++)
734 gcry_mpi_release (pub_params[idx]);
738 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
742 err = gpg_error (GPG_ERR_BAD_SECKEY);
747 /* Use the key transfer format given in S_PGP to create the secinfo
748 structure in PK and change the parameter array in PK to include the
749 secret parameters. */
751 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
754 gcry_sexp_t top_list;
755 gcry_sexp_t list = NULL;
761 int is_v4, is_protected;
762 enum gcry_pk_algos pk_algo;
763 int protect_algo = 0;
772 gcry_mpi_t skey[10]; /* We support up to 9 parameters. */
774 struct seckey_info *ski;
776 /* gcry_log_debugsxp ("transferkey", s_pgp); */
777 top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
781 list = gcry_sexp_find_token (top_list, "version", 0);
784 value = gcry_sexp_nth_data (list, 1, &valuelen);
785 if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
787 is_v4 = (value[0] == '4');
789 gcry_sexp_release (list);
790 list = gcry_sexp_find_token (top_list, "protection", 0);
793 value = gcry_sexp_nth_data (list, 1, &valuelen);
796 if (valuelen == 4 && !memcmp (value, "sha1", 4))
798 else if (valuelen == 3 && !memcmp (value, "sum", 3))
800 else if (valuelen == 4 && !memcmp (value, "none", 4))
806 string = gcry_sexp_nth_string (list, 2);
809 protect_algo = gcry_cipher_map_name (string);
812 value = gcry_sexp_nth_data (list, 3, &valuelen);
813 if (!value || !valuelen || valuelen > sizeof iv)
815 memcpy (iv, value, valuelen);
818 string = gcry_sexp_nth_string (list, 4);
821 s2k_mode = strtol (string, NULL, 10);
824 string = gcry_sexp_nth_string (list, 5);
827 s2k_algo = gcry_md_map_name (string);
830 value = gcry_sexp_nth_data (list, 6, &valuelen);
831 if (!value || !valuelen || valuelen > sizeof s2k_salt)
833 memcpy (s2k_salt, value, valuelen);
835 string = gcry_sexp_nth_string (list, 7);
838 s2k_count = strtoul (string, NULL, 10);
842 /* Parse the gcrypt PK algo and check that it is okay. */
843 gcry_sexp_release (list);
844 list = gcry_sexp_find_token (top_list, "algo", 0);
847 string = gcry_sexp_nth_string (list, 1);
850 pk_algo = gcry_pk_map_name (string);
851 xfree (string); string = NULL;
852 if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
853 || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
854 || !npkey || npkey >= nskey)
857 /* Check that the pubkey algo matches the one from the public key. */
858 switch (canon_pk_algo (pk_algo))
861 if (!is_RSA (pk->pubkey_algo))
862 pk_algo = 0; /* Does not match. */
865 if (!is_DSA (pk->pubkey_algo))
866 pk_algo = 0; /* Does not match. */
869 if (!is_ELGAMAL (pk->pubkey_algo))
870 pk_algo = 0; /* Does not match. */
873 if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
875 else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
877 else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
880 pk_algo = 0; /* Does not match. */
881 /* For ECC we do not have the domain parameters thus fix our info. */
886 pk_algo = 0; /* Oops. */
891 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
895 /* This check has to go after the ecc adjustments. */
896 if (nskey > PUBKEY_MAX_NSKEY)
899 /* Parse the key parameters. */
900 gcry_sexp_release (list);
901 list = gcry_sexp_find_token (top_list, "skey", 0);
908 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
909 if (!value && skeyidx >= npkey)
912 /* Check for too many parameters. Note that depending on the
913 protection mode and version number we may see less than NSKEY
914 (but at least NPKEY+1) parameters. */
917 if (skeyidx >= DIM (skey)-1)
920 if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
922 is_enc = (value[0] == 'e');
923 value = gcry_sexp_nth_data (list, ++idx, &valuelen);
924 if (!value || !valuelen)
928 void *p = xtrymalloc (valuelen);
931 memcpy (p, value, valuelen);
932 skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
938 if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
939 value, valuelen, NULL))
944 skey[skeyidx++] = NULL;
946 gcry_sexp_release (list); list = NULL;
948 /* We have no need for the CSUM value thus we don't parse it. */
949 /* list = gcry_sexp_find_token (top_list, "csum", 0); */
952 /* string = gcry_sexp_nth_string (list, 1); */
954 /* goto bad_seckey; */
955 /* desired_csum = strtoul (string, NULL, 10); */
956 /* xfree (string); */
959 /* desired_csum = 0; */
960 /* gcry_sexp_release (list); list = NULL; */
962 /* Get the curve name if any, */
963 list = gcry_sexp_find_token (top_list, "curve", 0);
966 curve = gcry_sexp_nth_string (list, 1);
967 gcry_sexp_release (list); list = NULL;
970 gcry_sexp_release (top_list); top_list = NULL;
972 /* log_debug ("XXX is_v4=%d\n", is_v4); */
973 /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
974 /* log_debug ("XXX is_protected=%d\n", is_protected); */
975 /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
976 /* log_printhex ("XXX iv", iv, ivlen); */
977 /* log_debug ("XXX ivlen=%d\n", ivlen); */
978 /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
979 /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
980 /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
981 /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
982 /* for (idx=0; skey[idx]; idx++) */
984 /* int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
985 /* log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
989 /* unsigned int nbits; */
990 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
991 /* log_printhex (NULL, p, (nbits+7)/8); */
994 /* gcry_mpi_dump (skey[idx]); */
995 /* log_printf ("\n"); */
998 if (!is_v4 || is_protected != 2 )
1000 /* We only support the v4 format and a SHA-1 checksum. */
1001 err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1005 /* We need to change the received parameters for ECC algorithms.
1006 The transfer format has the curve name and the parameters
1007 separate. We put them all into the SKEY array. */
1008 if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
1012 /* Assert that all required parameters are available. We also
1013 check that the array does not contain more parameters than
1014 needed (this was used by some beta versions of 2.1. */
1015 if (!curve || !skey[0] || !skey[1] || skey[2])
1017 err = gpg_error (GPG_ERR_INTERNAL);
1021 oidstr = openpgp_curve_to_oid (curve, NULL);
1024 log_error ("no OID known for curve '%s'\n", curve);
1025 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1028 /* Put the curve's OID into the MPI array. This requires
1029 that we shift Q and D. For ECDH also insert the KDF parms. */
1034 skey[2] = gcry_mpi_copy (pk->pkey[2]);
1043 err = openpgp_oid_from_str (oidstr, skey + 0);
1046 /* Fixup the NPKEY and NSKEY to match OpenPGP reality. */
1047 npkey = 2 + is_ecdh;
1048 nskey = 3 + is_ecdh;
1050 /* for (idx=0; skey[idx]; idx++) */
1052 /* log_info ("YYY skey[%d]:", idx); */
1053 /* if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
1056 /* unsigned int nbits; */
1057 /* p = gcry_mpi_get_opaque (skey[idx], &nbits); */
1058 /* log_printhex (NULL, p, (nbits+7)/8); */
1061 /* gcry_mpi_dump (skey[idx]); */
1062 /* log_printf ("\n"); */
1066 /* Do some sanity checks. */
1067 if (s2k_count > 255)
1069 /* We expect an already encoded S2K count. */
1070 err = gpg_error (GPG_ERR_INV_DATA);
1073 err = openpgp_cipher_test_algo (protect_algo);
1076 err = openpgp_md_test_algo (s2k_algo);
1080 /* Check that the public key parameters match. Note that since
1081 Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly. */
1082 for (idx=0; idx < npkey; idx++)
1083 if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
1085 err = gpg_error (GPG_ERR_BAD_PUBKEY);
1089 /* Check that the first secret key parameter in SKEY is encrypted
1090 and that there are no more secret key parameters. The latter is
1091 guaranteed by the v4 packet format. */
1092 if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
1094 if (npkey+1 < DIM (skey) && skey[npkey+1])
1097 /* Check that the secret key parameters in PK are all set to NULL. */
1098 for (idx=npkey; idx < nskey; idx++)
1102 /* Now build the protection info. */
1103 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1106 err = gpg_error_from_syserror ();
1110 ski->is_protected = 1;
1112 ski->algo = protect_algo;
1113 ski->s2k.mode = s2k_mode;
1114 ski->s2k.hash_algo = s2k_algo;
1115 log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
1116 memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
1117 ski->s2k.count = s2k_count;
1118 log_assert (ivlen <= sizeof ski->iv);
1119 memcpy (ski->iv, iv, ivlen);
1122 /* Store the protected secret key parameter. */
1123 pk->pkey[npkey] = skey[npkey];
1130 gcry_sexp_release (list);
1131 gcry_sexp_release (top_list);
1132 for (idx=0; idx < skeyidx; idx++)
1133 gcry_mpi_release (skey[idx]);
1137 err = gpg_error (GPG_ERR_BAD_SECKEY);
1141 err = gpg_error (GPG_ERR_ENOMEM);
1146 /* Print an "EXPORTED" status line. PK is the primary public key. */
1148 print_status_exported (PKT_public_key *pk)
1152 if (!is_status_enabled ())
1155 hexfpr = hexfingerprint (pk, NULL, 0);
1156 write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
1162 * Receive a secret key from agent specified by HEXGRIP.
1164 * Since the key data from the agent is encrypted, decrypt it using
1165 * CIPHERHD context. Then, parse the decrypted key data into transfer
1166 * format, and put secret parameters into PK.
1168 * If CLEARTEXT is 0, store the secret key material
1169 * passphrase-protected. Otherwise, store secret key material in the
1172 * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
1175 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
1177 char **cache_nonce_addr, const char *hexgrip,
1180 gpg_error_t err = 0;
1181 unsigned char *wrappedkey = NULL;
1182 size_t wrappedkeylen;
1183 unsigned char *key = NULL;
1184 size_t keylen, realkeylen;
1189 log_info ("key %s: asking agent for the secret parts\n", hexgrip);
1191 prompt = gpg_format_keydesc (ctrl, pk, FORMAT_KEYDESC_EXPORT,1);
1192 err = agent_export_key (ctrl, hexgrip, prompt, !cleartext, cache_nonce_addr,
1193 &wrappedkey, &wrappedkeylen,
1194 pk->keyid, pk->main_keyid, pk->pubkey_algo);
1199 if (wrappedkeylen < 24)
1201 err = gpg_error (GPG_ERR_INV_LENGTH);
1204 keylen = wrappedkeylen - 8;
1205 key = xtrymalloc_secure (keylen);
1208 err = gpg_error_from_syserror ();
1211 err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
1214 realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
1216 goto unwraperror; /* Invalid csexp. */
1218 err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
1222 err = cleartext_secret_key_to_openpgp (s_skey, pk);
1224 err = transfer_format_to_openpgp (s_skey, pk);
1225 gcry_sexp_release (s_skey);
1233 log_error ("key %s: error receiving key from agent:"
1234 " %s%s\n", hexgrip, gpg_strerror (err),
1235 gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
1236 "":_(" - skipped"));
1242 /* Write KEYBLOCK either to stdout or to the file set with the
1243 * --output option. This is a simplified version of do_export_stream
1244 * which supports only a few export options. */
1246 write_keyblock_to_output (kbnode_t keyblock, int with_armor,
1247 unsigned int options)
1253 armor_filter_context_t *afx = NULL;
1254 iobuf_t out_help = NULL;
1255 PKT_public_key *pk = NULL;
1257 fname = opt.outfile? opt.outfile : "-";
1258 if (is_secured_filename (fname) )
1259 return gpg_error (GPG_ERR_EPERM);
1261 out = iobuf_create (fname, 0);
1264 err = gpg_error_from_syserror ();
1265 log_error(_("can't create '%s': %s\n"), fname, gpg_strerror (err));
1269 log_info (_("writing to '%s'\n"), iobuf_get_fname_nonnull (out));
1271 if ((options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)))
1274 out_help = iobuf_temp ();
1279 afx = new_armor_context ();
1281 push_armor_filter (afx, out);
1284 for (node = keyblock; node; node = node->next)
1286 if (is_deleted_kbnode (node))
1288 if (node->pkt->pkttype == PKT_RING_TRUST)
1289 continue; /* Skip - they should not be here anyway. */
1291 if (!pk && (node->pkt->pkttype == PKT_PUBLIC_KEY
1292 || node->pkt->pkttype == PKT_SECRET_KEY))
1293 pk = node->pkt->pkt.public_key;
1295 if ((options & EXPORT_BACKUP))
1296 err = build_packet_and_meta (out_help? out_help : out, node->pkt);
1298 err = build_packet (out_help? out_help : out, node->pkt);
1301 log_error ("build_packet(%d) failed: %s\n",
1302 node->pkt->pkttype, gpg_strerror (err) );
1313 iobuf_flush_temp (out_help);
1314 data = iobuf_get_temp_buffer (out_help);
1315 datalen = iobuf_get_temp_length (out_help);
1317 err = print_pka_or_dane_records (out,
1318 keyblock, pk, data, datalen,
1319 (options & EXPORT_PKA_FORMAT),
1320 (options & EXPORT_DANE_FORMAT));
1328 iobuf_cancel (out_help);
1329 release_armor_context (afx);
1335 * Apply the keep-uid filter to the keyblock. The deleted nodes are
1336 * marked and thus the caller should call commit_kbnode afterwards.
1337 * KEYBLOCK must not have any blocks marked as deleted.
1340 apply_keep_uid_filter (ctrl_t ctrl, kbnode_t keyblock, recsel_expr_t selector)
1343 struct impex_filter_parm_s parm;
1347 for (node = keyblock->next; node; node = node->next )
1349 if (node->pkt->pkttype == PKT_USER_ID)
1352 if (!recsel_select (selector, impex_filter_getval, &parm))
1354 /* log_debug ("keep-uid: deleting '%s'\n", */
1355 /* node->pkt->pkt.user_id->name); */
1356 /* The UID packet and all following packets up to the
1357 * next UID or a subkey. */
1358 delete_kbnode (node);
1360 && node->next->pkt->pkttype != PKT_USER_ID
1361 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1362 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1364 delete_kbnode (node->next);
1367 /* log_debug ("keep-uid: keeping '%s'\n", */
1368 /* node->pkt->pkt.user_id->name); */
1375 * Apply the drop-subkey filter to the keyblock. The deleted nodes are
1376 * marked and thus the caller should call commit_kbnode afterwards.
1377 * KEYBLOCK must not have any blocks marked as deleted.
1380 apply_drop_subkey_filter (ctrl_t ctrl, kbnode_t keyblock,
1381 recsel_expr_t selector)
1384 struct impex_filter_parm_s parm;
1388 for (node = keyblock->next; node; node = node->next )
1390 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1391 || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1394 if (recsel_select (selector, impex_filter_getval, &parm))
1396 /*log_debug ("drop-subkey: deleting a key\n");*/
1397 /* The subkey packet and all following packets up to the
1399 delete_kbnode (node);
1401 && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1402 && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1404 delete_kbnode (node->next);
1411 /* Print DANE or PKA records for all user IDs in KEYBLOCK to OUT. The
1412 * data for the record is taken from (DATA,DATELEN). PK is the public
1413 * key packet with the primary key. */
1415 print_pka_or_dane_records (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
1416 const void *data, size_t datalen,
1417 int print_pka, int print_dane)
1419 gpg_error_t err = 0;
1420 kbnode_t kbctx, node;
1428 estream_t fp = NULL;
1429 char *hexdata = NULL;
1432 hexfpr = hexfingerprint (pk, NULL, 0);
1433 hexdata = bin2hex (data, datalen, NULL);
1436 err = gpg_error_from_syserror ();
1439 ascii_strlwr (hexdata);
1440 fp = es_fopenmem (0, "rw,samethread");
1443 err = gpg_error_from_syserror ();
1447 for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1449 if (node->pkt->pkttype != PKT_USER_ID)
1451 uid = node->pkt->pkt.user_id;
1453 if (uid->flags.expired || uid->flags.revoked)
1457 mbox = mailbox_from_userid (uid->name);
1461 domain = strchr (mbox, '@');
1466 es_fprintf (fp, "$ORIGIN _pka.%s.\n; %s\n; ", domain, hexfpr);
1467 print_utf8_buffer (fp, uid->name, uid->len);
1469 gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
1471 hash = zb32_encode (hashbuf, 8*20);
1474 err = gpg_error_from_syserror ();
1477 len = strlen (hexfpr)/2;
1478 es_fprintf (fp, "%s TYPE37 \\# %u 0006 0000 00 %02X %s\n\n",
1479 hash, 6 + len, len, hexfpr);
1482 if (print_dane && hexdata)
1484 es_fprintf (fp, "$ORIGIN _openpgpkey.%s.\n; %s\n; ", domain, hexfpr);
1485 print_utf8_buffer (fp, uid->name, uid->len);
1487 gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
1489 hash = bin2hex (hashbuf, 28, NULL);
1492 err = gpg_error_from_syserror ();
1495 ascii_strlwr (hash);
1496 len = strlen (hexdata)/2;
1497 es_fprintf (fp, "%s TYPE61 \\# %u (\n", hash, len);
1498 for (s = hexdata; ;)
1500 es_fprintf (fp, "\t%.64s\n", s);
1501 if (strlen (s) < 64)
1505 es_fputs ("\t)\n\n", fp);
1509 /* Make sure it is a string and write it. */
1514 if (es_fclose_snatch (fp, &vp, NULL))
1516 err = gpg_error_from_syserror ();
1520 iobuf_writestr (out, vp);
1535 /* Helper for do_export_stream which writes one keyblock to OUT. */
1537 do_export_one_keyblock (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
1538 iobuf_t out, int secret, unsigned int options,
1539 export_stats_t stats, int *any,
1540 KEYDB_SEARCH_DESC *desc, size_t ndesc,
1541 size_t descindex, gcry_cipher_hd_t cipherhd)
1543 gpg_error_t err = gpg_error (GPG_ERR_NOT_FOUND);
1544 char *cache_nonce = NULL;
1545 subkey_list_t subkey_list = NULL; /* Track already processed subkeys. */
1546 int skip_until_subkey = 0;
1548 char *hexgrip = NULL;
1549 char *serialno = NULL;
1551 u32 subkidbuf[2], *subkid;
1552 kbnode_t kbctx, node;
1554 /* NB: walk_kbnode skips packets marked as deleted. */
1555 for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1557 if (skip_until_subkey)
1559 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1560 skip_until_subkey = 0;
1565 /* We used to use comment packets, but not any longer. In
1566 * case we still have comments on a key, strip them here
1567 * before we call build_packet(). */
1568 if (node->pkt->pkttype == PKT_COMMENT)
1571 /* Skip ring trust packets - they should not ne here anyway. */
1572 if (node->pkt->pkttype == PKT_RING_TRUST)
1575 /* If exact is set, then we only export what was requested
1576 * (plus the primary key, if the user didn't specifically
1578 if (desc[descindex].exact && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1580 if (!exact_subkey_match_p (desc+descindex, node))
1582 /* Before skipping this subkey, check whether any
1583 * other description wants an exact match on a
1584 * subkey and include that subkey into the output
1585 * too. Need to add this subkey to a list so that
1586 * it won't get processed a second time.
1588 * So the first step here is to check that list and
1589 * skip in any case if the key is in that list.
1591 * We need this whole mess because the import
1592 * function of GnuPG < 2.1 is not able to merge
1593 * secret keys and thus it is useless to output them
1594 * as two separate keys and have import merge them.
1596 if (subkey_in_list_p (subkey_list, node))
1597 skip_until_subkey = 1; /* Already processed this one. */
1602 for (j=0; j < ndesc; j++)
1603 if (j != descindex && desc[j].exact
1604 && exact_subkey_match_p (desc+j, node))
1607 skip_until_subkey = 1; /* No other one matching. */
1611 if (skip_until_subkey)
1614 /* Mark this one as processed. */
1616 subkey_list_t tmp = new_subkey_list_item (node);
1617 tmp->next = subkey_list;
1622 if (node->pkt->pkttype == PKT_SIGNATURE)
1624 /* Do not export packets which are marked as not
1626 if (!(options & EXPORT_LOCAL_SIGS)
1627 && !node->pkt->pkt.signature->flags.exportable)
1628 continue; /* not exportable */
1630 /* Do not export packets with a "sensitive" revocation key
1631 * unless the user wants us to. Note that we do export
1632 * these when issuing the actual revocation (see revoke.c). */
1633 if (!(options & EXPORT_SENSITIVE_REVKEYS)
1634 && node->pkt->pkt.signature->revkey)
1638 for (i = 0; i < node->pkt->pkt.signature->numrevkeys; i++)
1639 if ((node->pkt->pkt.signature->revkey[i].class & 0x40))
1641 if (i < node->pkt->pkt.signature->numrevkeys)
1646 /* Don't export attribs? */
1647 if (!(options & EXPORT_ATTRIBUTES)
1648 && node->pkt->pkttype == PKT_USER_ID
1649 && node->pkt->pkt.user_id->attrib_data)
1651 /* Skip until we get to something that is not an attrib or a
1652 * signature on an attrib. */
1653 while (kbctx->next && kbctx->next->pkt->pkttype == PKT_SIGNATURE)
1654 kbctx = kbctx->next;
1659 if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1660 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1662 pk = node->pkt->pkt.public_key;
1663 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1667 keyid_from_pk (pk, subkidbuf);
1671 if (pk->seckey_info)
1673 log_error ("key %s: oops: seckey_info already set"
1674 " - skipped\n", keystr_with_sub (keyid, subkid));
1675 skip_until_subkey = 1;
1680 err = hexkeygrip_from_pk (pk, &hexgrip);
1683 log_error ("key %s: error computing keygrip: %s"
1684 " - skipped\n", keystr_with_sub (keyid, subkid),
1685 gpg_strerror (err));
1686 skip_until_subkey = 1;
1693 if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1695 /* We are asked not to export the secret parts of the
1696 * primary key. Make up an error code to create the
1698 err = GPG_ERR_NOT_FOUND;
1701 err = agent_get_keyinfo (ctrl, hexgrip, &serialno, &cleartext);
1703 if ((!err && serialno)
1704 && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1706 /* It does not make sense to export a key with its
1707 * primary key on card using a non-key stub. Thus we
1708 * skip those keys when used with --export-secret-subkeys. */
1709 log_info (_("key %s: key material on-card - skipped\n"),
1710 keystr_with_sub (keyid, subkid));
1711 skip_until_subkey = 1;
1713 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1714 || (!err && serialno))
1716 /* Create a key stub. */
1717 struct seckey_info *ski;
1720 pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1723 err = gpg_error_from_syserror ();
1727 ski->is_protected = 1;
1729 ski->s2k.mode = 1001; /* GNU dummy (no secret key). */
1732 ski->s2k.mode = 1002; /* GNU-divert-to-card. */
1733 for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1734 ski->ivlen++, s += 2)
1735 ski->iv[ski->ivlen] = xtoi_2 (s);
1738 if ((options & EXPORT_BACKUP))
1739 err = build_packet_and_meta (out, node->pkt);
1741 err = build_packet (out, node->pkt);
1742 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1745 print_status_exported (node->pkt->pkt.public_key);
1750 err = receive_seckey_from_agent (ctrl, cipherhd,
1751 cleartext, &cache_nonce,
1755 if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1757 skip_until_subkey = 1;
1762 if ((options & EXPORT_BACKUP))
1763 err = build_packet_and_meta (out, node->pkt);
1765 err = build_packet (out, node->pkt);
1766 if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1769 print_status_exported (node->pkt->pkt.public_key);
1775 log_error ("key %s: error getting keyinfo from agent: %s"
1776 " - skipped\n", keystr_with_sub (keyid, subkid),
1777 gpg_strerror (err));
1778 skip_until_subkey = 1;
1782 xfree (pk->seckey_info);
1783 pk->seckey_info = NULL;
1786 for (i = pubkey_get_npkey (pk->pubkey_algo);
1787 i < pubkey_get_nskey (pk->pubkey_algo); i++)
1789 gcry_mpi_release (pk->pkey[i]);
1794 else /* Not secret or common packets. */
1796 if ((options & EXPORT_BACKUP))
1797 err = build_packet_and_meta (out, node->pkt);
1799 err = build_packet (out, node->pkt);
1800 if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1803 print_status_exported (node->pkt->pkt.public_key);
1809 log_error ("build_packet(%d) failed: %s\n",
1810 node->pkt->pkttype, gpg_strerror (err));
1814 if (!skip_until_subkey)
1819 release_subkey_list (subkey_list);
1822 xfree (cache_nonce);
1827 /* Export the keys identified by the list of strings in USERS to the
1828 stream OUT. If SECRET is false public keys will be exported. With
1829 secret true secret keys will be exported; in this case 1 means the
1830 entire secret keyblock and 2 only the subkeys. OPTIONS are the
1831 export options to apply. If KEYBLOCK_OUT is not NULL, AND the exit
1832 code is zero, a pointer to the first keyblock found and exported
1833 will be stored at this address; no other keyblocks are exported in
1834 this case. The caller must free the returned keyblock. If any
1835 key has been exported true is stored at ANY. */
1837 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
1838 kbnode_t *keyblock_out, unsigned int options,
1839 export_stats_t stats, int *any)
1841 gpg_error_t err = 0;
1843 kbnode_t keyblock = NULL;
1845 size_t ndesc, descindex;
1846 KEYDB_SEARCH_DESC *desc = NULL;
1849 gcry_cipher_hd_t cipherhd = NULL;
1850 struct export_stats_s dummystats;
1851 iobuf_t out_help = NULL;
1854 stats = &dummystats;
1857 kdbhd = keydb_new ();
1859 return gpg_error_from_syserror ();
1861 /* For the PKA and DANE format open a helper iobuf and for DANE
1862 * enforce some options. */
1863 if ((options & (EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT)))
1865 out_help = iobuf_temp ();
1866 if ((options & EXPORT_DANE_FORMAT))
1867 options |= EXPORT_MINIMAL | EXPORT_CLEAN;
1873 desc = xcalloc (ndesc, sizeof *desc);
1874 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1878 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1880 desc = xmalloc ( ndesc * sizeof *desc);
1882 for (ndesc=0, sl=users; sl; sl = sl->next)
1884 if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
1887 log_error (_("key \"%s\" not found: %s\n"),
1888 sl->d, gpg_strerror (err));
1891 keydb_disable_caching (kdbhd); /* We are looping the search. */
1893 /* It would be nice to see which of the given users did actually
1894 match one in the keyring. To implement this we need to have
1895 a found flag for each entry in desc. To set this flag we
1896 must check all those entries after a match to mark all
1897 matched one - currently we stop at the first match. To do
1898 this we need an extra flag to enable this feature. */
1901 #ifdef ENABLE_SELINUX_HACKS
1904 log_error (_("exporting secret keys not allowed\n"));
1905 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1910 /* For secret key export we need to setup a decryption context. */
1916 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
1919 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1923 /* Prepare a cipher context. */
1924 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1925 GCRY_CIPHER_MODE_AESWRAP, 0);
1927 err = gcry_cipher_setkey (cipherhd, kek, keklen);
1930 log_error ("error setting up an encryption context: %s\n",
1931 gpg_strerror (err));
1943 err = keydb_search (kdbhd, desc, ndesc, &descindex);
1945 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1949 /* Read the keyblock. */
1950 release_kbnode (keyblock);
1952 err = keydb_get_keyblock (kdbhd, &keyblock);
1955 log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1959 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1962 log_error ("public key packet not found in keyblock - skipped\n");
1966 setup_main_keyids (keyblock); /* gpg_format_keydesc needs it. */
1967 pk = node->pkt->pkt.public_key;
1968 keyid_from_pk (pk, keyid);
1970 /* If a secret key export is required we need to check whether
1971 we have a secret key at all and if so create the seckey_info
1975 if (agent_probe_any_secret_key (ctrl, keyblock))
1976 continue; /* No secret key (neither primary nor subkey). */
1978 /* No v3 keys with GNU mode 1001. */
1979 if (secret == 2 && pk->version == 3)
1981 log_info (_("key %s: PGP 2.x style key - skipped\n"),
1986 /* The agent does not yet allow export of v3 packets. It is
1987 actually questionable whether we should allow them at
1989 if (pk->version == 3)
1991 log_info ("key %s: PGP 2.x style key (v3) export "
1992 "not yet supported - skipped\n", keystr (keyid));
1995 stats->secret_count++;
1998 /* Always do the cleaning on the public key part if requested.
1999 * Note that both export-clean and export-minimal only apply to
2000 * UID sigs (0x10, 0x11, 0x12, and 0x13). A designated
2001 * revocation is never stripped, even with export-minimal set. */
2002 if ((options & EXPORT_CLEAN))
2003 clean_key (ctrl, keyblock, opt.verbose,
2004 (options&EXPORT_MINIMAL), NULL, NULL);
2006 if (export_keep_uid)
2008 commit_kbnode (&keyblock);
2009 apply_keep_uid_filter (ctrl, keyblock, export_keep_uid);
2010 commit_kbnode (&keyblock);
2013 if (export_drop_subkey)
2015 commit_kbnode (&keyblock);
2016 apply_drop_subkey_filter (ctrl, keyblock, export_drop_subkey);
2017 commit_kbnode (&keyblock);
2021 err = do_export_one_keyblock (ctrl, keyblock, keyid,
2022 out_help? out_help : out,
2023 secret, options, stats, any,
2024 desc, ndesc, descindex, cipherhd);
2030 *keyblock_out = keyblock;
2036 /* We want to write PKA or DANE records. OUT_HELP has the
2037 * keyblock and we print a record for each uid to OUT. */
2041 iobuf_flush_temp (out_help);
2042 data = iobuf_get_temp_buffer (out_help);
2043 datalen = iobuf_get_temp_length (out_help);
2045 err = print_pka_or_dane_records (out,
2046 keyblock, pk, data, datalen,
2047 (options & EXPORT_PKA_FORMAT),
2048 (options & EXPORT_DANE_FORMAT));
2052 iobuf_close (out_help);
2053 out_help = iobuf_temp ();
2057 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2061 iobuf_cancel (out_help);
2062 gcry_cipher_close (cipherhd);
2064 keydb_release (kdbhd);
2065 if (err || !keyblock_out)
2066 release_kbnode( keyblock );
2068 log_info(_("WARNING: nothing exported\n"));
2076 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
2079 gpg_error_t err = 0;
2080 unsigned char nbuf[4];
2085 ulongtobuf (nbuf, (ulong)strlen (identifier));
2086 put_membuf (mb, nbuf, 4);
2087 put_membuf_str (mb, identifier);
2088 if (!strncmp (identifier, "ecdsa-sha2-", 11))
2090 ulongtobuf (nbuf, (ulong)strlen (identifier+11));
2091 put_membuf (mb, nbuf, 4);
2092 put_membuf_str (mb, identifier+11);
2094 va_start (arg_ptr, identifier);
2095 while ((a = va_arg (arg_ptr, gcry_mpi_t)))
2097 err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
2100 if (!strcmp (identifier, "ssh-ed25519")
2101 && buflen > 5 && buf[4] == 0x40)
2103 /* We need to strip our 0x40 prefix. */
2104 put_membuf (mb, "\x00\x00\x00\x20", 4);
2105 put_membuf (mb, buf+5, buflen-5);
2108 put_membuf (mb, buf, buflen);
2115 /* Export the key identified by USERID in the SSH public key format.
2116 The function exports the latest subkey with Authentication
2117 capability unless the '!' suffix is used to export a specific
2120 export_ssh_key (ctrl_t ctrl, const char *userid)
2123 kbnode_t keyblock = NULL;
2124 KEYDB_SEARCH_DESC desc;
2126 u32 curtime = make_timestamp ();
2127 kbnode_t latest_key, node;
2129 const char *identifier = NULL;
2131 estream_t fp = NULL;
2132 struct b64state b64_state;
2133 const char *fname = "-";
2135 init_membuf (&mb, 4096);
2137 /* We need to know whether the key has been specified using the
2138 exact syntax ('!' suffix). Thus we need to run a
2139 classify_user_id on our own. */
2140 err = classify_user_id (userid, &desc, 1);
2142 /* Get the public key. */
2145 getkey_ctx_t getkeyctx;
2147 err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
2149 0 /* Only usable keys or given exact. */,
2150 1 /* No AKL lookup. */);
2153 err = getkey_next (ctrl, getkeyctx, NULL, NULL);
2155 err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2156 else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
2159 getkey_end (ctrl, getkeyctx);
2163 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2167 /* The finish_lookup code in getkey.c does not handle auth keys,
2168 thus we have to duplicate the code here to find the latest
2169 subkey. However, if the key has been found using an exact match
2170 ('!' notation) we use that key without any further checks and
2171 even allow the use of the primary key. */
2174 for (node = keyblock; node; node = node->next)
2176 if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2177 || node->pkt->pkttype == PKT_PUBLIC_KEY)
2178 && node->pkt->pkt.public_key->flags.exact)
2186 for (node = keyblock; node; node = node->next)
2188 if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2191 pk = node->pkt->pkt.public_key;
2193 log_debug ("\tchecking subkey %08lX\n",
2194 (ulong) keyid_from_pk (pk, NULL));
2195 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2198 log_debug ("\tsubkey not usable for authentication\n");
2201 if (!pk->flags.valid)
2204 log_debug ("\tsubkey not valid\n");
2207 if (pk->flags.revoked)
2210 log_debug ("\tsubkey has been revoked\n");
2213 if (pk->has_expired)
2216 log_debug ("\tsubkey has expired\n");
2219 if (pk->timestamp > curtime && !opt.ignore_valid_from)
2222 log_debug ("\tsubkey not yet valid\n");
2226 log_debug ("\tsubkey might be fine\n");
2227 /* In case a key has a timestamp of 0 set, we make sure that it
2228 is used. A better change would be to compare ">=" but that
2229 might also change the selected keys and is as such a more
2230 intrusive change. */
2231 if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2233 latest_date = pk->timestamp;
2238 /* If no subkey was suitable check the primary key. */
2240 && (node = keyblock) && node->pkt->pkttype == PKT_PUBLIC_KEY)
2242 pk = node->pkt->pkt.public_key;
2244 log_debug ("\tchecking primary key %08lX\n",
2245 (ulong) keyid_from_pk (pk, NULL));
2246 if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2249 log_debug ("\tprimary key not usable for authentication\n");
2251 else if (!pk->flags.valid)
2254 log_debug ("\tprimary key not valid\n");
2256 else if (pk->flags.revoked)
2259 log_debug ("\tprimary key has been revoked\n");
2261 else if (pk->has_expired)
2264 log_debug ("\tprimary key has expired\n");
2266 else if (pk->timestamp > curtime && !opt.ignore_valid_from)
2269 log_debug ("\tprimary key not yet valid\n");
2274 log_debug ("\tprimary key is fine\n");
2275 latest_date = pk->timestamp;
2283 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2284 log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2288 pk = latest_key->pkt->pkt.public_key;
2290 log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
2292 switch (pk->pubkey_algo)
2294 case PUBKEY_ALGO_DSA:
2295 identifier = "ssh-dss";
2296 err = key_to_sshblob (&mb, identifier,
2297 pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
2301 case PUBKEY_ALGO_RSA:
2302 case PUBKEY_ALGO_RSA_S:
2303 identifier = "ssh-rsa";
2304 err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
2307 case PUBKEY_ALGO_ECDSA:
2312 curveoid = openpgp_oid_to_str (pk->pkey[0]);
2314 err = gpg_error_from_syserror ();
2315 else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
2316 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2319 if (!strcmp (curve, "nistp256"))
2320 identifier = "ecdsa-sha2-nistp256";
2321 else if (!strcmp (curve, "nistp384"))
2322 identifier = "ecdsa-sha2-nistp384";
2323 else if (!strcmp (curve, "nistp521"))
2324 identifier = "ecdsa-sha2-nistp521";
2327 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2329 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2335 case PUBKEY_ALGO_EDDSA:
2336 if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
2337 err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2340 identifier = "ssh-ed25519";
2341 err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2345 case PUBKEY_ALGO_ELGAMAL_E:
2346 case PUBKEY_ALGO_ELGAMAL:
2347 err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2351 err = GPG_ERR_PUBKEY_ALGO;
2358 if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
2359 fp = es_fopen ((fname = opt.outfile), "w");
2364 err = gpg_error_from_syserror ();
2365 log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
2369 es_fprintf (fp, "%s ", identifier);
2370 err = b64enc_start_es (&b64_state, fp, "");
2376 blob = get_membuf (&mb, &bloblen);
2379 err = b64enc_write (&b64_state, blob, bloblen);
2384 err = b64enc_finish (&b64_state);
2388 es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
2391 err = gpg_error_from_syserror ();
2395 err = gpg_error_from_syserror ();
2400 log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
2404 xfree (get_membuf (&mb, NULL));
2405 release_kbnode (keyblock);