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