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,
58 const void *buf, size_t len)
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 err = es_fseek (fp, 0, SEEK_SET);
100 err = nvc_write (pk, fp);
103 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
108 if (ftruncate (es_fileno (fp), es_ftello (fp)))
110 err = gpg_error_from_syserror ();
111 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
118 err = gpg_error_from_syserror ();
119 log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
126 bump_key_eventcounter ();
131 gnupg_remove (fname);
133 gcry_sexp_release (key);
138 /* Write an S-expression formatted key to our key storage. With FORCE
139 passed as true an existing key with the given GRIP will get
142 agent_write_private_key (const unsigned char *grip,
143 const void *buffer, size_t length, int force)
147 char hexgrip[40+4+1];
149 bin2hex (grip, 20, hexgrip);
150 strcpy (hexgrip+40, ".key");
152 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
155 /* FIXME: Write to a temp file first so that write failures during
156 key updates won't lead to a key loss. */
158 if (!force && !access (fname, F_OK))
160 log_error ("secret key file '%s' already exists\n", fname);
162 return gpg_error (GPG_ERR_EEXIST);
165 fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
168 gpg_error_t tmperr = gpg_error_from_syserror ();
170 if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
172 fp = es_fopen (fname, "wbx,mode=-rw");
174 tmperr = gpg_error_from_syserror ();
178 log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
188 /* See if an existing key is in extended format. */
189 if (es_fread (&first, 1, 1, fp) != 1)
191 rc = gpg_error_from_syserror ();
192 log_error ("error reading first byte from '%s': %s\n",
193 fname, strerror (errno));
199 rc = es_fseek (fp, 0, SEEK_SET);
202 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
210 /* Key is already in the extended format. */
211 return write_extended_private_key (fname, fp, 1, buffer, length);
213 if (first == '(' && opt.enable_extended_key_format)
215 /* Key is in the old format - but we want the extended format. */
216 return write_extended_private_key (fname, fp, 0, buffer, length);
220 if (opt.enable_extended_key_format)
221 return write_extended_private_key (fname, fp, 0, buffer, length);
223 if (es_fwrite (buffer, length, 1, fp) != 1)
225 gpg_error_t tmperr = gpg_error_from_syserror ();
226 log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
228 gnupg_remove (fname);
233 /* When force is given, the file might have to be truncated. */
234 if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
236 gpg_error_t tmperr = gpg_error_from_syserror ();
237 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
239 gnupg_remove (fname);
246 gpg_error_t tmperr = gpg_error_from_syserror ();
247 log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
248 gnupg_remove (fname);
252 bump_key_eventcounter ();
258 /* Callback function to try the unprotection from the passphrase query
261 try_unprotect_cb (struct pin_entry_info_s *pi)
263 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
264 ctrl_t ctrl = arg->ctrl;
267 gnupg_isotime_t now, protected_at, tmptime;
270 assert (!arg->unprotected_key);
272 arg->change_required = 0;
273 err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
274 &arg->unprotected_key, &dummy);
277 if (!opt.max_passphrase_days || ctrl->in_passwd)
278 return 0; /* No regular passphrase change required. */
282 /* No protection date known - must force passphrase change. */
283 desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
284 "Please change it now."));
286 return gpg_error_from_syserror ();
290 gnupg_get_isotime (now);
291 gnupg_copy_time (tmptime, protected_at);
292 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
295 if (strcmp (now, tmptime) > 0 )
297 /* Passphrase "expired". */
299 (L_("This passphrase has not been changed%%0A"
300 "since %.4s-%.2s-%.2s. Please change it now."),
301 protected_at, protected_at+4, protected_at+6);
303 return gpg_error_from_syserror ();
309 /* Change required. */
310 if (opt.enforce_passphrase_constraints)
312 err = agent_get_confirmation (ctrl, desc,
313 L_("Change passphrase"), NULL, 0);
315 arg->change_required = 1;
319 err = agent_get_confirmation (ctrl, desc,
320 L_("Change passphrase"),
321 L_("I'll change it later"), 0);
323 arg->change_required = 1;
324 else if (gpg_err_code (err) == GPG_ERR_CANCELED
325 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
335 /* Modify a Key description, replacing certain special format
336 characters. List of currently supported replacements:
338 %% - Replaced by a single %
339 %c - Replaced by the content of COMMENT.
340 %C - Same as %c but put into parentheses.
341 %F - Replaced by an ssh style fingerprint computed from KEY.
343 The functions returns 0 on success or an error code. On success a
344 newly allocated string is stored at the address of RESULT.
347 agent_modify_description (const char *in, const char *comment,
348 const gcry_sexp_t key, char **result)
350 size_t comment_length;
356 char *ssh_fpr = NULL;
364 comment_length = strlen (comment);
365 in_len = strlen (in);
367 /* First pass calculates the length, second pass does the actual
369 /* FIXME: This can be simplified by using es_fopenmem. */
372 for (pass=0; pass < 2; pass++)
375 for (i = 0; i < in_len; i++)
389 case 'c': /* Comment. */
392 memcpy (out, comment, comment_length);
393 out += comment_length;
396 out_len += comment_length;
399 case 'C': /* Comment. */
405 memcpy (out, comment, comment_length);
406 out += comment_length;
410 out_len += comment_length + 2;
413 case 'F': /* SSH style fingerprint. */
415 ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
420 out = stpcpy (out, ssh_fpr);
422 out_len += strlen (ssh_fpr);
426 default: /* Invalid special sequences are kept as they are. */
437 else if (in[i] == '%')
450 *result = out = xtrymalloc (out_len + 1);
454 return gpg_error_from_syserror ();
460 log_assert (*result + out_len == out);
463 /* The ssh prompt may sometimes end in
465 * The empty parentheses doesn't look very good. We use this hack
466 * here to remove them as well as the indentation spaces. */
469 if (i > 2 && !strcmp (p + i - 2, "()"))
473 while (p > *result && spacep (p))
482 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
483 should be the hex encoded keygrip of that key to be used with the
484 caching mechanism. DESC_TEXT may be set to override the default
485 description used for the pinentry. If LOOKUP_TTL is given this
486 function is used to lookup the default ttl. If R_PASSPHRASE is not
487 NULL, the function succeeded and the key was protected the used
488 passphrase (entered or from the cache) is stored there; if not NULL
489 will be stored. The caller needs to free the returned
492 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
493 unsigned char **keybuf, const unsigned char *grip,
494 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
497 struct pin_entry_info_s *pi;
498 struct try_unprotect_arg_s arg;
500 unsigned char *result;
505 *r_passphrase = NULL;
507 bin2hex (grip, 20, hexgrip);
509 /* Initially try to get it using a cache nonce. */
514 pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
517 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
532 /* First try to get it from the cache - if there is none or we can't
533 unprotect it, we fall back to ask the user */
534 if (cache_mode != CACHE_MODE_IGNORE)
539 pw = agent_get_cache (ctrl, hexgrip, cache_mode);
542 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
545 if (cache_mode == CACHE_MODE_NORMAL)
546 agent_store_cache_hit (hexgrip);
557 else if (cache_mode == CACHE_MODE_NORMAL)
559 /* The standard use of GPG keys is to have a signing and an
560 encryption subkey. Commonly both use the same
561 passphrase. We try to help the user to enter the
562 passphrase only once by silently trying the last
563 correctly entered passphrase. Checking one additional
564 passphrase should be acceptable; despite the S2K
565 introduced delays. The assumed workflow is:
567 1. Read encrypted message in a MUA and thus enter a
568 passphrase for the encryption subkey.
570 2. Reply to that mail with an encrypted and signed
571 mail, thus entering the passphrase for the signing
574 We can often avoid the passphrase entry in the second
575 step. We do this only in normal mode, so not to
576 interfere with unrelated cache entries. */
577 pw = agent_get_cache (ctrl, NULL, cache_mode);
580 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
581 &result, &resultlen);
596 /* If the pinentry is currently in use, we wait up to 60 seconds
597 for it to close and check the cache again. This solves a common
598 situation where several requests for unprotecting a key have
599 been made but the user is still entering the passphrase for
600 the first request. Because all requests to agent_askpin are
601 serialized they would then pop up one after the other to
602 request the passphrase - despite that the user has already
603 entered it and is then available in the cache. This
604 implementation is not race free but in the worst case the
605 user has to enter the passphrase only once more. */
606 if (pinentry_active_p (ctrl, 0))
609 if (!pinentry_active_p (ctrl, 60))
611 /* We need to give the other thread a chance to actually put
612 it into the cache. */
616 /* Timeout - better call pinentry now the plain way. */
620 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
622 return gpg_error_from_syserror ();
623 pi->max_length = MAX_PASSPHRASE_LEN + 1;
624 pi->min_digits = 0; /* we want a real passphrase */
627 pi->check_cb = try_unprotect_cb;
629 arg.protected_key = *keybuf;
630 arg.unprotected_key = NULL;
631 arg.change_required = 0;
632 pi->check_cb_arg = &arg;
634 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
637 if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE))
639 log_error ("Clearing pinentry cache which caused error %s\n",
642 agent_clear_passphrase (ctrl, hexgrip, cache_mode);
647 assert (arg.unprotected_key);
648 if (arg.change_required)
650 /* The callback told as that the user should change their
651 passphrase. Present the dialog to do. */
652 size_t canlen, erroff;
655 assert (arg.unprotected_key);
656 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
657 rc = gcry_sexp_sscan (&s_skey, &erroff,
658 (char*)arg.unprotected_key, canlen);
661 log_error ("failed to build S-Exp (off=%u): %s\n",
662 (unsigned int)erroff, gpg_strerror (rc));
663 wipememory (arg.unprotected_key, canlen);
664 xfree (arg.unprotected_key);
668 rc = agent_protect_and_store (ctrl, s_skey, NULL);
669 gcry_sexp_release (s_skey);
672 log_error ("changing the passphrase failed: %s\n",
674 wipememory (arg.unprotected_key, canlen);
675 xfree (arg.unprotected_key);
682 /* Passphrase is fine. */
683 agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
684 lookup_ttl? lookup_ttl (hexgrip) : 0);
685 agent_store_cache_hit (hexgrip);
686 if (r_passphrase && *pi->pin)
687 *r_passphrase = xtrystrdup (pi->pin);
690 *keybuf = arg.unprotected_key;
697 /* Read the key identified by GRIP from the private key directory and
698 return it as an gcrypt S-expression object in RESULT. On failure
699 returns an error code and stores NULL at RESULT. */
701 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
708 size_t buflen, erroff;
710 char hexgrip[40+4+1];
715 bin2hex (grip, 20, hexgrip);
716 strcpy (hexgrip+40, ".key");
718 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
720 fp = es_fopen (fname, "rb");
723 err = gpg_error_from_syserror ();
724 if (gpg_err_code (err) != GPG_ERR_ENOENT)
725 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
730 if (es_fread (&first, 1, 1, fp) != 1)
732 err = gpg_error_from_syserror ();
733 log_error ("error reading first byte from '%s': %s\n",
734 fname, gpg_strerror (err));
740 if (es_fseek (fp, 0, SEEK_SET))
742 err = gpg_error_from_syserror ();
743 log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
751 /* Key is in extended format. */
755 err = nvc_parse_private_key (&pk, &line, fp);
759 log_error ("error parsing '%s' line %d: %s\n",
760 fname, line, gpg_strerror (err));
763 err = nvc_get_private_key (pk, result);
766 log_error ("error getting private key from '%s': %s\n",
767 fname, gpg_strerror (err));
774 if (fstat (es_fileno (fp), &st))
776 err = gpg_error_from_syserror ();
777 log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
784 buf = xtrymalloc (buflen+1);
787 err = gpg_error_from_syserror ();
788 log_error ("error allocating %zu bytes for '%s': %s\n",
789 buflen, fname, gpg_strerror (err));
797 if (es_fread (buf, buflen, 1, fp) != 1)
799 err = gpg_error_from_syserror ();
800 log_error ("error reading %zu bytes from '%s': %s\n",
801 buflen, fname, gpg_strerror (err));
808 /* Convert the file into a gcrypt S-expression object. */
809 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
815 log_error ("failed to build S-Exp (off=%u): %s\n",
816 (unsigned int)erroff, gpg_strerror (err));
824 /* Remove the key identified by GRIP from the private key directory. */
826 remove_key_file (const unsigned char *grip)
830 char hexgrip[40+4+1];
832 bin2hex (grip, 20, hexgrip);
833 strcpy (hexgrip+40, ".key");
834 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
836 if (gnupg_remove (fname))
837 err = gpg_error_from_syserror ();
843 /* Return the secret key as an S-Exp in RESULT after locating it using
844 the GRIP. If the operation shall be diverted to a token, an
845 allocated S-expression with the shadow_info part from the file is
846 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
847 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
848 set to present a custom description for the pinentry. LOOKUP_TTL
849 is an optional function to convey a TTL to the cache manager; we do
850 not simply pass the TTL value because the value is only needed if
851 an unprotect action was needed and looking up the TTL may have some
852 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
853 given that cache item is first tried to get a passphrase. If
854 R_PASSPHRASE is not NULL, the function succeeded and the key was
855 protected the used passphrase (entered or from the cache) is stored
856 there; if not NULL will be stored. The caller needs to free the
857 returned passphrase. */
859 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
860 const char *desc_text,
861 const unsigned char *grip, unsigned char **shadow_info,
862 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
863 gcry_sexp_t *result, char **r_passphrase)
867 size_t len, buflen, erroff;
874 *r_passphrase = NULL;
876 err = read_key_file (grip, &s_skey);
879 if (gpg_err_code (err) == GPG_ERR_ENOENT)
880 err = gpg_error (GPG_ERR_NO_SECKEY);
884 /* For use with the protection functions we also need the key as an
885 canonical encoded S-expression in a buffer. Create this buffer
887 err = make_canon_sexp (s_skey, &buf, &len);
891 switch (agent_private_key_type (buf))
893 case PRIVATE_KEY_CLEAR:
894 break; /* no unprotection needed */
895 case PRIVATE_KEY_OPENPGP_NONE:
897 unsigned char *buf_new;
900 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
902 log_error ("failed to convert unprotected openpgp key: %s\n",
911 case PRIVATE_KEY_PROTECTED:
913 char *desc_text_final;
914 char *comment = NULL;
916 /* Note, that we will take the comment as a C string for
917 display purposes; i.e. all stuff beyond a Nul character is
920 gcry_sexp_t comment_sexp;
922 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
924 comment = gcry_sexp_nth_string (comment_sexp, 1);
925 gcry_sexp_release (comment_sexp);
928 desc_text_final = NULL;
930 err = agent_modify_description (desc_text, comment, s_skey,
936 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
937 cache_mode, lookup_ttl, r_passphrase);
939 log_error ("failed to unprotect the secret key: %s\n",
943 xfree (desc_text_final);
946 case PRIVATE_KEY_SHADOWED:
949 const unsigned char *s;
952 err = agent_get_shadow_info (buf, &s);
955 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
957 *shadow_info = xtrymalloc (n);
959 err = out_of_core ();
962 memcpy (*shadow_info, s, n);
967 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
970 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
973 log_error ("invalid private key format\n");
974 err = gpg_error (GPG_ERR_BAD_SECKEY);
977 gcry_sexp_release (s_skey);
984 xfree (*r_passphrase);
985 *r_passphrase = NULL;
990 buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
991 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
992 wipememory (buf, buflen);
996 log_error ("failed to build S-Exp (off=%u): %s\n",
997 (unsigned int)erroff, gpg_strerror (err));
1000 xfree (*r_passphrase);
1001 *r_passphrase = NULL;
1011 /* Return the string name from the S-expression S_KEY as well as a
1012 string describing the names of the parameters. ALGONAMESIZE and
1013 ELEMSSIZE give the allocated size of the provided buffers. The
1014 buffers may be NULL if not required. If R_LIST is not NULL the top
1015 level list will be stored there; the caller needs to release it in
1018 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
1019 char *r_algoname, size_t algonamesize,
1020 char *r_elems, size_t elemssize)
1022 gcry_sexp_t list, l2;
1023 const char *name, *algoname, *elems;
1029 list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1031 list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1033 list = gcry_sexp_find_token (s_key, "private-key", 0 );
1036 log_error ("invalid private key format\n");
1037 return gpg_error (GPG_ERR_BAD_SECKEY);
1040 l2 = gcry_sexp_cadr (list);
1041 gcry_sexp_release (list);
1043 name = gcry_sexp_nth_data (list, 0, &n);
1044 if (n==3 && !memcmp (name, "rsa", 3))
1049 else if (n==3 && !memcmp (name, "dsa", 3))
1054 else if (n==3 && !memcmp (name, "ecc", 3))
1059 else if (n==5 && !memcmp (name, "ecdsa", 5))
1064 else if (n==4 && !memcmp (name, "ecdh", 4))
1069 else if (n==3 && !memcmp (name, "elg", 3))
1076 log_error ("unknown private key algorithm\n");
1077 gcry_sexp_release (list);
1078 return gpg_error (GPG_ERR_BAD_SECKEY);
1083 if (strlen (algoname) >= algonamesize)
1084 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1085 strcpy (r_algoname, algoname);
1089 if (strlen (elems) >= elemssize)
1090 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1091 strcpy (r_elems, elems);
1097 gcry_sexp_release (list);
1103 /* Return true if KEYPARMS holds an EdDSA key. */
1105 is_eddsa (gcry_sexp_t keyparms)
1113 list = gcry_sexp_find_token (keyparms, "flags", 0);
1114 for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
1116 s = gcry_sexp_nth_data (list, i, &n);
1118 continue; /* Not a data element. */
1120 if (n == 5 && !memcmp (s, "eddsa", 5))
1126 gcry_sexp_release (list);
1131 /* Return the public key algorithm number if S_KEY is a DSA style key.
1132 If it is not a DSA style key, return 0. */
1134 agent_is_dsa_key (gcry_sexp_t s_key)
1143 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1144 return 0; /* Error - assume it is not an DSA key. */
1146 if (!strcmp (algoname, "dsa"))
1147 result = GCRY_PK_DSA;
1148 else if (!strcmp (algoname, "ecc"))
1150 if (is_eddsa (list))
1153 result = GCRY_PK_ECDSA;
1155 else if (!strcmp (algoname, "ecdsa"))
1156 result = GCRY_PK_ECDSA;
1160 gcry_sexp_release (list);
1165 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519. */
1167 agent_is_eddsa_key (gcry_sexp_t s_key)
1176 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1177 return 0; /* Error - assume it is not an EdDSA key. */
1179 if (!strcmp (algoname, "ecc") && is_eddsa (list))
1181 else if (!strcmp (algoname, "eddsa")) /* backward compatibility. */
1186 gcry_sexp_release (list);
1191 /* Return the key for the keygrip GRIP. The result is stored at
1192 RESULT. This function extracts the key from the private key
1193 database and returns it as an S-expression object as it is. On
1194 failure an error code is returned and NULL stored at RESULT. */
1196 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1197 gcry_sexp_t *result)
1206 err = read_key_file (grip, &s_skey);
1213 /* Return the public key for the keygrip GRIP. The result is stored
1214 at RESULT. This function extracts the public key from the private
1215 key database. On failure an error code is returned and NULL stored
1218 agent_public_key_from_file (ctrl_t ctrl,
1219 const unsigned char *grip,
1220 gcry_sexp_t *result)
1225 const char *algoname, *elems;
1227 gcry_mpi_t array[10];
1228 gcry_sexp_t curve = NULL;
1229 gcry_sexp_t flags = NULL;
1230 gcry_sexp_t uri_sexp, comment_sexp;
1231 const char *uri, *comment;
1232 size_t uri_length, comment_length;
1234 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1235 for comment + end-of-list. */
1237 gcry_sexp_t list = NULL;
1244 err = read_key_file (grip, &s_skey);
1248 for (i=0; i < DIM (array); i++)
1251 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1252 array, DIM (array), &curve, &flags);
1255 gcry_sexp_release (s_skey);
1261 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1263 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1267 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1269 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1271 gcry_sexp_release (s_skey);
1275 /* FIXME: The following thing is pretty ugly code; we should
1276 investigate how to make it cleaner. Probably code to handle
1277 canonical S-expressions in a memory buffer is better suited for
1278 such a task. After all that is what we do in protect.c. Need
1279 to find common patterns and write a straightformward API to use
1281 assert (sizeof (size_t) <= sizeof (void*));
1283 format = xtrymalloc (15+4+7*npkey+10+15+1+1);
1286 err = gpg_error_from_syserror ();
1287 for (i=0; array[i]; i++)
1288 gcry_mpi_release (array[i]);
1289 gcry_sexp_release (curve);
1290 gcry_sexp_release (flags);
1291 gcry_sexp_release (uri_sexp);
1292 gcry_sexp_release (comment_sexp);
1297 p = stpcpy (stpcpy (format, "(public-key("), algoname);
1298 p = stpcpy (p, "%S%S"); /* curve name and flags. */
1299 args[argidx++] = &curve;
1300 args[argidx++] = &flags;
1301 for (idx=0, s=elems; idx < npkey; idx++)
1305 p = stpcpy (p, " %m)");
1306 assert (argidx < DIM (args));
1307 args[argidx++] = &array[idx];
1312 p = stpcpy (p, "(uri %b)");
1313 assert (argidx+1 < DIM (args));
1314 args[argidx++] = (void *)&uri_length;
1315 args[argidx++] = (void *)&uri;
1319 p = stpcpy (p, "(comment %b)");
1320 assert (argidx+1 < DIM (args));
1321 args[argidx++] = (void *)&comment_length;
1322 args[argidx++] = (void*)&comment;
1326 assert (argidx < DIM (args));
1327 args[argidx] = NULL;
1329 err = gcry_sexp_build_array (&list, NULL, format, args);
1331 for (i=0; array[i]; i++)
1332 gcry_mpi_release (array[i]);
1333 gcry_sexp_release (curve);
1334 gcry_sexp_release (flags);
1335 gcry_sexp_release (uri_sexp);
1336 gcry_sexp_release (comment_sexp);
1345 /* Check whether the secret key identified by GRIP is available.
1346 Returns 0 is the key is available. */
1348 agent_key_available (const unsigned char *grip)
1352 char hexgrip[40+4+1];
1354 bin2hex (grip, 20, hexgrip);
1355 strcpy (hexgrip+40, ".key");
1357 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1359 result = !access (fname, R_OK)? 0 : -1;
1366 /* Return the information about the secret key specified by the binary
1367 keygrip GRIP. If the key is a shadowed one the shadow information
1368 will be stored at the address R_SHADOW_INFO as an allocated
1371 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1372 int *r_keytype, unsigned char **r_shadow_info)
1382 *r_keytype = PRIVATE_KEY_UNKNOWN;
1384 *r_shadow_info = NULL;
1389 err = read_key_file (grip, &sexp);
1392 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1393 return gpg_error (GPG_ERR_NOT_FOUND);
1397 err = make_canon_sexp (sexp, &buf, &len);
1398 gcry_sexp_release (sexp);
1403 keytype = agent_private_key_type (buf);
1406 case PRIVATE_KEY_CLEAR:
1407 case PRIVATE_KEY_OPENPGP_NONE:
1409 case PRIVATE_KEY_PROTECTED:
1410 /* If we ever require it we could retrieve the comment fields
1413 case PRIVATE_KEY_SHADOWED:
1416 const unsigned char *s;
1419 err = agent_get_shadow_info (buf, &s);
1422 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1424 *r_shadow_info = xtrymalloc (n);
1425 if (!*r_shadow_info)
1426 err = gpg_error_from_syserror ();
1428 memcpy (*r_shadow_info, s, n);
1433 err = gpg_error (GPG_ERR_BAD_SECKEY);
1437 if (!err && r_keytype)
1438 *r_keytype = keytype;
1446 /* Delete the key with GRIP from the disk after having asked for
1447 * confirmation using DESC_TEXT. If FORCE is set the function won't
1448 * require a confirmation via Pinentry or warns if the key is also
1449 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1450 * smartcards) will be affected.
1452 * Common error codes are:
1454 * GPG_ERR_KEY_ON_CARD
1455 * GPG_ERR_NOT_CONFIRMED
1456 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1459 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1460 const unsigned char *grip, int force, int only_stubs)
1463 gcry_sexp_t s_skey = NULL;
1464 unsigned char *buf = NULL;
1466 char *desc_text_final = NULL;
1467 char *comment = NULL;
1468 ssh_control_file_t cf = NULL;
1469 char hexgrip[40+4+1];
1470 char *default_desc = NULL;
1473 err = read_key_file (grip, &s_skey);
1474 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1475 err = gpg_error (GPG_ERR_NO_SECKEY);
1479 err = make_canon_sexp (s_skey, &buf, &len);
1483 key_type = agent_private_key_type (buf);
1484 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1486 err = gpg_error (GPG_ERR_FORBIDDEN);
1492 case PRIVATE_KEY_CLEAR:
1493 case PRIVATE_KEY_OPENPGP_NONE:
1494 case PRIVATE_KEY_PROTECTED:
1495 bin2hex (grip, 20, hexgrip);
1500 default_desc = xtryasprintf
1501 (L_("Do you really want to delete the key identified by keygrip%%0A"
1502 " %s%%0A %%C%%0A?"), hexgrip);
1503 desc_text = default_desc;
1506 /* Note, that we will take the comment as a C string for
1507 display purposes; i.e. all stuff beyond a Nul character is
1510 gcry_sexp_t comment_sexp;
1512 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1514 comment = gcry_sexp_nth_string (comment_sexp, 1);
1515 gcry_sexp_release (comment_sexp);
1519 err = agent_modify_description (desc_text, comment, s_skey,
1524 err = agent_get_confirmation (ctrl, desc_text_final,
1525 L_("Delete key"), L_("No"), 0);
1529 cf = ssh_open_control_file ();
1532 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1534 err = agent_get_confirmation
1536 L_("Warning: This key is also listed for use with SSH!\n"
1537 "Deleting the key might remove your ability to "
1538 "access remote machines."),
1539 L_("Delete key"), L_("No"), 0);
1545 err = remove_key_file (grip);
1548 case PRIVATE_KEY_SHADOWED:
1549 err = remove_key_file (grip);
1553 log_error ("invalid private key format\n");
1554 err = gpg_error (GPG_ERR_BAD_SECKEY);
1559 ssh_close_control_file (cf);
1560 gcry_free (comment);
1561 xfree (desc_text_final);
1562 xfree (default_desc);
1564 gcry_sexp_release (s_skey);
1569 /* Write an S-expression formatted shadow key to our key storage.
1570 Shadow key is created by an S-expression public key in PKBUF and
1571 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1572 existing key with the given GRIP will get overwritten. */
1574 agent_write_shadow_key (const unsigned char *grip,
1575 const char *serialno, const char *keyid,
1576 const unsigned char *pkbuf, int force)
1579 unsigned char *shadow_info;
1580 unsigned char *shdkey;
1583 shadow_info = make_shadow_info (serialno, keyid);
1585 return gpg_error_from_syserror ();
1587 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1588 xfree (shadow_info);
1591 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1595 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1596 err = agent_write_private_key (grip, shdkey, len, force);
1599 log_error ("error writing key: %s\n", gpg_strerror (err));