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, 2019 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/>.
31 #include <npth.h> /* (we use pth_sleep) */
34 #include "../common/i18n.h"
35 #include "../common/ssh-utils.h"
36 #include "../common/name-value.h"
42 /* Helper to pass data to the check callback of the unprotect function. */
43 struct try_unprotect_arg_s
46 const unsigned char *protected_key;
47 unsigned char *unprotected_key;
48 int change_required; /* Set by the callback to indicate that the
49 user should change the passphrase. */
53 /* Repalce all linefeeds in STRING by "%0A" and return a new malloced
54 * string. May return NULL on memory error. */
56 linefeed_to_percent0A (const char *string)
62 for (n=0, s=string; *s; s++)
67 p = buf = xtrymalloc (n+1);
70 for (s=string; *s; s++)
83 /* Note: Ownership of FNAME and FP are moved to this function. */
85 write_extended_private_key (char *fname, estream_t fp, int update, int newkey,
86 const void *buf, size_t len,
87 const char *serialno, const char *keyref,
92 gcry_sexp_t key = NULL;
100 err = nvc_parse_private_key (&pk, &line, fp);
101 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
103 log_error ("error parsing '%s' line %d: %s\n",
104 fname, line, gpg_strerror (err));
110 pk = nvc_new_private_key ();
113 err = gpg_error_from_syserror ();
119 err = gcry_sexp_sscan (&key, NULL, buf, len);
123 err = nvc_set_private_key (pk, key);
127 /* If requested write a Token line. */
128 if (serialno && keyref)
133 token = strconcat (serialno, " ", keyref, NULL);
136 err = gpg_error_from_syserror ();
140 /* fixme: the strcmp should compare only the first two strings. */
141 for (item = nvc_lookup (pk, "Token:");
143 item = nve_next_value (item, "Token:"))
144 if ((s = nve_value (item)) && !strcmp (s, token))
148 /* No token or no token with that value exists. Add a new
149 * one so that keys which have been stored on several cards
150 * are well supported. */
151 err = nvc_add (pk, "Token:", token);
157 /* If a timestamp has been supplied and the key is new write a
158 * creation timestamp. (We douple check that there is no Created
160 if (timestamp && newkey && !nvc_lookup (pk, "Created:"))
162 gnupg_isotime_t timebuf;
164 epoch2isotime (timebuf, timestamp);
165 err = nvc_add (pk, "Created:", timebuf);
171 err = es_fseek (fp, 0, SEEK_SET);
175 err = nvc_write (pk, fp);
178 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
183 if (ftruncate (es_fileno (fp), es_ftello (fp)))
185 err = gpg_error_from_syserror ();
186 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
193 err = gpg_error_from_syserror ();
194 log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
201 bump_key_eventcounter ();
206 gnupg_remove (fname);
208 gcry_sexp_release (key);
214 /* Write an S-expression formatted key to our key storage. With FORCE
215 * passed as true an existing key with the given GRIP will get
216 * overwritten. If SERIALNO and KEYREF are given a Token line is
217 * added to the key if the extended format is used. If TIMESTAMP is
218 * not zero and the key doies not yet exists it will be recorded as
221 agent_write_private_key (const unsigned char *grip,
222 const void *buffer, size_t length, int force,
223 const char *serialno, const char *keyref,
228 char hexgrip[40+4+1];
230 bin2hex (grip, 20, hexgrip);
231 strcpy (hexgrip+40, ".key");
233 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
236 /* FIXME: Write to a temp file first so that write failures during
237 key updates won't lead to a key loss. */
239 if (!force && !gnupg_access (fname, F_OK))
241 log_error ("secret key file '%s' already exists\n", fname);
243 return gpg_error (GPG_ERR_EEXIST);
246 fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
249 gpg_error_t tmperr = gpg_error_from_syserror ();
251 if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
253 fp = es_fopen (fname, "wbx,mode=-rw");
255 tmperr = gpg_error_from_syserror ();
259 log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
269 /* See if an existing key is in extended format. */
270 if (es_fread (&first, 1, 1, fp) != 1)
272 rc = gpg_error_from_syserror ();
273 log_error ("error reading first byte from '%s': %s\n",
274 fname, strerror (errno));
280 rc = es_fseek (fp, 0, SEEK_SET);
283 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
291 /* Key is already in the extended format. */
292 return write_extended_private_key (fname, fp, 1, 0, buffer, length,
293 serialno, keyref, timestamp);
295 if (first == '(' && opt.enable_extended_key_format)
297 /* Key is in the old format - but we want the extended format. */
298 return write_extended_private_key (fname, fp, 0, 0, buffer, length,
299 serialno, keyref, timestamp);
303 if (opt.enable_extended_key_format)
304 return write_extended_private_key (fname, fp, 0, 1, buffer, length,
305 serialno, keyref, timestamp);
307 if (es_fwrite (buffer, length, 1, fp) != 1)
309 gpg_error_t tmperr = gpg_error_from_syserror ();
310 log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
312 gnupg_remove (fname);
317 /* When force is given, the file might have to be truncated. */
318 if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
320 gpg_error_t tmperr = gpg_error_from_syserror ();
321 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
323 gnupg_remove (fname);
330 gpg_error_t tmperr = gpg_error_from_syserror ();
331 log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
332 gnupg_remove (fname);
336 bump_key_eventcounter ();
342 /* Callback function to try the unprotection from the passphrase query
345 try_unprotect_cb (struct pin_entry_info_s *pi)
347 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
348 ctrl_t ctrl = arg->ctrl;
351 gnupg_isotime_t now, protected_at, tmptime;
354 log_assert (!arg->unprotected_key);
356 arg->change_required = 0;
357 err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
358 &arg->unprotected_key, &dummy);
361 if (!opt.max_passphrase_days || ctrl->in_passwd)
362 return 0; /* No regular passphrase change required. */
366 /* No protection date known - must force passphrase change. */
367 desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
368 "Please change it now."));
370 return gpg_error_from_syserror ();
374 gnupg_get_isotime (now);
375 gnupg_copy_time (tmptime, protected_at);
376 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
379 if (strcmp (now, tmptime) > 0 )
381 /* Passphrase "expired". */
383 (L_("This passphrase has not been changed%%0A"
384 "since %.4s-%.2s-%.2s. Please change it now."),
385 protected_at, protected_at+4, protected_at+6);
387 return gpg_error_from_syserror ();
393 /* Change required. */
394 if (opt.enforce_passphrase_constraints)
396 err = agent_get_confirmation (ctrl, desc,
397 L_("Change passphrase"), NULL, 0);
399 arg->change_required = 1;
403 err = agent_get_confirmation (ctrl, desc,
404 L_("Change passphrase"),
405 L_("I'll change it later"), 0);
407 arg->change_required = 1;
408 else if (gpg_err_code (err) == GPG_ERR_CANCELED
409 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
419 /* Return true if the STRING has an %C or %c expando. */
421 has_comment_expando (const char *string)
429 for (s = string; *s; s++)
433 if (*s == 'c' || *s == 'C')
446 /* Modify a Key description, replacing certain special format
447 characters. List of currently supported replacements:
449 %% - Replaced by a single %
450 %c - Replaced by the content of COMMENT.
451 %C - Same as %c but put into parentheses.
452 %F - Replaced by an ssh style fingerprint computed from KEY.
454 The functions returns 0 on success or an error code. On success a
455 newly allocated string is stored at the address of RESULT.
458 agent_modify_description (const char *in, const char *comment,
459 const gcry_sexp_t key, char **result)
461 size_t comment_length;
467 char *ssh_fpr = NULL;
475 comment_length = strlen (comment);
476 in_len = strlen (in);
478 /* First pass calculates the length, second pass does the actual
480 /* FIXME: This can be simplified by using es_fopenmem. */
483 for (pass=0; pass < 2; pass++)
486 for (i = 0; i < in_len; i++)
500 case 'c': /* Comment. */
503 memcpy (out, comment, comment_length);
504 out += comment_length;
507 out_len += comment_length;
510 case 'C': /* Comment. */
516 memcpy (out, comment, comment_length);
517 out += comment_length;
521 out_len += comment_length + 2;
524 case 'F': /* SSH style fingerprint. */
526 ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
531 out = stpcpy (out, ssh_fpr);
533 out_len += strlen (ssh_fpr);
537 default: /* Invalid special sequences are kept as they are. */
548 else if (in[i] == '%')
561 *result = out = xtrymalloc (out_len + 1);
565 return gpg_error_from_syserror ();
571 log_assert (*result + out_len == out);
574 /* The ssh prompt may sometimes end in
576 * The empty parentheses doesn't look very good. We use this hack
577 * here to remove them as well as the indentation spaces. */
580 if (i > 2 && !strcmp (p + i - 2, "()"))
584 while (p > *result && spacep (p))
593 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
594 should be the hex encoded keygrip of that key to be used with the
595 caching mechanism. DESC_TEXT may be set to override the default
596 description used for the pinentry. If LOOKUP_TTL is given this
597 function is used to lookup the default ttl. If R_PASSPHRASE is not
598 NULL, the function succeeded and the key was protected the used
599 passphrase (entered or from the cache) is stored there; if not NULL
600 will be stored. The caller needs to free the returned
603 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
604 unsigned char **keybuf, const unsigned char *grip,
605 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
608 struct pin_entry_info_s *pi;
609 struct try_unprotect_arg_s arg;
611 unsigned char *result;
616 *r_passphrase = NULL;
618 bin2hex (grip, 20, hexgrip);
620 /* Initially try to get it using a cache nonce. */
625 pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
628 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
643 /* First try to get it from the cache - if there is none or we can't
644 unprotect it, we fall back to ask the user */
645 if (cache_mode != CACHE_MODE_IGNORE)
650 pw = agent_get_cache (ctrl, hexgrip, cache_mode);
653 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
656 if (cache_mode == CACHE_MODE_NORMAL)
657 agent_store_cache_hit (hexgrip);
668 else if (cache_mode == CACHE_MODE_NORMAL)
670 /* The standard use of GPG keys is to have a signing and an
671 encryption subkey. Commonly both use the same
672 passphrase. We try to help the user to enter the
673 passphrase only once by silently trying the last
674 correctly entered passphrase. Checking one additional
675 passphrase should be acceptable; despite the S2K
676 introduced delays. The assumed workflow is:
678 1. Read encrypted message in a MUA and thus enter a
679 passphrase for the encryption subkey.
681 2. Reply to that mail with an encrypted and signed
682 mail, thus entering the passphrase for the signing
685 We can often avoid the passphrase entry in the second
686 step. We do this only in normal mode, so not to
687 interfere with unrelated cache entries. */
688 pw = agent_get_cache (ctrl, NULL, cache_mode);
691 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
692 &result, &resultlen);
707 /* If the pinentry is currently in use, we wait up to 60 seconds
708 for it to close and check the cache again. This solves a common
709 situation where several requests for unprotecting a key have
710 been made but the user is still entering the passphrase for
711 the first request. Because all requests to agent_askpin are
712 serialized they would then pop up one after the other to
713 request the passphrase - despite that the user has already
714 entered it and is then available in the cache. This
715 implementation is not race free but in the worst case the
716 user has to enter the passphrase only once more. */
717 if (pinentry_active_p (ctrl, 0))
720 if (!pinentry_active_p (ctrl, 60))
722 /* We need to give the other thread a chance to actually put
723 it into the cache. */
727 /* Timeout - better call pinentry now the plain way. */
731 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
733 return gpg_error_from_syserror ();
734 pi->max_length = MAX_PASSPHRASE_LEN + 1;
735 pi->min_digits = 0; /* we want a real passphrase */
738 pi->check_cb = try_unprotect_cb;
740 arg.protected_key = *keybuf;
741 arg.unprotected_key = NULL;
742 arg.change_required = 0;
743 pi->check_cb_arg = &arg;
745 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
748 if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE))
750 log_error ("Clearing pinentry cache which caused error %s\n",
753 agent_clear_passphrase (ctrl, hexgrip, cache_mode);
758 log_assert (arg.unprotected_key);
759 if (arg.change_required)
761 /* The callback told as that the user should change their
762 passphrase. Present the dialog to do. */
763 size_t canlen, erroff;
766 log_assert (arg.unprotected_key);
767 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
768 rc = gcry_sexp_sscan (&s_skey, &erroff,
769 (char*)arg.unprotected_key, canlen);
772 log_error ("failed to build S-Exp (off=%u): %s\n",
773 (unsigned int)erroff, gpg_strerror (rc));
774 wipememory (arg.unprotected_key, canlen);
775 xfree (arg.unprotected_key);
779 rc = agent_protect_and_store (ctrl, s_skey, NULL);
780 gcry_sexp_release (s_skey);
783 log_error ("changing the passphrase failed: %s\n",
785 wipememory (arg.unprotected_key, canlen);
786 xfree (arg.unprotected_key);
793 /* Passphrase is fine. */
794 agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
795 lookup_ttl? lookup_ttl (hexgrip) : 0);
796 agent_store_cache_hit (hexgrip);
797 if (r_passphrase && *pi->pin)
798 *r_passphrase = xtrystrdup (pi->pin);
801 *keybuf = arg.unprotected_key;
808 /* Read the key identified by GRIP from the private key directory and
809 * return it as an gcrypt S-expression object in RESULT. If R_KEYMETA
810 * is not NULl and the extended key format is used, the meta data
811 * items are stored there. However the "Key:" item is removed from
812 * it. On failure returns an error code and stores NULL at RESULT and
815 read_key_file (const unsigned char *grip, gcry_sexp_t *result, nvc_t *r_keymeta)
822 size_t buflen, erroff;
824 char hexgrip[40+4+1];
831 bin2hex (grip, 20, hexgrip);
832 strcpy (hexgrip+40, ".key");
834 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
836 fp = es_fopen (fname, "rb");
839 err = gpg_error_from_syserror ();
840 if (gpg_err_code (err) != GPG_ERR_ENOENT)
841 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
846 if (es_fread (&first, 1, 1, fp) != 1)
848 err = gpg_error_from_syserror ();
849 log_error ("error reading first byte from '%s': %s\n",
850 fname, gpg_strerror (err));
856 if (es_fseek (fp, 0, SEEK_SET))
858 err = gpg_error_from_syserror ();
859 log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
867 /* Key is in extended format. */
871 err = nvc_parse_private_key (&pk, &line, fp);
875 log_error ("error parsing '%s' line %d: %s\n",
876 fname, line, gpg_strerror (err));
879 err = nvc_get_private_key (pk, result);
881 log_error ("error getting private key from '%s': %s\n",
882 fname, gpg_strerror (err));
884 nvc_delete_named (pk, "Key:");
887 if (!err && r_keymeta)
895 if (fstat (es_fileno (fp), &st))
897 err = gpg_error_from_syserror ();
898 log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
905 buf = xtrymalloc (buflen+1);
908 err = gpg_error_from_syserror ();
909 log_error ("error allocating %zu bytes for '%s': %s\n",
910 buflen, fname, gpg_strerror (err));
918 if (es_fread (buf, buflen, 1, fp) != 1)
920 err = gpg_error_from_syserror ();
921 log_error ("error reading %zu bytes from '%s': %s\n",
922 buflen, fname, gpg_strerror (err));
929 /* Convert the file into a gcrypt S-expression object. */
930 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
936 log_error ("failed to build S-Exp (off=%u): %s\n",
937 (unsigned int)erroff, gpg_strerror (err));
945 /* Remove the key identified by GRIP from the private key directory. */
947 remove_key_file (const unsigned char *grip)
951 char hexgrip[40+4+1];
953 bin2hex (grip, 20, hexgrip);
954 strcpy (hexgrip+40, ".key");
955 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
957 if (gnupg_remove (fname))
958 err = gpg_error_from_syserror ();
964 /* Return the secret key as an S-Exp in RESULT after locating it using
965 the GRIP. If the operation shall be diverted to a token, an
966 allocated S-expression with the shadow_info part from the file is
967 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
968 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
969 set to present a custom description for the pinentry. LOOKUP_TTL
970 is an optional function to convey a TTL to the cache manager; we do
971 not simply pass the TTL value because the value is only needed if
972 an unprotect action was needed and looking up the TTL may have some
973 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
974 given that cache item is first tried to get a passphrase. If
975 R_PASSPHRASE is not NULL, the function succeeded and the key was
976 protected the used passphrase (entered or from the cache) is stored
977 there; if not NULL will be stored. The caller needs to free the
978 returned passphrase. */
980 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
981 const char *desc_text,
982 const unsigned char *grip, unsigned char **shadow_info,
983 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
984 gcry_sexp_t *result, char **r_passphrase)
990 nvc_t keymeta = NULL;
991 char *desc_text_buffer = NULL; /* Used in case we extend DESC_TEXT. */
997 *r_passphrase = NULL;
999 err = read_key_file (grip, &s_skey, &keymeta);
1002 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1003 err = gpg_error (GPG_ERR_NO_SECKEY);
1007 /* For use with the protection functions we also need the key as an
1008 canonical encoded S-expression in a buffer. Create this buffer
1010 err = make_canon_sexp (s_skey, &buf, &len);
1013 nvc_release (keymeta);
1014 xfree (desc_text_buffer);
1018 switch (agent_private_key_type (buf))
1020 case PRIVATE_KEY_CLEAR:
1021 break; /* no unprotection needed */
1022 case PRIVATE_KEY_OPENPGP_NONE:
1024 unsigned char *buf_new;
1027 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
1029 log_error ("failed to convert unprotected openpgp key: %s\n",
1030 gpg_strerror (err));
1038 case PRIVATE_KEY_PROTECTED:
1040 char *desc_text_final;
1041 char *comment_buffer = NULL;
1042 const char *comment = NULL;
1044 /* Note, that we will take the comment as a C string for
1045 * display purposes; i.e. all stuff beyond a Nul character is
1046 * ignored. If a "Label" entry is available in the meta data
1047 * this is used instead of the s-expression comment. */
1048 if (keymeta && (comment = nvc_get_string (keymeta, "Label:")))
1050 if (strchr (comment, '\n')
1051 && (comment_buffer = linefeed_to_percent0A (comment)))
1052 comment = comment_buffer;
1053 /* In case DESC_TEXT has no escape pattern for a comment
1055 if (desc_text && !has_comment_expando (desc_text))
1057 desc_text_buffer = strconcat (desc_text, "%0A%C", NULL);
1058 if (desc_text_buffer)
1059 desc_text = desc_text_buffer;
1064 gcry_sexp_t comment_sexp;
1066 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1068 comment_buffer = gcry_sexp_nth_string (comment_sexp, 1);
1069 gcry_sexp_release (comment_sexp);
1070 comment = comment_buffer;
1073 desc_text_final = NULL;
1075 err = agent_modify_description (desc_text, comment, s_skey,
1077 gcry_free (comment_buffer);
1081 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
1082 cache_mode, lookup_ttl, r_passphrase);
1084 log_error ("failed to unprotect the secret key: %s\n",
1085 gpg_strerror (err));
1088 xfree (desc_text_final);
1091 case PRIVATE_KEY_SHADOWED:
1094 const unsigned char *s;
1097 err = agent_get_shadow_info (buf, &s);
1100 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
1102 *shadow_info = xtrymalloc (n);
1104 err = out_of_core ();
1107 memcpy (*shadow_info, s, n);
1112 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
1115 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
1118 log_error ("invalid private key format\n");
1119 err = gpg_error (GPG_ERR_BAD_SECKEY);
1122 gcry_sexp_release (s_skey);
1129 xfree (*r_passphrase);
1130 *r_passphrase = NULL;
1132 nvc_release (keymeta);
1133 xfree (desc_text_buffer);
1137 err = sexp_sscan_private_key (result, &erroff, buf);
1139 nvc_release (keymeta);
1140 xfree (desc_text_buffer);
1143 log_error ("failed to build S-Exp (off=%u): %s\n",
1144 (unsigned int)erroff, gpg_strerror (err));
1147 xfree (*r_passphrase);
1148 *r_passphrase = NULL;
1156 /* Return the key for the keygrip GRIP. The result is stored at
1157 RESULT. This function extracts the key from the private key
1158 database and returns it as an S-expression object as it is. On
1159 failure an error code is returned and NULL stored at RESULT. */
1161 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1162 gcry_sexp_t *result)
1171 err = read_key_file (grip, &s_skey, NULL);
1178 /* Return the public key for the keygrip GRIP. The result is stored
1179 at RESULT. This function extracts the public key from the private
1180 key database. On failure an error code is returned and NULL stored
1183 agent_public_key_from_file (ctrl_t ctrl,
1184 const unsigned char *grip,
1185 gcry_sexp_t *result)
1190 const char *algoname, *elems;
1192 gcry_mpi_t array[10];
1193 gcry_sexp_t curve = NULL;
1194 gcry_sexp_t flags = NULL;
1195 gcry_sexp_t uri_sexp, comment_sexp;
1196 const char *uri, *comment;
1197 size_t uri_length, comment_length;
1198 int uri_intlen, comment_intlen;
1201 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1202 for comment + end-of-list. */
1204 gcry_sexp_t list = NULL;
1211 err = read_key_file (grip, &s_skey, NULL);
1215 for (i=0; i < DIM (array); i++)
1218 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1219 array, DIM (array), &curve, &flags);
1222 gcry_sexp_release (s_skey);
1228 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1230 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1234 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1236 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1238 gcry_sexp_release (s_skey);
1242 log_assert (sizeof (size_t) <= sizeof (void*));
1244 init_membuf (&format_mb, 256);
1246 put_membuf_printf (&format_mb, "(public-key(%s%%S%%S", algoname);
1247 args[argidx++] = &curve;
1248 args[argidx++] = &flags;
1249 for (idx=0, s=elems; idx < npkey; idx++)
1251 put_membuf_printf (&format_mb, "(%c %%m)", *s++);
1252 log_assert (argidx < DIM (args));
1253 args[argidx++] = &array[idx];
1255 put_membuf_str (&format_mb, ")");
1258 put_membuf_str (&format_mb, "(uri %b)");
1259 log_assert (argidx+1 < DIM (args));
1260 uri_intlen = (int)uri_length;
1261 args[argidx++] = (void *)&uri_intlen;
1262 args[argidx++] = (void *)&uri;
1266 put_membuf_str (&format_mb, "(comment %b)");
1267 log_assert (argidx+1 < DIM (args));
1268 comment_intlen = (int)comment_length;
1269 args[argidx++] = (void *)&comment_intlen;
1270 args[argidx++] = (void *)&comment;
1272 put_membuf (&format_mb, ")", 2);
1273 log_assert (argidx < DIM (args));
1274 args[argidx] = NULL;
1276 format = get_membuf (&format_mb, NULL);
1279 err = gpg_error_from_syserror ();
1280 for (i=0; array[i]; i++)
1281 gcry_mpi_release (array[i]);
1282 gcry_sexp_release (curve);
1283 gcry_sexp_release (flags);
1284 gcry_sexp_release (uri_sexp);
1285 gcry_sexp_release (comment_sexp);
1289 err = gcry_sexp_build_array (&list, NULL, format, args);
1291 for (i=0; array[i]; i++)
1292 gcry_mpi_release (array[i]);
1293 gcry_sexp_release (curve);
1294 gcry_sexp_release (flags);
1295 gcry_sexp_release (uri_sexp);
1296 gcry_sexp_release (comment_sexp);
1304 /* Check whether the secret key identified by GRIP is available.
1305 Returns 0 is the key is available. */
1307 agent_key_available (const unsigned char *grip)
1311 char hexgrip[40+4+1];
1313 bin2hex (grip, 20, hexgrip);
1314 strcpy (hexgrip+40, ".key");
1316 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1318 result = !gnupg_access (fname, R_OK)? 0 : -1;
1325 /* Return the information about the secret key specified by the binary
1326 keygrip GRIP. If the key is a shadowed one the shadow information
1327 will be stored at the address R_SHADOW_INFO as an allocated
1330 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1331 int *r_keytype, unsigned char **r_shadow_info,
1332 unsigned char **r_shadow_info_type)
1342 *r_keytype = PRIVATE_KEY_UNKNOWN;
1344 *r_shadow_info = NULL;
1349 err = read_key_file (grip, &sexp, NULL);
1352 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1353 return gpg_error (GPG_ERR_NOT_FOUND);
1357 err = make_canon_sexp (sexp, &buf, &len);
1358 gcry_sexp_release (sexp);
1363 keytype = agent_private_key_type (buf);
1366 case PRIVATE_KEY_CLEAR:
1367 case PRIVATE_KEY_OPENPGP_NONE:
1369 case PRIVATE_KEY_PROTECTED:
1370 /* If we ever require it we could retrieve the comment fields
1373 case PRIVATE_KEY_SHADOWED:
1376 const unsigned char *s;
1379 err = agent_get_shadow_info_type (buf, &s, r_shadow_info_type);
1382 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1384 *r_shadow_info = xtrymalloc (n);
1385 if (!*r_shadow_info)
1386 err = gpg_error_from_syserror ();
1388 memcpy (*r_shadow_info, s, n);
1393 err = gpg_error (GPG_ERR_BAD_SECKEY);
1397 if (!err && r_keytype)
1398 *r_keytype = keytype;
1406 /* Delete the key with GRIP from the disk after having asked for
1407 * confirmation using DESC_TEXT. If FORCE is set the function won't
1408 * require a confirmation via Pinentry or warns if the key is also
1409 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1410 * smartcards) will be affected.
1412 * Common error codes are:
1414 * GPG_ERR_KEY_ON_CARD
1415 * GPG_ERR_NOT_CONFIRMED
1416 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1419 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1420 const unsigned char *grip, int force, int only_stubs)
1423 gcry_sexp_t s_skey = NULL;
1424 unsigned char *buf = NULL;
1426 char *desc_text_final = NULL;
1427 char *comment = NULL;
1428 ssh_control_file_t cf = NULL;
1429 char hexgrip[40+4+1];
1430 char *default_desc = NULL;
1433 err = read_key_file (grip, &s_skey, NULL);
1434 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1435 err = gpg_error (GPG_ERR_NO_SECKEY);
1439 err = make_canon_sexp (s_skey, &buf, &len);
1443 key_type = agent_private_key_type (buf);
1444 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1446 err = gpg_error (GPG_ERR_FORBIDDEN);
1452 case PRIVATE_KEY_CLEAR:
1453 case PRIVATE_KEY_OPENPGP_NONE:
1454 case PRIVATE_KEY_PROTECTED:
1455 bin2hex (grip, 20, hexgrip);
1460 default_desc = xtryasprintf
1461 (L_("Do you really want to delete the key identified by keygrip%%0A"
1462 " %s%%0A %%C%%0A?"), hexgrip);
1463 desc_text = default_desc;
1466 /* Note, that we will take the comment as a C string for
1467 display purposes; i.e. all stuff beyond a Nul character is
1470 gcry_sexp_t comment_sexp;
1472 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1474 comment = gcry_sexp_nth_string (comment_sexp, 1);
1475 gcry_sexp_release (comment_sexp);
1479 err = agent_modify_description (desc_text, comment, s_skey,
1484 err = agent_get_confirmation (ctrl, desc_text_final,
1485 L_("Delete key"), L_("No"), 0);
1489 cf = ssh_open_control_file ();
1492 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1494 err = agent_get_confirmation
1496 L_("Warning: This key is also listed for use with SSH!\n"
1497 "Deleting the key might remove your ability to "
1498 "access remote machines."),
1499 L_("Delete key"), L_("No"), 0);
1505 err = remove_key_file (grip);
1508 case PRIVATE_KEY_SHADOWED:
1509 err = remove_key_file (grip);
1513 log_error ("invalid private key format\n");
1514 err = gpg_error (GPG_ERR_BAD_SECKEY);
1519 ssh_close_control_file (cf);
1520 gcry_free (comment);
1521 xfree (desc_text_final);
1522 xfree (default_desc);
1524 gcry_sexp_release (s_skey);
1529 /* Write an S-expression formatted shadow key to our key storage.
1530 Shadow key is created by an S-expression public key in PKBUF and
1531 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1532 existing key with the given GRIP will get overwritten. */
1534 agent_write_shadow_key (const unsigned char *grip,
1535 const char *serialno, const char *keyid,
1536 const unsigned char *pkbuf, int force)
1539 unsigned char *shadow_info;
1540 unsigned char *shdkey;
1543 /* Just in case some caller did not parse the stuff correctly, skip
1544 * leading spaces. */
1545 while (spacep (serialno))
1547 while (spacep (keyid))
1550 shadow_info = make_shadow_info (serialno, keyid);
1552 return gpg_error_from_syserror ();
1554 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1555 xfree (shadow_info);
1558 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1562 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1563 err = agent_write_private_key (grip, shdkey, len, force, serialno, keyid, 0);
1566 log_error ("error writing key: %s\n", gpg_strerror (err));