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