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