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