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, &ssh_fpr);
419 out = stpcpy (out, ssh_fpr);
421 out_len += strlen (ssh_fpr);
425 default: /* Invalid special sequences are kept as they are. */
436 else if (in[i] == '%')
449 *result = out = xtrymalloc (out_len + 1);
453 return gpg_error_from_syserror ();
459 log_assert (*result + out_len == out);
462 /* The ssh prompt may sometimes end in
464 * The empty parentheses doesn't look very good. We use this hack
465 * here to remove them as well as the indentation spaces. */
468 if (i > 2 && !strcmp (p + i - 2, "()"))
472 while (p > *result && spacep (p))
481 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
482 should be the hex encoded keygrip of that key to be used with the
483 caching mechanism. DESC_TEXT may be set to override the default
484 description used for the pinentry. If LOOKUP_TTL is given this
485 function is used to lookup the default ttl. If R_PASSPHRASE is not
486 NULL, the function succeeded and the key was protected the used
487 passphrase (entered or from the cache) is stored there; if not NULL
488 will be stored. The caller needs to free the returned
491 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
492 unsigned char **keybuf, const unsigned char *grip,
493 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
496 struct pin_entry_info_s *pi;
497 struct try_unprotect_arg_s arg;
499 unsigned char *result;
504 *r_passphrase = NULL;
506 bin2hex (grip, 20, hexgrip);
508 /* Initially try to get it using a cache nonce. */
513 pw = agent_get_cache (cache_nonce, CACHE_MODE_NONCE);
516 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
531 /* First try to get it from the cache - if there is none or we can't
532 unprotect it, we fall back to ask the user */
533 if (cache_mode != CACHE_MODE_IGNORE)
538 pw = agent_get_cache (hexgrip, cache_mode);
541 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
544 if (cache_mode == CACHE_MODE_NORMAL)
545 agent_store_cache_hit (hexgrip);
556 else if (cache_mode == CACHE_MODE_NORMAL)
558 /* The standard use of GPG keys is to have a signing and an
559 encryption subkey. Commonly both use the same
560 passphrase. We try to help the user to enter the
561 passphrase only once by silently trying the last
562 correctly entered passphrase. Checking one additional
563 passphrase should be acceptable; despite the S2K
564 introduced delays. The assumed workflow is:
566 1. Read encrypted message in a MUA and thus enter a
567 passphrase for the encryption subkey.
569 2. Reply to that mail with an encrypted and signed
570 mail, thus entering the passphrase for the signing
573 We can often avoid the passphrase entry in the second
574 step. We do this only in normal mode, so not to
575 interfere with unrelated cache entries. */
576 pw = agent_get_cache (NULL, cache_mode);
579 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
580 &result, &resultlen);
595 /* If the pinentry is currently in use, we wait up to 60 seconds
596 for it to close and check the cache again. This solves a common
597 situation where several requests for unprotecting a key have
598 been made but the user is still entering the passphrase for
599 the first request. Because all requests to agent_askpin are
600 serialized they would then pop up one after the other to
601 request the passphrase - despite that the user has already
602 entered it and is then available in the cache. This
603 implementation is not race free but in the worst case the
604 user has to enter the passphrase only once more. */
605 if (pinentry_active_p (ctrl, 0))
608 if (!pinentry_active_p (ctrl, 60))
610 /* We need to give the other thread a chance to actually put
611 it into the cache. */
615 /* Timeout - better call pinentry now the plain way. */
619 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
621 return gpg_error_from_syserror ();
622 pi->max_length = MAX_PASSPHRASE_LEN + 1;
623 pi->min_digits = 0; /* we want a real passphrase */
626 pi->check_cb = try_unprotect_cb;
628 arg.protected_key = *keybuf;
629 arg.unprotected_key = NULL;
630 arg.change_required = 0;
631 pi->check_cb_arg = &arg;
633 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
636 assert (arg.unprotected_key);
637 if (arg.change_required)
639 /* The callback told as that the user should change their
640 passphrase. Present the dialog to do. */
641 size_t canlen, erroff;
644 assert (arg.unprotected_key);
645 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
646 rc = gcry_sexp_sscan (&s_skey, &erroff,
647 (char*)arg.unprotected_key, canlen);
650 log_error ("failed to build S-Exp (off=%u): %s\n",
651 (unsigned int)erroff, gpg_strerror (rc));
652 wipememory (arg.unprotected_key, canlen);
653 xfree (arg.unprotected_key);
657 rc = agent_protect_and_store (ctrl, s_skey, NULL);
658 gcry_sexp_release (s_skey);
661 log_error ("changing the passphrase failed: %s\n",
663 wipememory (arg.unprotected_key, canlen);
664 xfree (arg.unprotected_key);
671 /* Passphrase is fine. */
672 agent_put_cache (hexgrip, cache_mode, pi->pin,
673 lookup_ttl? lookup_ttl (hexgrip) : 0);
674 agent_store_cache_hit (hexgrip);
675 if (r_passphrase && *pi->pin)
676 *r_passphrase = xtrystrdup (pi->pin);
679 *keybuf = arg.unprotected_key;
686 /* Read the key identified by GRIP from the private key directory and
687 return it as an gcrypt S-expression object in RESULT. On failure
688 returns an error code and stores NULL at RESULT. */
690 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
697 size_t buflen, erroff;
699 char hexgrip[40+4+1];
704 bin2hex (grip, 20, hexgrip);
705 strcpy (hexgrip+40, ".key");
707 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
709 fp = es_fopen (fname, "rb");
712 rc = gpg_error_from_syserror ();
713 if (gpg_err_code (rc) != GPG_ERR_ENOENT)
714 log_error ("can't open '%s': %s\n", fname, strerror (errno));
719 if (es_fread (&first, 1, 1, fp) != 1)
721 rc = gpg_error_from_syserror ();
722 log_error ("error reading first byte from '%s': %s\n",
723 fname, strerror (errno));
729 rc = es_fseek (fp, 0, SEEK_SET);
732 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
740 /* Key is in extended format. */
744 rc = nvc_parse_private_key (&pk, &line, fp);
748 log_error ("error parsing '%s' line %d: %s\n",
749 fname, line, gpg_strerror (rc));
752 rc = nvc_get_private_key (pk, result);
755 log_error ("error getting private key from '%s': %s\n",
756 fname, gpg_strerror (rc));
763 if (fstat (es_fileno (fp), &st))
765 rc = gpg_error_from_syserror ();
766 log_error ("can't stat '%s': %s\n", fname, strerror (errno));
773 buf = xtrymalloc (buflen+1);
776 rc = gpg_error_from_syserror ();
777 log_error ("error allocating %zu bytes for '%s': %s\n",
778 buflen, fname, strerror (errno));
786 if (es_fread (buf, buflen, 1, fp) != 1)
788 rc = gpg_error_from_syserror ();
789 log_error ("error reading %zu bytes from '%s': %s\n",
790 buflen, fname, strerror (errno));
797 /* Convert the file into a gcrypt S-expression object. */
798 rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
804 log_error ("failed to build S-Exp (off=%u): %s\n",
805 (unsigned int)erroff, gpg_strerror (rc));
813 /* Remove the key identified by GRIP from the private key directory. */
815 remove_key_file (const unsigned char *grip)
819 char hexgrip[40+4+1];
821 bin2hex (grip, 20, hexgrip);
822 strcpy (hexgrip+40, ".key");
823 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
825 if (gnupg_remove (fname))
826 err = gpg_error_from_syserror ();
832 /* Return the secret key as an S-Exp in RESULT after locating it using
833 the GRIP. If the operation shall be diverted to a token, an
834 allocated S-expression with the shadow_info part from the file is
835 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
836 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
837 set to present a custom description for the pinentry. LOOKUP_TTL
838 is an optional function to convey a TTL to the cache manager; we do
839 not simply pass the TTL value because the value is only needed if
840 an unprotect action was needed and looking up the TTL may have some
841 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
842 given that cache item is first tried to get a passphrase. If
843 R_PASSPHRASE is not NULL, the function succeeded and the key was
844 protected the used passphrase (entered or from the cache) is stored
845 there; if not NULL will be stored. The caller needs to free the
846 returned passphrase. */
848 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
849 const char *desc_text,
850 const unsigned char *grip, unsigned char **shadow_info,
851 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
852 gcry_sexp_t *result, char **r_passphrase)
856 size_t len, buflen, erroff;
863 *r_passphrase = NULL;
865 rc = read_key_file (grip, &s_skey);
868 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
869 rc = gpg_error (GPG_ERR_NO_SECKEY);
873 /* For use with the protection functions we also need the key as an
874 canonical encoded S-expression in a buffer. Create this buffer
876 rc = make_canon_sexp (s_skey, &buf, &len);
880 switch (agent_private_key_type (buf))
882 case PRIVATE_KEY_CLEAR:
883 break; /* no unprotection needed */
884 case PRIVATE_KEY_OPENPGP_NONE:
886 unsigned char *buf_new;
889 rc = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
891 log_error ("failed to convert unprotected openpgp key: %s\n",
900 case PRIVATE_KEY_PROTECTED:
902 char *desc_text_final;
903 char *comment = NULL;
905 /* Note, that we will take the comment as a C string for
906 display purposes; i.e. all stuff beyond a Nul character is
909 gcry_sexp_t comment_sexp;
911 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
913 comment = gcry_sexp_nth_string (comment_sexp, 1);
914 gcry_sexp_release (comment_sexp);
917 desc_text_final = NULL;
919 rc = agent_modify_description (desc_text, comment, s_skey,
925 rc = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
926 cache_mode, lookup_ttl, r_passphrase);
928 log_error ("failed to unprotect the secret key: %s\n",
932 xfree (desc_text_final);
935 case PRIVATE_KEY_SHADOWED:
938 const unsigned char *s;
941 rc = agent_get_shadow_info (buf, &s);
944 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
946 *shadow_info = xtrymalloc (n);
951 memcpy (*shadow_info, s, n);
956 log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
959 rc = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
962 log_error ("invalid private key format\n");
963 rc = gpg_error (GPG_ERR_BAD_SECKEY);
966 gcry_sexp_release (s_skey);
973 xfree (*r_passphrase);
974 *r_passphrase = NULL;
979 buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
980 rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
981 wipememory (buf, buflen);
985 log_error ("failed to build S-Exp (off=%u): %s\n",
986 (unsigned int)erroff, gpg_strerror (rc));
989 xfree (*r_passphrase);
990 *r_passphrase = NULL;
1000 /* Return the string name from the S-expression S_KEY as well as a
1001 string describing the names of the parameters. ALGONAMESIZE and
1002 ELEMSSIZE give the allocated size of the provided buffers. The
1003 buffers may be NULL if not required. If R_LIST is not NULL the top
1004 level list will be stored there; the caller needs to release it in
1007 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
1008 char *r_algoname, size_t algonamesize,
1009 char *r_elems, size_t elemssize)
1011 gcry_sexp_t list, l2;
1012 const char *name, *algoname, *elems;
1018 list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1020 list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1022 list = gcry_sexp_find_token (s_key, "private-key", 0 );
1025 log_error ("invalid private key format\n");
1026 return gpg_error (GPG_ERR_BAD_SECKEY);
1029 l2 = gcry_sexp_cadr (list);
1030 gcry_sexp_release (list);
1032 name = gcry_sexp_nth_data (list, 0, &n);
1033 if (n==3 && !memcmp (name, "rsa", 3))
1038 else if (n==3 && !memcmp (name, "dsa", 3))
1043 else if (n==3 && !memcmp (name, "ecc", 3))
1048 else if (n==5 && !memcmp (name, "ecdsa", 5))
1053 else if (n==4 && !memcmp (name, "ecdh", 4))
1058 else if (n==3 && !memcmp (name, "elg", 3))
1065 log_error ("unknown private key algorithm\n");
1066 gcry_sexp_release (list);
1067 return gpg_error (GPG_ERR_BAD_SECKEY);
1072 if (strlen (algoname) >= algonamesize)
1073 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1074 strcpy (r_algoname, algoname);
1078 if (strlen (elems) >= elemssize)
1079 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1080 strcpy (r_elems, elems);
1086 gcry_sexp_release (list);
1092 /* Return true if KEYPARMS holds an EdDSA key. */
1094 is_eddsa (gcry_sexp_t keyparms)
1102 list = gcry_sexp_find_token (keyparms, "flags", 0);
1103 for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
1105 s = gcry_sexp_nth_data (list, i, &n);
1107 continue; /* Not a data element. */
1109 if (n == 5 && !memcmp (s, "eddsa", 5))
1115 gcry_sexp_release (list);
1120 /* Return the public key algorithm number if S_KEY is a DSA style key.
1121 If it is not a DSA style key, return 0. */
1123 agent_is_dsa_key (gcry_sexp_t s_key)
1132 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1133 return 0; /* Error - assume it is not an DSA key. */
1135 if (!strcmp (algoname, "dsa"))
1136 result = GCRY_PK_DSA;
1137 else if (!strcmp (algoname, "ecc"))
1139 if (is_eddsa (list))
1142 result = GCRY_PK_ECDSA;
1144 else if (!strcmp (algoname, "ecdsa"))
1145 result = GCRY_PK_ECDSA;
1149 gcry_sexp_release (list);
1154 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519. */
1156 agent_is_eddsa_key (gcry_sexp_t s_key)
1165 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1166 return 0; /* Error - assume it is not an EdDSA key. */
1168 if (!strcmp (algoname, "ecc") && is_eddsa (list))
1170 else if (!strcmp (algoname, "eddsa")) /* backward compatibility. */
1175 gcry_sexp_release (list);
1180 /* Return the key for the keygrip GRIP. The result is stored at
1181 RESULT. This function extracts the key from the private key
1182 database and returns it as an S-expression object as it is. On
1183 failure an error code is returned and NULL stored at RESULT. */
1185 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1186 gcry_sexp_t *result)
1195 err = read_key_file (grip, &s_skey);
1202 /* Return the public key for the keygrip GRIP. The result is stored
1203 at RESULT. This function extracts the public key from the private
1204 key database. On failure an error code is returned and NULL stored
1207 agent_public_key_from_file (ctrl_t ctrl,
1208 const unsigned char *grip,
1209 gcry_sexp_t *result)
1214 const char *algoname, *elems;
1216 gcry_mpi_t array[10];
1217 gcry_sexp_t curve = NULL;
1218 gcry_sexp_t flags = NULL;
1219 gcry_sexp_t uri_sexp, comment_sexp;
1220 const char *uri, *comment;
1221 size_t uri_length, comment_length;
1223 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1224 for comment + end-of-list. */
1226 gcry_sexp_t list = NULL;
1233 err = read_key_file (grip, &s_skey);
1237 for (i=0; i < DIM (array); i++)
1240 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1241 array, DIM (array), &curve, &flags);
1244 gcry_sexp_release (s_skey);
1250 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1252 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1256 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1258 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1260 gcry_sexp_release (s_skey);
1264 /* FIXME: The following thing is pretty ugly code; we should
1265 investigate how to make it cleaner. Probably code to handle
1266 canonical S-expressions in a memory buffer is better suited for
1267 such a task. After all that is what we do in protect.c. Need
1268 to find common patterns and write a straightformward API to use
1270 assert (sizeof (size_t) <= sizeof (void*));
1272 format = xtrymalloc (15+4+7*npkey+10+15+1+1);
1275 err = gpg_error_from_syserror ();
1276 for (i=0; array[i]; i++)
1277 gcry_mpi_release (array[i]);
1278 gcry_sexp_release (curve);
1279 gcry_sexp_release (flags);
1280 gcry_sexp_release (uri_sexp);
1281 gcry_sexp_release (comment_sexp);
1286 p = stpcpy (stpcpy (format, "(public-key("), algoname);
1287 p = stpcpy (p, "%S%S"); /* curve name and flags. */
1288 args[argidx++] = &curve;
1289 args[argidx++] = &flags;
1290 for (idx=0, s=elems; idx < npkey; idx++)
1294 p = stpcpy (p, " %m)");
1295 assert (argidx < DIM (args));
1296 args[argidx++] = &array[idx];
1301 p = stpcpy (p, "(uri %b)");
1302 assert (argidx+1 < DIM (args));
1303 args[argidx++] = (void *)&uri_length;
1304 args[argidx++] = (void *)&uri;
1308 p = stpcpy (p, "(comment %b)");
1309 assert (argidx+1 < DIM (args));
1310 args[argidx++] = (void *)&comment_length;
1311 args[argidx++] = (void*)&comment;
1315 assert (argidx < DIM (args));
1316 args[argidx] = NULL;
1318 err = gcry_sexp_build_array (&list, NULL, format, args);
1320 for (i=0; array[i]; i++)
1321 gcry_mpi_release (array[i]);
1322 gcry_sexp_release (curve);
1323 gcry_sexp_release (flags);
1324 gcry_sexp_release (uri_sexp);
1325 gcry_sexp_release (comment_sexp);
1334 /* Check whether the secret key identified by GRIP is available.
1335 Returns 0 is the key is available. */
1337 agent_key_available (const unsigned char *grip)
1341 char hexgrip[40+4+1];
1343 bin2hex (grip, 20, hexgrip);
1344 strcpy (hexgrip+40, ".key");
1346 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1348 result = !access (fname, R_OK)? 0 : -1;
1355 /* Return the information about the secret key specified by the binary
1356 keygrip GRIP. If the key is a shadowed one the shadow information
1357 will be stored at the address R_SHADOW_INFO as an allocated
1360 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1361 int *r_keytype, unsigned char **r_shadow_info)
1371 *r_keytype = PRIVATE_KEY_UNKNOWN;
1373 *r_shadow_info = NULL;
1378 err = read_key_file (grip, &sexp);
1381 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1382 return gpg_error (GPG_ERR_NOT_FOUND);
1386 err = make_canon_sexp (sexp, &buf, &len);
1387 gcry_sexp_release (sexp);
1392 keytype = agent_private_key_type (buf);
1395 case PRIVATE_KEY_CLEAR:
1396 case PRIVATE_KEY_OPENPGP_NONE:
1398 case PRIVATE_KEY_PROTECTED:
1399 /* If we ever require it we could retrieve the comment fields
1402 case PRIVATE_KEY_SHADOWED:
1405 const unsigned char *s;
1408 err = agent_get_shadow_info (buf, &s);
1411 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1413 *r_shadow_info = xtrymalloc (n);
1414 if (!*r_shadow_info)
1415 err = gpg_error_from_syserror ();
1417 memcpy (*r_shadow_info, s, n);
1422 err = gpg_error (GPG_ERR_BAD_SECKEY);
1426 if (!err && r_keytype)
1427 *r_keytype = keytype;
1435 /* Delete the key with GRIP from the disk after having asked for
1436 * confirmation using DESC_TEXT. If FORCE is set the function won't
1437 * require a confirmation via Pinentry or warns if the key is also
1438 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1439 * smartcards) will be affected.
1441 * Common error codes are:
1443 * GPG_ERR_KEY_ON_CARD
1444 * GPG_ERR_NOT_CONFIRMED
1445 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1448 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1449 const unsigned char *grip, int force, int only_stubs)
1452 gcry_sexp_t s_skey = NULL;
1453 unsigned char *buf = NULL;
1455 char *desc_text_final = NULL;
1456 char *comment = NULL;
1457 ssh_control_file_t cf = NULL;
1458 char hexgrip[40+4+1];
1459 char *default_desc = NULL;
1462 err = read_key_file (grip, &s_skey);
1463 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1464 err = gpg_error (GPG_ERR_NO_SECKEY);
1468 err = make_canon_sexp (s_skey, &buf, &len);
1472 key_type = agent_private_key_type (buf);
1473 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1475 err = gpg_error (GPG_ERR_FORBIDDEN);
1481 case PRIVATE_KEY_CLEAR:
1482 case PRIVATE_KEY_OPENPGP_NONE:
1483 case PRIVATE_KEY_PROTECTED:
1484 bin2hex (grip, 20, hexgrip);
1489 default_desc = xtryasprintf
1490 (L_("Do you really want to delete the key identified by keygrip%%0A"
1491 " %s%%0A %%C%%0A?"), hexgrip);
1492 desc_text = default_desc;
1495 /* Note, that we will take the comment as a C string for
1496 display purposes; i.e. all stuff beyond a Nul character is
1499 gcry_sexp_t comment_sexp;
1501 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1503 comment = gcry_sexp_nth_string (comment_sexp, 1);
1504 gcry_sexp_release (comment_sexp);
1508 err = agent_modify_description (desc_text, comment, s_skey,
1513 err = agent_get_confirmation (ctrl, desc_text_final,
1514 L_("Delete key"), L_("No"), 0);
1518 cf = ssh_open_control_file ();
1521 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1523 err = agent_get_confirmation
1525 L_("Warning: This key is also listed for use with SSH!\n"
1526 "Deleting the key might remove your ability to "
1527 "access remote machines."),
1528 L_("Delete key"), L_("No"), 0);
1534 err = remove_key_file (grip);
1537 case PRIVATE_KEY_SHADOWED:
1538 err = remove_key_file (grip);
1542 log_error ("invalid private key format\n");
1543 err = gpg_error (GPG_ERR_BAD_SECKEY);
1548 ssh_close_control_file (cf);
1549 gcry_free (comment);
1550 xfree (desc_text_final);
1551 xfree (default_desc);
1553 gcry_sexp_release (s_skey);
1558 /* Write an S-expression formatted shadow key to our key storage.
1559 Shadow key is created by an S-expression public key in PKBUF and
1560 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1561 existing key with the given GRIP will get overwritten. */
1563 agent_write_shadow_key (const unsigned char *grip,
1564 const char *serialno, const char *keyid,
1565 const unsigned char *pkbuf, int force)
1568 unsigned char *shadow_info;
1569 unsigned char *shdkey;
1572 shadow_info = make_shadow_info (serialno, keyid);
1574 return gpg_error_from_syserror ();
1576 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1577 xfree (shadow_info);
1580 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1584 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1585 err = agent_write_private_key (grip, shdkey, len, force);
1588 log_error ("error writing key: %s\n", gpg_strerror (err));