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