Imported Upstream version 2.1.0
[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_PROTECTED:
668       {
669         char *desc_text_final;
670         char *comment = NULL;
671
672         /* Note, that we will take the comment as a C string for
673            display purposes; i.e. all stuff beyond a Nul character is
674            ignored.  */
675         {
676           gcry_sexp_t comment_sexp;
677
678           comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
679           if (comment_sexp)
680             comment = gcry_sexp_nth_string (comment_sexp, 1);
681           gcry_sexp_release (comment_sexp);
682         }
683
684         desc_text_final = NULL;
685         if (desc_text)
686           rc = modify_description (desc_text, comment? comment:"", s_skey,
687                                    &desc_text_final);
688         gcry_free (comment);
689
690         if (!rc)
691           {
692             rc = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
693                             cache_mode, lookup_ttl, r_passphrase);
694             if (rc)
695               log_error ("failed to unprotect the secret key: %s\n",
696                          gpg_strerror (rc));
697           }
698
699         xfree (desc_text_final);
700       }
701       break;
702     case PRIVATE_KEY_SHADOWED:
703       if (shadow_info)
704         {
705           const unsigned char *s;
706           size_t n;
707
708           rc = agent_get_shadow_info (buf, &s);
709           if (!rc)
710             {
711               n = gcry_sexp_canon_len (s, 0, NULL,NULL);
712               assert (n);
713               *shadow_info = xtrymalloc (n);
714               if (!*shadow_info)
715                 rc = out_of_core ();
716               else
717                 {
718                   memcpy (*shadow_info, s, n);
719                   rc = 0;
720                 }
721             }
722           if (rc)
723             log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
724         }
725       else
726         rc = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
727       break;
728     default:
729       log_error ("invalid private key format\n");
730       rc = gpg_error (GPG_ERR_BAD_SECKEY);
731       break;
732     }
733   gcry_sexp_release (s_skey);
734   s_skey = NULL;
735   if (rc)
736     {
737       xfree (buf);
738       if (r_passphrase)
739         {
740           xfree (*r_passphrase);
741           *r_passphrase = NULL;
742         }
743       return rc;
744     }
745
746   buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
747   rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
748   wipememory (buf, buflen);
749   xfree (buf);
750   if (rc)
751     {
752       log_error ("failed to build S-Exp (off=%u): %s\n",
753                  (unsigned int)erroff, gpg_strerror (rc));
754       if (r_passphrase)
755         {
756           xfree (*r_passphrase);
757           *r_passphrase = NULL;
758         }
759       return rc;
760     }
761
762   *result = s_skey;
763   return 0;
764 }
765
766
767 /* Return the string name from the S-expression S_KEY as well as a
768    string describing the names of the parameters.  ALGONAMESIZE and
769    ELEMSSIZE give the allocated size of the provided buffers.  The
770    buffers may be NULL if not required.  If R_LIST is not NULL the top
771    level list will be stored there; the caller needs to release it in
772    this case.  */
773 static gpg_error_t
774 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
775                      char *r_algoname, size_t algonamesize,
776                      char *r_elems, size_t elemssize)
777 {
778   gcry_sexp_t list, l2;
779   const char *name, *algoname, *elems;
780   size_t n;
781
782   if (r_list)
783     *r_list = NULL;
784
785   list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
786   if (!list)
787     list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
788   if (!list)
789     list = gcry_sexp_find_token (s_key, "private-key", 0 );
790   if (!list)
791     {
792       log_error ("invalid private key format\n");
793       return gpg_error (GPG_ERR_BAD_SECKEY);
794     }
795
796   l2 = gcry_sexp_cadr (list);
797   gcry_sexp_release (list);
798   list = l2;
799   name = gcry_sexp_nth_data (list, 0, &n);
800   if (n==3 && !memcmp (name, "rsa", 3))
801     {
802       algoname = "rsa";
803       elems = "ne";
804     }
805   else if (n==3 && !memcmp (name, "dsa", 3))
806     {
807       algoname = "dsa";
808       elems = "pqgy";
809     }
810   else if (n==3 && !memcmp (name, "ecc", 3))
811     {
812       algoname = "ecc";
813       elems = "pabgnq";
814     }
815   else if (n==5 && !memcmp (name, "ecdsa", 5))
816     {
817       algoname = "ecdsa";
818       elems = "pabgnq";
819     }
820   else if (n==4 && !memcmp (name, "ecdh", 4))
821     {
822       algoname = "ecdh";
823       elems = "pabgnq";
824     }
825   else if (n==3 && !memcmp (name, "elg", 3))
826     {
827       algoname = "elg";
828       elems = "pgy";
829     }
830   else
831     {
832       log_error ("unknown private key algorithm\n");
833       gcry_sexp_release (list);
834       return gpg_error (GPG_ERR_BAD_SECKEY);
835     }
836
837   if (r_algoname)
838     {
839       if (strlen (algoname) >= algonamesize)
840         return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
841       strcpy (r_algoname, algoname);
842     }
843   if (r_elems)
844     {
845       if (strlen (elems) >= elemssize)
846         return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
847       strcpy (r_elems, elems);
848     }
849
850   if (r_list)
851     *r_list = list;
852   else
853     gcry_sexp_release (list);
854
855   return 0;
856 }
857
858
859 /* Return true if KEYPARMS holds an EdDSA key.  */
860 static int
861 is_eddsa (gcry_sexp_t keyparms)
862 {
863   int result = 0;
864   gcry_sexp_t list;
865   const char *s;
866   size_t n;
867   int i;
868
869   list = gcry_sexp_find_token (keyparms, "flags", 0);
870   for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
871     {
872       s = gcry_sexp_nth_data (list, i, &n);
873       if (!s)
874         continue; /* Not a data element. */
875
876       if (n == 5 && !memcmp (s, "eddsa", 5))
877         {
878           result = 1;
879           break;
880         }
881     }
882   gcry_sexp_release (list);
883   return result;
884 }
885
886
887 /* Return the public key algorithm number if S_KEY is a DSA style key.
888    If it is not a DSA style key, return 0.  */
889 int
890 agent_is_dsa_key (gcry_sexp_t s_key)
891 {
892   int result;
893   gcry_sexp_t list;
894   char algoname[6];
895
896   if (!s_key)
897     return 0;
898
899   if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
900     return 0; /* Error - assume it is not an DSA key.  */
901
902   if (!strcmp (algoname, "dsa"))
903     result = GCRY_PK_DSA;
904   else if (!strcmp (algoname, "ecc"))
905     {
906       if (is_eddsa (list))
907         result = 0;
908       else
909         result = GCRY_PK_ECDSA;
910     }
911   else if (!strcmp (algoname, "ecdsa"))
912     result = GCRY_PK_ECDSA;
913   else
914     result = 0;
915
916   gcry_sexp_release (list);
917   return result;
918 }
919
920
921 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519.  */
922 int
923 agent_is_eddsa_key (gcry_sexp_t s_key)
924 {
925   int result;
926   gcry_sexp_t list;
927   char algoname[6];
928
929   if (!s_key)
930     return 0;
931
932   if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
933     return 0; /* Error - assume it is not an EdDSA key.  */
934
935   if (!strcmp (algoname, "ecc") && is_eddsa (list))
936     result = 1;
937   else if (!strcmp (algoname, "eddsa")) /* backward compatibility.  */
938     result = 1;
939   else
940     result = 0;
941
942   gcry_sexp_release (list);
943   return result;
944 }
945
946
947 /* Return the key for the keygrip GRIP.  The result is stored at
948    RESULT.  This function extracts the key from the private key
949    database and returns it as an S-expression object as it is.  On
950    failure an error code is returned and NULL stored at RESULT. */
951 gpg_error_t
952 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
953                          gcry_sexp_t *result)
954 {
955   gpg_error_t err;
956   gcry_sexp_t s_skey;
957
958   (void)ctrl;
959
960   *result = NULL;
961
962   err = read_key_file (grip, &s_skey);
963   if (!err)
964     *result = s_skey;
965   return err;
966 }
967
968
969 /* Return the public key for the keygrip GRIP.  The result is stored
970    at RESULT.  This function extracts the public key from the private
971    key database.  On failure an error code is returned and NULL stored
972    at RESULT. */
973 gpg_error_t
974 agent_public_key_from_file (ctrl_t ctrl,
975                             const unsigned char *grip,
976                             gcry_sexp_t *result)
977 {
978   gpg_error_t err;
979   int i, idx;
980   gcry_sexp_t s_skey;
981   char algoname[6];
982   char elems[7];
983   gcry_sexp_t uri_sexp, comment_sexp;
984   const char *uri, *comment;
985   size_t uri_length, comment_length;
986   char *format, *p;
987   void *args[4+2+2+1]; /* Size is max. # of elements + 2 for uri + 2
988                            for comment + end-of-list.  */
989   int argidx;
990   gcry_sexp_t list, l2;
991   const char *s;
992   gcry_mpi_t *array;
993
994   (void)ctrl;
995
996   *result = NULL;
997
998   err = read_key_file (grip, &s_skey);
999   if (err)
1000     return err;
1001
1002   err = key_parms_from_sexp (s_skey, &list,
1003                             algoname, sizeof algoname,
1004                             elems, sizeof elems);
1005   if (err)
1006     {
1007       gcry_sexp_release (s_skey);
1008       return err;
1009     }
1010
1011   /* Allocate an array for the parameters and copy them out of the
1012      secret key.   FIXME: We should have a generic copy function. */
1013   array = xtrycalloc (strlen(elems) + 1, sizeof *array);
1014   if (!array)
1015     {
1016       err = gpg_error_from_syserror ();
1017       gcry_sexp_release (list);
1018       gcry_sexp_release (s_skey);
1019       return err;
1020     }
1021
1022   for (idx=0, s=elems; *s; s++, idx++ )
1023     {
1024       l2 = gcry_sexp_find_token (list, s, 1);
1025       if (!l2)
1026         {
1027           /* Required parameter not found.  */
1028           for (i=0; i<idx; i++)
1029             gcry_mpi_release (array[i]);
1030           xfree (array);
1031           gcry_sexp_release (list);
1032           gcry_sexp_release (s_skey);
1033           return gpg_error (GPG_ERR_BAD_SECKEY);
1034         }
1035       array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1036       gcry_sexp_release (l2);
1037       if (!array[idx])
1038         {
1039           /* Required parameter is invalid. */
1040           for (i=0; i<idx; i++)
1041             gcry_mpi_release (array[i]);
1042           xfree (array);
1043           gcry_sexp_release (list);
1044           gcry_sexp_release (s_skey);
1045           return gpg_error (GPG_ERR_BAD_SECKEY);
1046         }
1047     }
1048   gcry_sexp_release (list);
1049   list = NULL;
1050
1051   uri = NULL;
1052   uri_length = 0;
1053   uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1054   if (uri_sexp)
1055     uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1056
1057   comment = NULL;
1058   comment_length = 0;
1059   comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1060   if (comment_sexp)
1061     comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1062
1063   gcry_sexp_release (s_skey);
1064   s_skey = NULL;
1065
1066
1067   /* FIXME: The following thing is pretty ugly code; we should
1068      investigate how to make it cleaner.  Probably code to handle
1069      canonical S-expressions in a memory buffer is better suited for
1070      such a task.  After all that is what we do in protect.c.  Neeed
1071      to find common patterns and write a straightformward API to use
1072      them.  */
1073   assert (sizeof (size_t) <= sizeof (void*));
1074
1075   format = xtrymalloc (15+7*strlen (elems)+10+15+1+1);
1076   if (!format)
1077     {
1078       err = gpg_error_from_syserror ();
1079       for (i=0; array[i]; i++)
1080         gcry_mpi_release (array[i]);
1081       xfree (array);
1082       gcry_sexp_release (uri_sexp);
1083       gcry_sexp_release (comment_sexp);
1084       return err;
1085     }
1086
1087   argidx = 0;
1088   p = stpcpy (stpcpy (format, "(public-key("), algoname);
1089   for (idx=0, s=elems; *s; s++, idx++ )
1090     {
1091       *p++ = '(';
1092       *p++ = *s;
1093       p = stpcpy (p, " %m)");
1094       assert (argidx < DIM (args));
1095       args[argidx++] = &array[idx];
1096     }
1097   *p++ = ')';
1098   if (uri)
1099     {
1100       p = stpcpy (p, "(uri %b)");
1101       assert (argidx+1 < DIM (args));
1102       args[argidx++] = (void *)&uri_length;
1103       args[argidx++] = (void *)&uri;
1104     }
1105   if (comment)
1106     {
1107       p = stpcpy (p, "(comment %b)");
1108       assert (argidx+1 < DIM (args));
1109       args[argidx++] = (void *)&comment_length;
1110       args[argidx++] = (void*)&comment;
1111     }
1112   *p++ = ')';
1113   *p = 0;
1114   assert (argidx < DIM (args));
1115   args[argidx] = NULL;
1116
1117   err = gcry_sexp_build_array (&list, NULL, format, args);
1118   xfree (format);
1119   for (i=0; array[i]; i++)
1120     gcry_mpi_release (array[i]);
1121   xfree (array);
1122   gcry_sexp_release (uri_sexp);
1123   gcry_sexp_release (comment_sexp);
1124
1125   if (!err)
1126     *result = list;
1127   return err;
1128 }
1129
1130
1131
1132 /* Check whether the the secret key identified by GRIP is available.
1133    Returns 0 is the key is available.  */
1134 int
1135 agent_key_available (const unsigned char *grip)
1136 {
1137   int result;
1138   char *fname;
1139   char hexgrip[40+4+1];
1140
1141   bin2hex (grip, 20, hexgrip);
1142   strcpy (hexgrip+40, ".key");
1143
1144   fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
1145   result = !access (fname, R_OK)? 0 : -1;
1146   xfree (fname);
1147   return result;
1148 }
1149
1150
1151
1152 /* Return the information about the secret key specified by the binary
1153    keygrip GRIP.  If the key is a shadowed one the shadow information
1154    will be stored at the address R_SHADOW_INFO as an allocated
1155    S-expression.  */
1156 gpg_error_t
1157 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1158                           int *r_keytype, unsigned char **r_shadow_info)
1159 {
1160   gpg_error_t err;
1161   unsigned char *buf;
1162   size_t len;
1163   int keytype;
1164
1165   (void)ctrl;
1166
1167   if (r_keytype)
1168     *r_keytype = PRIVATE_KEY_UNKNOWN;
1169   if (r_shadow_info)
1170     *r_shadow_info = NULL;
1171
1172   {
1173     gcry_sexp_t sexp;
1174
1175     err = read_key_file (grip, &sexp);
1176     if (err)
1177       {
1178         if (gpg_err_code (err) == GPG_ERR_ENOENT)
1179           return gpg_error (GPG_ERR_NOT_FOUND);
1180         else
1181           return err;
1182       }
1183     err = make_canon_sexp (sexp, &buf, &len);
1184     gcry_sexp_release (sexp);
1185     if (err)
1186       return err;
1187   }
1188
1189   keytype = agent_private_key_type (buf);
1190   switch (keytype)
1191     {
1192     case PRIVATE_KEY_CLEAR:
1193       break;
1194     case PRIVATE_KEY_PROTECTED:
1195       /* If we ever require it we could retrieve the comment fields
1196          from such a key. */
1197       break;
1198     case PRIVATE_KEY_SHADOWED:
1199       if (r_shadow_info)
1200         {
1201           const unsigned char *s;
1202           size_t n;
1203
1204           err = agent_get_shadow_info (buf, &s);
1205           if (!err)
1206             {
1207               n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1208               assert (n);
1209               *r_shadow_info = xtrymalloc (n);
1210               if (!*r_shadow_info)
1211                 err = gpg_error_from_syserror ();
1212               else
1213                 memcpy (*r_shadow_info, s, n);
1214             }
1215         }
1216       break;
1217     default:
1218       err = gpg_error (GPG_ERR_BAD_SECKEY);
1219       break;
1220     }
1221
1222   if (!err && r_keytype)
1223     *r_keytype = keytype;
1224
1225   xfree (buf);
1226   return err;
1227 }
1228
1229
1230 \f
1231 /* Delete the key with GRIP from the disk after having asked for
1232    confirmation using DESC_TEXT.  Common error codes are:
1233      GPG_ERR_NO_SECKEY
1234      GPG_ERR_KEY_ON_CARD
1235      GPG_ERR_NOT_CONFIRMED
1236 */
1237 gpg_error_t
1238 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1239                   const unsigned char *grip)
1240 {
1241   gpg_error_t err;
1242   gcry_sexp_t s_skey = NULL;
1243   unsigned char *buf = NULL;
1244   size_t len;
1245   char *desc_text_final = NULL;
1246   char *comment = NULL;
1247   ssh_control_file_t cf = NULL;
1248   char hexgrip[40+4+1];
1249   char *default_desc = NULL;
1250
1251   err = read_key_file (grip, &s_skey);
1252   if (gpg_err_code (err) == GPG_ERR_ENOENT)
1253     err = gpg_error (GPG_ERR_NO_SECKEY);
1254   if (err)
1255     goto leave;
1256
1257   err = make_canon_sexp (s_skey, &buf, &len);
1258   if (err)
1259     goto leave;
1260
1261   switch (agent_private_key_type (buf))
1262     {
1263     case PRIVATE_KEY_CLEAR:
1264     case PRIVATE_KEY_PROTECTED:
1265       {
1266         bin2hex (grip, 20, hexgrip);
1267         if (!desc_text)
1268           {
1269             default_desc = xtryasprintf
1270               ("Do you really want to delete the key identified by keygrip%%0A"
1271                "  %s%%0A  %%C%%0A?", hexgrip);
1272             desc_text = default_desc;
1273           }
1274
1275         /* Note, that we will take the comment as a C string for
1276            display purposes; i.e. all stuff beyond a Nul character is
1277            ignored.  */
1278         {
1279           gcry_sexp_t comment_sexp;
1280
1281           comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1282           if (comment_sexp)
1283             comment = gcry_sexp_nth_string (comment_sexp, 1);
1284           gcry_sexp_release (comment_sexp);
1285         }
1286
1287         if (desc_text)
1288           err = modify_description (desc_text, comment? comment:"", s_skey,
1289                                     &desc_text_final);
1290         if (err)
1291           goto leave;
1292
1293         err = agent_get_confirmation (ctrl, desc_text_final,
1294                                       _("Delete key"), _("No"), 0);
1295         if (err)
1296           goto leave;
1297
1298         cf = ssh_open_control_file ();
1299         if (cf)
1300           {
1301             if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1302               {
1303                 err = agent_get_confirmation
1304                   (ctrl,
1305                    _("Warning: This key is also listed for use with SSH!\n"
1306                      "Deleting the key might remove your ability to "
1307                      "access remote machines."),
1308                    _("Delete key"), _("No"), 0);
1309                 if (err)
1310                   goto leave;
1311               }
1312           }
1313
1314         err = remove_key_file (grip);
1315       }
1316       break;
1317
1318     case PRIVATE_KEY_SHADOWED:
1319       err = gpg_error (GPG_ERR_KEY_ON_CARD);
1320       break;
1321
1322     default:
1323       log_error ("invalid private key format\n");
1324       err = gpg_error (GPG_ERR_BAD_SECKEY);
1325       break;
1326     }
1327
1328  leave:
1329   ssh_close_control_file (cf);
1330   gcry_free (comment);
1331   xfree (desc_text_final);
1332   xfree (default_desc);
1333   xfree (buf);
1334   gcry_sexp_release (s_skey);
1335   return err;
1336 }