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,
991 nvc_t keymeta = NULL;
992 char *desc_text_buffer = NULL; /* Used in case we extend DESC_TEXT. */
998 *r_passphrase = NULL;
1000 *r_timestamp = (time_t)(-1);
1002 err = read_key_file (grip, &s_skey, &keymeta);
1005 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1006 err = gpg_error (GPG_ERR_NO_SECKEY);
1010 /* For use with the protection functions we also need the key as an
1011 canonical encoded S-expression in a buffer. Create this buffer
1013 err = make_canon_sexp (s_skey, &buf, &len);
1016 nvc_release (keymeta);
1017 xfree (desc_text_buffer);
1021 if (r_timestamp && keymeta)
1023 const char *created = nvc_get_string (keymeta, "Created:");
1026 *r_timestamp = isotime2epoch (created);
1029 switch (agent_private_key_type (buf))
1031 case PRIVATE_KEY_CLEAR:
1032 break; /* no unprotection needed */
1033 case PRIVATE_KEY_OPENPGP_NONE:
1035 unsigned char *buf_new;
1038 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
1040 log_error ("failed to convert unprotected openpgp key: %s\n",
1041 gpg_strerror (err));
1049 case PRIVATE_KEY_PROTECTED:
1051 char *desc_text_final;
1052 char *comment_buffer = NULL;
1053 const char *comment = NULL;
1055 /* Note, that we will take the comment as a C string for
1056 * display purposes; i.e. all stuff beyond a Nul character is
1057 * ignored. If a "Label" entry is available in the meta data
1058 * this is used instead of the s-expression comment. */
1059 if (keymeta && (comment = nvc_get_string (keymeta, "Label:")))
1061 if (strchr (comment, '\n')
1062 && (comment_buffer = linefeed_to_percent0A (comment)))
1063 comment = comment_buffer;
1064 /* In case DESC_TEXT has no escape pattern for a comment
1066 if (desc_text && !has_comment_expando (desc_text))
1068 desc_text_buffer = strconcat (desc_text, "%0A%C", NULL);
1069 if (desc_text_buffer)
1070 desc_text = desc_text_buffer;
1075 gcry_sexp_t comment_sexp;
1077 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1079 comment_buffer = gcry_sexp_nth_string (comment_sexp, 1);
1080 gcry_sexp_release (comment_sexp);
1081 comment = comment_buffer;
1084 desc_text_final = NULL;
1086 err = agent_modify_description (desc_text, comment, s_skey,
1088 gcry_free (comment_buffer);
1092 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
1093 cache_mode, lookup_ttl, r_passphrase);
1095 log_error ("failed to unprotect the secret key: %s\n",
1096 gpg_strerror (err));
1099 xfree (desc_text_final);
1102 case PRIVATE_KEY_SHADOWED:
1105 const unsigned char *s;
1108 err = agent_get_shadow_info (buf, &s);
1111 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
1113 *shadow_info = xtrymalloc (n);
1115 err = out_of_core ();
1118 memcpy (*shadow_info, s, n);
1123 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
1126 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
1129 log_error ("invalid private key format\n");
1130 err = gpg_error (GPG_ERR_BAD_SECKEY);
1133 gcry_sexp_release (s_skey);
1140 xfree (*r_passphrase);
1141 *r_passphrase = NULL;
1143 nvc_release (keymeta);
1144 xfree (desc_text_buffer);
1148 err = sexp_sscan_private_key (result, &erroff, buf);
1150 nvc_release (keymeta);
1151 xfree (desc_text_buffer);
1154 log_error ("failed to build S-Exp (off=%u): %s\n",
1155 (unsigned int)erroff, gpg_strerror (err));
1158 xfree (*r_passphrase);
1159 *r_passphrase = NULL;
1167 /* Return the key for the keygrip GRIP. The result is stored at
1168 RESULT. This function extracts the key from the private key
1169 database and returns it as an S-expression object as it is. On
1170 failure an error code is returned and NULL stored at RESULT. */
1172 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1173 gcry_sexp_t *result)
1182 err = read_key_file (grip, &s_skey, NULL);
1189 /* Return the public key for the keygrip GRIP. The result is stored
1190 at RESULT. This function extracts the public key from the private
1191 key database. On failure an error code is returned and NULL stored
1194 agent_public_key_from_file (ctrl_t ctrl,
1195 const unsigned char *grip,
1196 gcry_sexp_t *result)
1201 const char *algoname, *elems;
1203 gcry_mpi_t array[10];
1204 gcry_sexp_t curve = NULL;
1205 gcry_sexp_t flags = NULL;
1206 gcry_sexp_t uri_sexp, comment_sexp;
1207 const char *uri, *comment;
1208 size_t uri_length, comment_length;
1209 int uri_intlen, comment_intlen;
1212 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1213 for comment + end-of-list. */
1215 gcry_sexp_t list = NULL;
1222 err = read_key_file (grip, &s_skey, NULL);
1226 for (i=0; i < DIM (array); i++)
1229 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1230 array, DIM (array), &curve, &flags);
1233 gcry_sexp_release (s_skey);
1239 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1241 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1245 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1247 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1249 gcry_sexp_release (s_skey);
1253 log_assert (sizeof (size_t) <= sizeof (void*));
1255 init_membuf (&format_mb, 256);
1257 put_membuf_printf (&format_mb, "(public-key(%s%%S%%S", algoname);
1258 args[argidx++] = &curve;
1259 args[argidx++] = &flags;
1260 for (idx=0, s=elems; idx < npkey; idx++)
1262 put_membuf_printf (&format_mb, "(%c %%m)", *s++);
1263 log_assert (argidx < DIM (args));
1264 args[argidx++] = &array[idx];
1266 put_membuf_str (&format_mb, ")");
1269 put_membuf_str (&format_mb, "(uri %b)");
1270 log_assert (argidx+1 < DIM (args));
1271 uri_intlen = (int)uri_length;
1272 args[argidx++] = (void *)&uri_intlen;
1273 args[argidx++] = (void *)&uri;
1277 put_membuf_str (&format_mb, "(comment %b)");
1278 log_assert (argidx+1 < DIM (args));
1279 comment_intlen = (int)comment_length;
1280 args[argidx++] = (void *)&comment_intlen;
1281 args[argidx++] = (void *)&comment;
1283 put_membuf (&format_mb, ")", 2);
1284 log_assert (argidx < DIM (args));
1285 args[argidx] = NULL;
1287 format = get_membuf (&format_mb, NULL);
1290 err = gpg_error_from_syserror ();
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);
1300 err = gcry_sexp_build_array (&list, NULL, format, args);
1302 for (i=0; array[i]; i++)
1303 gcry_mpi_release (array[i]);
1304 gcry_sexp_release (curve);
1305 gcry_sexp_release (flags);
1306 gcry_sexp_release (uri_sexp);
1307 gcry_sexp_release (comment_sexp);
1315 /* Check whether the secret key identified by GRIP is available.
1316 Returns 0 is the key is available. */
1318 agent_key_available (const unsigned char *grip)
1322 char hexgrip[40+4+1];
1324 bin2hex (grip, 20, hexgrip);
1325 strcpy (hexgrip+40, ".key");
1327 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1329 result = !gnupg_access (fname, R_OK)? 0 : -1;
1336 /* Return the information about the secret key specified by the binary
1337 keygrip GRIP. If the key is a shadowed one the shadow information
1338 will be stored at the address R_SHADOW_INFO as an allocated
1341 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1342 int *r_keytype, unsigned char **r_shadow_info,
1343 unsigned char **r_shadow_info_type)
1353 *r_keytype = PRIVATE_KEY_UNKNOWN;
1355 *r_shadow_info = NULL;
1360 err = read_key_file (grip, &sexp, NULL);
1363 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1364 return gpg_error (GPG_ERR_NOT_FOUND);
1368 err = make_canon_sexp (sexp, &buf, &len);
1369 gcry_sexp_release (sexp);
1374 keytype = agent_private_key_type (buf);
1377 case PRIVATE_KEY_CLEAR:
1378 case PRIVATE_KEY_OPENPGP_NONE:
1380 case PRIVATE_KEY_PROTECTED:
1381 /* If we ever require it we could retrieve the comment fields
1384 case PRIVATE_KEY_SHADOWED:
1387 const unsigned char *s;
1390 err = agent_get_shadow_info_type (buf, &s, r_shadow_info_type);
1393 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1395 *r_shadow_info = xtrymalloc (n);
1396 if (!*r_shadow_info)
1397 err = gpg_error_from_syserror ();
1399 memcpy (*r_shadow_info, s, n);
1404 err = gpg_error (GPG_ERR_BAD_SECKEY);
1408 if (!err && r_keytype)
1409 *r_keytype = keytype;
1417 /* Delete the key with GRIP from the disk after having asked for
1418 * confirmation using DESC_TEXT. If FORCE is set the function won't
1419 * require a confirmation via Pinentry or warns if the key is also
1420 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1421 * smartcards) will be affected.
1423 * Common error codes are:
1425 * GPG_ERR_KEY_ON_CARD
1426 * GPG_ERR_NOT_CONFIRMED
1427 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1430 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1431 const unsigned char *grip, int force, int only_stubs)
1434 gcry_sexp_t s_skey = NULL;
1435 unsigned char *buf = NULL;
1437 char *desc_text_final = NULL;
1438 char *comment = NULL;
1439 ssh_control_file_t cf = NULL;
1440 char hexgrip[40+4+1];
1441 char *default_desc = NULL;
1444 err = read_key_file (grip, &s_skey, NULL);
1445 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1446 err = gpg_error (GPG_ERR_NO_SECKEY);
1450 err = make_canon_sexp (s_skey, &buf, &len);
1454 key_type = agent_private_key_type (buf);
1455 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1457 err = gpg_error (GPG_ERR_FORBIDDEN);
1463 case PRIVATE_KEY_CLEAR:
1464 case PRIVATE_KEY_OPENPGP_NONE:
1465 case PRIVATE_KEY_PROTECTED:
1466 bin2hex (grip, 20, hexgrip);
1471 default_desc = xtryasprintf
1472 (L_("Do you really want to delete the key identified by keygrip%%0A"
1473 " %s%%0A %%C%%0A?"), hexgrip);
1474 desc_text = default_desc;
1477 /* Note, that we will take the comment as a C string for
1478 display purposes; i.e. all stuff beyond a Nul character is
1481 gcry_sexp_t comment_sexp;
1483 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1485 comment = gcry_sexp_nth_string (comment_sexp, 1);
1486 gcry_sexp_release (comment_sexp);
1490 err = agent_modify_description (desc_text, comment, s_skey,
1495 err = agent_get_confirmation (ctrl, desc_text_final,
1496 L_("Delete key"), L_("No"), 0);
1500 cf = ssh_open_control_file ();
1503 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1505 err = agent_get_confirmation
1507 L_("Warning: This key is also listed for use with SSH!\n"
1508 "Deleting the key might remove your ability to "
1509 "access remote machines."),
1510 L_("Delete key"), L_("No"), 0);
1516 err = remove_key_file (grip);
1519 case PRIVATE_KEY_SHADOWED:
1520 err = remove_key_file (grip);
1524 log_error ("invalid private key format\n");
1525 err = gpg_error (GPG_ERR_BAD_SECKEY);
1530 ssh_close_control_file (cf);
1531 gcry_free (comment);
1532 xfree (desc_text_final);
1533 xfree (default_desc);
1535 gcry_sexp_release (s_skey);
1540 /* Write an S-expression formatted shadow key to our key storage.
1541 Shadow key is created by an S-expression public key in PKBUF and
1542 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1543 existing key with the given GRIP will get overwritten. */
1545 agent_write_shadow_key (const unsigned char *grip,
1546 const char *serialno, const char *keyid,
1547 const unsigned char *pkbuf, int force)
1550 unsigned char *shadow_info;
1551 unsigned char *shdkey;
1554 /* Just in case some caller did not parse the stuff correctly, skip
1555 * leading spaces. */
1556 while (spacep (serialno))
1558 while (spacep (keyid))
1561 shadow_info = make_shadow_info (serialno, keyid);
1563 return gpg_error_from_syserror ();
1565 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1566 xfree (shadow_info);
1569 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1573 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1574 err = agent_write_private_key (grip, shdkey, len, force, serialno, keyid, 0);
1577 log_error ("error writing key: %s\n", gpg_strerror (err));