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