chiark / gitweb /
gpg: Handle critical marked 'Reason for Revocation'.
[gnupg2.git] / g10 / export.c
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
5  *
6  * This file is part of GnuPG.
7  *
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.
12  *
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.
17  *
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/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "keydb.h"
33 #include "util.h"
34 #include "main.h"
35 #include "i18n.h"
36 #include "membuf.h"
37 #include "host2net.h"
38 #include "zb32.h"
39 #include "recsel.h"
40 #include "mbox-util.h"
41 #include "init.h"
42 #include "trustdb.h"
43 #include "call-agent.h"
44
45 /* An object to keep track of subkeys. */
46 struct subkey_list_s
47 {
48   struct subkey_list_s *next;
49   u32 kid[2];
50 };
51 typedef struct subkey_list_s *subkey_list_t;
52
53
54 /* An object to track statistics for export operations.  */
55 struct export_stats_s
56 {
57   ulong count;            /* Number of processed keys.        */
58   ulong secret_count;     /* Number of secret keys seen.      */
59   ulong exported;         /* Number of actual exported keys.  */
60 };
61
62
63 /* A global variable to store the selector created from
64  * --export-filter keep-uid=EXPR.
65  * --export-filter drop-subkey=EXPR.
66  *
67  * FIXME: We should put this into the CTRL object but that requires a
68  * lot more changes right now.
69  */
70 static recsel_expr_t export_keep_uid;
71 static recsel_expr_t export_drop_subkey;
72
73
74
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);
86
87 \f
88 static void
89 cleanup_export_globals (void)
90 {
91   recsel_release (export_keep_uid);
92   export_keep_uid = NULL;
93   recsel_release (export_drop_subkey);
94   export_drop_subkey = NULL;
95 }
96
97
98 /* Option parser for export options.  See parse_options fro
99    details.  */
100 int
101 parse_export_options(char *str,unsigned int *options,int noisy)
102 {
103   struct parse_options export_opts[]=
104     {
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")},
115
116       {"export-pka", EXPORT_PKA_FORMAT, NULL, NULL },
117       {"export-dane", EXPORT_DANE_FORMAT, NULL, NULL },
118
119       {"backup", EXPORT_BACKUP, NULL,
120        N_("use the GnuPG key backup format")},
121       {"export-backup", EXPORT_BACKUP, NULL, NULL },
122
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},
127       /* dummy */
128       {"export-unusable-sigs",0,NULL,NULL},
129       {"export-clean-sigs",0,NULL,NULL},
130       {"export-clean-uids",0,NULL,NULL},
131       {NULL,0,NULL,NULL}
132       /* add tags for include revoked and disabled? */
133     };
134   int rc;
135
136   rc = parse_options (str, options, export_opts, noisy);
137   if (rc && (*options & EXPORT_BACKUP))
138     {
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);
144     }
145   return rc;
146 }
147
148
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:
154  *
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
158  *                variables:
159  *
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.
163  *
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
167  *                variables:
168  *
169  *                - secret   :: 1 for a secret subkey, else 0.
170  *                - key_algo :: Public key algorithm id
171  */
172 gpg_error_t
173 parse_and_set_export_filter (const char *string)
174 {
175   gpg_error_t err;
176
177   /* Auto register the cleanup function.  */
178   register_mem_cleanup_func (cleanup_export_globals);
179
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);
184   else
185     err = gpg_error (GPG_ERR_INV_NAME);
186
187   return err;
188 }
189
190
191 /* Create a new export stats object initialized to zero.  On error
192    returns NULL and sets ERRNO.  */
193 export_stats_t
194 export_new_stats (void)
195 {
196   export_stats_t stats;
197
198   return xtrycalloc (1, sizeof *stats);
199 }
200
201
202 /* Release an export stats object.  */
203 void
204 export_release_stats (export_stats_t stats)
205 {
206   xfree (stats);
207 }
208
209
210 /* Print export statistics using the status interface.  */
211 void
212 export_print_stats (export_stats_t stats)
213 {
214   if (!stats)
215     return;
216
217   if (is_status_enabled ())
218     {
219       char buf[15*20];
220
221       snprintf (buf, sizeof buf, "%lu %lu %lu",
222                 stats->count,
223                 stats->secret_count,
224                 stats->exported );
225       write_status_text (STATUS_EXPORT_RES, buf);
226     }
227 }
228
229
230 /*
231  * Export public keys (to stdout or to --output FILE).
232  *
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.
236  *
237  * This function is the core of "gpg --export".
238  */
239 int
240 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
241                 export_stats_t stats)
242 {
243   return do_export (ctrl, users, 0, options, stats);
244 }
245
246
247 /*
248  * Export secret keys (to stdout or to --output FILE).
249  *
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.
253  *
254  * This function is the core of "gpg --export-secret-keys".
255  */
256 int
257 export_seckeys (ctrl_t ctrl, strlist_t users, unsigned int options,
258                 export_stats_t stats)
259 {
260   return do_export (ctrl, users, 1, options, stats);
261 }
262
263
264 /*
265  * Export secret sub keys (to stdout or to --output FILE).
266  *
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
271  * NULL.
272  *
273  * This function is the core of "gpg --export-secret-subkeys".
274  */
275 int
276 export_secsubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
277                    export_stats_t stats)
278 {
279   return do_export (ctrl, users, 2, options, stats);
280 }
281
282
283 /*
284  * Export a single key into a memory buffer.  STATS is either an
285  * export stats object for update or NULL.
286  */
287 gpg_error_t
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)
291 {
292   gpg_error_t err;
293   iobuf_t iobuf;
294   int any;
295   strlist_t helplist;
296
297   *r_keyblock = NULL;
298   *r_data = NULL;
299   *r_datalen = 0;
300
301   helplist = NULL;
302   if (!add_to_strlist_try (&helplist, keyspec))
303     return gpg_error_from_syserror ();
304
305   iobuf = iobuf_temp ();
306   err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
307                           stats, &any);
308   if (!err && !any)
309     err = gpg_error (GPG_ERR_NOT_FOUND);
310   if (!err)
311     {
312       const void *src;
313       size_t datalen;
314
315       iobuf_flush_temp (iobuf);
316       src = iobuf_get_temp_buffer (iobuf);
317       datalen = iobuf_get_temp_length (iobuf);
318       if (!datalen)
319         err = gpg_error (GPG_ERR_NO_PUBKEY);
320       else if (!(*r_data = xtrymalloc (datalen)))
321         err = gpg_error_from_syserror ();
322       else
323         {
324           memcpy (*r_data, src, datalen);
325           *r_datalen = datalen;
326         }
327     }
328   iobuf_close (iobuf);
329   free_strlist (helplist);
330   if (err && *r_keyblock)
331     {
332       release_kbnode (*r_keyblock);
333       *r_keyblock = NULL;
334     }
335   return err;
336 }
337
338
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
343    options to apply.  */
344 static int
345 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
346            export_stats_t stats)
347 {
348   IOBUF out = NULL;
349   int any, rc;
350   armor_filter_context_t *afx = NULL;
351   compress_filter_context_t zfx;
352
353   memset( &zfx, 0, sizeof zfx);
354
355   rc = open_outfile (-1, NULL, 0, !!secret, &out );
356   if (rc)
357     return rc;
358
359   if ( opt.armor && !(options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)) )
360     {
361       afx = new_armor_context ();
362       afx->what = secret? 5 : 1;
363       push_armor_filter (afx, out);
364     }
365
366   rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
367
368   if ( rc || !any )
369     iobuf_cancel (out);
370   else
371     iobuf_close (out);
372   release_armor_context (afx);
373   return rc;
374 }
375
376
377
378 /* Release an entire subkey list. */
379 static void
380 release_subkey_list (subkey_list_t list)
381 {
382   while (list)
383     {
384       subkey_list_t tmp = list->next;;
385       xfree (list);
386       list = tmp;
387     }
388 }
389
390
391 /* Returns true if NODE is a subkey and contained in LIST. */
392 static int
393 subkey_in_list_p (subkey_list_t list, KBNODE node)
394 {
395   if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
396       || node->pkt->pkttype == PKT_SECRET_SUBKEY )
397     {
398       u32 kid[2];
399
400       keyid_from_pk (node->pkt->pkt.public_key, kid);
401
402       for (; list; list = list->next)
403         if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
404           return 1;
405     }
406   return 0;
407 }
408
409 /* Allocate a new subkey list item from NODE. */
410 static subkey_list_t
411 new_subkey_list_item (KBNODE node)
412 {
413   subkey_list_t list = xcalloc (1, sizeof *list);
414
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);
418
419   return list;
420 }
421
422
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
428    subkey. */
429 static int
430 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
431 {
432   u32 kid[2];
433   byte fpr[MAX_FINGERPRINT_LEN];
434   size_t fprlen;
435   int result = 0;
436
437   switch(desc->mode)
438     {
439     case KEYDB_SEARCH_MODE_SHORT_KID:
440     case KEYDB_SEARCH_MODE_LONG_KID:
441       keyid_from_pk (node->pkt->pkt.public_key, kid);
442       break;
443
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);
448       break;
449
450     default:
451       break;
452     }
453
454   switch(desc->mode)
455     {
456     case KEYDB_SEARCH_MODE_SHORT_KID:
457       if (desc->u.kid[1] == kid[1])
458         result = 1;
459       break;
460
461     case KEYDB_SEARCH_MODE_LONG_KID:
462       if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
463         result = 1;
464       break;
465
466     case KEYDB_SEARCH_MODE_FPR16:
467       if (!memcmp (desc->u.fpr, fpr, 16))
468         result = 1;
469       break;
470
471     case KEYDB_SEARCH_MODE_FPR20:
472     case KEYDB_SEARCH_MODE_FPR:
473       if (!memcmp (desc->u.fpr, fpr, 20))
474         result = 1;
475       break;
476
477     default:
478       break;
479     }
480
481   return result;
482 }
483
484
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. */
487 static gpg_error_t
488 match_curve_skey_pk (gcry_sexp_t s_key, PKT_public_key *pk)
489 {
490   gcry_sexp_t curve = NULL;
491   gcry_sexp_t flags = NULL;
492   char *curve_str = NULL;
493   char *flag;
494   const char *oidstr = NULL;
495   gcry_mpi_t curve_as_mpi = NULL;
496   gpg_error_t err;
497   int is_eddsa = 0;
498   int idx = 0;
499
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);
504
505   curve = gcry_sexp_find_token (s_key, "curve", 0);
506   if (!curve)
507     {
508       log_error ("no reported curve\n");
509       return gpg_error (GPG_ERR_UNKNOWN_CURVE);
510     }
511   curve_str = gcry_sexp_nth_string (curve, 1);
512   gcry_sexp_release (curve); curve = NULL;
513   if (!curve_str)
514     {
515       log_error ("no curve name\n");
516       return gpg_error (GPG_ERR_UNKNOWN_CURVE);
517     }
518   oidstr = openpgp_curve_to_oid (curve_str, NULL);
519   if (!oidstr)
520     {
521       log_error ("no OID known for curve '%s'\n", curve_str);
522       xfree (curve_str);
523       return gpg_error (GPG_ERR_UNKNOWN_CURVE);
524     }
525   xfree (curve_str);
526   err = openpgp_oid_from_str (oidstr, &curve_as_mpi);
527   if (err)
528     return err;
529   if (gcry_mpi_cmp (pk->pkey[0], curve_as_mpi))
530     {
531       log_error ("curves do not match\n");
532       gcry_mpi_release (curve_as_mpi);
533       return gpg_error (GPG_ERR_INV_CURVE);
534     }
535   gcry_mpi_release (curve_as_mpi);
536   flags = gcry_sexp_find_token (s_key, "flags", 0);
537   if (flags)
538     {
539       for (idx = 1; idx < gcry_sexp_length (flags); idx++)
540         {
541           flag = gcry_sexp_nth_string (flags, idx);
542           if (flag && (strcmp ("eddsa", flag) == 0))
543             is_eddsa = 1;
544           gcry_free (flag);
545         }
546     }
547   if (is_eddsa != (pk->pubkey_algo == PUBKEY_ALGO_EDDSA))
548     {
549       log_error ("disagreement about EdDSA\n");
550       err = gpg_error (GPG_ERR_INV_CURVE);
551     }
552
553   return err;
554 }
555
556
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)
562 {
563   switch (algo)
564     {
565     case GCRY_PK_RSA:
566     case GCRY_PK_RSA_E:
567     case GCRY_PK_RSA_S: return GCRY_PK_RSA;
568     case GCRY_PK_ELG:
569     case GCRY_PK_ELG_E: return GCRY_PK_ELG;
570     case GCRY_PK_ECC:
571     case GCRY_PK_ECDSA:
572     case GCRY_PK_ECDH: return GCRY_PK_ECC;
573     default: return algo;
574     }
575 }
576
577
578 /* Take a cleartext dump of a secret key in PK and change the
579  * parameter array in PK to include the secret parameters.  */
580 static gpg_error_t
581 cleartext_secret_key_to_openpgp (gcry_sexp_t s_key, PKT_public_key *pk)
582 {
583   gpg_error_t err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
584   gcry_sexp_t top_list;
585   gcry_sexp_t key = NULL;
586   char *key_type = NULL;
587   enum gcry_pk_algos pk_algo;
588   struct seckey_info *ski;
589   int idx, sec_start;
590   gcry_mpi_t pub_params[10] = { NULL };
591
592   /* we look for a private-key, then the first element in it tells us
593      the type */
594   top_list = gcry_sexp_find_token (s_key, "private-key", 0);
595   if (!top_list)
596     goto bad_seckey;
597   if (gcry_sexp_length(top_list) != 2)
598     goto bad_seckey;
599   key = gcry_sexp_nth (top_list, 1);
600   if (!key)
601     goto bad_seckey;
602   key_type = gcry_sexp_nth_string(key, 0);
603   pk_algo = gcry_pk_map_name (key_type);
604
605   log_assert (!pk->seckey_info);
606
607   pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
608   if (!ski)
609     {
610       err = gpg_error_from_syserror ();
611       goto leave;
612     }
613
614   switch (canon_pk_algo (pk_algo))
615     {
616     case GCRY_PK_RSA:
617       if (!is_RSA (pk->pubkey_algo))
618         goto bad_pubkey_algo;
619       err = gcry_sexp_extract_param (key, NULL, "ne",
620                                      &pub_params[0],
621                                      &pub_params[1],
622                                      NULL);
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);
626       if (!err)
627         {
628           for (idx = 2; idx < 6 && !err; idx++)
629             {
630               gcry_mpi_release (pk->pkey[idx]);
631               pk->pkey[idx] = NULL;
632             }
633           err = gcry_sexp_extract_param (key, NULL, "dpqu",
634                                          &pk->pkey[2],
635                                          &pk->pkey[3],
636                                          &pk->pkey[4],
637                                          &pk->pkey[5],
638                                          NULL);
639         }
640       if (!err)
641         {
642           for (idx = 2; idx < 6; idx++)
643             ski->csum += checksum_mpi (pk->pkey[idx]);
644         }
645       break;
646
647     case GCRY_PK_DSA:
648       if (!is_DSA (pk->pubkey_algo))
649         goto bad_pubkey_algo;
650       err = gcry_sexp_extract_param (key, NULL, "pqgy",
651                                      &pub_params[0],
652                                      &pub_params[1],
653                                      &pub_params[2],
654                                      &pub_params[3],
655                                      NULL);
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);
659       if (!err)
660         {
661           gcry_mpi_release (pk->pkey[4]);
662           pk->pkey[4] = NULL;
663           err = gcry_sexp_extract_param (key, NULL, "x",
664                                          &pk->pkey[4],
665                                          NULL);
666         }
667       if (!err)
668         ski->csum += checksum_mpi (pk->pkey[4]);
669       break;
670
671     case GCRY_PK_ELG:
672       if (!is_ELGAMAL (pk->pubkey_algo))
673         goto bad_pubkey_algo;
674       err = gcry_sexp_extract_param (key, NULL, "pgy",
675                                      &pub_params[0],
676                                      &pub_params[1],
677                                      &pub_params[2],
678                                      NULL);
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);
682       if (!err)
683         {
684           gcry_mpi_release (pk->pkey[3]);
685           pk->pkey[3] = NULL;
686           err = gcry_sexp_extract_param (key, NULL, "x",
687                                          &pk->pkey[3],
688                                          NULL);
689         }
690       if (!err)
691         ski->csum += checksum_mpi (pk->pkey[3]);
692       break;
693
694     case GCRY_PK_ECC:
695       err = match_curve_skey_pk (key, pk);
696       if (err)
697         goto leave;
698       if (!err)
699         err = gcry_sexp_extract_param (key, NULL, "q",
700                                        &pub_params[0],
701                                        NULL);
702       if (!err && (gcry_mpi_cmp(pk->pkey[1], pub_params[0])))
703         err = gpg_error (GPG_ERR_BAD_PUBKEY);
704
705       sec_start = 2;
706       if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
707         sec_start += 1;
708       if (!err)
709         {
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],
714                                          NULL);
715         }
716
717       if (!err)
718         ski->csum += checksum_mpi (pk->pkey[sec_start]);
719       break;
720
721     default:
722       pk->seckey_info = NULL;
723       xfree (ski);
724       err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
725       break;
726     }
727
728  leave:
729   gcry_sexp_release (top_list);
730   gcry_sexp_release (key);
731   gcry_free (key_type);
732
733   for (idx=0; idx < DIM(pub_params); idx++)
734     gcry_mpi_release (pub_params[idx]);
735   return err;
736
737  bad_pubkey_algo:
738   err = gpg_error (GPG_ERR_PUBKEY_ALGO);
739   goto leave;
740
741  bad_seckey:
742   err = gpg_error (GPG_ERR_BAD_SECKEY);
743   goto leave;
744 }
745
746
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.  */
750 static gpg_error_t
751 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
752 {
753   gpg_error_t err;
754   gcry_sexp_t top_list;
755   gcry_sexp_t list = NULL;
756   char *curve = NULL;
757   const char *value;
758   size_t valuelen;
759   char *string;
760   int  idx;
761   int  is_v4, is_protected;
762   enum gcry_pk_algos pk_algo;
763   int  protect_algo = 0;
764   char iv[16];
765   int  ivlen = 0;
766   int  s2k_mode = 0;
767   int  s2k_algo = 0;
768   byte s2k_salt[8];
769   u32  s2k_count = 0;
770   int  is_ecdh = 0;
771   size_t npkey, nskey;
772   gcry_mpi_t skey[10];  /* We support up to 9 parameters.  */
773   int skeyidx = 0;
774   struct seckey_info *ski;
775
776   /* gcry_log_debugsxp ("transferkey", s_pgp); */
777   top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
778   if (!top_list)
779     goto bad_seckey;
780
781   list = gcry_sexp_find_token (top_list, "version", 0);
782   if (!list)
783     goto bad_seckey;
784   value = gcry_sexp_nth_data (list, 1, &valuelen);
785   if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
786     goto bad_seckey;
787   is_v4 = (value[0] == '4');
788
789   gcry_sexp_release (list);
790   list = gcry_sexp_find_token (top_list, "protection", 0);
791   if (!list)
792     goto bad_seckey;
793   value = gcry_sexp_nth_data (list, 1, &valuelen);
794   if (!value)
795     goto bad_seckey;
796   if (valuelen == 4 && !memcmp (value, "sha1", 4))
797     is_protected = 2;
798   else if (valuelen == 3 && !memcmp (value, "sum", 3))
799     is_protected = 1;
800   else if (valuelen == 4 && !memcmp (value, "none", 4))
801     is_protected = 0;
802   else
803     goto bad_seckey;
804   if (is_protected)
805     {
806       string = gcry_sexp_nth_string (list, 2);
807       if (!string)
808         goto bad_seckey;
809       protect_algo = gcry_cipher_map_name (string);
810       xfree (string);
811
812       value = gcry_sexp_nth_data (list, 3, &valuelen);
813       if (!value || !valuelen || valuelen > sizeof iv)
814         goto bad_seckey;
815       memcpy (iv, value, valuelen);
816       ivlen = valuelen;
817
818       string = gcry_sexp_nth_string (list, 4);
819       if (!string)
820         goto bad_seckey;
821       s2k_mode = strtol (string, NULL, 10);
822       xfree (string);
823
824       string = gcry_sexp_nth_string (list, 5);
825       if (!string)
826         goto bad_seckey;
827       s2k_algo = gcry_md_map_name (string);
828       xfree (string);
829
830       value = gcry_sexp_nth_data (list, 6, &valuelen);
831       if (!value || !valuelen || valuelen > sizeof s2k_salt)
832         goto bad_seckey;
833       memcpy (s2k_salt, value, valuelen);
834
835       string = gcry_sexp_nth_string (list, 7);
836       if (!string)
837         goto bad_seckey;
838       s2k_count = strtoul (string, NULL, 10);
839       xfree (string);
840     }
841
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);
845   if (!list)
846     goto bad_seckey;
847   string = gcry_sexp_nth_string (list, 1);
848   if (!string)
849     goto bad_seckey;
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)
855     goto bad_seckey;
856
857   /* Check that the pubkey algo matches the one from the public key.  */
858   switch (canon_pk_algo (pk_algo))
859     {
860     case GCRY_PK_RSA:
861       if (!is_RSA (pk->pubkey_algo))
862         pk_algo = 0;  /* Does not match.  */
863       break;
864     case GCRY_PK_DSA:
865       if (!is_DSA (pk->pubkey_algo))
866         pk_algo = 0;  /* Does not match.  */
867       break;
868     case GCRY_PK_ELG:
869       if (!is_ELGAMAL (pk->pubkey_algo))
870         pk_algo = 0;  /* Does not match.  */
871       break;
872     case GCRY_PK_ECC:
873       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
874         ;
875       else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
876         is_ecdh = 1;
877       else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
878         ;
879       else
880         pk_algo = 0;  /* Does not match.  */
881       /* For ECC we do not have the domain parameters thus fix our info.  */
882       npkey = 1;
883       nskey = 2;
884       break;
885     default:
886       pk_algo = 0;   /* Oops.  */
887       break;
888     }
889   if (!pk_algo)
890     {
891       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
892       goto leave;
893     }
894
895   /* This check has to go after the ecc adjustments. */
896   if (nskey > PUBKEY_MAX_NSKEY)
897     goto bad_seckey;
898
899   /* Parse the key parameters.  */
900   gcry_sexp_release (list);
901   list = gcry_sexp_find_token (top_list, "skey", 0);
902   if (!list)
903     goto bad_seckey;
904   for (idx=0;;)
905     {
906       int is_enc;
907
908       value = gcry_sexp_nth_data (list, ++idx, &valuelen);
909       if (!value && skeyidx >= npkey)
910         break;  /* Ready.  */
911
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.  */
915       if (idx >= 2*nskey)
916         goto bad_seckey;
917       if (skeyidx >= DIM (skey)-1)
918         goto bad_seckey;
919
920       if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
921         goto bad_seckey;
922       is_enc = (value[0] == 'e');
923       value = gcry_sexp_nth_data (list, ++idx, &valuelen);
924       if (!value || !valuelen)
925         goto bad_seckey;
926       if (is_enc)
927         {
928           void *p = xtrymalloc (valuelen);
929           if (!p)
930             goto outofmem;
931           memcpy (p, value, valuelen);
932           skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
933           if (!skey[skeyidx])
934             goto outofmem;
935         }
936       else
937         {
938           if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
939                              value, valuelen, NULL))
940             goto bad_seckey;
941         }
942       skeyidx++;
943     }
944   skey[skeyidx++] = NULL;
945
946   gcry_sexp_release (list); list = NULL;
947
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); */
950   /* if (list) */
951   /*   { */
952   /*     string = gcry_sexp_nth_string (list, 1); */
953   /*     if (!string) */
954   /*       goto bad_seckey; */
955   /*     desired_csum = strtoul (string, NULL, 10); */
956   /*     xfree (string); */
957   /*   } */
958   /* else */
959   /*   desired_csum = 0; */
960   /* gcry_sexp_release (list); list = NULL; */
961
962   /* Get the curve name if any,  */
963   list = gcry_sexp_find_token (top_list, "curve", 0);
964   if (list)
965     {
966       curve = gcry_sexp_nth_string (list, 1);
967       gcry_sexp_release (list); list = NULL;
968     }
969
970   gcry_sexp_release (top_list); top_list = NULL;
971
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++) */
983   /*   { */
984   /*     int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
985   /*     log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
986   /*     if (is_enc) */
987   /*       { */
988   /*         void *p; */
989   /*         unsigned int nbits; */
990   /*         p = gcry_mpi_get_opaque (skey[idx], &nbits); */
991   /*         log_printhex (NULL, p, (nbits+7)/8); */
992   /*       } */
993   /*     else */
994   /*       gcry_mpi_dump (skey[idx]); */
995   /*     log_printf ("\n"); */
996   /*   } */
997
998   if (!is_v4 || is_protected != 2 )
999     {
1000       /* We only support the v4 format and a SHA-1 checksum.  */
1001       err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
1002       goto leave;
1003     }
1004
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)
1009     {
1010       const char *oidstr;
1011
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])
1016         {
1017           err = gpg_error (GPG_ERR_INTERNAL);
1018           goto leave;
1019         }
1020
1021       oidstr = openpgp_curve_to_oid (curve, NULL);
1022       if (!oidstr)
1023         {
1024           log_error ("no OID known for curve '%s'\n", curve);
1025           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1026           goto leave;
1027         }
1028       /* Put the curve's OID into into the MPI array.  This requires
1029          that we shift Q and D.  For ECDH also insert the KDF parms. */
1030       if (is_ecdh)
1031         {
1032           skey[4] = NULL;
1033           skey[3] = skey[1];
1034           skey[2] = gcry_mpi_copy (pk->pkey[2]);
1035         }
1036       else
1037         {
1038           skey[3] = NULL;
1039           skey[2] = skey[1];
1040         }
1041       skey[1] = skey[0];
1042       skey[0] = NULL;
1043       err = openpgp_oid_from_str (oidstr, skey + 0);
1044       if (err)
1045         goto leave;
1046       /* Fixup the NPKEY and NSKEY to match OpenPGP reality.  */
1047       npkey = 2 + is_ecdh;
1048       nskey = 3 + is_ecdh;
1049
1050       /* for (idx=0; skey[idx]; idx++) */
1051       /*   { */
1052       /*     log_info ("YYY skey[%d]:", idx); */
1053       /*     if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
1054       /*       { */
1055       /*         void *p; */
1056       /*         unsigned int nbits; */
1057       /*         p = gcry_mpi_get_opaque (skey[idx], &nbits); */
1058       /*         log_printhex (NULL, p, (nbits+7)/8); */
1059       /*       } */
1060       /*     else */
1061       /*       gcry_mpi_dump (skey[idx]); */
1062       /*     log_printf ("\n"); */
1063       /*   } */
1064     }
1065
1066   /* Do some sanity checks.  */
1067   if (s2k_count > 255)
1068     {
1069       /* We expect an already encoded S2K count.  */
1070       err = gpg_error (GPG_ERR_INV_DATA);
1071       goto leave;
1072     }
1073   err = openpgp_cipher_test_algo (protect_algo);
1074   if (err)
1075     goto leave;
1076   err = openpgp_md_test_algo (s2k_algo);
1077   if (err)
1078     goto leave;
1079
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]))
1084       {
1085         err = gpg_error (GPG_ERR_BAD_PUBKEY);
1086         goto leave;
1087       }
1088
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))
1093     goto bad_seckey;
1094   if (npkey+1 < DIM (skey) && skey[npkey+1])
1095     goto bad_seckey;
1096
1097   /* Check that the secret key parameters in PK are all set to NULL. */
1098   for (idx=npkey; idx < nskey; idx++)
1099     if (pk->pkey[idx])
1100       goto bad_seckey;
1101
1102   /* Now build the protection info. */
1103   pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1104   if (!ski)
1105     {
1106       err = gpg_error_from_syserror ();
1107       goto leave;
1108     }
1109
1110   ski->is_protected = 1;
1111   ski->sha1chk = 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);
1120   ski->ivlen = ivlen;
1121
1122   /* Store the protected secret key parameter.  */
1123   pk->pkey[npkey] = skey[npkey];
1124   skey[npkey] = NULL;
1125
1126   /* That's it.  */
1127
1128  leave:
1129   gcry_free (curve);
1130   gcry_sexp_release (list);
1131   gcry_sexp_release (top_list);
1132   for (idx=0; idx < skeyidx; idx++)
1133     gcry_mpi_release (skey[idx]);
1134   return err;
1135
1136  bad_seckey:
1137   err = gpg_error (GPG_ERR_BAD_SECKEY);
1138   goto leave;
1139
1140  outofmem:
1141   err = gpg_error (GPG_ERR_ENOMEM);
1142   goto leave;
1143 }
1144
1145
1146 /* Print an "EXPORTED" status line.  PK is the primary public key.  */
1147 static void
1148 print_status_exported (PKT_public_key *pk)
1149 {
1150   char *hexfpr;
1151
1152   if (!is_status_enabled ())
1153     return;
1154
1155   hexfpr = hexfingerprint (pk, NULL, 0);
1156   write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
1157   xfree (hexfpr);
1158 }
1159
1160
1161 /*
1162  * Receive a secret key from agent specified by HEXGRIP.
1163  *
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.
1167  *
1168  * If CLEARTEXT is 0, store the secret key material
1169  * passphrase-protected.  Otherwise, store secret key material in the
1170  * clear.
1171  *
1172  * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
1173  */
1174 gpg_error_t
1175 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
1176                            int cleartext,
1177                            char **cache_nonce_addr, const char *hexgrip,
1178                            PKT_public_key *pk)
1179 {
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;
1185   gcry_sexp_t s_skey;
1186   char *prompt;
1187
1188   if (opt.verbose)
1189     log_info ("key %s: asking agent for the secret parts\n", hexgrip);
1190
1191   prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
1192   err = agent_export_key (ctrl, hexgrip, prompt, !cleartext, cache_nonce_addr,
1193                           &wrappedkey, &wrappedkeylen);
1194   xfree (prompt);
1195
1196   if (err)
1197     goto unwraperror;
1198   if (wrappedkeylen < 24)
1199     {
1200       err = gpg_error (GPG_ERR_INV_LENGTH);
1201       goto unwraperror;
1202     }
1203   keylen = wrappedkeylen - 8;
1204   key = xtrymalloc_secure (keylen);
1205   if (!key)
1206     {
1207       err = gpg_error_from_syserror ();
1208       goto unwraperror;
1209     }
1210   err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
1211   if (err)
1212     goto unwraperror;
1213   realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
1214   if (!realkeylen)
1215     goto unwraperror; /* Invalid csexp.  */
1216
1217   err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
1218   if (!err)
1219     {
1220       if (cleartext)
1221         err = cleartext_secret_key_to_openpgp (s_skey, pk);
1222       else
1223         err = transfer_format_to_openpgp (s_skey, pk);
1224       gcry_sexp_release (s_skey);
1225     }
1226
1227  unwraperror:
1228   xfree (key);
1229   xfree (wrappedkey);
1230   if (err)
1231     {
1232       log_error ("key %s: error receiving key from agent:"
1233                  " %s%s\n", hexgrip, gpg_strerror (err),
1234                  gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
1235                  "":_(" - skipped"));
1236     }
1237   return err;
1238 }
1239
1240
1241 /* Write KEYBLOCK either to stdout or to the file set with the
1242  * --output option.  This is a simplified version of do_export_stream
1243  * which supports only a few export options.  */
1244 gpg_error_t
1245 write_keyblock_to_output (kbnode_t keyblock, int with_armor,
1246                           unsigned int options)
1247 {
1248   gpg_error_t err;
1249   const char *fname;
1250   iobuf_t out;
1251   kbnode_t node;
1252   armor_filter_context_t *afx = NULL;
1253   iobuf_t out_help = NULL;
1254   PKT_public_key *pk = NULL;
1255
1256   fname = opt.outfile? opt.outfile : "-";
1257   if (is_secured_filename (fname) )
1258     return gpg_error (GPG_ERR_EPERM);
1259
1260   out = iobuf_create (fname, 0);
1261   if (!out)
1262     {
1263       err = gpg_error_from_syserror ();
1264       log_error(_("can't create '%s': %s\n"), fname, gpg_strerror (err));
1265       return err;
1266     }
1267   if (opt.verbose)
1268     log_info (_("writing to '%s'\n"), iobuf_get_fname_nonnull (out));
1269
1270   if ((options & (EXPORT_PKA_FORMAT|EXPORT_DANE_FORMAT)))
1271     {
1272       with_armor = 0;
1273       out_help = iobuf_temp ();
1274     }
1275
1276   if (with_armor)
1277     {
1278       afx = new_armor_context ();
1279       afx->what = 1;
1280       push_armor_filter (afx, out);
1281     }
1282
1283   for (node = keyblock; node; node = node->next)
1284     {
1285       if (is_deleted_kbnode (node) || node->pkt->pkttype == PKT_RING_TRUST)
1286         continue;
1287       if (!pk && (node->pkt->pkttype == PKT_PUBLIC_KEY
1288                   || node->pkt->pkttype == PKT_SECRET_KEY))
1289         pk = node->pkt->pkt.public_key;
1290
1291       err = build_packet (out_help? out_help : out, node->pkt);
1292       if (err)
1293         {
1294           log_error ("build_packet(%d) failed: %s\n",
1295                      node->pkt->pkttype, gpg_strerror (err) );
1296           goto leave;
1297         }
1298     }
1299   err = 0;
1300
1301   if (out_help && pk)
1302     {
1303       const void *data;
1304       size_t datalen;
1305
1306       iobuf_flush_temp (out_help);
1307       data = iobuf_get_temp_buffer (out_help);
1308       datalen = iobuf_get_temp_length (out_help);
1309
1310       err = print_pka_or_dane_records (out,
1311                                        keyblock, pk, data, datalen,
1312                                        (options & EXPORT_PKA_FORMAT),
1313                                        (options & EXPORT_DANE_FORMAT));
1314     }
1315
1316  leave:
1317   if (err)
1318     iobuf_cancel (out);
1319   else
1320     iobuf_close (out);
1321   iobuf_cancel (out_help);
1322   release_armor_context (afx);
1323   return err;
1324 }
1325
1326
1327 /*
1328  * Apply the keep-uid filter to the keyblock.  The deleted nodes are
1329  * marked and thus the caller should call commit_kbnode afterwards.
1330  * KEYBLOCK must not have any blocks marked as deleted.
1331  */
1332 static void
1333 apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
1334 {
1335   kbnode_t node;
1336
1337   for (node = keyblock->next; node; node = node->next )
1338     {
1339       if (node->pkt->pkttype == PKT_USER_ID)
1340         {
1341           if (!recsel_select (selector, impex_filter_getval, node))
1342             {
1343               /* log_debug ("keep-uid: deleting '%s'\n", */
1344               /*            node->pkt->pkt.user_id->name); */
1345               /* The UID packet and all following packets up to the
1346                * next UID or a subkey.  */
1347               delete_kbnode (node);
1348               for (; node->next
1349                      && node->next->pkt->pkttype != PKT_USER_ID
1350                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1351                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1352                    node = node->next)
1353                 delete_kbnode (node->next);
1354             }
1355           /* else */
1356           /*   log_debug ("keep-uid: keeping '%s'\n", */
1357           /*              node->pkt->pkt.user_id->name); */
1358         }
1359     }
1360 }
1361
1362
1363 /*
1364  * Apply the drop-subkey filter to the keyblock.  The deleted nodes are
1365  * marked and thus the caller should call commit_kbnode afterwards.
1366  * KEYBLOCK must not have any blocks marked as deleted.
1367  */
1368 static void
1369 apply_drop_subkey_filter (kbnode_t keyblock, recsel_expr_t selector)
1370 {
1371   kbnode_t node;
1372
1373   for (node = keyblock->next; node; node = node->next )
1374     {
1375       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1376           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1377         {
1378           if (recsel_select (selector, impex_filter_getval, node))
1379             {
1380               log_debug ("drop-subkey: deleting a key\n");
1381               /* The subkey packet and all following packets up to the
1382                * next subkey.  */
1383               delete_kbnode (node);
1384               for (; node->next
1385                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
1386                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
1387                    node = node->next)
1388                 delete_kbnode (node->next);
1389             }
1390         }
1391     }
1392 }
1393
1394
1395 /* Print DANE or PKA records for all user IDs in KEYBLOCK to OUT.  The
1396  * data for the record is taken from (DATA,DATELEN).  PK is the public
1397  * key packet with the primary key. */
1398 static gpg_error_t
1399 print_pka_or_dane_records (iobuf_t out, kbnode_t keyblock, PKT_public_key *pk,
1400                            const void *data, size_t datalen,
1401                            int print_pka, int print_dane)
1402 {
1403   gpg_error_t err = 0;
1404   kbnode_t kbctx, node;
1405   PKT_user_id *uid;
1406   char *mbox = NULL;
1407   char hashbuf[32];
1408   char *hash = NULL;
1409   char *domain;
1410   const char *s;
1411   unsigned int len;
1412   estream_t fp = NULL;
1413   char *hexdata = NULL;
1414   char *hexfpr;
1415
1416   hexfpr = hexfingerprint (pk, NULL, 0);
1417   hexdata = bin2hex (data, datalen, NULL);
1418   if (!hexdata)
1419     {
1420       err = gpg_error_from_syserror ();
1421       goto leave;
1422     }
1423   ascii_strlwr (hexdata);
1424   fp = es_fopenmem (0, "rw,samethread");
1425   if (!fp)
1426     {
1427       err = gpg_error_from_syserror ();
1428       goto leave;
1429     }
1430
1431   for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1432     {
1433       if (node->pkt->pkttype != PKT_USER_ID)
1434         continue;
1435       uid = node->pkt->pkt.user_id;
1436
1437       if (uid->is_expired || uid->is_revoked)
1438         continue;
1439
1440       xfree (mbox);
1441       mbox = mailbox_from_userid (uid->name);
1442       if (!mbox)
1443         continue;
1444
1445       domain = strchr (mbox, '@');
1446       *domain++ = 0;
1447
1448       if (print_pka)
1449         {
1450           es_fprintf (fp, "$ORIGIN _pka.%s.\n; %s\n; ", domain, hexfpr);
1451           print_utf8_buffer (fp, uid->name, uid->len);
1452           es_putc ('\n', fp);
1453           gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf, mbox, strlen (mbox));
1454           xfree (hash);
1455           hash = zb32_encode (hashbuf, 8*20);
1456           if (!hash)
1457             {
1458               err = gpg_error_from_syserror ();
1459               goto leave;
1460             }
1461           len = strlen (hexfpr)/2;
1462           es_fprintf (fp, "%s TYPE37 \\# %u 0006 0000 00 %02X %s\n\n",
1463                       hash, 6 + len, len, hexfpr);
1464         }
1465
1466       if (print_dane && hexdata)
1467         {
1468           es_fprintf (fp, "$ORIGIN _openpgpkey.%s.\n; %s\n; ", domain, hexfpr);
1469           print_utf8_buffer (fp, uid->name, uid->len);
1470           es_putc ('\n', fp);
1471           gcry_md_hash_buffer (GCRY_MD_SHA256, hashbuf, mbox, strlen (mbox));
1472           xfree (hash);
1473           hash = bin2hex (hashbuf, 28, NULL);
1474           if (!hash)
1475             {
1476               err = gpg_error_from_syserror ();
1477               goto leave;
1478             }
1479           ascii_strlwr (hash);
1480           len = strlen (hexdata)/2;
1481           es_fprintf (fp, "%s TYPE61 \\# %u (\n", hash, len);
1482           for (s = hexdata; ;)
1483             {
1484               es_fprintf (fp, "\t%.64s\n", s);
1485               if (strlen (s) < 64)
1486                 break;
1487               s += 64;
1488             }
1489           es_fputs ("\t)\n\n", fp);
1490         }
1491     }
1492
1493   /* Make sure it is a string and write it.  */
1494   es_fputc (0, fp);
1495   {
1496     void *vp;
1497
1498     if (es_fclose_snatch (fp, &vp, NULL))
1499       {
1500         err = gpg_error_from_syserror ();
1501         goto leave;
1502       }
1503     fp = NULL;
1504     iobuf_writestr (out, vp);
1505     es_free (vp);
1506   }
1507   err = 0;
1508
1509  leave:
1510   xfree (hash);
1511   xfree (mbox);
1512   es_fclose (fp);
1513   xfree (hexdata);
1514   xfree (hexfpr);
1515   return err;
1516 }
1517
1518
1519 /* Helper for do_export_stream which writes one keyblock to OUT.  */
1520 static gpg_error_t
1521 do_export_one_keyblock (ctrl_t ctrl, kbnode_t keyblock, u32 *keyid,
1522                         iobuf_t out, int secret, unsigned int options,
1523                         export_stats_t stats, int *any,
1524                         KEYDB_SEARCH_DESC *desc, size_t ndesc,
1525                         size_t descindex, gcry_cipher_hd_t cipherhd)
1526 {
1527   gpg_error_t err;
1528   char *cache_nonce = NULL;
1529   subkey_list_t subkey_list = NULL;  /* Track already processed subkeys. */
1530   int skip_until_subkey = 0;
1531   int cleartext = 0;
1532   char *hexgrip = NULL;
1533   char *serialno = NULL;
1534   PKT_public_key *pk;
1535   u32 subkidbuf[2], *subkid;
1536   kbnode_t kbctx, node;
1537
1538   /* NB: walk_kbnode skips packets marked as deleted.  */
1539   for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1540     {
1541       if (skip_until_subkey)
1542         {
1543           if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1544             skip_until_subkey = 0;
1545           else
1546             continue;
1547         }
1548
1549       /* We used to use comment packets, but not any longer.  In
1550        * case we still have comments on a key, strip them here
1551        * before we call build_packet(). */
1552       if (node->pkt->pkttype == PKT_COMMENT)
1553         continue;
1554
1555       /* Make sure that ring_trust packets are only exported in backup
1556        * mode. */
1557       if (node->pkt->pkttype == PKT_RING_TRUST && !(options & EXPORT_BACKUP))
1558         continue;
1559
1560       /* If exact is set, then we only export what was requested
1561        * (plus the primary key, if the user didn't specifically
1562        * request it). */
1563       if (desc[descindex].exact && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1564         {
1565           if (!exact_subkey_match_p (desc+descindex, node))
1566             {
1567               /* Before skipping this subkey, check whether any
1568                * other description wants an exact match on a
1569                * subkey and include that subkey into the output
1570                * too.  Need to add this subkey to a list so that
1571                * it won't get processed a second time.
1572                *
1573                * So the first step here is to check that list and
1574                * skip in any case if the key is in that list.
1575                *
1576                * We need this whole mess because the import
1577                * function of GnuPG < 2.1 is not able to merge
1578                * secret keys and thus it is useless to output them
1579                * as two separate keys and have import merge them.
1580                */
1581               if (subkey_in_list_p (subkey_list, node))
1582                 skip_until_subkey = 1; /* Already processed this one. */
1583               else
1584                 {
1585                   size_t j;
1586
1587                   for (j=0; j < ndesc; j++)
1588                     if (j != descindex && desc[j].exact
1589                         && exact_subkey_match_p (desc+j, node))
1590                       break;
1591                   if (!(j < ndesc))
1592                     skip_until_subkey = 1; /* No other one matching. */
1593                 }
1594             }
1595
1596           if (skip_until_subkey)
1597             continue;
1598
1599           /* Mark this one as processed. */
1600           {
1601             subkey_list_t tmp = new_subkey_list_item (node);
1602             tmp->next = subkey_list;
1603             subkey_list = tmp;
1604           }
1605         }
1606
1607       if (node->pkt->pkttype == PKT_SIGNATURE)
1608         {
1609           /* Do not export packets which are marked as not
1610            * exportable.  */
1611           if (!(options & EXPORT_LOCAL_SIGS)
1612               && !node->pkt->pkt.signature->flags.exportable)
1613             continue; /* not exportable */
1614
1615           /* Do not export packets with a "sensitive" revocation key
1616            * unless the user wants us to.  Note that we do export
1617            * these when issuing the actual revocation (see revoke.c). */
1618           if (!(options & EXPORT_SENSITIVE_REVKEYS)
1619               && node->pkt->pkt.signature->revkey)
1620             {
1621               int i;
1622
1623               for (i = 0; i < node->pkt->pkt.signature->numrevkeys; i++)
1624                 if ((node->pkt->pkt.signature->revkey[i].class & 0x40))
1625                   break;
1626               if (i < node->pkt->pkt.signature->numrevkeys)
1627                 continue;
1628             }
1629         }
1630
1631       /* Don't export attribs? */
1632       if (!(options & EXPORT_ATTRIBUTES)
1633           && node->pkt->pkttype == PKT_USER_ID
1634           && node->pkt->pkt.user_id->attrib_data)
1635         {
1636           /* Skip until we get to something that is not an attrib or a
1637            * signature on an attrib.  */
1638           while (kbctx->next && kbctx->next->pkt->pkttype == PKT_SIGNATURE)
1639             kbctx = kbctx->next;
1640
1641           continue;
1642         }
1643
1644       if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1645                      || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1646         {
1647           pk = node->pkt->pkt.public_key;
1648           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1649             subkid = NULL;
1650           else
1651             {
1652               keyid_from_pk (pk, subkidbuf);
1653               subkid = subkidbuf;
1654             }
1655
1656           if (pk->seckey_info)
1657             {
1658               log_error ("key %s: oops: seckey_info already set"
1659                          " - skipped\n", keystr_with_sub (keyid, subkid));
1660               skip_until_subkey = 1;
1661               continue;
1662             }
1663
1664           xfree (hexgrip);
1665           err = hexkeygrip_from_pk (pk, &hexgrip);
1666           if (err)
1667             {
1668               log_error ("key %s: error computing keygrip: %s"
1669                          " - skipped\n", keystr_with_sub (keyid, subkid),
1670                          gpg_strerror (err));
1671               skip_until_subkey = 1;
1672               err = 0;
1673               continue;
1674             }
1675
1676           xfree (serialno);
1677           serialno = NULL;
1678           if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1679             {
1680               /* We are asked not to export the secret parts of the
1681                * primary key.  Make up an error code to create the
1682                * stub.  */
1683               err = GPG_ERR_NOT_FOUND;
1684             }
1685           else
1686             err = agent_get_keyinfo (ctrl, hexgrip, &serialno, &cleartext);
1687
1688           if ((!err && serialno)
1689               && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1690             {
1691               /* It does not make sense to export a key with its
1692                * primary key on card using a non-key stub.  Thus we
1693                * skip those keys when used with --export-secret-subkeys. */
1694               log_info (_("key %s: key material on-card - skipped\n"),
1695                         keystr_with_sub (keyid, subkid));
1696               skip_until_subkey = 1;
1697             }
1698           else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1699                    || (!err && serialno))
1700             {
1701               /* Create a key stub.  */
1702               struct seckey_info *ski;
1703               const char *s;
1704
1705               pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1706               if (!ski)
1707                 {
1708                   err = gpg_error_from_syserror ();
1709                   goto leave;
1710                 }
1711
1712               ski->is_protected = 1;
1713               if (err)
1714                 ski->s2k.mode = 1001; /* GNU dummy (no secret key).  */
1715               else
1716                 {
1717                   ski->s2k.mode = 1002; /* GNU-divert-to-card.  */
1718                   for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1719                        ski->ivlen++, s += 2)
1720                     ski->iv[ski->ivlen] = xtoi_2 (s);
1721                 }
1722
1723               err = build_packet (out, node->pkt);
1724               if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1725                 {
1726                   stats->exported++;
1727                   print_status_exported (node->pkt->pkt.public_key);
1728                 }
1729             }
1730           else if (!err)
1731             {
1732               err = receive_seckey_from_agent (ctrl, cipherhd,
1733                                                cleartext, &cache_nonce,
1734                                                hexgrip, pk);
1735               if (err)
1736                 {
1737                   if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1738                     goto leave;
1739                   skip_until_subkey = 1;
1740                   err = 0;
1741                 }
1742               else
1743                 {
1744                   err = build_packet (out, node->pkt);
1745                   if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1746                     {
1747                       stats->exported++;
1748                       print_status_exported (node->pkt->pkt.public_key);
1749                     }
1750                 }
1751             }
1752           else
1753             {
1754               log_error ("key %s: error getting keyinfo from agent: %s"
1755                          " - skipped\n", keystr_with_sub (keyid, subkid),
1756                              gpg_strerror (err));
1757               skip_until_subkey = 1;
1758               err = 0;
1759             }
1760
1761           xfree (pk->seckey_info);
1762           pk->seckey_info = NULL;
1763           {
1764             int i;
1765             for (i = pubkey_get_npkey (pk->pubkey_algo);
1766                  i < pubkey_get_nskey (pk->pubkey_algo); i++)
1767               {
1768                 gcry_mpi_release (pk->pkey[i]);
1769                 pk->pkey[i] = NULL;
1770               }
1771           }
1772         }
1773       else /* Not secret or common packets.  */
1774         {
1775           err = build_packet (out, node->pkt);
1776           if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1777             {
1778               stats->exported++;
1779               print_status_exported (node->pkt->pkt.public_key);
1780             }
1781         }
1782
1783       if (err)
1784         {
1785           log_error ("build_packet(%d) failed: %s\n",
1786                      node->pkt->pkttype, gpg_strerror (err));
1787           goto leave;
1788         }
1789
1790       if (!skip_until_subkey)
1791         *any = 1;
1792     }
1793
1794  leave:
1795   release_subkey_list (subkey_list);
1796   xfree (serialno);
1797   xfree (hexgrip);
1798   xfree (cache_nonce);
1799   return err;
1800 }
1801
1802
1803 /* Export the keys identified by the list of strings in USERS to the
1804    stream OUT.  If SECRET is false public keys will be exported.  With
1805    secret true secret keys will be exported; in this case 1 means the
1806    entire secret keyblock and 2 only the subkeys.  OPTIONS are the
1807    export options to apply.  If KEYBLOCK_OUT is not NULL, AND the exit
1808    code is zero, a pointer to the first keyblock found and exported
1809    will be stored at this address; no other keyblocks are exported in
1810    this case.  The caller must free the returned keyblock.  If any
1811    key has been exported true is stored at ANY. */
1812 static int
1813 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
1814                   kbnode_t *keyblock_out, unsigned int options,
1815                   export_stats_t stats, int *any)
1816 {
1817   gpg_error_t err = 0;
1818   PACKET pkt;
1819   kbnode_t keyblock = NULL;
1820   kbnode_t node;
1821   size_t ndesc, descindex;
1822   KEYDB_SEARCH_DESC *desc = NULL;
1823   KEYDB_HANDLE kdbhd;
1824   strlist_t sl;
1825   gcry_cipher_hd_t cipherhd = NULL;
1826   struct export_stats_s dummystats;
1827   iobuf_t out_help = NULL;
1828
1829   if (!stats)
1830     stats = &dummystats;
1831   *any = 0;
1832   init_packet (&pkt);
1833   kdbhd = keydb_new ();
1834   if (!kdbhd)
1835     return gpg_error_from_syserror ();
1836
1837   /* For the PKA and DANE format open a helper iobuf and for DANE
1838    * enforce some options.  */
1839   if ((options & (EXPORT_PKA_FORMAT | EXPORT_DANE_FORMAT)))
1840     {
1841       out_help = iobuf_temp ();
1842       if ((options & EXPORT_DANE_FORMAT))
1843         options |= EXPORT_MINIMAL | EXPORT_CLEAN;
1844     }
1845
1846   if (!users)
1847     {
1848       ndesc = 1;
1849       desc = xcalloc (ndesc, sizeof *desc);
1850       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1851     }
1852   else
1853     {
1854       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1855         ;
1856       desc = xmalloc ( ndesc * sizeof *desc);
1857
1858       for (ndesc=0, sl=users; sl; sl = sl->next)
1859         {
1860           if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
1861             ndesc++;
1862           else
1863             log_error (_("key \"%s\" not found: %s\n"),
1864                        sl->d, gpg_strerror (err));
1865         }
1866
1867       keydb_disable_caching (kdbhd);  /* We are looping the search.  */
1868
1869       /* It would be nice to see which of the given users did actually
1870          match one in the keyring.  To implement this we need to have
1871          a found flag for each entry in desc.  To set this flag we
1872          must check all those entries after a match to mark all
1873          matched one - currently we stop at the first match.  To do
1874          this we need an extra flag to enable this feature.  */
1875     }
1876
1877 #ifdef ENABLE_SELINUX_HACKS
1878   if (secret)
1879     {
1880       log_error (_("exporting secret keys not allowed\n"));
1881       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
1882       goto leave;
1883     }
1884 #endif
1885
1886   /* For secret key export we need to setup a decryption context.  */
1887   if (secret)
1888     {
1889       void *kek = NULL;
1890       size_t keklen;
1891
1892       err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
1893       if (err)
1894         {
1895           log_error ("error getting the KEK: %s\n", gpg_strerror (err));
1896           goto leave;
1897         }
1898
1899       /* Prepare a cipher context.  */
1900       err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
1901                               GCRY_CIPHER_MODE_AESWRAP, 0);
1902       if (!err)
1903         err = gcry_cipher_setkey (cipherhd, kek, keklen);
1904       if (err)
1905         {
1906           log_error ("error setting up an encryption context: %s\n",
1907                      gpg_strerror (err));
1908           goto leave;
1909         }
1910       xfree (kek);
1911       kek = NULL;
1912     }
1913
1914   for (;;)
1915     {
1916       u32 keyid[2];
1917       PKT_public_key *pk;
1918
1919       err = keydb_search (kdbhd, desc, ndesc, &descindex);
1920       if (!users)
1921         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1922       if (err)
1923         break;
1924
1925       /* Read the keyblock. */
1926       release_kbnode (keyblock);
1927       keyblock = NULL;
1928       err = keydb_get_keyblock (kdbhd, &keyblock);
1929       if (err)
1930         {
1931           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1932           goto leave;
1933         }
1934
1935       node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1936       if (!node)
1937         {
1938           log_error ("public key packet not found in keyblock - skipped\n");
1939           continue;
1940         }
1941       stats->count++;
1942       setup_main_keyids (keyblock);  /* gpg_format_keydesc needs it.  */
1943       pk = node->pkt->pkt.public_key;
1944       keyid_from_pk (pk, keyid);
1945
1946       /* If a secret key export is required we need to check whether
1947          we have a secret key at all and if so create the seckey_info
1948          structure.  */
1949       if (secret)
1950         {
1951           if (agent_probe_any_secret_key (ctrl, keyblock))
1952             continue;  /* No secret key (neither primary nor subkey).  */
1953
1954           /* No v3 keys with GNU mode 1001. */
1955           if (secret == 2 && pk->version == 3)
1956             {
1957               log_info (_("key %s: PGP 2.x style key - skipped\n"),
1958                         keystr (keyid));
1959               continue;
1960             }
1961
1962           /* The agent does not yet allow export of v3 packets.  It is
1963              actually questionable whether we should allow them at
1964              all.  */
1965           if (pk->version == 3)
1966             {
1967               log_info ("key %s: PGP 2.x style key (v3) export "
1968                         "not yet supported - skipped\n", keystr (keyid));
1969               continue;
1970             }
1971           stats->secret_count++;
1972         }
1973
1974       /* Always do the cleaning on the public key part if requested.
1975        * Note that both export-clean and export-minimal only apply to
1976        * UID sigs (0x10, 0x11, 0x12, and 0x13).  A designated
1977        * revocation is never stripped, even with export-minimal set.  */
1978       if ((options & EXPORT_CLEAN))
1979         clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1980
1981       if (export_keep_uid)
1982         {
1983           commit_kbnode (&keyblock);
1984           apply_keep_uid_filter (keyblock, export_keep_uid);
1985           commit_kbnode (&keyblock);
1986         }
1987
1988       if (export_drop_subkey)
1989         {
1990           commit_kbnode (&keyblock);
1991           apply_drop_subkey_filter (keyblock, export_drop_subkey);
1992           commit_kbnode (&keyblock);
1993         }
1994
1995       /* And write it. */
1996       err = do_export_one_keyblock (ctrl, keyblock, keyid,
1997                                     out_help? out_help : out,
1998                                     secret, options, stats, any,
1999                                     desc, ndesc, descindex, cipherhd);
2000       if (err)
2001         break;
2002
2003       if (keyblock_out)
2004         {
2005           *keyblock_out = keyblock;
2006           break;
2007         }
2008
2009       if (out_help)
2010         {
2011           /* We want to write PKA or DANE records.  OUT_HELP has the
2012            * keyblock and we print a record for each uid to OUT. */
2013           const void *data;
2014           size_t datalen;
2015
2016           iobuf_flush_temp (out_help);
2017           data = iobuf_get_temp_buffer (out_help);
2018           datalen = iobuf_get_temp_length (out_help);
2019
2020           err = print_pka_or_dane_records (out,
2021                                            keyblock, pk, data, datalen,
2022                                            (options & EXPORT_PKA_FORMAT),
2023                                            (options & EXPORT_DANE_FORMAT));
2024           if (err)
2025             goto leave;
2026
2027           iobuf_close (out_help);
2028           out_help = iobuf_temp ();
2029         }
2030
2031     }
2032   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2033     err = 0;
2034
2035  leave:
2036   iobuf_cancel (out_help);
2037   gcry_cipher_close (cipherhd);
2038   xfree(desc);
2039   keydb_release (kdbhd);
2040   if (err || !keyblock_out)
2041     release_kbnode( keyblock );
2042   if( !*any )
2043     log_info(_("WARNING: nothing exported\n"));
2044   return err;
2045 }
2046
2047
2048
2049 \f
2050 static gpg_error_t
2051 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
2052 {
2053   va_list arg_ptr;
2054   gpg_error_t err = 0;
2055   unsigned char nbuf[4];
2056   unsigned char *buf;
2057   size_t buflen;
2058   gcry_mpi_t a;
2059
2060   ulongtobuf (nbuf, (ulong)strlen (identifier));
2061   put_membuf (mb, nbuf, 4);
2062   put_membuf_str (mb, identifier);
2063   if (!strncmp (identifier, "ecdsa-sha2-", 11))
2064     {
2065       ulongtobuf (nbuf, (ulong)strlen (identifier+11));
2066       put_membuf (mb, nbuf, 4);
2067       put_membuf_str (mb, identifier+11);
2068     }
2069   va_start (arg_ptr, identifier);
2070   while ((a = va_arg (arg_ptr, gcry_mpi_t)))
2071     {
2072       err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
2073       if (err)
2074         break;
2075       if (!strcmp (identifier, "ssh-ed25519")
2076           && buflen > 5 && buf[4] == 0x40)
2077         {
2078           /* We need to strip our 0x40 prefix.  */
2079           put_membuf (mb, "\x00\x00\x00\x20", 4);
2080           put_membuf (mb, buf+5, buflen-5);
2081         }
2082       else
2083         put_membuf (mb, buf, buflen);
2084       gcry_free (buf);
2085     }
2086   va_end (arg_ptr);
2087   return err;
2088 }
2089
2090 /* Export the key identified by USERID in the SSH public key format.
2091    The function exports the latest subkey with Authentication
2092    capability unless the '!' suffix is used to export a specific
2093    key.  */
2094 gpg_error_t
2095 export_ssh_key (ctrl_t ctrl, const char *userid)
2096 {
2097   gpg_error_t err;
2098   kbnode_t keyblock = NULL;
2099   KEYDB_SEARCH_DESC desc;
2100   u32 latest_date;
2101   u32 curtime = make_timestamp ();
2102   kbnode_t latest_key, node;
2103   PKT_public_key *pk;
2104   const char *identifier;
2105   membuf_t mb;
2106   estream_t fp = NULL;
2107   struct b64state b64_state;
2108   const char *fname = "-";
2109
2110   init_membuf (&mb, 4096);
2111
2112   /* We need to know whether the key has been specified using the
2113      exact syntax ('!' suffix).  Thus we need to run a
2114      classify_user_id on our own.  */
2115   err = classify_user_id (userid, &desc, 1);
2116
2117   /* Get the public key.  */
2118   if (!err)
2119     {
2120       getkey_ctx_t getkeyctx;
2121
2122       err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
2123                                NULL,
2124                                0  /* Only usable keys or given exact. */,
2125                                1  /* No AKL lookup.  */);
2126       if (!err)
2127         {
2128           err = getkey_next (getkeyctx, NULL, NULL);
2129           if (!err)
2130             err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2131           else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
2132             err = 0;
2133         }
2134       getkey_end (getkeyctx);
2135     }
2136   if (err)
2137     {
2138       log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2139       return err;
2140     }
2141
2142   /* The finish_lookup code in getkey.c does not handle auth keys,
2143      thus we have to duplicate the code here to find the latest
2144      subkey.  However, if the key has been found using an exact match
2145      ('!' notation) we use that key without any further checks and
2146      even allow the use of the primary key. */
2147   latest_date = 0;
2148   latest_key = NULL;
2149   for (node = keyblock; node; node = node->next)
2150     {
2151       if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2152            || node->pkt->pkttype == PKT_PUBLIC_KEY)
2153           && node->pkt->pkt.public_key->flags.exact)
2154         {
2155           latest_key = node;
2156           break;
2157         }
2158     }
2159   if (!latest_key)
2160     {
2161       for (node = keyblock; node; node = node->next)
2162         {
2163           if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2164             continue;
2165
2166           pk = node->pkt->pkt.public_key;
2167           if (DBG_LOOKUP)
2168             log_debug ("\tchecking subkey %08lX\n",
2169                        (ulong) keyid_from_pk (pk, NULL));
2170           if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2171             {
2172               if (DBG_LOOKUP)
2173                 log_debug ("\tsubkey not usable for authentication\n");
2174               continue;
2175             }
2176           if (!pk->flags.valid)
2177             {
2178               if (DBG_LOOKUP)
2179                 log_debug ("\tsubkey not valid\n");
2180               continue;
2181             }
2182           if (pk->flags.revoked)
2183             {
2184               if (DBG_LOOKUP)
2185                 log_debug ("\tsubkey has been revoked\n");
2186               continue;
2187             }
2188           if (pk->has_expired)
2189             {
2190               if (DBG_LOOKUP)
2191                 log_debug ("\tsubkey has expired\n");
2192               continue;
2193             }
2194           if (pk->timestamp > curtime && !opt.ignore_valid_from)
2195             {
2196               if (DBG_LOOKUP)
2197                 log_debug ("\tsubkey not yet valid\n");
2198               continue;
2199             }
2200           if (DBG_LOOKUP)
2201             log_debug ("\tsubkey might be fine\n");
2202           /* In case a key has a timestamp of 0 set, we make sure that it
2203              is used.  A better change would be to compare ">=" but that
2204              might also change the selected keys and is as such a more
2205              intrusive change.  */
2206           if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2207             {
2208               latest_date = pk->timestamp;
2209               latest_key = node;
2210             }
2211         }
2212
2213       /* If no subkey was suitable check the primary key.  */
2214       if (!latest_key
2215           && (node = keyblock) && node->pkt->pkttype == PKT_PUBLIC_KEY)
2216         {
2217           pk = node->pkt->pkt.public_key;
2218           if (DBG_LOOKUP)
2219             log_debug ("\tchecking primary key %08lX\n",
2220                        (ulong) keyid_from_pk (pk, NULL));
2221           if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
2222             {
2223               if (DBG_LOOKUP)
2224                 log_debug ("\tprimary key not usable for authentication\n");
2225             }
2226           else if (!pk->flags.valid)
2227             {
2228               if (DBG_LOOKUP)
2229                 log_debug ("\tprimary key not valid\n");
2230             }
2231           else if (pk->flags.revoked)
2232             {
2233               if (DBG_LOOKUP)
2234                 log_debug ("\tprimary key has been revoked\n");
2235             }
2236           else if (pk->has_expired)
2237             {
2238               if (DBG_LOOKUP)
2239                 log_debug ("\tprimary key has expired\n");
2240             }
2241           else if (pk->timestamp > curtime && !opt.ignore_valid_from)
2242             {
2243               if (DBG_LOOKUP)
2244                 log_debug ("\tprimary key not yet valid\n");
2245             }
2246           else
2247             {
2248               if (DBG_LOOKUP)
2249                 log_debug ("\tprimary key is fine\n");
2250               latest_date = pk->timestamp;
2251               latest_key = node;
2252             }
2253         }
2254     }
2255
2256   if (!latest_key)
2257     {
2258       err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2259       log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
2260       goto leave;
2261     }
2262
2263   pk = latest_key->pkt->pkt.public_key;
2264   if (DBG_LOOKUP)
2265     log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
2266
2267   switch (pk->pubkey_algo)
2268     {
2269     case PUBKEY_ALGO_DSA:
2270       identifier = "ssh-dss";
2271       err = key_to_sshblob (&mb, identifier,
2272                             pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
2273                             NULL);
2274       break;
2275
2276     case PUBKEY_ALGO_RSA:
2277     case PUBKEY_ALGO_RSA_S:
2278       identifier = "ssh-rsa";
2279       err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
2280       break;
2281
2282     case PUBKEY_ALGO_ECDSA:
2283       {
2284         char *curveoid;
2285         const char *curve;
2286
2287         curveoid = openpgp_oid_to_str (pk->pkey[0]);
2288         if (!curveoid)
2289           err = gpg_error_from_syserror ();
2290         else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
2291           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2292         else
2293           {
2294             if (!strcmp (curve, "nistp256"))
2295               identifier = "ecdsa-sha2-nistp256";
2296             else if (!strcmp (curve, "nistp384"))
2297               identifier = "ecdsa-sha2-nistp384";
2298             else if (!strcmp (curve, "nistp521"))
2299               identifier = "ecdsa-sha2-nistp521";
2300             else
2301               identifier = NULL;
2302
2303             if (!identifier)
2304               err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2305             else
2306               err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2307           }
2308         xfree (curveoid);
2309       }
2310       break;
2311
2312     case PUBKEY_ALGO_EDDSA:
2313       if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
2314         err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
2315       else
2316         {
2317           identifier = "ssh-ed25519";
2318           err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
2319         }
2320       break;
2321
2322     case PUBKEY_ALGO_ELGAMAL_E:
2323     case PUBKEY_ALGO_ELGAMAL:
2324       err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
2325       break;
2326
2327     default:
2328       err = GPG_ERR_PUBKEY_ALGO;
2329       break;
2330     }
2331
2332   if (err)
2333     goto leave;
2334
2335   if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
2336     fp = es_fopen ((fname = opt.outfile), "w");
2337   else
2338     fp = es_stdout;
2339   if (!fp)
2340     {
2341       err = gpg_error_from_syserror ();
2342       log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
2343       goto leave;
2344     }
2345
2346   es_fprintf (fp, "%s ", identifier);
2347   err = b64enc_start_es (&b64_state, fp, "");
2348   if (err)
2349     goto leave;
2350   {
2351     void *blob;
2352     size_t bloblen;
2353
2354     blob = get_membuf (&mb, &bloblen);
2355     if (!blob)
2356       err = gpg_error_from_syserror ();
2357     else
2358       err = b64enc_write (&b64_state, blob, bloblen);
2359     xfree (blob);
2360     if (err)
2361       goto leave;
2362   }
2363   err = b64enc_finish (&b64_state);
2364   if (err)
2365     goto leave;
2366   es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
2367
2368   if (es_ferror (fp))
2369     err = gpg_error_from_syserror ();
2370   else
2371     {
2372       if (es_fclose (fp))
2373         err = gpg_error_from_syserror ();
2374       fp = NULL;
2375     }
2376
2377   if (err)
2378     log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
2379
2380  leave:
2381   es_fclose (fp);
2382   xfree (get_membuf (&mb, NULL));
2383   release_kbnode (keyblock);
2384   return err;
2385 }