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
6 * This file is part of GnuPG.
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
33 #include <npth.h> /* (we use pth_sleep) */
36 #include "../common/i18n.h"
37 #include "../common/ssh-utils.h"
38 #include "../common/name-value.h"
44 /* Helper to pass data to the check callback of the unprotect function. */
45 struct try_unprotect_arg_s
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. */
55 /* Note: Ownership of FNAME and FP are moved to this function. */
57 write_extended_private_key (char *fname, estream_t fp, int update, int newkey,
58 const void *buf, size_t len, time_t timestamp)
62 gcry_sexp_t key = NULL;
69 err = nvc_parse_private_key (&pk, &line, fp);
70 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
72 log_error ("error parsing '%s' line %d: %s\n",
73 fname, line, gpg_strerror (err));
79 pk = nvc_new_private_key ();
82 err = gpg_error_from_syserror ();
88 err = gcry_sexp_sscan (&key, NULL, buf, len);
92 err = nvc_set_private_key (pk, key);
96 /* If a timestamp has been supplied and the key is new write a
97 * creation timestamp. (We double check that there is no Created
99 if (timestamp && newkey && !nvc_lookup (pk, "Created:"))
101 gnupg_isotime_t timebuf;
103 epoch2isotime (timebuf, timestamp);
104 err = nvc_add (pk, "Created:", timebuf);
109 err = es_fseek (fp, 0, SEEK_SET);
113 err = nvc_write (pk, fp);
116 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
121 if (ftruncate (es_fileno (fp), es_ftello (fp)))
123 err = gpg_error_from_syserror ();
124 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
131 err = gpg_error_from_syserror ();
132 log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
139 bump_key_eventcounter ();
144 gnupg_remove (fname);
146 gcry_sexp_release (key);
151 /* Write an S-expression formatted key to our key storage. With FORCE
152 * passed as true an existing key with the given GRIP will get
153 * overwritten. If TIMESTAMP is not zero and the key does not yet
154 * exists it will be recorded as creation date. */
156 agent_write_private_key (const unsigned char *grip,
157 const void *buffer, size_t length,
158 int force, time_t timestamp)
162 char hexgrip[40+4+1];
164 bin2hex (grip, 20, hexgrip);
165 strcpy (hexgrip+40, ".key");
167 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
170 /* FIXME: Write to a temp file first so that write failures during
171 key updates won't lead to a key loss. */
173 if (!force && !gnupg_access (fname, F_OK))
175 log_error ("secret key file '%s' already exists\n", fname);
177 return gpg_error (GPG_ERR_EEXIST);
180 fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
183 gpg_error_t tmperr = gpg_error_from_syserror ();
185 if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
187 fp = es_fopen (fname, "wbx,mode=-rw");
189 tmperr = gpg_error_from_syserror ();
193 log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
203 /* See if an existing key is in extended format. */
204 if (es_fread (&first, 1, 1, fp) != 1)
206 rc = gpg_error_from_syserror ();
207 log_error ("error reading first byte from '%s': %s\n",
208 fname, strerror (errno));
214 rc = es_fseek (fp, 0, SEEK_SET);
217 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
225 /* Key is already in the extended format. */
226 return write_extended_private_key (fname, fp, 1, 0, buffer, length,
229 if (first == '(' && opt.enable_extended_key_format)
231 /* Key is in the old format - but we want the extended format. */
232 return write_extended_private_key (fname, fp, 0, 0, buffer, length,
237 if (opt.enable_extended_key_format)
238 return write_extended_private_key (fname, fp, 0, 1, buffer, length,
241 if (es_fwrite (buffer, length, 1, fp) != 1)
243 gpg_error_t tmperr = gpg_error_from_syserror ();
244 log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
246 gnupg_remove (fname);
251 /* When force is given, the file might have to be truncated. */
252 if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
254 gpg_error_t tmperr = gpg_error_from_syserror ();
255 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
257 gnupg_remove (fname);
264 gpg_error_t tmperr = gpg_error_from_syserror ();
265 log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
266 gnupg_remove (fname);
270 bump_key_eventcounter ();
276 /* Callback function to try the unprotection from the passphrase query
279 try_unprotect_cb (struct pin_entry_info_s *pi)
281 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
282 ctrl_t ctrl = arg->ctrl;
285 gnupg_isotime_t now, protected_at, tmptime;
288 assert (!arg->unprotected_key);
290 arg->change_required = 0;
291 err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
292 &arg->unprotected_key, &dummy);
295 if (!opt.max_passphrase_days || ctrl->in_passwd)
296 return 0; /* No regular passphrase change required. */
300 /* No protection date known - must force passphrase change. */
301 desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
302 "Please change it now."));
304 return gpg_error_from_syserror ();
308 gnupg_get_isotime (now);
309 gnupg_copy_time (tmptime, protected_at);
310 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
313 if (strcmp (now, tmptime) > 0 )
315 /* Passphrase "expired". */
317 (L_("This passphrase has not been changed%%0A"
318 "since %.4s-%.2s-%.2s. Please change it now."),
319 protected_at, protected_at+4, protected_at+6);
321 return gpg_error_from_syserror ();
327 /* Change required. */
328 if (opt.enforce_passphrase_constraints)
330 err = agent_get_confirmation (ctrl, desc,
331 L_("Change passphrase"), NULL, 0);
333 arg->change_required = 1;
337 err = agent_get_confirmation (ctrl, desc,
338 L_("Change passphrase"),
339 L_("I'll change it later"), 0);
341 arg->change_required = 1;
342 else if (gpg_err_code (err) == GPG_ERR_CANCELED
343 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
353 /* Modify a Key description, replacing certain special format
354 characters. List of currently supported replacements:
356 %% - Replaced by a single %
357 %c - Replaced by the content of COMMENT.
358 %C - Same as %c but put into parentheses.
359 %F - Replaced by an ssh style fingerprint computed from KEY.
361 The functions returns 0 on success or an error code. On success a
362 newly allocated string is stored at the address of RESULT.
365 agent_modify_description (const char *in, const char *comment,
366 const gcry_sexp_t key, char **result)
368 size_t comment_length;
374 char *ssh_fpr = NULL;
382 comment_length = strlen (comment);
383 in_len = strlen (in);
385 /* First pass calculates the length, second pass does the actual
387 /* FIXME: This can be simplified by using es_fopenmem. */
390 for (pass=0; pass < 2; pass++)
393 for (i = 0; i < in_len; i++)
407 case 'c': /* Comment. */
410 memcpy (out, comment, comment_length);
411 out += comment_length;
414 out_len += comment_length;
417 case 'C': /* Comment. */
423 memcpy (out, comment, comment_length);
424 out += comment_length;
428 out_len += comment_length + 2;
431 case 'F': /* SSH style fingerprint. */
433 ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
438 out = stpcpy (out, ssh_fpr);
440 out_len += strlen (ssh_fpr);
444 default: /* Invalid special sequences are kept as they are. */
455 else if (in[i] == '%')
468 *result = out = xtrymalloc (out_len + 1);
472 return gpg_error_from_syserror ();
478 log_assert (*result + out_len == out);
481 /* The ssh prompt may sometimes end in
483 * The empty parentheses doesn't look very good. We use this hack
484 * here to remove them as well as the indentation spaces. */
487 if (i > 2 && !strcmp (p + i - 2, "()"))
491 while (p > *result && spacep (p))
500 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
501 should be the hex encoded keygrip of that key to be used with the
502 caching mechanism. DESC_TEXT may be set to override the default
503 description used for the pinentry. If LOOKUP_TTL is given this
504 function is used to lookup the default ttl. If R_PASSPHRASE is not
505 NULL, the function succeeded and the key was protected the used
506 passphrase (entered or from the cache) is stored there; if not NULL
507 will be stored. The caller needs to free the returned
510 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
511 unsigned char **keybuf, const unsigned char *grip,
512 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
515 struct pin_entry_info_s *pi;
516 struct try_unprotect_arg_s arg;
518 unsigned char *result;
523 *r_passphrase = NULL;
525 bin2hex (grip, 20, hexgrip);
527 /* Initially try to get it using a cache nonce. */
532 pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
535 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
550 /* First try to get it from the cache - if there is none or we can't
551 unprotect it, we fall back to ask the user */
552 if (cache_mode != CACHE_MODE_IGNORE)
557 pw = agent_get_cache (ctrl, hexgrip, cache_mode);
560 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
563 if (cache_mode == CACHE_MODE_NORMAL)
564 agent_store_cache_hit (hexgrip);
575 else if (cache_mode == CACHE_MODE_NORMAL)
577 /* The standard use of GPG keys is to have a signing and an
578 encryption subkey. Commonly both use the same
579 passphrase. We try to help the user to enter the
580 passphrase only once by silently trying the last
581 correctly entered passphrase. Checking one additional
582 passphrase should be acceptable; despite the S2K
583 introduced delays. The assumed workflow is:
585 1. Read encrypted message in a MUA and thus enter a
586 passphrase for the encryption subkey.
588 2. Reply to that mail with an encrypted and signed
589 mail, thus entering the passphrase for the signing
592 We can often avoid the passphrase entry in the second
593 step. We do this only in normal mode, so not to
594 interfere with unrelated cache entries. */
595 pw = agent_get_cache (ctrl, NULL, cache_mode);
598 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
599 &result, &resultlen);
614 /* If the pinentry is currently in use, we wait up to 60 seconds
615 for it to close and check the cache again. This solves a common
616 situation where several requests for unprotecting a key have
617 been made but the user is still entering the passphrase for
618 the first request. Because all requests to agent_askpin are
619 serialized they would then pop up one after the other to
620 request the passphrase - despite that the user has already
621 entered it and is then available in the cache. This
622 implementation is not race free but in the worst case the
623 user has to enter the passphrase only once more. */
624 if (pinentry_active_p (ctrl, 0))
627 if (!pinentry_active_p (ctrl, 60))
629 /* We need to give the other thread a chance to actually put
630 it into the cache. */
634 /* Timeout - better call pinentry now the plain way. */
638 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
640 return gpg_error_from_syserror ();
641 pi->max_length = MAX_PASSPHRASE_LEN + 1;
642 pi->min_digits = 0; /* we want a real passphrase */
645 pi->check_cb = try_unprotect_cb;
647 arg.protected_key = *keybuf;
648 arg.unprotected_key = NULL;
649 arg.change_required = 0;
650 pi->check_cb_arg = &arg;
652 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
655 if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE))
657 log_error ("Clearing pinentry cache which caused error %s\n",
660 agent_clear_passphrase (ctrl, hexgrip, cache_mode);
665 assert (arg.unprotected_key);
666 if (arg.change_required)
668 /* The callback told as that the user should change their
669 passphrase. Present the dialog to do. */
670 size_t canlen, erroff;
673 assert (arg.unprotected_key);
674 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
675 rc = gcry_sexp_sscan (&s_skey, &erroff,
676 (char*)arg.unprotected_key, canlen);
679 log_error ("failed to build S-Exp (off=%u): %s\n",
680 (unsigned int)erroff, gpg_strerror (rc));
681 wipememory (arg.unprotected_key, canlen);
682 xfree (arg.unprotected_key);
686 rc = agent_protect_and_store (ctrl, s_skey, NULL);
687 gcry_sexp_release (s_skey);
690 log_error ("changing the passphrase failed: %s\n",
692 wipememory (arg.unprotected_key, canlen);
693 xfree (arg.unprotected_key);
700 /* Passphrase is fine. */
701 agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
702 lookup_ttl? lookup_ttl (hexgrip) : 0);
703 agent_store_cache_hit (hexgrip);
704 if (r_passphrase && *pi->pin)
705 *r_passphrase = xtrystrdup (pi->pin);
708 *keybuf = arg.unprotected_key;
715 /* Read the key identified by GRIP from the private key directory and
716 return it as an gcrypt S-expression object in RESULT. On failure
717 returns an error code and stores NULL at RESULT. */
719 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
726 size_t buflen, erroff;
728 char hexgrip[40+4+1];
733 bin2hex (grip, 20, hexgrip);
734 strcpy (hexgrip+40, ".key");
736 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
738 fp = es_fopen (fname, "rb");
741 err = gpg_error_from_syserror ();
742 if (gpg_err_code (err) != GPG_ERR_ENOENT)
743 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
748 if (es_fread (&first, 1, 1, fp) != 1)
750 err = gpg_error_from_syserror ();
751 log_error ("error reading first byte from '%s': %s\n",
752 fname, gpg_strerror (err));
758 if (es_fseek (fp, 0, SEEK_SET))
760 err = gpg_error_from_syserror ();
761 log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
769 /* Key is in extended format. */
773 err = nvc_parse_private_key (&pk, &line, fp);
777 log_error ("error parsing '%s' line %d: %s\n",
778 fname, line, gpg_strerror (err));
781 err = nvc_get_private_key (pk, result);
784 log_error ("error getting private key from '%s': %s\n",
785 fname, gpg_strerror (err));
792 if (fstat (es_fileno (fp), &st))
794 err = gpg_error_from_syserror ();
795 log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
802 buf = xtrymalloc (buflen+1);
805 err = gpg_error_from_syserror ();
806 log_error ("error allocating %zu bytes for '%s': %s\n",
807 buflen, fname, gpg_strerror (err));
815 if (es_fread (buf, buflen, 1, fp) != 1)
817 err = gpg_error_from_syserror ();
818 log_error ("error reading %zu bytes from '%s': %s\n",
819 buflen, fname, gpg_strerror (err));
826 /* Convert the file into a gcrypt S-expression object. */
827 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
833 log_error ("failed to build S-Exp (off=%u): %s\n",
834 (unsigned int)erroff, gpg_strerror (err));
842 /* Remove the key identified by GRIP from the private key directory. */
844 remove_key_file (const unsigned char *grip)
848 char hexgrip[40+4+1];
850 bin2hex (grip, 20, hexgrip);
851 strcpy (hexgrip+40, ".key");
852 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
854 if (gnupg_remove (fname))
855 err = gpg_error_from_syserror ();
861 /* Return the secret key as an S-Exp in RESULT after locating it using
862 the GRIP. If the operation shall be diverted to a token, an
863 allocated S-expression with the shadow_info part from the file is
864 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
865 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
866 set to present a custom description for the pinentry. LOOKUP_TTL
867 is an optional function to convey a TTL to the cache manager; we do
868 not simply pass the TTL value because the value is only needed if
869 an unprotect action was needed and looking up the TTL may have some
870 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
871 given that cache item is first tried to get a passphrase. If
872 R_PASSPHRASE is not NULL, the function succeeded and the key was
873 protected the used passphrase (entered or from the cache) is stored
874 there; if not NULL will be stored. The caller needs to free the
875 returned passphrase. */
877 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
878 const char *desc_text,
879 const unsigned char *grip, unsigned char **shadow_info,
880 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
881 gcry_sexp_t *result, char **r_passphrase)
885 size_t len, buflen, erroff;
892 *r_passphrase = NULL;
894 err = read_key_file (grip, &s_skey);
897 if (gpg_err_code (err) == GPG_ERR_ENOENT)
898 err = gpg_error (GPG_ERR_NO_SECKEY);
902 /* For use with the protection functions we also need the key as an
903 canonical encoded S-expression in a buffer. Create this buffer
905 err = make_canon_sexp (s_skey, &buf, &len);
909 switch (agent_private_key_type (buf))
911 case PRIVATE_KEY_CLEAR:
912 break; /* no unprotection needed */
913 case PRIVATE_KEY_OPENPGP_NONE:
915 unsigned char *buf_new;
918 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
920 log_error ("failed to convert unprotected openpgp key: %s\n",
929 case PRIVATE_KEY_PROTECTED:
931 char *desc_text_final;
932 char *comment = NULL;
934 /* Note, that we will take the comment as a C string for
935 display purposes; i.e. all stuff beyond a Nul character is
938 gcry_sexp_t comment_sexp;
940 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
942 comment = gcry_sexp_nth_string (comment_sexp, 1);
943 gcry_sexp_release (comment_sexp);
946 desc_text_final = NULL;
948 err = agent_modify_description (desc_text, comment, s_skey,
954 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
955 cache_mode, lookup_ttl, r_passphrase);
957 log_error ("failed to unprotect the secret key: %s\n",
961 xfree (desc_text_final);
964 case PRIVATE_KEY_SHADOWED:
967 const unsigned char *s;
970 err = agent_get_shadow_info (buf, &s);
973 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
975 *shadow_info = xtrymalloc (n);
977 err = out_of_core ();
980 memcpy (*shadow_info, s, n);
985 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
988 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
991 log_error ("invalid private key format\n");
992 err = gpg_error (GPG_ERR_BAD_SECKEY);
995 gcry_sexp_release (s_skey);
1002 xfree (*r_passphrase);
1003 *r_passphrase = NULL;
1008 buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
1009 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
1010 wipememory (buf, buflen);
1014 log_error ("failed to build S-Exp (off=%u): %s\n",
1015 (unsigned int)erroff, gpg_strerror (err));
1018 xfree (*r_passphrase);
1019 *r_passphrase = NULL;
1029 /* Return the string name from the S-expression S_KEY as well as a
1030 string describing the names of the parameters. ALGONAMESIZE and
1031 ELEMSSIZE give the allocated size of the provided buffers. The
1032 buffers may be NULL if not required. If R_LIST is not NULL the top
1033 level list will be stored there; the caller needs to release it in
1036 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
1037 char *r_algoname, size_t algonamesize,
1038 char *r_elems, size_t elemssize)
1040 gcry_sexp_t list, l2;
1041 const char *name, *algoname, *elems;
1047 list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1049 list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1051 list = gcry_sexp_find_token (s_key, "private-key", 0 );
1054 log_error ("invalid private key format\n");
1055 return gpg_error (GPG_ERR_BAD_SECKEY);
1058 l2 = gcry_sexp_cadr (list);
1059 gcry_sexp_release (list);
1061 name = gcry_sexp_nth_data (list, 0, &n);
1062 if (n==3 && !memcmp (name, "rsa", 3))
1067 else if (n==3 && !memcmp (name, "dsa", 3))
1072 else if (n==3 && !memcmp (name, "ecc", 3))
1077 else if (n==5 && !memcmp (name, "ecdsa", 5))
1082 else if (n==4 && !memcmp (name, "ecdh", 4))
1087 else if (n==3 && !memcmp (name, "elg", 3))
1094 log_error ("unknown private key algorithm\n");
1095 gcry_sexp_release (list);
1096 return gpg_error (GPG_ERR_BAD_SECKEY);
1101 if (strlen (algoname) >= algonamesize)
1102 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1103 strcpy (r_algoname, algoname);
1107 if (strlen (elems) >= elemssize)
1108 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1109 strcpy (r_elems, elems);
1115 gcry_sexp_release (list);
1121 /* Return true if KEYPARMS holds an EdDSA key. */
1123 is_eddsa (gcry_sexp_t keyparms)
1131 list = gcry_sexp_find_token (keyparms, "flags", 0);
1132 for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
1134 s = gcry_sexp_nth_data (list, i, &n);
1136 continue; /* Not a data element. */
1138 if (n == 5 && !memcmp (s, "eddsa", 5))
1144 gcry_sexp_release (list);
1149 /* Return the public key algorithm number if S_KEY is a DSA style key.
1150 If it is not a DSA style key, return 0. */
1152 agent_is_dsa_key (gcry_sexp_t s_key)
1161 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1162 return 0; /* Error - assume it is not an DSA key. */
1164 if (!strcmp (algoname, "dsa"))
1165 result = GCRY_PK_DSA;
1166 else if (!strcmp (algoname, "ecc"))
1168 if (is_eddsa (list))
1171 result = GCRY_PK_ECDSA;
1173 else if (!strcmp (algoname, "ecdsa"))
1174 result = GCRY_PK_ECDSA;
1178 gcry_sexp_release (list);
1183 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519. */
1185 agent_is_eddsa_key (gcry_sexp_t s_key)
1194 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1195 return 0; /* Error - assume it is not an EdDSA key. */
1197 if (!strcmp (algoname, "ecc") && is_eddsa (list))
1199 else if (!strcmp (algoname, "eddsa")) /* backward compatibility. */
1204 gcry_sexp_release (list);
1209 /* Return the key for the keygrip GRIP. The result is stored at
1210 RESULT. This function extracts the key from the private key
1211 database and returns it as an S-expression object as it is. On
1212 failure an error code is returned and NULL stored at RESULT. */
1214 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1215 gcry_sexp_t *result)
1224 err = read_key_file (grip, &s_skey);
1231 /* Return the public key for the keygrip GRIP. The result is stored
1232 at RESULT. This function extracts the public key from the private
1233 key database. On failure an error code is returned and NULL stored
1236 agent_public_key_from_file (ctrl_t ctrl,
1237 const unsigned char *grip,
1238 gcry_sexp_t *result)
1243 const char *algoname, *elems;
1245 gcry_mpi_t array[10];
1246 gcry_sexp_t curve = NULL;
1247 gcry_sexp_t flags = NULL;
1248 gcry_sexp_t uri_sexp, comment_sexp;
1249 const char *uri, *comment;
1250 size_t uri_length, comment_length;
1251 int uri_intlen, comment_intlen;
1253 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1254 for comment + end-of-list. */
1256 gcry_sexp_t list = NULL;
1263 err = read_key_file (grip, &s_skey);
1267 for (i=0; i < DIM (array); i++)
1270 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1271 array, DIM (array), &curve, &flags);
1274 gcry_sexp_release (s_skey);
1280 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1282 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1286 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1288 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1290 gcry_sexp_release (s_skey);
1294 /* FIXME: The following thing is pretty ugly code; we should
1295 investigate how to make it cleaner. Probably code to handle
1296 canonical S-expressions in a memory buffer is better suited for
1297 such a task. After all that is what we do in protect.c. Need
1298 to find common patterns and write a straightformward API to use
1300 assert (sizeof (size_t) <= sizeof (void*));
1302 format = xtrymalloc (15+4+7*npkey+10+15+1+1);
1305 err = gpg_error_from_syserror ();
1306 for (i=0; array[i]; i++)
1307 gcry_mpi_release (array[i]);
1308 gcry_sexp_release (curve);
1309 gcry_sexp_release (flags);
1310 gcry_sexp_release (uri_sexp);
1311 gcry_sexp_release (comment_sexp);
1316 p = stpcpy (stpcpy (format, "(public-key("), algoname);
1317 p = stpcpy (p, "%S%S"); /* curve name and flags. */
1318 args[argidx++] = &curve;
1319 args[argidx++] = &flags;
1320 for (idx=0, s=elems; idx < npkey; idx++)
1324 p = stpcpy (p, " %m)");
1325 assert (argidx < DIM (args));
1326 args[argidx++] = &array[idx];
1331 p = stpcpy (p, "(uri %b)");
1332 assert (argidx+1 < DIM (args));
1333 uri_intlen = (int)uri_length;
1334 args[argidx++] = (void *)&uri_intlen;
1335 args[argidx++] = (void *)&uri;
1339 p = stpcpy (p, "(comment %b)");
1340 assert (argidx+1 < DIM (args));
1341 comment_intlen = (int)comment_length;
1342 args[argidx++] = (void *)&comment_intlen;
1343 args[argidx++] = (void*)&comment;
1347 assert (argidx < DIM (args));
1348 args[argidx] = NULL;
1350 err = gcry_sexp_build_array (&list, NULL, format, args);
1352 for (i=0; array[i]; i++)
1353 gcry_mpi_release (array[i]);
1354 gcry_sexp_release (curve);
1355 gcry_sexp_release (flags);
1356 gcry_sexp_release (uri_sexp);
1357 gcry_sexp_release (comment_sexp);
1366 /* Check whether the secret key identified by GRIP is available.
1367 Returns 0 is the key is available. */
1369 agent_key_available (const unsigned char *grip)
1373 char hexgrip[40+4+1];
1375 bin2hex (grip, 20, hexgrip);
1376 strcpy (hexgrip+40, ".key");
1378 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1380 result = !gnupg_access (fname, R_OK)? 0 : -1;
1387 /* Return the information about the secret key specified by the binary
1388 keygrip GRIP. If the key is a shadowed one the shadow information
1389 will be stored at the address R_SHADOW_INFO as an allocated
1392 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1393 int *r_keytype, unsigned char **r_shadow_info)
1403 *r_keytype = PRIVATE_KEY_UNKNOWN;
1405 *r_shadow_info = NULL;
1410 err = read_key_file (grip, &sexp);
1413 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1414 return gpg_error (GPG_ERR_NOT_FOUND);
1418 err = make_canon_sexp (sexp, &buf, &len);
1419 gcry_sexp_release (sexp);
1424 keytype = agent_private_key_type (buf);
1427 case PRIVATE_KEY_CLEAR:
1428 case PRIVATE_KEY_OPENPGP_NONE:
1430 case PRIVATE_KEY_PROTECTED:
1431 /* If we ever require it we could retrieve the comment fields
1434 case PRIVATE_KEY_SHADOWED:
1437 const unsigned char *s;
1440 err = agent_get_shadow_info (buf, &s);
1443 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1445 *r_shadow_info = xtrymalloc (n);
1446 if (!*r_shadow_info)
1447 err = gpg_error_from_syserror ();
1449 memcpy (*r_shadow_info, s, n);
1454 err = gpg_error (GPG_ERR_BAD_SECKEY);
1458 if (!err && r_keytype)
1459 *r_keytype = keytype;
1467 /* Delete the key with GRIP from the disk after having asked for
1468 * confirmation using DESC_TEXT. If FORCE is set the function won't
1469 * require a confirmation via Pinentry or warns if the key is also
1470 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1471 * smartcards) will be affected.
1473 * Common error codes are:
1475 * GPG_ERR_KEY_ON_CARD
1476 * GPG_ERR_NOT_CONFIRMED
1477 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1480 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1481 const unsigned char *grip, int force, int only_stubs)
1484 gcry_sexp_t s_skey = NULL;
1485 unsigned char *buf = NULL;
1487 char *desc_text_final = NULL;
1488 char *comment = NULL;
1489 ssh_control_file_t cf = NULL;
1490 char hexgrip[40+4+1];
1491 char *default_desc = NULL;
1494 err = read_key_file (grip, &s_skey);
1495 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1496 err = gpg_error (GPG_ERR_NO_SECKEY);
1500 err = make_canon_sexp (s_skey, &buf, &len);
1504 key_type = agent_private_key_type (buf);
1505 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1507 err = gpg_error (GPG_ERR_FORBIDDEN);
1513 case PRIVATE_KEY_CLEAR:
1514 case PRIVATE_KEY_OPENPGP_NONE:
1515 case PRIVATE_KEY_PROTECTED:
1516 bin2hex (grip, 20, hexgrip);
1521 default_desc = xtryasprintf
1522 (L_("Do you really want to delete the key identified by keygrip%%0A"
1523 " %s%%0A %%C%%0A?"), hexgrip);
1524 desc_text = default_desc;
1527 /* Note, that we will take the comment as a C string for
1528 display purposes; i.e. all stuff beyond a Nul character is
1531 gcry_sexp_t comment_sexp;
1533 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1535 comment = gcry_sexp_nth_string (comment_sexp, 1);
1536 gcry_sexp_release (comment_sexp);
1540 err = agent_modify_description (desc_text, comment, s_skey,
1545 err = agent_get_confirmation (ctrl, desc_text_final,
1546 L_("Delete key"), L_("No"), 0);
1550 cf = ssh_open_control_file ();
1553 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1555 err = agent_get_confirmation
1557 L_("Warning: This key is also listed for use with SSH!\n"
1558 "Deleting the key might remove your ability to "
1559 "access remote machines."),
1560 L_("Delete key"), L_("No"), 0);
1566 err = remove_key_file (grip);
1569 case PRIVATE_KEY_SHADOWED:
1570 err = remove_key_file (grip);
1574 log_error ("invalid private key format\n");
1575 err = gpg_error (GPG_ERR_BAD_SECKEY);
1580 ssh_close_control_file (cf);
1581 gcry_free (comment);
1582 xfree (desc_text_final);
1583 xfree (default_desc);
1585 gcry_sexp_release (s_skey);
1590 /* Write an S-expression formatted shadow key to our key storage.
1591 Shadow key is created by an S-expression public key in PKBUF and
1592 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1593 existing key with the given GRIP will get overwritten. */
1595 agent_write_shadow_key (const unsigned char *grip,
1596 const char *serialno, const char *keyid,
1597 const unsigned char *pkbuf, int force)
1600 unsigned char *shadow_info;
1601 unsigned char *shdkey;
1604 shadow_info = make_shadow_info (serialno, keyid);
1606 return gpg_error_from_syserror ();
1608 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1609 xfree (shadow_info);
1612 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1616 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1617 err = agent_write_private_key (grip, shdkey, len, force, 0);
1620 log_error ("error writing key: %s\n", gpg_strerror (err));