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