Imported Upstream version 2.1.12
[platform/upstream/gpg2.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 <http://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 "trustdb.h"
39 #include "call-agent.h"
40
41 /* An object to keep track of subkeys. */
42 struct subkey_list_s
43 {
44   struct subkey_list_s *next;
45   u32 kid[2];
46 };
47 typedef struct subkey_list_s *subkey_list_t;
48
49
50 /* An object to track statistics for export operations.  */
51 struct export_stats_s
52 {
53   ulong count;            /* Number of processed keys.        */
54   ulong secret_count;     /* Number of secret keys seen.      */
55   ulong exported;         /* Number of actual exported keys.  */
56 };
57
58
59 /* Local prototypes.  */
60 static int do_export (ctrl_t ctrl, strlist_t users, int secret,
61                       unsigned int options, export_stats_t stats);
62 static int do_export_stream (ctrl_t ctrl, iobuf_t out,
63                              strlist_t users, int secret,
64                              kbnode_t *keyblock_out, unsigned int options,
65                              export_stats_t stats, int *any);
66
67 \f
68
69
70 /* Option parser for export options.  See parse_options fro
71    details.  */
72 int
73 parse_export_options(char *str,unsigned int *options,int noisy)
74 {
75   struct parse_options export_opts[]=
76     {
77       {"export-local-sigs",EXPORT_LOCAL_SIGS,NULL,
78        N_("export signatures that are marked as local-only")},
79       {"export-attributes",EXPORT_ATTRIBUTES,NULL,
80        N_("export attribute user IDs (generally photo IDs)")},
81       {"export-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,
82        N_("export revocation keys marked as \"sensitive\"")},
83       {"export-clean",EXPORT_CLEAN,NULL,
84        N_("remove unusable parts from key during export")},
85       {"export-minimal",EXPORT_MINIMAL|EXPORT_CLEAN,NULL,
86        N_("remove as much as possible from key during export")},
87       /* Aliases for backward compatibility */
88       {"include-local-sigs",EXPORT_LOCAL_SIGS,NULL,NULL},
89       {"include-attributes",EXPORT_ATTRIBUTES,NULL,NULL},
90       {"include-sensitive-revkeys",EXPORT_SENSITIVE_REVKEYS,NULL,NULL},
91       /* dummy */
92       {"export-unusable-sigs",0,NULL,NULL},
93       {"export-clean-sigs",0,NULL,NULL},
94       {"export-clean-uids",0,NULL,NULL},
95       {NULL,0,NULL,NULL}
96       /* add tags for include revoked and disabled? */
97     };
98
99   return parse_options(str,options,export_opts,noisy);
100 }
101
102
103 /* Create a new export stats object initialized to zero.  On error
104    returns NULL and sets ERRNO.  */
105 export_stats_t
106 export_new_stats (void)
107 {
108   export_stats_t stats;
109
110   return xtrycalloc (1, sizeof *stats);
111 }
112
113
114 /* Release an export stats object.  */
115 void
116 export_release_stats (export_stats_t stats)
117 {
118   xfree (stats);
119 }
120
121
122 /* Print export statistics using the status interface.  */
123 void
124 export_print_stats (export_stats_t stats)
125 {
126   if (!stats)
127     return;
128
129   if (is_status_enabled ())
130     {
131       char buf[15*20];
132
133       snprintf (buf, sizeof buf, "%lu %lu %lu",
134                 stats->count,
135                 stats->secret_count,
136                 stats->exported );
137       write_status_text (STATUS_EXPORT_RES, buf);
138     }
139 }
140
141
142 /*
143  * Export public keys (to stdout or to --output FILE).
144  *
145  * Depending on opt.armor the output is armored.  OPTIONS are defined
146  * in main.h.  If USERS is NULL, all keys will be exported.  STATS is
147  * either an export stats object for update or NULL.
148  *
149  * This function is the core of "gpg --export".
150  */
151 int
152 export_pubkeys (ctrl_t ctrl, strlist_t users, unsigned int options,
153                 export_stats_t stats)
154 {
155   return do_export (ctrl, users, 0, options, stats);
156 }
157
158
159 /*
160  * Export secret keys (to stdout or to --output FILE).
161  *
162  * Depending on opt.armor the output is armored.  If USERS is NULL,
163  * all secret keys will be exported.  STATS is either an export stats
164  * object for update or NULL.
165  *
166  * This function is the core of "gpg --export-secret-keys".
167  */
168 int
169 export_seckeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
170 {
171   return do_export (ctrl, users, 1, 0, stats);
172 }
173
174
175 /*
176  * Export secret sub keys (to stdout or to --output FILE).
177  *
178  * This is the same as export_seckeys but replaces the primary key by
179  * a stub key.  Depending on opt.armor the output is armored.  If
180  * USERS is NULL, all secret subkeys will be exported.  STATS is
181  * either an export stats object for update or NULL.
182  *
183  * This function is the core of "gpg --export-secret-subkeys".
184  */
185 int
186 export_secsubkeys (ctrl_t ctrl, strlist_t users, export_stats_t stats)
187 {
188   return do_export (ctrl, users, 2, 0, stats);
189 }
190
191
192 /*
193  * Export a single key into a memory buffer.  STATS is either an
194  * export stats object for update or NULL.
195  */
196 gpg_error_t
197 export_pubkey_buffer (ctrl_t ctrl, const char *keyspec, unsigned int options,
198                       export_stats_t stats,
199                       kbnode_t *r_keyblock, void **r_data, size_t *r_datalen)
200 {
201   gpg_error_t err;
202   iobuf_t iobuf;
203   int any;
204   strlist_t helplist;
205
206   *r_keyblock = NULL;
207   *r_data = NULL;
208   *r_datalen = 0;
209
210   helplist = NULL;
211   if (!add_to_strlist_try (&helplist, keyspec))
212     return gpg_error_from_syserror ();
213
214   iobuf = iobuf_temp ();
215   err = do_export_stream (ctrl, iobuf, helplist, 0, r_keyblock, options,
216                           stats, &any);
217   if (!err && !any)
218     err = gpg_error (GPG_ERR_NOT_FOUND);
219   if (!err)
220     {
221       const void *src;
222       size_t datalen;
223
224       iobuf_flush_temp (iobuf);
225       src = iobuf_get_temp_buffer (iobuf);
226       datalen = iobuf_get_temp_length (iobuf);
227       if (!datalen)
228         err = gpg_error (GPG_ERR_NO_PUBKEY);
229       else if (!(*r_data = xtrymalloc (datalen)))
230         err = gpg_error_from_syserror ();
231       else
232         {
233           memcpy (*r_data, src, datalen);
234           *r_datalen = datalen;
235         }
236     }
237   iobuf_close (iobuf);
238   free_strlist (helplist);
239   if (err && *r_keyblock)
240     {
241       release_kbnode (*r_keyblock);
242       *r_keyblock = NULL;
243     }
244   return err;
245 }
246
247
248 /* Export the keys identified by the list of strings in USERS.  If
249    Secret is false public keys will be exported.  With secret true
250    secret keys will be exported; in this case 1 means the entire
251    secret keyblock and 2 only the subkeys.  OPTIONS are the export
252    options to apply.  */
253 static int
254 do_export (ctrl_t ctrl, strlist_t users, int secret, unsigned int options,
255            export_stats_t stats)
256 {
257   IOBUF out = NULL;
258   int any, rc;
259   armor_filter_context_t *afx = NULL;
260   compress_filter_context_t zfx;
261
262   memset( &zfx, 0, sizeof zfx);
263
264   rc = open_outfile (-1, NULL, 0, !!secret, &out );
265   if (rc)
266     return rc;
267
268   if ( opt.armor )
269     {
270       afx = new_armor_context ();
271       afx->what = secret? 5 : 1;
272       push_armor_filter (afx, out);
273     }
274
275   rc = do_export_stream (ctrl, out, users, secret, NULL, options, stats, &any);
276
277   if ( rc || !any )
278     iobuf_cancel (out);
279   else
280     iobuf_close (out);
281   release_armor_context (afx);
282   return rc;
283 }
284
285
286
287 /* Release an entire subkey list. */
288 static void
289 release_subkey_list (subkey_list_t list)
290 {
291   while (list)
292     {
293       subkey_list_t tmp = list->next;;
294       xfree (list);
295       list = tmp;
296     }
297 }
298
299
300 /* Returns true if NODE is a subkey and contained in LIST. */
301 static int
302 subkey_in_list_p (subkey_list_t list, KBNODE node)
303 {
304   if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
305       || node->pkt->pkttype == PKT_SECRET_SUBKEY )
306     {
307       u32 kid[2];
308
309       keyid_from_pk (node->pkt->pkt.public_key, kid);
310
311       for (; list; list = list->next)
312         if (list->kid[0] == kid[0] && list->kid[1] == kid[1])
313           return 1;
314     }
315   return 0;
316 }
317
318 /* Allocate a new subkey list item from NODE. */
319 static subkey_list_t
320 new_subkey_list_item (KBNODE node)
321 {
322   subkey_list_t list = xcalloc (1, sizeof *list);
323
324   if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
325       || node->pkt->pkttype == PKT_SECRET_SUBKEY)
326     keyid_from_pk (node->pkt->pkt.public_key, list->kid);
327
328   return list;
329 }
330
331
332 /* Helper function to check whether the subkey at NODE actually
333    matches the description at DESC.  The function returns true if the
334    key under question has been specified by an exact specification
335    (keyID or fingerprint) and does match the one at NODE.  It is
336    assumed that the packet at NODE is either a public or secret
337    subkey. */
338 static int
339 exact_subkey_match_p (KEYDB_SEARCH_DESC *desc, KBNODE node)
340 {
341   u32 kid[2];
342   byte fpr[MAX_FINGERPRINT_LEN];
343   size_t fprlen;
344   int result = 0;
345
346   switch(desc->mode)
347     {
348     case KEYDB_SEARCH_MODE_SHORT_KID:
349     case KEYDB_SEARCH_MODE_LONG_KID:
350       keyid_from_pk (node->pkt->pkt.public_key, kid);
351       break;
352
353     case KEYDB_SEARCH_MODE_FPR16:
354     case KEYDB_SEARCH_MODE_FPR20:
355     case KEYDB_SEARCH_MODE_FPR:
356       fingerprint_from_pk (node->pkt->pkt.public_key, fpr,&fprlen);
357       break;
358
359     default:
360       break;
361     }
362
363   switch(desc->mode)
364     {
365     case KEYDB_SEARCH_MODE_SHORT_KID:
366       if (desc->u.kid[1] == kid[1])
367         result = 1;
368       break;
369
370     case KEYDB_SEARCH_MODE_LONG_KID:
371       if (desc->u.kid[0] == kid[0] && desc->u.kid[1] == kid[1])
372         result = 1;
373       break;
374
375     case KEYDB_SEARCH_MODE_FPR16:
376       if (!memcmp (desc->u.fpr, fpr, 16))
377         result = 1;
378       break;
379
380     case KEYDB_SEARCH_MODE_FPR20:
381     case KEYDB_SEARCH_MODE_FPR:
382       if (!memcmp (desc->u.fpr, fpr, 20))
383         result = 1;
384       break;
385
386     default:
387       break;
388     }
389
390   return result;
391 }
392
393
394 /* Return a canonicalized public key algoithms.  This is used to
395    compare different flavors of algorithms (e.g. ELG and ELG_E are
396    considered the same).  */
397 static enum gcry_pk_algos
398 canon_pk_algo (enum gcry_pk_algos algo)
399 {
400   switch (algo)
401     {
402     case GCRY_PK_RSA:
403     case GCRY_PK_RSA_E:
404     case GCRY_PK_RSA_S: return GCRY_PK_RSA;
405     case GCRY_PK_ELG:
406     case GCRY_PK_ELG_E: return GCRY_PK_ELG;
407     case GCRY_PK_ECC:
408     case GCRY_PK_ECDSA:
409     case GCRY_PK_ECDH: return GCRY_PK_ECC;
410     default: return algo;
411     }
412 }
413
414
415 /* Use the key transfer format given in S_PGP to create the secinfo
416    structure in PK and change the parameter array in PK to include the
417    secret parameters.  */
418 static gpg_error_t
419 transfer_format_to_openpgp (gcry_sexp_t s_pgp, PKT_public_key *pk)
420 {
421   gpg_error_t err;
422   gcry_sexp_t top_list;
423   gcry_sexp_t list = NULL;
424   char *curve = NULL;
425   const char *value;
426   size_t valuelen;
427   char *string;
428   int  idx;
429   int  is_v4, is_protected;
430   enum gcry_pk_algos pk_algo;
431   int  protect_algo = 0;
432   char iv[16];
433   int  ivlen = 0;
434   int  s2k_mode = 0;
435   int  s2k_algo = 0;
436   byte s2k_salt[8];
437   u32  s2k_count = 0;
438   int  is_ecdh = 0;
439   size_t npkey, nskey;
440   gcry_mpi_t skey[10];  /* We support up to 9 parameters.  */
441   int skeyidx = 0;
442   struct seckey_info *ski;
443
444   /* gcry_log_debugsxp ("transferkey", s_pgp); */
445   top_list = gcry_sexp_find_token (s_pgp, "openpgp-private-key", 0);
446   if (!top_list)
447     goto bad_seckey;
448
449   list = gcry_sexp_find_token (top_list, "version", 0);
450   if (!list)
451     goto bad_seckey;
452   value = gcry_sexp_nth_data (list, 1, &valuelen);
453   if (!value || valuelen != 1 || !(value[0] == '3' || value[0] == '4'))
454     goto bad_seckey;
455   is_v4 = (value[0] == '4');
456
457   gcry_sexp_release (list);
458   list = gcry_sexp_find_token (top_list, "protection", 0);
459   if (!list)
460     goto bad_seckey;
461   value = gcry_sexp_nth_data (list, 1, &valuelen);
462   if (!value)
463     goto bad_seckey;
464   if (valuelen == 4 && !memcmp (value, "sha1", 4))
465     is_protected = 2;
466   else if (valuelen == 3 && !memcmp (value, "sum", 3))
467     is_protected = 1;
468   else if (valuelen == 4 && !memcmp (value, "none", 4))
469     is_protected = 0;
470   else
471     goto bad_seckey;
472   if (is_protected)
473     {
474       string = gcry_sexp_nth_string (list, 2);
475       if (!string)
476         goto bad_seckey;
477       protect_algo = gcry_cipher_map_name (string);
478       xfree (string);
479
480       value = gcry_sexp_nth_data (list, 3, &valuelen);
481       if (!value || !valuelen || valuelen > sizeof iv)
482         goto bad_seckey;
483       memcpy (iv, value, valuelen);
484       ivlen = valuelen;
485
486       string = gcry_sexp_nth_string (list, 4);
487       if (!string)
488         goto bad_seckey;
489       s2k_mode = strtol (string, NULL, 10);
490       xfree (string);
491
492       string = gcry_sexp_nth_string (list, 5);
493       if (!string)
494         goto bad_seckey;
495       s2k_algo = gcry_md_map_name (string);
496       xfree (string);
497
498       value = gcry_sexp_nth_data (list, 6, &valuelen);
499       if (!value || !valuelen || valuelen > sizeof s2k_salt)
500         goto bad_seckey;
501       memcpy (s2k_salt, value, valuelen);
502
503       string = gcry_sexp_nth_string (list, 7);
504       if (!string)
505         goto bad_seckey;
506       s2k_count = strtoul (string, NULL, 10);
507       xfree (string);
508     }
509
510   /* Parse the gcrypt PK algo and check that it is okay.  */
511   gcry_sexp_release (list);
512   list = gcry_sexp_find_token (top_list, "algo", 0);
513   if (!list)
514     goto bad_seckey;
515   string = gcry_sexp_nth_string (list, 1);
516   if (!string)
517     goto bad_seckey;
518   pk_algo = gcry_pk_map_name (string);
519   xfree (string); string = NULL;
520   if (gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NPKEY, NULL, &npkey)
521       || gcry_pk_algo_info (pk_algo, GCRYCTL_GET_ALGO_NSKEY, NULL, &nskey)
522       || !npkey || npkey >= nskey)
523     goto bad_seckey;
524
525   /* Check that the pubkey algo matches the one from the public key.  */
526   switch (canon_pk_algo (pk_algo))
527     {
528     case GCRY_PK_RSA:
529       if (!is_RSA (pk->pubkey_algo))
530         pk_algo = 0;  /* Does not match.  */
531       break;
532     case GCRY_PK_DSA:
533       if (!is_DSA (pk->pubkey_algo))
534         pk_algo = 0;  /* Does not match.  */
535       break;
536     case GCRY_PK_ELG:
537       if (!is_ELGAMAL (pk->pubkey_algo))
538         pk_algo = 0;  /* Does not match.  */
539       break;
540     case GCRY_PK_ECC:
541       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
542         ;
543       else if (pk->pubkey_algo == PUBKEY_ALGO_ECDH)
544         is_ecdh = 1;
545       else if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
546         ;
547       else
548         pk_algo = 0;  /* Does not match.  */
549       /* For ECC we do not have the domain parameters thus fix our info.  */
550       npkey = 1;
551       nskey = 2;
552       break;
553     default:
554       pk_algo = 0;   /* Oops.  */
555       break;
556     }
557   if (!pk_algo)
558     {
559       err = gpg_error (GPG_ERR_PUBKEY_ALGO);
560       goto leave;
561     }
562
563   /* This check has to go after the ecc adjustments. */
564   if (nskey > PUBKEY_MAX_NSKEY)
565     goto bad_seckey;
566
567   /* Parse the key parameters.  */
568   gcry_sexp_release (list);
569   list = gcry_sexp_find_token (top_list, "skey", 0);
570   if (!list)
571     goto bad_seckey;
572   for (idx=0;;)
573     {
574       int is_enc;
575
576       value = gcry_sexp_nth_data (list, ++idx, &valuelen);
577       if (!value && skeyidx >= npkey)
578         break;  /* Ready.  */
579
580       /* Check for too many parameters.  Note that depending on the
581          protection mode and version number we may see less than NSKEY
582          (but at least NPKEY+1) parameters.  */
583       if (idx >= 2*nskey)
584         goto bad_seckey;
585       if (skeyidx >= DIM (skey)-1)
586         goto bad_seckey;
587
588       if (!value || valuelen != 1 || !(value[0] == '_' || value[0] == 'e'))
589         goto bad_seckey;
590       is_enc = (value[0] == 'e');
591       value = gcry_sexp_nth_data (list, ++idx, &valuelen);
592       if (!value || !valuelen)
593         goto bad_seckey;
594       if (is_enc)
595         {
596           void *p = xtrymalloc (valuelen);
597           if (!p)
598             goto outofmem;
599           memcpy (p, value, valuelen);
600           skey[skeyidx] = gcry_mpi_set_opaque (NULL, p, valuelen*8);
601           if (!skey[skeyidx])
602             goto outofmem;
603         }
604       else
605         {
606           if (gcry_mpi_scan (skey + skeyidx, GCRYMPI_FMT_STD,
607                              value, valuelen, NULL))
608             goto bad_seckey;
609         }
610       skeyidx++;
611     }
612   skey[skeyidx++] = NULL;
613
614   gcry_sexp_release (list); list = NULL;
615
616   /* We have no need for the CSUM value thus we don't parse it.  */
617   /* list = gcry_sexp_find_token (top_list, "csum", 0); */
618   /* if (list) */
619   /*   { */
620   /*     string = gcry_sexp_nth_string (list, 1); */
621   /*     if (!string) */
622   /*       goto bad_seckey; */
623   /*     desired_csum = strtoul (string, NULL, 10); */
624   /*     xfree (string); */
625   /*   } */
626   /* else */
627   /*   desired_csum = 0; */
628   /* gcry_sexp_release (list); list = NULL; */
629
630   /* Get the curve name if any,  */
631   list = gcry_sexp_find_token (top_list, "curve", 0);
632   if (list)
633     {
634       curve = gcry_sexp_nth_string (list, 1);
635       gcry_sexp_release (list); list = NULL;
636     }
637
638   gcry_sexp_release (top_list); top_list = NULL;
639
640   /* log_debug ("XXX is_v4=%d\n", is_v4); */
641   /* log_debug ("XXX pubkey_algo=%d\n", pubkey_algo); */
642   /* log_debug ("XXX is_protected=%d\n", is_protected); */
643   /* log_debug ("XXX protect_algo=%d\n", protect_algo); */
644   /* log_printhex ("XXX iv", iv, ivlen); */
645   /* log_debug ("XXX ivlen=%d\n", ivlen); */
646   /* log_debug ("XXX s2k_mode=%d\n", s2k_mode); */
647   /* log_debug ("XXX s2k_algo=%d\n", s2k_algo); */
648   /* log_printhex ("XXX s2k_salt", s2k_salt, sizeof s2k_salt); */
649   /* log_debug ("XXX s2k_count=%lu\n", (unsigned long)s2k_count); */
650   /* for (idx=0; skey[idx]; idx++) */
651   /*   { */
652   /*     int is_enc = gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE); */
653   /*     log_info ("XXX skey[%d]%s:", idx, is_enc? " (enc)":""); */
654   /*     if (is_enc) */
655   /*       { */
656   /*         void *p; */
657   /*         unsigned int nbits; */
658   /*         p = gcry_mpi_get_opaque (skey[idx], &nbits); */
659   /*         log_printhex (NULL, p, (nbits+7)/8); */
660   /*       } */
661   /*     else */
662   /*       gcry_mpi_dump (skey[idx]); */
663   /*     log_printf ("\n"); */
664   /*   } */
665
666   if (!is_v4 || is_protected != 2 )
667     {
668       /* We only support the v4 format and a SHA-1 checksum.  */
669       err = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
670       goto leave;
671     }
672
673   /* We need to change the received parameters for ECC algorithms.
674      The transfer format has the curve name and the parameters
675      separate.  We put them all into the SKEY array.  */
676   if (canon_pk_algo (pk_algo) == GCRY_PK_ECC)
677     {
678       const char *oidstr;
679
680       /* Assert that all required parameters are available.  We also
681          check that the array does not contain more parameters than
682          needed (this was used by some beta versions of 2.1.  */
683       if (!curve || !skey[0] || !skey[1] || skey[2])
684         {
685           err = gpg_error (GPG_ERR_INTERNAL);
686           goto leave;
687         }
688
689       oidstr = openpgp_curve_to_oid (curve, NULL);
690       if (!oidstr)
691         {
692           log_error ("no OID known for curve '%s'\n", curve);
693           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
694           goto leave;
695         }
696       /* Put the curve's OID into into the MPI array.  This requires
697          that we shift Q and D.  For ECDH also insert the KDF parms. */
698       if (is_ecdh)
699         {
700           skey[4] = NULL;
701           skey[3] = skey[1];
702           skey[2] = gcry_mpi_copy (pk->pkey[2]);
703         }
704       else
705         {
706           skey[3] = NULL;
707           skey[2] = skey[1];
708         }
709       skey[1] = skey[0];
710       skey[0] = NULL;
711       err = openpgp_oid_from_str (oidstr, skey + 0);
712       if (err)
713         goto leave;
714       /* Fixup the NPKEY and NSKEY to match OpenPGP reality.  */
715       npkey = 2 + is_ecdh;
716       nskey = 3 + is_ecdh;
717
718       /* for (idx=0; skey[idx]; idx++) */
719       /*   { */
720       /*     log_info ("YYY skey[%d]:", idx); */
721       /*     if (gcry_mpi_get_flag (skey[idx], GCRYMPI_FLAG_OPAQUE)) */
722       /*       { */
723       /*         void *p; */
724       /*         unsigned int nbits; */
725       /*         p = gcry_mpi_get_opaque (skey[idx], &nbits); */
726       /*         log_printhex (NULL, p, (nbits+7)/8); */
727       /*       } */
728       /*     else */
729       /*       gcry_mpi_dump (skey[idx]); */
730       /*     log_printf ("\n"); */
731       /*   } */
732     }
733
734   /* Do some sanity checks.  */
735   if (s2k_count > 255)
736     {
737       /* We expect an already encoded S2K count.  */
738       err = gpg_error (GPG_ERR_INV_DATA);
739       goto leave;
740     }
741   err = openpgp_cipher_test_algo (protect_algo);
742   if (err)
743     goto leave;
744   err = openpgp_md_test_algo (s2k_algo);
745   if (err)
746     goto leave;
747
748   /* Check that the public key parameters match.  Note that since
749      Libgcrypt 1.5 gcry_mpi_cmp handles opaque MPI correctly.  */
750   for (idx=0; idx < npkey; idx++)
751     if (gcry_mpi_cmp (pk->pkey[idx], skey[idx]))
752       {
753         err = gpg_error (GPG_ERR_BAD_PUBKEY);
754         goto leave;
755       }
756
757   /* Check that the first secret key parameter in SKEY is encrypted
758      and that there are no more secret key parameters.  The latter is
759      guaranteed by the v4 packet format.  */
760   if (!gcry_mpi_get_flag (skey[npkey], GCRYMPI_FLAG_OPAQUE))
761     goto bad_seckey;
762   if (npkey+1 < DIM (skey) && skey[npkey+1])
763     goto bad_seckey;
764
765   /* Check that the secret key parameters in PK are all set to NULL. */
766   for (idx=npkey; idx < nskey; idx++)
767     if (pk->pkey[idx])
768       goto bad_seckey;
769
770   /* Now build the protection info. */
771   pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
772   if (!ski)
773     {
774       err = gpg_error_from_syserror ();
775       goto leave;
776     }
777
778   ski->is_protected = 1;
779   ski->sha1chk = 1;
780   ski->algo = protect_algo;
781   ski->s2k.mode = s2k_mode;
782   ski->s2k.hash_algo = s2k_algo;
783   log_assert (sizeof ski->s2k.salt == sizeof s2k_salt);
784   memcpy (ski->s2k.salt, s2k_salt, sizeof s2k_salt);
785   ski->s2k.count = s2k_count;
786   log_assert (ivlen <= sizeof ski->iv);
787   memcpy (ski->iv, iv, ivlen);
788   ski->ivlen = ivlen;
789
790   /* Store the protected secret key parameter.  */
791   pk->pkey[npkey] = skey[npkey];
792   skey[npkey] = NULL;
793
794   /* That's it.  */
795
796  leave:
797   gcry_free (curve);
798   gcry_sexp_release (list);
799   gcry_sexp_release (top_list);
800   for (idx=0; idx < skeyidx; idx++)
801     gcry_mpi_release (skey[idx]);
802   return err;
803
804  bad_seckey:
805   err = gpg_error (GPG_ERR_BAD_SECKEY);
806   goto leave;
807
808  outofmem:
809   err = gpg_error (GPG_ERR_ENOMEM);
810   goto leave;
811 }
812
813
814 /* Print an "EXPORTED" status line.  PK is the primary public key.  */
815 static void
816 print_status_exported (PKT_public_key *pk)
817 {
818   char *hexfpr;
819
820   if (!is_status_enabled ())
821     return;
822
823   hexfpr = hexfingerprint (pk, NULL, 0);
824   write_status_text (STATUS_EXPORTED, hexfpr? hexfpr : "[?]");
825   xfree (hexfpr);
826 }
827
828
829 /*
830  * Receive a secret key from agent specified by HEXGRIP.
831  *
832  * Since the key data from agant is encrypted, decrypt it by CIPHERHD.
833  * Then, parse the decrypted key data in transfer format, and put
834  * secret papameters into PK.
835  *
836  * CACHE_NONCE_ADDR is used to share nonce for multple key retrievals.
837  */
838 gpg_error_t
839 receive_seckey_from_agent (ctrl_t ctrl, gcry_cipher_hd_t cipherhd,
840                            char **cache_nonce_addr, const char *hexgrip,
841                            PKT_public_key *pk)
842 {
843   gpg_error_t err = 0;
844   unsigned char *wrappedkey = NULL;
845   size_t wrappedkeylen;
846   unsigned char *key = NULL;
847   size_t keylen, realkeylen;
848   gcry_sexp_t s_skey;
849   char *prompt;
850
851   if (opt.verbose)
852     log_info ("key %s: asking agent for the secret parts\n", hexgrip);
853
854   prompt = gpg_format_keydesc (pk, FORMAT_KEYDESC_EXPORT,1);
855   err = agent_export_key (ctrl, hexgrip, prompt, cache_nonce_addr,
856                           &wrappedkey, &wrappedkeylen);
857   xfree (prompt);
858
859   if (err)
860     goto unwraperror;
861   if (wrappedkeylen < 24)
862     {
863       err = gpg_error (GPG_ERR_INV_LENGTH);
864       goto unwraperror;
865     }
866   keylen = wrappedkeylen - 8;
867   key = xtrymalloc_secure (keylen);
868   if (!key)
869     {
870       err = gpg_error_from_syserror ();
871       goto unwraperror;
872     }
873   err = gcry_cipher_decrypt (cipherhd, key, keylen, wrappedkey, wrappedkeylen);
874   if (err)
875     goto unwraperror;
876   realkeylen = gcry_sexp_canon_len (key, keylen, NULL, &err);
877   if (!realkeylen)
878     goto unwraperror; /* Invalid csexp.  */
879
880   err = gcry_sexp_sscan (&s_skey, NULL, key, realkeylen);
881   if (!err)
882     {
883       err = transfer_format_to_openpgp (s_skey, pk);
884       gcry_sexp_release (s_skey);
885     }
886
887  unwraperror:
888   xfree (key);
889   xfree (wrappedkey);
890   if (err)
891     {
892       log_error ("key %s: error receiving key from agent:"
893                  " %s%s\n", hexgrip, gpg_strerror (err),
894                  gpg_err_code (err) == GPG_ERR_FULLY_CANCELED?
895                  "":_(" - skipped"));
896     }
897   return err;
898 }
899
900
901 /* Export the keys identified by the list of strings in USERS to the
902    stream OUT.  If Secret is false public keys will be exported.  With
903    secret true secret keys will be exported; in this case 1 means the
904    entire secret keyblock and 2 only the subkeys.  OPTIONS are the
905    export options to apply.  If KEYBLOCK_OUT is not NULL, AND the exit
906    code is zero, a pointer to the first keyblock found and exported
907    will be stored at this address; no other keyblocks are exported in
908    this case.  The caller must free the returned keyblock.  If any
909    key has been exported true is stored at ANY. */
910 static int
911 do_export_stream (ctrl_t ctrl, iobuf_t out, strlist_t users, int secret,
912                   kbnode_t *keyblock_out, unsigned int options,
913                   export_stats_t stats, int *any)
914 {
915   gpg_error_t err = 0;
916   PACKET pkt;
917   KBNODE keyblock = NULL;
918   KBNODE kbctx, node;
919   size_t ndesc, descindex;
920   KEYDB_SEARCH_DESC *desc = NULL;
921   subkey_list_t subkey_list = NULL;  /* Track already processed subkeys. */
922   KEYDB_HANDLE kdbhd;
923   strlist_t sl;
924   gcry_cipher_hd_t cipherhd = NULL;
925   char *cache_nonce = NULL;
926   struct export_stats_s dummystats;
927
928   if (!stats)
929     stats = &dummystats;
930   *any = 0;
931   init_packet (&pkt);
932   kdbhd = keydb_new ();
933   if (!kdbhd)
934     return gpg_error_from_syserror ();
935
936   /* For the DANE format override the options.  */
937   if ((options & EXPORT_DANE_FORMAT))
938     options = (EXPORT_DANE_FORMAT | EXPORT_MINIMAL | EXPORT_CLEAN);
939
940
941   if (!users)
942     {
943       ndesc = 1;
944       desc = xcalloc (ndesc, sizeof *desc);
945       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
946     }
947   else
948     {
949       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
950         ;
951       desc = xmalloc ( ndesc * sizeof *desc);
952
953       for (ndesc=0, sl=users; sl; sl = sl->next)
954         {
955           if (!(err=classify_user_id (sl->d, desc+ndesc, 1)))
956             ndesc++;
957           else
958             log_error (_("key \"%s\" not found: %s\n"),
959                        sl->d, gpg_strerror (err));
960         }
961
962       keydb_disable_caching (kdbhd);  /* We are looping the search.  */
963
964       /* It would be nice to see which of the given users did actually
965          match one in the keyring.  To implement this we need to have
966          a found flag for each entry in desc.  To set this flag we
967          must check all those entries after a match to mark all
968          matched one - currently we stop at the first match.  To do
969          this we need an extra flag to enable this feature.  */
970     }
971
972 #ifdef ENABLE_SELINUX_HACKS
973   if (secret)
974     {
975       log_error (_("exporting secret keys not allowed\n"));
976       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
977       goto leave;
978     }
979 #endif
980
981   /* For secret key export we need to setup a decryption context.  */
982   if (secret)
983     {
984       void *kek = NULL;
985       size_t keklen;
986
987       err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
988       if (err)
989         {
990           log_error ("error getting the KEK: %s\n", gpg_strerror (err));
991           goto leave;
992         }
993
994       /* Prepare a cipher context.  */
995       err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
996                               GCRY_CIPHER_MODE_AESWRAP, 0);
997       if (!err)
998         err = gcry_cipher_setkey (cipherhd, kek, keklen);
999       if (err)
1000         {
1001           log_error ("error setting up an encryption context: %s\n",
1002                      gpg_strerror (err));
1003           goto leave;
1004         }
1005       xfree (kek);
1006       kek = NULL;
1007     }
1008
1009   for (;;)
1010     {
1011       int skip_until_subkey = 0;
1012       u32 keyid[2];
1013       PKT_public_key *pk;
1014
1015       err = keydb_search (kdbhd, desc, ndesc, &descindex);
1016       if (!users)
1017         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1018       if (err)
1019         break;
1020
1021       /* Read the keyblock. */
1022       release_kbnode (keyblock);
1023       keyblock = NULL;
1024       err = keydb_get_keyblock (kdbhd, &keyblock);
1025       if (err)
1026         {
1027           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
1028           goto leave;
1029         }
1030
1031       node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1032       if (!node)
1033         {
1034           log_error ("public key packet not found in keyblock - skipped\n");
1035           continue;
1036         }
1037       stats->count++;
1038       setup_main_keyids (keyblock);  /* gpg_format_keydesc needs it.  */
1039       pk = node->pkt->pkt.public_key;
1040       keyid_from_pk (pk, keyid);
1041
1042       /* If a secret key export is required we need to check whether
1043          we have a secret key at all and if so create the seckey_info
1044          structure.  */
1045       if (secret)
1046         {
1047           if (agent_probe_any_secret_key (ctrl, keyblock))
1048             continue;  /* No secret key (neither primary nor subkey).  */
1049
1050           /* No v3 keys with GNU mode 1001. */
1051           if (secret == 2 && pk->version == 3)
1052             {
1053               log_info (_("key %s: PGP 2.x style key - skipped\n"),
1054                         keystr (keyid));
1055               continue;
1056             }
1057
1058           /* The agent does not yet allow to export v3 packets.  It is
1059              actually questionable whether we should allow them at
1060              all.  */
1061           if (pk->version == 3)
1062             {
1063               log_info ("key %s: PGP 2.x style key (v3) export "
1064                         "not yet supported - skipped\n", keystr (keyid));
1065               continue;
1066             }
1067           stats->secret_count++;
1068         }
1069
1070       /* Always do the cleaning on the public key part if requested.
1071          Note that we don't yet set this option if we are exporting
1072          secret keys.  Note that both export-clean and export-minimal
1073          only apply to UID sigs (0x10, 0x11, 0x12, and 0x13).  A
1074          designated revocation is never stripped, even with
1075          export-minimal set.  */
1076       if ((options & EXPORT_CLEAN))
1077         clean_key (keyblock, opt.verbose, (options&EXPORT_MINIMAL), NULL, NULL);
1078
1079       /* And write it. */
1080       xfree (cache_nonce);
1081       cache_nonce = NULL;
1082       for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1083         {
1084           if (skip_until_subkey)
1085             {
1086               if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1087                 skip_until_subkey = 0;
1088               else
1089                 continue;
1090             }
1091
1092           /* We used to use comment packets, but not any longer.  In
1093              case we still have comments on a key, strip them here
1094              before we call build_packet(). */
1095           if (node->pkt->pkttype == PKT_COMMENT)
1096             continue;
1097
1098           /* Make sure that ring_trust packets never get exported. */
1099           if (node->pkt->pkttype == PKT_RING_TRUST)
1100             continue;
1101
1102           /* If exact is set, then we only export what was requested
1103              (plus the primary key, if the user didn't specifically
1104              request it). */
1105           if (desc[descindex].exact
1106               && node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1107             {
1108               if (!exact_subkey_match_p (desc+descindex, node))
1109                 {
1110                   /* Before skipping this subkey, check whether any
1111                      other description wants an exact match on a
1112                      subkey and include that subkey into the output
1113                      too.  Need to add this subkey to a list so that
1114                      it won't get processed a second time.
1115
1116                      So the first step here is to check that list and
1117                      skip in any case if the key is in that list.
1118
1119                      We need this whole mess because the import
1120                      function of GnuPG < 2.1 is not able to merge
1121                      secret keys and thus it is useless to output them
1122                      as two separate keys and have import merge them.  */
1123                   if (subkey_in_list_p (subkey_list, node))
1124                     skip_until_subkey = 1; /* Already processed this one. */
1125                   else
1126                     {
1127                       size_t j;
1128
1129                       for (j=0; j < ndesc; j++)
1130                         if (j != descindex && desc[j].exact
1131                             && exact_subkey_match_p (desc+j, node))
1132                           break;
1133                       if (!(j < ndesc))
1134                         skip_until_subkey = 1; /* No other one matching. */
1135                     }
1136                 }
1137
1138               if(skip_until_subkey)
1139                 continue;
1140
1141               /* Mark this one as processed. */
1142               {
1143                 subkey_list_t tmp = new_subkey_list_item (node);
1144                 tmp->next = subkey_list;
1145                 subkey_list = tmp;
1146               }
1147             }
1148
1149           if (node->pkt->pkttype == PKT_SIGNATURE)
1150             {
1151               /* Do not export packets which are marked as not
1152                  exportable.  */
1153               if (!(options&EXPORT_LOCAL_SIGS)
1154                   && !node->pkt->pkt.signature->flags.exportable)
1155                 continue; /* not exportable */
1156
1157               /* Do not export packets with a "sensitive" revocation
1158                  key unless the user wants us to.  Note that we do
1159                  export these when issuing the actual revocation
1160                  (see revoke.c). */
1161               if (!(options&EXPORT_SENSITIVE_REVKEYS)
1162                   && node->pkt->pkt.signature->revkey)
1163                 {
1164                   int i;
1165
1166                   for (i=0;i<node->pkt->pkt.signature->numrevkeys;i++)
1167                     if ( (node->pkt->pkt.signature->revkey[i].class & 0x40))
1168                       break;
1169
1170                   if (i < node->pkt->pkt.signature->numrevkeys)
1171                     continue;
1172                 }
1173             }
1174
1175           /* Don't export attribs? */
1176           if (!(options&EXPORT_ATTRIBUTES)
1177               && node->pkt->pkttype == PKT_USER_ID
1178               && node->pkt->pkt.user_id->attrib_data )
1179             {
1180               /* Skip until we get to something that is not an attrib
1181                  or a signature on an attrib */
1182               while (kbctx->next && kbctx->next->pkt->pkttype==PKT_SIGNATURE)
1183                 kbctx = kbctx->next;
1184
1185               continue;
1186             }
1187
1188           if (secret && (node->pkt->pkttype == PKT_PUBLIC_KEY
1189                          || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1190             {
1191               u32 subkidbuf[2], *subkid;
1192               char *hexgrip, *serialno;
1193
1194               pk = node->pkt->pkt.public_key;
1195               if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1196                 subkid = NULL;
1197               else
1198                 {
1199                   keyid_from_pk (pk, subkidbuf);
1200                   subkid = subkidbuf;
1201                 }
1202
1203               if (pk->seckey_info)
1204                 {
1205                   log_error ("key %s: oops: seckey_info already set"
1206                              " - skipped\n", keystr_with_sub (keyid, subkid));
1207                   skip_until_subkey = 1;
1208                   continue;
1209                 }
1210
1211               err = hexkeygrip_from_pk (pk, &hexgrip);
1212               if (err)
1213                 {
1214                   log_error ("key %s: error computing keygrip: %s"
1215                              " - skipped\n", keystr_with_sub (keyid, subkid),
1216                              gpg_strerror (err));
1217                   skip_until_subkey = 1;
1218                   err = 0;
1219                   continue;
1220                 }
1221
1222               if (secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1223                 {
1224                   /* We are asked not to export the secret parts of
1225                      the primary key.  Make up an error code to create
1226                      the stub.  */
1227                   err = GPG_ERR_NOT_FOUND;
1228                   serialno = NULL;
1229                 }
1230               else
1231                 err = agent_get_keyinfo (ctrl, hexgrip, &serialno);
1232
1233               if ((!err && serialno)
1234                   && secret == 2 && node->pkt->pkttype == PKT_PUBLIC_KEY)
1235                 {
1236                   /* It does not make sense to export a key with its
1237                      primary key on card using a non-key stub.  Thus
1238                      we skip those keys when used with
1239                      --export-secret-subkeys. */
1240                   log_info (_("key %s: key material on-card - skipped\n"),
1241                             keystr_with_sub (keyid, subkid));
1242                   skip_until_subkey = 1;
1243                 }
1244               else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND
1245                        || (!err && serialno))
1246                 {
1247                   /* Create a key stub.  */
1248                   struct seckey_info *ski;
1249                   const char *s;
1250
1251                   pk->seckey_info = ski = xtrycalloc (1, sizeof *ski);
1252                   if (!ski)
1253                     {
1254                       err = gpg_error_from_syserror ();
1255                       xfree (hexgrip);
1256                       goto leave;
1257                     }
1258
1259                   ski->is_protected = 1;
1260                   if (err)
1261                     ski->s2k.mode = 1001; /* GNU dummy (no secret key).  */
1262                   else
1263                     {
1264                       ski->s2k.mode = 1002; /* GNU-divert-to-card.  */
1265                       for (s=serialno; sizeof (ski->ivlen) && *s && s[1];
1266                            ski->ivlen++, s += 2)
1267                         ski->iv[ski->ivlen] = xtoi_2 (s);
1268                     }
1269
1270                   err = build_packet (out, node->pkt);
1271                   if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1272                     {
1273                       stats->exported++;
1274                       print_status_exported (node->pkt->pkt.public_key);
1275                     }
1276                 }
1277               else if (!err)
1278                 {
1279                   err = receive_seckey_from_agent (ctrl, cipherhd, &cache_nonce,
1280                                                    hexgrip, pk);
1281                   if (err)
1282                     {
1283                       if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1284                         goto leave;
1285                       skip_until_subkey = 1;
1286                       err = 0;
1287                     }
1288                   else
1289                     {
1290                       err = build_packet (out, node->pkt);
1291                       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1292                         {
1293                           stats->exported++;
1294                           print_status_exported (node->pkt->pkt.public_key);
1295                         }
1296                     }
1297                 }
1298               else
1299                 {
1300                   log_error ("key %s: error getting keyinfo from agent: %s"
1301                              " - skipped\n", keystr_with_sub (keyid, subkid),
1302                              gpg_strerror (err));
1303                   skip_until_subkey = 1;
1304                   err = 0;
1305                 }
1306
1307               xfree (pk->seckey_info);
1308               pk->seckey_info = NULL;
1309               xfree (hexgrip);
1310             }
1311           else
1312             {
1313               err = build_packet (out, node->pkt);
1314               if (!err && node->pkt->pkttype == PKT_PUBLIC_KEY)
1315                 {
1316                   stats->exported++;
1317                   print_status_exported (node->pkt->pkt.public_key);
1318                 }
1319             }
1320
1321
1322           if (err)
1323             {
1324               log_error ("build_packet(%d) failed: %s\n",
1325                          node->pkt->pkttype, gpg_strerror (err));
1326               goto leave;
1327             }
1328
1329           if (!skip_until_subkey)
1330             *any = 1;
1331         }
1332
1333       if (keyblock_out)
1334         {
1335           *keyblock_out = keyblock;
1336           break;
1337         }
1338     }
1339   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1340     err = 0;
1341
1342  leave:
1343   gcry_cipher_close (cipherhd);
1344   release_subkey_list (subkey_list);
1345   xfree(desc);
1346   keydb_release (kdbhd);
1347   if (err || !keyblock_out)
1348     release_kbnode( keyblock );
1349   xfree (cache_nonce);
1350   if( !*any )
1351     log_info(_("WARNING: nothing exported\n"));
1352   return err;
1353 }
1354
1355
1356
1357 \f
1358 static gpg_error_t
1359 key_to_sshblob (membuf_t *mb, const char *identifier, ...)
1360 {
1361   va_list arg_ptr;
1362   gpg_error_t err = 0;
1363   unsigned char nbuf[4];
1364   unsigned char *buf;
1365   size_t buflen;
1366   gcry_mpi_t a;
1367
1368   ulongtobuf (nbuf, (ulong)strlen (identifier));
1369   put_membuf (mb, nbuf, 4);
1370   put_membuf_str (mb, identifier);
1371   if (!strncmp (identifier, "ecdsa-sha2-", 11))
1372     {
1373       ulongtobuf (nbuf, (ulong)strlen (identifier+11));
1374       put_membuf (mb, nbuf, 4);
1375       put_membuf_str (mb, identifier+11);
1376     }
1377   va_start (arg_ptr, identifier);
1378   while ((a = va_arg (arg_ptr, gcry_mpi_t)))
1379     {
1380       err = gcry_mpi_aprint (GCRYMPI_FMT_SSH, &buf, &buflen, a);
1381       if (err)
1382         break;
1383       if (!strcmp (identifier, "ssh-ed25519")
1384           && buflen > 5 && buf[4] == 0x40)
1385         {
1386           /* We need to strip our 0x40 prefix.  */
1387           put_membuf (mb, "\x00\x00\x00\x20", 4);
1388           put_membuf (mb, buf+5, buflen-5);
1389         }
1390       else
1391         put_membuf (mb, buf, buflen);
1392       gcry_free (buf);
1393     }
1394   va_end (arg_ptr);
1395   return err;
1396 }
1397
1398 /* Export the key identified by USERID in the SSH public key format.
1399    The function exports the latest subkey with Authentication
1400    capability unless the '!' suffix is used to export a specific
1401    key.  */
1402 gpg_error_t
1403 export_ssh_key (ctrl_t ctrl, const char *userid)
1404 {
1405   gpg_error_t err;
1406   kbnode_t keyblock = NULL;
1407   KEYDB_SEARCH_DESC desc;
1408   u32 latest_date;
1409   u32 curtime = make_timestamp ();
1410   kbnode_t latest_key, node;
1411   PKT_public_key *pk;
1412   const char *identifier;
1413   membuf_t mb;
1414   estream_t fp = NULL;
1415   struct b64state b64_state;
1416   const char *fname = "-";
1417
1418   init_membuf (&mb, 4096);
1419
1420   /* We need to know whether the key has been specified using the
1421      exact syntax ('!' suffix).  Thus we need to run a
1422      classify_user_id on our own.  */
1423   err = classify_user_id (userid, &desc, 1);
1424
1425   /* Get the public key.  */
1426   if (!err)
1427     {
1428       getkey_ctx_t getkeyctx;
1429
1430       err = get_pubkey_byname (ctrl, &getkeyctx, NULL, userid, &keyblock,
1431                                NULL,
1432                                0  /* Only usable keys or given exact. */,
1433                                1  /* No AKL lookup.  */);
1434       if (!err)
1435         {
1436           err = getkey_next (getkeyctx, NULL, NULL);
1437           if (!err)
1438             err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
1439           else if (gpg_err_code (err) == GPG_ERR_NO_PUBKEY)
1440             err = 0;
1441         }
1442       getkey_end (getkeyctx);
1443     }
1444   if (err)
1445     {
1446       log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
1447       return err;
1448     }
1449
1450   /* The finish_lookup code in getkey.c does not handle auth keys,
1451      thus we have to duplicate the code here to find the latest
1452      subkey.  However, if the key has been found using an exact match
1453      ('!' notation) we use that key without any further checks and
1454      even allow the use of the primary key. */
1455   latest_date = 0;
1456   latest_key = NULL;
1457   for (node = keyblock; node; node = node->next)
1458     {
1459       if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1460            || node->pkt->pkttype == PKT_PUBLIC_KEY)
1461           && node->pkt->pkt.public_key->flags.exact)
1462         {
1463           latest_key = node;
1464           break;
1465         }
1466     }
1467   if (!latest_key)
1468     {
1469       for (node = keyblock; node; node = node->next)
1470         {
1471           if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
1472             continue;
1473
1474           pk = node->pkt->pkt.public_key;
1475           if (DBG_LOOKUP)
1476             log_debug ("\tchecking subkey %08lX\n",
1477                        (ulong) keyid_from_pk (pk, NULL));
1478           if (!(pk->pubkey_usage & PUBKEY_USAGE_AUTH))
1479             {
1480               if (DBG_LOOKUP)
1481                 log_debug ("\tsubkey not usable for authentication\n");
1482               continue;
1483             }
1484           if (!pk->flags.valid)
1485             {
1486               if (DBG_LOOKUP)
1487                 log_debug ("\tsubkey not valid\n");
1488               continue;
1489             }
1490           if (pk->flags.revoked)
1491             {
1492               if (DBG_LOOKUP)
1493                 log_debug ("\tsubkey has been revoked\n");
1494               continue;
1495             }
1496           if (pk->has_expired)
1497             {
1498               if (DBG_LOOKUP)
1499                 log_debug ("\tsubkey has expired\n");
1500               continue;
1501             }
1502           if (pk->timestamp > curtime && !opt.ignore_valid_from)
1503             {
1504               if (DBG_LOOKUP)
1505                 log_debug ("\tsubkey not yet valid\n");
1506               continue;
1507             }
1508           if (DBG_LOOKUP)
1509             log_debug ("\tsubkey might be fine\n");
1510           /* In case a key has a timestamp of 0 set, we make sure that it
1511              is used.  A better change would be to compare ">=" but that
1512              might also change the selected keys and is as such a more
1513              intrusive change.  */
1514           if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
1515             {
1516               latest_date = pk->timestamp;
1517               latest_key = node;
1518             }
1519         }
1520     }
1521
1522   if (!latest_key)
1523     {
1524       err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1525       log_error (_("key \"%s\" not found: %s\n"), userid, gpg_strerror (err));
1526       goto leave;
1527     }
1528
1529   pk = latest_key->pkt->pkt.public_key;
1530   if (DBG_LOOKUP)
1531     log_debug ("\tusing key %08lX\n", (ulong) keyid_from_pk (pk, NULL));
1532
1533   switch (pk->pubkey_algo)
1534     {
1535     case PUBKEY_ALGO_DSA:
1536       identifier = "ssh-dss";
1537       err = key_to_sshblob (&mb, identifier,
1538                             pk->pkey[0], pk->pkey[1], pk->pkey[2], pk->pkey[3],
1539                             NULL);
1540       break;
1541
1542     case PUBKEY_ALGO_RSA:
1543     case PUBKEY_ALGO_RSA_S:
1544       identifier = "ssh-rsa";
1545       err = key_to_sshblob (&mb, identifier, pk->pkey[1], pk->pkey[0], NULL);
1546       break;
1547
1548     case PUBKEY_ALGO_ECDSA:
1549       {
1550         char *curveoid;
1551         const char *curve;
1552
1553         curveoid = openpgp_oid_to_str (pk->pkey[0]);
1554         if (!curveoid)
1555           err = gpg_error_from_syserror ();
1556         else if (!(curve = openpgp_oid_to_curve (curveoid, 0)))
1557           err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1558         else
1559           {
1560             if (!strcmp (curve, "nistp256"))
1561               identifier = "ecdsa-sha2-nistp256";
1562             else if (!strcmp (curve, "nistp384"))
1563               identifier = "ecdsa-sha2-nistp384";
1564             else if (!strcmp (curve, "nistp521"))
1565               identifier = "ecdsa-sha2-nistp521";
1566             else
1567               identifier = NULL;
1568
1569             if (!identifier)
1570               err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1571             else
1572               err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
1573           }
1574         xfree (curveoid);
1575       }
1576       break;
1577
1578     case PUBKEY_ALGO_EDDSA:
1579       if (!openpgp_oid_is_ed25519 (pk->pkey[0]))
1580         err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
1581       else
1582         {
1583           identifier = "ssh-ed25519";
1584           err = key_to_sshblob (&mb, identifier, pk->pkey[1], NULL);
1585         }
1586       break;
1587
1588     case PUBKEY_ALGO_ELGAMAL_E:
1589     case PUBKEY_ALGO_ELGAMAL:
1590       err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1591       break;
1592
1593     default:
1594       err = GPG_ERR_PUBKEY_ALGO;
1595       break;
1596     }
1597
1598   if (err)
1599     goto leave;
1600
1601   if (opt.outfile && *opt.outfile && strcmp (opt.outfile, "-"))
1602     fp = es_fopen ((fname = opt.outfile), "w");
1603   else
1604     fp = es_stdout;
1605   if (!fp)
1606     {
1607       err = gpg_error_from_syserror ();
1608       log_error (_("error creating '%s': %s\n"), fname, gpg_strerror (err));
1609       goto leave;
1610     }
1611
1612   es_fprintf (fp, "%s ", identifier);
1613   err = b64enc_start_es (&b64_state, fp, "");
1614   if (err)
1615     goto leave;
1616   {
1617     void *blob;
1618     size_t bloblen;
1619
1620     blob = get_membuf (&mb, &bloblen);
1621     if (!blob)
1622       err = gpg_error_from_syserror ();
1623     else
1624       err = b64enc_write (&b64_state, blob, bloblen);
1625     xfree (blob);
1626     if (err)
1627       goto leave;
1628   }
1629   err = b64enc_finish (&b64_state);
1630   if (err)
1631     goto leave;
1632   es_fprintf (fp, " openpgp:0x%08lX\n", (ulong)keyid_from_pk (pk, NULL));
1633
1634   if (es_ferror (fp))
1635     err = gpg_error_from_syserror ();
1636   else
1637     {
1638       if (es_fclose (fp))
1639         err = gpg_error_from_syserror ();
1640       fp = NULL;
1641     }
1642
1643   if (err)
1644     log_error (_("error writing '%s': %s\n"), fname, gpg_strerror (err));
1645
1646  leave:
1647   es_fclose (fp);
1648   xfree (get_membuf (&mb, NULL));
1649   release_kbnode (keyblock);
1650   return err;
1651 }