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