Imported Upstream version 2.2.13
[platform/upstream/gpg2.git] / agent / findkey.c
1 /* findkey.c - Locate the secret key
2  * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007,
3  *               2010, 2011 Free Software Foundation, Inc.
4  * Copyright (C) 2014 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 <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <fcntl.h>
29 #include <assert.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <assert.h>
33 #include <npth.h> /* (we use pth_sleep) */
34
35 #include "agent.h"
36 #include "../common/i18n.h"
37 #include "../common/ssh-utils.h"
38 #include "../common/name-value.h"
39
40 #ifndef O_BINARY
41 #define O_BINARY 0
42 #endif
43
44 /* Helper to pass data to the check callback of the unprotect function. */
45 struct try_unprotect_arg_s
46 {
47   ctrl_t ctrl;
48   const unsigned char *protected_key;
49   unsigned char *unprotected_key;
50   int change_required; /* Set by the callback to indicate that the
51                           user should change the passphrase.  */
52 };
53
54
55 /* Note: Ownership of FNAME and FP are moved to this function.  */
56 static gpg_error_t
57 write_extended_private_key (char *fname, estream_t fp, int update,
58                             const void *buf, size_t len)
59 {
60   gpg_error_t err;
61   nvc_t pk = NULL;
62   gcry_sexp_t key = NULL;
63   int remove = 0;
64
65   if (update)
66     {
67       int line;
68
69       err = nvc_parse_private_key (&pk, &line, fp);
70       if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
71         {
72           log_error ("error parsing '%s' line %d: %s\n",
73                      fname, line, gpg_strerror (err));
74           goto leave;
75         }
76     }
77   else
78     {
79       pk = nvc_new_private_key ();
80       if (!pk)
81         {
82           err = gpg_error_from_syserror ();
83           goto leave;
84         }
85     }
86   es_clearerr (fp);
87
88   err = gcry_sexp_sscan (&key, NULL, buf, len);
89   if (err)
90     goto leave;
91
92   err = nvc_set_private_key (pk, key);
93   if (err)
94     goto leave;
95
96   err = es_fseek (fp, 0, SEEK_SET);
97   if (err)
98     goto leave;
99
100   err = nvc_write (pk, fp);
101   if (err)
102     {
103       log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
104       remove = 1;
105       goto leave;
106     }
107
108   if (ftruncate (es_fileno (fp), es_ftello (fp)))
109     {
110       err = gpg_error_from_syserror ();
111       log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
112       remove = 1;
113       goto leave;
114     }
115
116   if (es_fclose (fp))
117     {
118       err = gpg_error_from_syserror ();
119       log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
120       remove = 1;
121       goto leave;
122     }
123   else
124     fp = NULL;
125
126   bump_key_eventcounter ();
127
128  leave:
129   es_fclose (fp);
130   if (remove)
131     gnupg_remove (fname);
132   xfree (fname);
133   gcry_sexp_release (key);
134   nvc_release (pk);
135   return err;
136 }
137
138 /* Write an S-expression formatted key to our key storage.  With FORCE
139    passed as true an existing key with the given GRIP will get
140    overwritten.  */
141 int
142 agent_write_private_key (const unsigned char *grip,
143                          const void *buffer, size_t length, int force)
144 {
145   char *fname;
146   estream_t fp;
147   char hexgrip[40+4+1];
148
149   bin2hex (grip, 20, hexgrip);
150   strcpy (hexgrip+40, ".key");
151
152   fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
153                          hexgrip, NULL);
154
155   /* FIXME: Write to a temp file first so that write failures during
156      key updates won't lead to a key loss.  */
157
158   if (!force && !access (fname, F_OK))
159     {
160       log_error ("secret key file '%s' already exists\n", fname);
161       xfree (fname);
162       return gpg_error (GPG_ERR_EEXIST);
163     }
164
165   fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
166   if (!fp)
167     {
168       gpg_error_t tmperr = gpg_error_from_syserror ();
169
170       if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
171         {
172           fp = es_fopen (fname, "wbx,mode=-rw");
173           if (!fp)
174             tmperr = gpg_error_from_syserror ();
175         }
176       if (!fp)
177         {
178           log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
179           xfree (fname);
180           return tmperr;
181         }
182     }
183   else if (force)
184     {
185       gpg_error_t rc;
186       char first;
187
188       /* See if an existing key is in extended format.  */
189       if (es_fread (&first, 1, 1, fp) != 1)
190         {
191           rc = gpg_error_from_syserror ();
192           log_error ("error reading first byte from '%s': %s\n",
193                      fname, strerror (errno));
194           xfree (fname);
195           es_fclose (fp);
196           return rc;
197         }
198
199       rc = es_fseek (fp, 0, SEEK_SET);
200       if (rc)
201         {
202           log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
203           xfree (fname);
204           es_fclose (fp);
205           return rc;
206         }
207
208       if (first != '(')
209         {
210           /* Key is already in the extended format.  */
211           return write_extended_private_key (fname, fp, 1, buffer, length);
212         }
213       if (first == '(' && opt.enable_extended_key_format)
214         {
215           /* Key is in the old format - but we want the extended format.  */
216           return write_extended_private_key (fname, fp, 0, buffer, length);
217         }
218     }
219
220   if (opt.enable_extended_key_format)
221     return write_extended_private_key (fname, fp, 0, buffer, length);
222
223   if (es_fwrite (buffer, length, 1, fp) != 1)
224     {
225       gpg_error_t tmperr = gpg_error_from_syserror ();
226       log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
227       es_fclose (fp);
228       gnupg_remove (fname);
229       xfree (fname);
230       return tmperr;
231     }
232
233   /* When force is given, the file might have to be truncated.  */
234   if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
235     {
236       gpg_error_t tmperr = gpg_error_from_syserror ();
237       log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
238       es_fclose (fp);
239       gnupg_remove (fname);
240       xfree (fname);
241       return tmperr;
242     }
243
244   if (es_fclose (fp))
245     {
246       gpg_error_t tmperr = gpg_error_from_syserror ();
247       log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
248       gnupg_remove (fname);
249       xfree (fname);
250       return tmperr;
251     }
252   bump_key_eventcounter ();
253   xfree (fname);
254   return 0;
255 }
256
257
258 /* Callback function to try the unprotection from the passphrase query
259    code. */
260 static gpg_error_t
261 try_unprotect_cb (struct pin_entry_info_s *pi)
262 {
263   struct try_unprotect_arg_s *arg = pi->check_cb_arg;
264   ctrl_t ctrl = arg->ctrl;
265   size_t dummy;
266   gpg_error_t err;
267   gnupg_isotime_t now, protected_at, tmptime;
268   char *desc = NULL;
269
270   assert (!arg->unprotected_key);
271
272   arg->change_required = 0;
273   err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
274                          &arg->unprotected_key, &dummy);
275   if (err)
276     return err;
277   if (!opt.max_passphrase_days || ctrl->in_passwd)
278     return 0;  /* No regular passphrase change required.  */
279
280   if (!*protected_at)
281     {
282       /* No protection date known - must force passphrase change.  */
283       desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
284                             "Please change it now."));
285       if (!desc)
286         return gpg_error_from_syserror ();
287     }
288   else
289     {
290       gnupg_get_isotime (now);
291       gnupg_copy_time (tmptime, protected_at);
292       err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
293       if (err)
294         return err;
295       if (strcmp (now, tmptime) > 0 )
296         {
297           /* Passphrase "expired".  */
298           desc = xtryasprintf
299             (L_("This passphrase has not been changed%%0A"
300                 "since %.4s-%.2s-%.2s.  Please change it now."),
301              protected_at, protected_at+4, protected_at+6);
302           if (!desc)
303             return gpg_error_from_syserror ();
304         }
305     }
306
307   if (desc)
308     {
309       /* Change required.  */
310       if (opt.enforce_passphrase_constraints)
311         {
312           err = agent_get_confirmation (ctrl, desc,
313                                         L_("Change passphrase"), NULL, 0);
314           if (!err)
315             arg->change_required = 1;
316         }
317       else
318         {
319           err = agent_get_confirmation (ctrl, desc,
320                                         L_("Change passphrase"),
321                                         L_("I'll change it later"), 0);
322           if (!err)
323             arg->change_required = 1;
324           else if (gpg_err_code (err) == GPG_ERR_CANCELED
325                    || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
326             err = 0;
327         }
328       xfree (desc);
329     }
330
331   return err;
332 }
333
334
335 /* Modify a Key description, replacing certain special format
336    characters.  List of currently supported replacements:
337
338    %% - Replaced by a single %
339    %c - Replaced by the content of COMMENT.
340    %C - Same as %c but put into parentheses.
341    %F - Replaced by an ssh style fingerprint computed from KEY.
342
343    The functions returns 0 on success or an error code.  On success a
344    newly allocated string is stored at the address of RESULT.
345  */
346 gpg_error_t
347 agent_modify_description (const char *in, const char *comment,
348                           const gcry_sexp_t key, char **result)
349 {
350   size_t comment_length;
351   size_t in_len;
352   size_t out_len;
353   char *out;
354   size_t i;
355   int special, pass;
356   char *ssh_fpr = NULL;
357   char *p;
358
359   *result = NULL;
360
361   if (!comment)
362     comment = "";
363
364   comment_length = strlen (comment);
365   in_len  = strlen (in);
366
367   /* First pass calculates the length, second pass does the actual
368      copying.  */
369   /* FIXME: This can be simplified by using es_fopenmem.  */
370   out = NULL;
371   out_len = 0;
372   for (pass=0; pass < 2; pass++)
373     {
374       special = 0;
375       for (i = 0; i < in_len; i++)
376         {
377           if (special)
378             {
379               special = 0;
380               switch (in[i])
381                 {
382                 case '%':
383                   if (out)
384                     *out++ = '%';
385                   else
386                     out_len++;
387                   break;
388
389                 case 'c': /* Comment.  */
390                   if (out)
391                     {
392                       memcpy (out, comment, comment_length);
393                       out += comment_length;
394                     }
395                   else
396                     out_len += comment_length;
397                   break;
398
399                 case 'C': /* Comment.  */
400                   if (!comment_length)
401                     ;
402                   else if (out)
403                     {
404                       *out++ = '(';
405                       memcpy (out, comment, comment_length);
406                       out += comment_length;
407                       *out++ = ')';
408                     }
409                   else
410                     out_len += comment_length + 2;
411                   break;
412
413                 case 'F': /* SSH style fingerprint.  */
414                   if (!ssh_fpr && key)
415                     ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
416                                                 &ssh_fpr);
417                   if (ssh_fpr)
418                     {
419                       if (out)
420                         out = stpcpy (out, ssh_fpr);
421                       else
422                         out_len += strlen (ssh_fpr);
423                     }
424                   break;
425
426                 default: /* Invalid special sequences are kept as they are. */
427                   if (out)
428                     {
429                       *out++ = '%';
430                       *out++ = in[i];
431                     }
432                   else
433                     out_len+=2;
434                   break;
435                 }
436             }
437           else if (in[i] == '%')
438             special = 1;
439           else
440             {
441               if (out)
442                 *out++ = in[i];
443               else
444                 out_len++;
445             }
446         }
447
448       if (!pass)
449         {
450           *result = out = xtrymalloc (out_len + 1);
451           if (!out)
452             {
453               xfree (ssh_fpr);
454               return gpg_error_from_syserror ();
455             }
456         }
457     }
458
459   *out = 0;
460   log_assert (*result + out_len == out);
461   xfree (ssh_fpr);
462
463   /* The ssh prompt may sometimes end in
464    *    "...%0A  ()"
465    * The empty parentheses doesn't look very good.  We use this hack
466    * here to remove them as well as the indentation spaces. */
467   p = *result;
468   i = strlen (p);
469   if (i > 2 && !strcmp (p + i - 2, "()"))
470     {
471       p += i - 2;
472       *p-- = 0;
473       while (p > *result && spacep (p))
474         *p-- = 0;
475     }
476
477   return 0;
478 }
479
480
481
482 /* Unprotect the canconical encoded S-expression key in KEYBUF.  GRIP
483    should be the hex encoded keygrip of that key to be used with the
484    caching mechanism. DESC_TEXT may be set to override the default
485    description used for the pinentry.  If LOOKUP_TTL is given this
486    function is used to lookup the default ttl.  If R_PASSPHRASE is not
487    NULL, the function succeeded and the key was protected the used
488    passphrase (entered or from the cache) is stored there; if not NULL
489    will be stored.  The caller needs to free the returned
490    passphrase. */
491 static gpg_error_t
492 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
493            unsigned char **keybuf, const unsigned char *grip,
494            cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
495            char **r_passphrase)
496 {
497   struct pin_entry_info_s *pi;
498   struct try_unprotect_arg_s arg;
499   int rc;
500   unsigned char *result;
501   size_t resultlen;
502   char hexgrip[40+1];
503
504   if (r_passphrase)
505     *r_passphrase = NULL;
506
507   bin2hex (grip, 20, hexgrip);
508
509   /* Initially try to get it using a cache nonce.  */
510   if (cache_nonce)
511     {
512       char *pw;
513
514       pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
515       if (pw)
516         {
517           rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
518           if (!rc)
519             {
520               if (r_passphrase)
521                 *r_passphrase = pw;
522               else
523                 xfree (pw);
524               xfree (*keybuf);
525               *keybuf = result;
526               return 0;
527             }
528           xfree (pw);
529         }
530     }
531
532   /* First try to get it from the cache - if there is none or we can't
533      unprotect it, we fall back to ask the user */
534   if (cache_mode != CACHE_MODE_IGNORE)
535     {
536       char *pw;
537
538     retry:
539       pw = agent_get_cache (ctrl, hexgrip, cache_mode);
540       if (pw)
541         {
542           rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
543           if (!rc)
544             {
545               if (cache_mode == CACHE_MODE_NORMAL)
546                 agent_store_cache_hit (hexgrip);
547               if (r_passphrase)
548                 *r_passphrase = pw;
549               else
550                 xfree (pw);
551               xfree (*keybuf);
552               *keybuf = result;
553               return 0;
554             }
555           xfree (pw);
556         }
557       else if (cache_mode == CACHE_MODE_NORMAL)
558         {
559           /* The standard use of GPG keys is to have a signing and an
560              encryption subkey.  Commonly both use the same
561              passphrase.  We try to help the user to enter the
562              passphrase only once by silently trying the last
563              correctly entered passphrase.  Checking one additional
564              passphrase should be acceptable; despite the S2K
565              introduced delays. The assumed workflow is:
566
567                1. Read encrypted message in a MUA and thus enter a
568                   passphrase for the encryption subkey.
569
570                2. Reply to that mail with an encrypted and signed
571                   mail, thus entering the passphrase for the signing
572                   subkey.
573
574              We can often avoid the passphrase entry in the second
575              step.  We do this only in normal mode, so not to
576              interfere with unrelated cache entries.  */
577           pw = agent_get_cache (ctrl, NULL, cache_mode);
578           if (pw)
579             {
580               rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
581                                     &result, &resultlen);
582               if (!rc)
583                 {
584                   if (r_passphrase)
585                     *r_passphrase = pw;
586                   else
587                     xfree (pw);
588                   xfree (*keybuf);
589                   *keybuf = result;
590                   return 0;
591                 }
592               xfree (pw);
593             }
594         }
595
596       /* If the pinentry is currently in use, we wait up to 60 seconds
597          for it to close and check the cache again.  This solves a common
598          situation where several requests for unprotecting a key have
599          been made but the user is still entering the passphrase for
600          the first request.  Because all requests to agent_askpin are
601          serialized they would then pop up one after the other to
602          request the passphrase - despite that the user has already
603          entered it and is then available in the cache.  This
604          implementation is not race free but in the worst case the
605          user has to enter the passphrase only once more. */
606       if (pinentry_active_p (ctrl, 0))
607         {
608           /* Active - wait */
609           if (!pinentry_active_p (ctrl, 60))
610             {
611               /* We need to give the other thread a chance to actually put
612                  it into the cache. */
613               npth_sleep (1);
614               goto retry;
615             }
616           /* Timeout - better call pinentry now the plain way. */
617         }
618     }
619
620   pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
621   if (!pi)
622     return gpg_error_from_syserror ();
623   pi->max_length = MAX_PASSPHRASE_LEN + 1;
624   pi->min_digits = 0;  /* we want a real passphrase */
625   pi->max_digits = 16;
626   pi->max_tries = 3;
627   pi->check_cb = try_unprotect_cb;
628   arg.ctrl = ctrl;
629   arg.protected_key = *keybuf;
630   arg.unprotected_key = NULL;
631   arg.change_required = 0;
632   pi->check_cb_arg = &arg;
633
634   rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
635   if (rc)
636     {
637       if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE))
638         {
639           log_error ("Clearing pinentry cache which caused error %s\n",
640                      gpg_strerror (rc));
641
642           agent_clear_passphrase (ctrl, hexgrip, cache_mode);
643         }
644     }
645   else
646     {
647       assert (arg.unprotected_key);
648       if (arg.change_required)
649         {
650           /* The callback told as that the user should change their
651              passphrase.  Present the dialog to do.  */
652           size_t canlen, erroff;
653           gcry_sexp_t s_skey;
654
655           assert (arg.unprotected_key);
656           canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
657           rc = gcry_sexp_sscan (&s_skey, &erroff,
658                                 (char*)arg.unprotected_key, canlen);
659           if (rc)
660             {
661               log_error ("failed to build S-Exp (off=%u): %s\n",
662                          (unsigned int)erroff, gpg_strerror (rc));
663               wipememory (arg.unprotected_key, canlen);
664               xfree (arg.unprotected_key);
665               xfree (pi);
666               return rc;
667             }
668           rc = agent_protect_and_store (ctrl, s_skey, NULL);
669           gcry_sexp_release (s_skey);
670           if (rc)
671             {
672               log_error ("changing the passphrase failed: %s\n",
673                          gpg_strerror (rc));
674               wipememory (arg.unprotected_key, canlen);
675               xfree (arg.unprotected_key);
676               xfree (pi);
677               return rc;
678             }
679         }
680       else
681         {
682           /* Passphrase is fine.  */
683           agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
684                            lookup_ttl? lookup_ttl (hexgrip) : 0);
685           agent_store_cache_hit (hexgrip);
686           if (r_passphrase && *pi->pin)
687             *r_passphrase = xtrystrdup (pi->pin);
688         }
689       xfree (*keybuf);
690       *keybuf = arg.unprotected_key;
691     }
692   xfree (pi);
693   return rc;
694 }
695
696
697 /* Read the key identified by GRIP from the private key directory and
698    return it as an gcrypt S-expression object in RESULT.  On failure
699    returns an error code and stores NULL at RESULT. */
700 static gpg_error_t
701 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
702 {
703   gpg_error_t err;
704   char *fname;
705   estream_t fp;
706   struct stat st;
707   unsigned char *buf;
708   size_t buflen, erroff;
709   gcry_sexp_t s_skey;
710   char hexgrip[40+4+1];
711   char first;
712
713   *result = NULL;
714
715   bin2hex (grip, 20, hexgrip);
716   strcpy (hexgrip+40, ".key");
717
718   fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
719                          hexgrip, NULL);
720   fp = es_fopen (fname, "rb");
721   if (!fp)
722     {
723       err = gpg_error_from_syserror ();
724       if (gpg_err_code (err) != GPG_ERR_ENOENT)
725         log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
726       xfree (fname);
727       return err;
728     }
729
730   if (es_fread (&first, 1, 1, fp) != 1)
731     {
732       err = gpg_error_from_syserror ();
733       log_error ("error reading first byte from '%s': %s\n",
734                  fname, gpg_strerror (err));
735       xfree (fname);
736       es_fclose (fp);
737       return err;
738     }
739
740   if (es_fseek (fp, 0, SEEK_SET))
741     {
742       err = gpg_error_from_syserror ();
743       log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
744       xfree (fname);
745       es_fclose (fp);
746       return err;
747     }
748
749   if (first != '(')
750     {
751       /* Key is in extended format.  */
752       nvc_t pk;
753       int line;
754
755       err = nvc_parse_private_key (&pk, &line, fp);
756       es_fclose (fp);
757
758       if (err)
759         log_error ("error parsing '%s' line %d: %s\n",
760                    fname, line, gpg_strerror (err));
761       else
762         {
763           err = nvc_get_private_key (pk, result);
764           nvc_release (pk);
765           if (err)
766             log_error ("error getting private key from '%s': %s\n",
767                        fname, gpg_strerror (err));
768         }
769
770       xfree (fname);
771       return err;
772     }
773
774   if (fstat (es_fileno (fp), &st))
775     {
776       err = gpg_error_from_syserror ();
777       log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
778       xfree (fname);
779       es_fclose (fp);
780       return err;
781     }
782
783   buflen = st.st_size;
784   buf = xtrymalloc (buflen+1);
785   if (!buf)
786     {
787       err = gpg_error_from_syserror ();
788       log_error ("error allocating %zu bytes for '%s': %s\n",
789                  buflen, fname, gpg_strerror (err));
790       xfree (fname);
791       es_fclose (fp);
792       xfree (buf);
793       return err;
794
795     }
796
797   if (es_fread (buf, buflen, 1, fp) != 1)
798     {
799       err = gpg_error_from_syserror ();
800       log_error ("error reading %zu bytes from '%s': %s\n",
801                  buflen, fname, gpg_strerror (err));
802       xfree (fname);
803       es_fclose (fp);
804       xfree (buf);
805       return err;
806     }
807
808   /* Convert the file into a gcrypt S-expression object.  */
809   err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
810   xfree (fname);
811   es_fclose (fp);
812   xfree (buf);
813   if (err)
814     {
815       log_error ("failed to build S-Exp (off=%u): %s\n",
816                  (unsigned int)erroff, gpg_strerror (err));
817       return err;
818     }
819   *result = s_skey;
820   return 0;
821 }
822
823
824 /* Remove the key identified by GRIP from the private key directory.  */
825 static gpg_error_t
826 remove_key_file (const unsigned char *grip)
827 {
828   gpg_error_t err = 0;
829   char *fname;
830   char hexgrip[40+4+1];
831
832   bin2hex (grip, 20, hexgrip);
833   strcpy (hexgrip+40, ".key");
834   fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
835                          hexgrip, NULL);
836   if (gnupg_remove (fname))
837     err = gpg_error_from_syserror ();
838   xfree (fname);
839   return err;
840 }
841
842
843 /* Return the secret key as an S-Exp in RESULT after locating it using
844    the GRIP.  If the operation shall be diverted to a token, an
845    allocated S-expression with the shadow_info part from the file is
846    stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
847    CACHE_MODE defines now the cache shall be used.  DESC_TEXT may be
848    set to present a custom description for the pinentry.  LOOKUP_TTL
849    is an optional function to convey a TTL to the cache manager; we do
850    not simply pass the TTL value because the value is only needed if
851    an unprotect action was needed and looking up the TTL may have some
852    overhead (e.g. scanning the sshcontrol file).  If a CACHE_NONCE is
853    given that cache item is first tried to get a passphrase.  If
854    R_PASSPHRASE is not NULL, the function succeeded and the key was
855    protected the used passphrase (entered or from the cache) is stored
856    there; if not NULL will be stored.  The caller needs to free the
857    returned passphrase.   */
858 gpg_error_t
859 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
860                      const char *desc_text,
861                      const unsigned char *grip, unsigned char **shadow_info,
862                      cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
863                      gcry_sexp_t *result, char **r_passphrase)
864 {
865   gpg_error_t err;
866   unsigned char *buf;
867   size_t len, buflen, erroff;
868   gcry_sexp_t s_skey;
869
870   *result = NULL;
871   if (shadow_info)
872     *shadow_info = NULL;
873   if (r_passphrase)
874     *r_passphrase = NULL;
875
876   err = read_key_file (grip, &s_skey);
877   if (err)
878     {
879       if (gpg_err_code (err) == GPG_ERR_ENOENT)
880         err = gpg_error (GPG_ERR_NO_SECKEY);
881       return err;
882     }
883
884   /* For use with the protection functions we also need the key as an
885      canonical encoded S-expression in a buffer.  Create this buffer
886      now.  */
887   err = make_canon_sexp (s_skey, &buf, &len);
888   if (err)
889     return err;
890
891   switch (agent_private_key_type (buf))
892     {
893     case PRIVATE_KEY_CLEAR:
894       break; /* no unprotection needed */
895     case PRIVATE_KEY_OPENPGP_NONE:
896       {
897         unsigned char *buf_new;
898         size_t buf_newlen;
899
900         err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
901         if (err)
902           log_error ("failed to convert unprotected openpgp key: %s\n",
903                      gpg_strerror (err));
904         else
905           {
906             xfree (buf);
907             buf = buf_new;
908           }
909       }
910       break;
911     case PRIVATE_KEY_PROTECTED:
912       {
913         char *desc_text_final;
914         char *comment = NULL;
915
916         /* Note, that we will take the comment as a C string for
917            display purposes; i.e. all stuff beyond a Nul character is
918            ignored.  */
919         {
920           gcry_sexp_t comment_sexp;
921
922           comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
923           if (comment_sexp)
924             comment = gcry_sexp_nth_string (comment_sexp, 1);
925           gcry_sexp_release (comment_sexp);
926         }
927
928         desc_text_final = NULL;
929         if (desc_text)
930           err = agent_modify_description (desc_text, comment, s_skey,
931                                           &desc_text_final);
932         gcry_free (comment);
933
934         if (!err)
935           {
936             err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
937                             cache_mode, lookup_ttl, r_passphrase);
938             if (err)
939               log_error ("failed to unprotect the secret key: %s\n",
940                          gpg_strerror (err));
941           }
942
943         xfree (desc_text_final);
944       }
945       break;
946     case PRIVATE_KEY_SHADOWED:
947       if (shadow_info)
948         {
949           const unsigned char *s;
950           size_t n;
951
952           err = agent_get_shadow_info (buf, &s);
953           if (!err)
954             {
955               n = gcry_sexp_canon_len (s, 0, NULL,NULL);
956               log_assert (n);
957               *shadow_info = xtrymalloc (n);
958               if (!*shadow_info)
959                 err = out_of_core ();
960               else
961                 {
962                   memcpy (*shadow_info, s, n);
963                   err = 0;
964                 }
965             }
966           if (err)
967             log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
968         }
969       else
970         err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
971       break;
972     default:
973       log_error ("invalid private key format\n");
974       err = gpg_error (GPG_ERR_BAD_SECKEY);
975       break;
976     }
977   gcry_sexp_release (s_skey);
978   s_skey = NULL;
979   if (err)
980     {
981       xfree (buf);
982       if (r_passphrase)
983         {
984           xfree (*r_passphrase);
985           *r_passphrase = NULL;
986         }
987       return err;
988     }
989
990   buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
991   err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
992   wipememory (buf, buflen);
993   xfree (buf);
994   if (err)
995     {
996       log_error ("failed to build S-Exp (off=%u): %s\n",
997                  (unsigned int)erroff, gpg_strerror (err));
998       if (r_passphrase)
999         {
1000           xfree (*r_passphrase);
1001           *r_passphrase = NULL;
1002         }
1003       return err;
1004     }
1005
1006   *result = s_skey;
1007   return 0;
1008 }
1009
1010
1011 /* Return the string name from the S-expression S_KEY as well as a
1012    string describing the names of the parameters.  ALGONAMESIZE and
1013    ELEMSSIZE give the allocated size of the provided buffers.  The
1014    buffers may be NULL if not required.  If R_LIST is not NULL the top
1015    level list will be stored there; the caller needs to release it in
1016    this case.  */
1017 static gpg_error_t
1018 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
1019                      char *r_algoname, size_t algonamesize,
1020                      char *r_elems, size_t elemssize)
1021 {
1022   gcry_sexp_t list, l2;
1023   const char *name, *algoname, *elems;
1024   size_t n;
1025
1026   if (r_list)
1027     *r_list = NULL;
1028
1029   list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1030   if (!list)
1031     list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1032   if (!list)
1033     list = gcry_sexp_find_token (s_key, "private-key", 0 );
1034   if (!list)
1035     {
1036       log_error ("invalid private key format\n");
1037       return gpg_error (GPG_ERR_BAD_SECKEY);
1038     }
1039
1040   l2 = gcry_sexp_cadr (list);
1041   gcry_sexp_release (list);
1042   list = l2;
1043   name = gcry_sexp_nth_data (list, 0, &n);
1044   if (n==3 && !memcmp (name, "rsa", 3))
1045     {
1046       algoname = "rsa";
1047       elems = "ne";
1048     }
1049   else if (n==3 && !memcmp (name, "dsa", 3))
1050     {
1051       algoname = "dsa";
1052       elems = "pqgy";
1053     }
1054   else if (n==3 && !memcmp (name, "ecc", 3))
1055     {
1056       algoname = "ecc";
1057       elems = "pabgnq";
1058     }
1059   else if (n==5 && !memcmp (name, "ecdsa", 5))
1060     {
1061       algoname = "ecdsa";
1062       elems = "pabgnq";
1063     }
1064   else if (n==4 && !memcmp (name, "ecdh", 4))
1065     {
1066       algoname = "ecdh";
1067       elems = "pabgnq";
1068     }
1069   else if (n==3 && !memcmp (name, "elg", 3))
1070     {
1071       algoname = "elg";
1072       elems = "pgy";
1073     }
1074   else
1075     {
1076       log_error ("unknown private key algorithm\n");
1077       gcry_sexp_release (list);
1078       return gpg_error (GPG_ERR_BAD_SECKEY);
1079     }
1080
1081   if (r_algoname)
1082     {
1083       if (strlen (algoname) >= algonamesize)
1084         return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1085       strcpy (r_algoname, algoname);
1086     }
1087   if (r_elems)
1088     {
1089       if (strlen (elems) >= elemssize)
1090         return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1091       strcpy (r_elems, elems);
1092     }
1093
1094   if (r_list)
1095     *r_list = list;
1096   else
1097     gcry_sexp_release (list);
1098
1099   return 0;
1100 }
1101
1102
1103 /* Return true if KEYPARMS holds an EdDSA key.  */
1104 static int
1105 is_eddsa (gcry_sexp_t keyparms)
1106 {
1107   int result = 0;
1108   gcry_sexp_t list;
1109   const char *s;
1110   size_t n;
1111   int i;
1112
1113   list = gcry_sexp_find_token (keyparms, "flags", 0);
1114   for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
1115     {
1116       s = gcry_sexp_nth_data (list, i, &n);
1117       if (!s)
1118         continue; /* Not a data element. */
1119
1120       if (n == 5 && !memcmp (s, "eddsa", 5))
1121         {
1122           result = 1;
1123           break;
1124         }
1125     }
1126   gcry_sexp_release (list);
1127   return result;
1128 }
1129
1130
1131 /* Return the public key algorithm number if S_KEY is a DSA style key.
1132    If it is not a DSA style key, return 0.  */
1133 int
1134 agent_is_dsa_key (gcry_sexp_t s_key)
1135 {
1136   int result;
1137   gcry_sexp_t list;
1138   char algoname[6];
1139
1140   if (!s_key)
1141     return 0;
1142
1143   if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1144     return 0; /* Error - assume it is not an DSA key.  */
1145
1146   if (!strcmp (algoname, "dsa"))
1147     result = GCRY_PK_DSA;
1148   else if (!strcmp (algoname, "ecc"))
1149     {
1150       if (is_eddsa (list))
1151         result = 0;
1152       else
1153         result = GCRY_PK_ECDSA;
1154     }
1155   else if (!strcmp (algoname, "ecdsa"))
1156     result = GCRY_PK_ECDSA;
1157   else
1158     result = 0;
1159
1160   gcry_sexp_release (list);
1161   return result;
1162 }
1163
1164
1165 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519.  */
1166 int
1167 agent_is_eddsa_key (gcry_sexp_t s_key)
1168 {
1169   int result;
1170   gcry_sexp_t list;
1171   char algoname[6];
1172
1173   if (!s_key)
1174     return 0;
1175
1176   if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1177     return 0; /* Error - assume it is not an EdDSA key.  */
1178
1179   if (!strcmp (algoname, "ecc") && is_eddsa (list))
1180     result = 1;
1181   else if (!strcmp (algoname, "eddsa")) /* backward compatibility.  */
1182     result = 1;
1183   else
1184     result = 0;
1185
1186   gcry_sexp_release (list);
1187   return result;
1188 }
1189
1190
1191 /* Return the key for the keygrip GRIP.  The result is stored at
1192    RESULT.  This function extracts the key from the private key
1193    database and returns it as an S-expression object as it is.  On
1194    failure an error code is returned and NULL stored at RESULT. */
1195 gpg_error_t
1196 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1197                          gcry_sexp_t *result)
1198 {
1199   gpg_error_t err;
1200   gcry_sexp_t s_skey;
1201
1202   (void)ctrl;
1203
1204   *result = NULL;
1205
1206   err = read_key_file (grip, &s_skey);
1207   if (!err)
1208     *result = s_skey;
1209   return err;
1210 }
1211
1212
1213 /* Return the public key for the keygrip GRIP.  The result is stored
1214    at RESULT.  This function extracts the public key from the private
1215    key database.  On failure an error code is returned and NULL stored
1216    at RESULT. */
1217 gpg_error_t
1218 agent_public_key_from_file (ctrl_t ctrl,
1219                             const unsigned char *grip,
1220                             gcry_sexp_t *result)
1221 {
1222   gpg_error_t err;
1223   int i, idx;
1224   gcry_sexp_t s_skey;
1225   const char *algoname, *elems;
1226   int npkey;
1227   gcry_mpi_t array[10];
1228   gcry_sexp_t curve = NULL;
1229   gcry_sexp_t flags = NULL;
1230   gcry_sexp_t uri_sexp, comment_sexp;
1231   const char *uri, *comment;
1232   size_t uri_length, comment_length;
1233   char *format, *p;
1234   void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1235                             for comment + end-of-list.  */
1236   int argidx;
1237   gcry_sexp_t list = NULL;
1238   const char *s;
1239
1240   (void)ctrl;
1241
1242   *result = NULL;
1243
1244   err = read_key_file (grip, &s_skey);
1245   if (err)
1246     return err;
1247
1248   for (i=0; i < DIM (array); i++)
1249     array[i] = NULL;
1250
1251   err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1252                              array, DIM (array), &curve, &flags);
1253   if (err)
1254     {
1255       gcry_sexp_release (s_skey);
1256       return err;
1257     }
1258
1259   uri = NULL;
1260   uri_length = 0;
1261   uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1262   if (uri_sexp)
1263     uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1264
1265   comment = NULL;
1266   comment_length = 0;
1267   comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1268   if (comment_sexp)
1269     comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1270
1271   gcry_sexp_release (s_skey);
1272   s_skey = NULL;
1273
1274
1275   /* FIXME: The following thing is pretty ugly code; we should
1276      investigate how to make it cleaner.  Probably code to handle
1277      canonical S-expressions in a memory buffer is better suited for
1278      such a task.  After all that is what we do in protect.c.  Need
1279      to find common patterns and write a straightformward API to use
1280      them.  */
1281   assert (sizeof (size_t) <= sizeof (void*));
1282
1283   format = xtrymalloc (15+4+7*npkey+10+15+1+1);
1284   if (!format)
1285     {
1286       err = gpg_error_from_syserror ();
1287       for (i=0; array[i]; i++)
1288         gcry_mpi_release (array[i]);
1289       gcry_sexp_release (curve);
1290       gcry_sexp_release (flags);
1291       gcry_sexp_release (uri_sexp);
1292       gcry_sexp_release (comment_sexp);
1293       return err;
1294     }
1295
1296   argidx = 0;
1297   p = stpcpy (stpcpy (format, "(public-key("), algoname);
1298   p = stpcpy (p, "%S%S");       /* curve name and flags.  */
1299   args[argidx++] = &curve;
1300   args[argidx++] = &flags;
1301   for (idx=0, s=elems; idx < npkey; idx++)
1302     {
1303       *p++ = '(';
1304       *p++ = *s++;
1305       p = stpcpy (p, " %m)");
1306       assert (argidx < DIM (args));
1307       args[argidx++] = &array[idx];
1308     }
1309   *p++ = ')';
1310   if (uri)
1311     {
1312       p = stpcpy (p, "(uri %b)");
1313       assert (argidx+1 < DIM (args));
1314       args[argidx++] = (void *)&uri_length;
1315       args[argidx++] = (void *)&uri;
1316     }
1317   if (comment)
1318     {
1319       p = stpcpy (p, "(comment %b)");
1320       assert (argidx+1 < DIM (args));
1321       args[argidx++] = (void *)&comment_length;
1322       args[argidx++] = (void*)&comment;
1323     }
1324   *p++ = ')';
1325   *p = 0;
1326   assert (argidx < DIM (args));
1327   args[argidx] = NULL;
1328
1329   err = gcry_sexp_build_array (&list, NULL, format, args);
1330   xfree (format);
1331   for (i=0; array[i]; i++)
1332     gcry_mpi_release (array[i]);
1333   gcry_sexp_release (curve);
1334   gcry_sexp_release (flags);
1335   gcry_sexp_release (uri_sexp);
1336   gcry_sexp_release (comment_sexp);
1337
1338   if (!err)
1339     *result = list;
1340   return err;
1341 }
1342
1343
1344
1345 /* Check whether the secret key identified by GRIP is available.
1346    Returns 0 is the key is available.  */
1347 int
1348 agent_key_available (const unsigned char *grip)
1349 {
1350   int result;
1351   char *fname;
1352   char hexgrip[40+4+1];
1353
1354   bin2hex (grip, 20, hexgrip);
1355   strcpy (hexgrip+40, ".key");
1356
1357   fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1358                          hexgrip, NULL);
1359   result = !access (fname, R_OK)? 0 : -1;
1360   xfree (fname);
1361   return result;
1362 }
1363
1364
1365
1366 /* Return the information about the secret key specified by the binary
1367    keygrip GRIP.  If the key is a shadowed one the shadow information
1368    will be stored at the address R_SHADOW_INFO as an allocated
1369    S-expression.  */
1370 gpg_error_t
1371 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1372                           int *r_keytype, unsigned char **r_shadow_info)
1373 {
1374   gpg_error_t err;
1375   unsigned char *buf;
1376   size_t len;
1377   int keytype;
1378
1379   (void)ctrl;
1380
1381   if (r_keytype)
1382     *r_keytype = PRIVATE_KEY_UNKNOWN;
1383   if (r_shadow_info)
1384     *r_shadow_info = NULL;
1385
1386   {
1387     gcry_sexp_t sexp;
1388
1389     err = read_key_file (grip, &sexp);
1390     if (err)
1391       {
1392         if (gpg_err_code (err) == GPG_ERR_ENOENT)
1393           return gpg_error (GPG_ERR_NOT_FOUND);
1394         else
1395           return err;
1396       }
1397     err = make_canon_sexp (sexp, &buf, &len);
1398     gcry_sexp_release (sexp);
1399     if (err)
1400       return err;
1401   }
1402
1403   keytype = agent_private_key_type (buf);
1404   switch (keytype)
1405     {
1406     case PRIVATE_KEY_CLEAR:
1407     case PRIVATE_KEY_OPENPGP_NONE:
1408       break;
1409     case PRIVATE_KEY_PROTECTED:
1410       /* If we ever require it we could retrieve the comment fields
1411          from such a key. */
1412       break;
1413     case PRIVATE_KEY_SHADOWED:
1414       if (r_shadow_info)
1415         {
1416           const unsigned char *s;
1417           size_t n;
1418
1419           err = agent_get_shadow_info (buf, &s);
1420           if (!err)
1421             {
1422               n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1423               assert (n);
1424               *r_shadow_info = xtrymalloc (n);
1425               if (!*r_shadow_info)
1426                 err = gpg_error_from_syserror ();
1427               else
1428                 memcpy (*r_shadow_info, s, n);
1429             }
1430         }
1431       break;
1432     default:
1433       err = gpg_error (GPG_ERR_BAD_SECKEY);
1434       break;
1435     }
1436
1437   if (!err && r_keytype)
1438     *r_keytype = keytype;
1439
1440   xfree (buf);
1441   return err;
1442 }
1443
1444
1445 \f
1446 /* Delete the key with GRIP from the disk after having asked for
1447  * confirmation using DESC_TEXT.  If FORCE is set the function won't
1448  * require a confirmation via Pinentry or warns if the key is also
1449  * used by ssh.  If ONLY_STUBS is set only stub keys (references to
1450  * smartcards) will be affected.
1451  *
1452  * Common error codes are:
1453  *   GPG_ERR_NO_SECKEY
1454  *   GPG_ERR_KEY_ON_CARD
1455  *   GPG_ERR_NOT_CONFIRMED
1456  *   GPG_ERR_FORBIDDEN     - Not a stub key and ONLY_STUBS requested.
1457  */
1458 gpg_error_t
1459 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1460                   const unsigned char *grip, int force, int only_stubs)
1461 {
1462   gpg_error_t err;
1463   gcry_sexp_t s_skey = NULL;
1464   unsigned char *buf = NULL;
1465   size_t len;
1466   char *desc_text_final = NULL;
1467   char *comment = NULL;
1468   ssh_control_file_t cf = NULL;
1469   char hexgrip[40+4+1];
1470   char *default_desc = NULL;
1471   int key_type;
1472
1473   err = read_key_file (grip, &s_skey);
1474   if (gpg_err_code (err) == GPG_ERR_ENOENT)
1475     err = gpg_error (GPG_ERR_NO_SECKEY);
1476   if (err)
1477     goto leave;
1478
1479   err = make_canon_sexp (s_skey, &buf, &len);
1480   if (err)
1481     goto leave;
1482
1483   key_type = agent_private_key_type (buf);
1484   if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1485     {
1486       err  = gpg_error (GPG_ERR_FORBIDDEN);
1487       goto leave;
1488     }
1489
1490   switch (key_type)
1491     {
1492     case PRIVATE_KEY_CLEAR:
1493     case PRIVATE_KEY_OPENPGP_NONE:
1494     case PRIVATE_KEY_PROTECTED:
1495       bin2hex (grip, 20, hexgrip);
1496       if (!force)
1497         {
1498           if (!desc_text)
1499             {
1500               default_desc = xtryasprintf
1501           (L_("Do you really want to delete the key identified by keygrip%%0A"
1502               "  %s%%0A  %%C%%0A?"), hexgrip);
1503               desc_text = default_desc;
1504             }
1505
1506           /* Note, that we will take the comment as a C string for
1507              display purposes; i.e. all stuff beyond a Nul character is
1508              ignored.  */
1509           {
1510             gcry_sexp_t comment_sexp;
1511
1512             comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1513             if (comment_sexp)
1514               comment = gcry_sexp_nth_string (comment_sexp, 1);
1515             gcry_sexp_release (comment_sexp);
1516           }
1517
1518           if (desc_text)
1519             err = agent_modify_description (desc_text, comment, s_skey,
1520                                             &desc_text_final);
1521           if (err)
1522             goto leave;
1523
1524           err = agent_get_confirmation (ctrl, desc_text_final,
1525                                         L_("Delete key"), L_("No"), 0);
1526           if (err)
1527             goto leave;
1528
1529           cf = ssh_open_control_file ();
1530           if (cf)
1531             {
1532               if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1533                 {
1534                   err = agent_get_confirmation
1535                     (ctrl,
1536                      L_("Warning: This key is also listed for use with SSH!\n"
1537                         "Deleting the key might remove your ability to "
1538                         "access remote machines."),
1539                      L_("Delete key"), L_("No"), 0);
1540                   if (err)
1541                     goto leave;
1542                 }
1543             }
1544         }
1545       err = remove_key_file (grip);
1546       break;
1547
1548     case PRIVATE_KEY_SHADOWED:
1549       err = remove_key_file (grip);
1550       break;
1551
1552     default:
1553       log_error ("invalid private key format\n");
1554       err = gpg_error (GPG_ERR_BAD_SECKEY);
1555       break;
1556     }
1557
1558  leave:
1559   ssh_close_control_file (cf);
1560   gcry_free (comment);
1561   xfree (desc_text_final);
1562   xfree (default_desc);
1563   xfree (buf);
1564   gcry_sexp_release (s_skey);
1565   return err;
1566 }
1567
1568
1569 /* Write an S-expression formatted shadow key to our key storage.
1570    Shadow key is created by an S-expression public key in PKBUF and
1571    card's SERIALNO and the IDSTRING.  With FORCE passed as true an
1572    existing key with the given GRIP will get overwritten.  */
1573 gpg_error_t
1574 agent_write_shadow_key (const unsigned char *grip,
1575                         const char *serialno, const char *keyid,
1576                         const unsigned char *pkbuf, int force)
1577 {
1578   gpg_error_t err;
1579   unsigned char *shadow_info;
1580   unsigned char *shdkey;
1581   size_t len;
1582
1583   shadow_info = make_shadow_info (serialno, keyid);
1584   if (!shadow_info)
1585     return gpg_error_from_syserror ();
1586
1587   err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1588   xfree (shadow_info);
1589   if (err)
1590     {
1591       log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1592       return err;
1593     }
1594
1595   len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1596   err = agent_write_private_key (grip, shdkey, len, force);
1597   xfree (shdkey);
1598   if (err)
1599     log_error ("error writing key: %s\n", gpg_strerror (err));
1600
1601   return err;
1602 }