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"
41 /* Helper to pass data to the check callback of the unprotect function. */
42 struct try_unprotect_arg_s
45 const unsigned char *protected_key;
46 unsigned char *unprotected_key;
47 int change_required; /* Set by the callback to indicate that the
48 user should change the passphrase. */
52 /* Repalce all linefeeds in STRING by "%0A" and return a new malloced
53 * string. May return NULL on memory error. */
55 linefeed_to_percent0A (const char *string)
61 for (n=0, s=string; *s; s++)
66 p = buf = xtrymalloc (n+1);
69 for (s=string; *s; s++)
82 /* Note: Ownership of FNAME and FP are moved to this function. */
84 write_extended_private_key (char *fname, estream_t fp, int update, int newkey,
85 const void *buf, size_t len,
86 const char *serialno, const char *keyref,
91 gcry_sexp_t key = NULL;
99 err = nvc_parse_private_key (&pk, &line, fp);
100 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
102 log_error ("error parsing '%s' line %d: %s\n",
103 fname, line, gpg_strerror (err));
109 pk = nvc_new_private_key ();
112 err = gpg_error_from_syserror ();
118 err = gcry_sexp_sscan (&key, NULL, buf, len);
122 err = nvc_set_private_key (pk, key);
126 /* If requested write a Token line. */
127 if (serialno && keyref)
132 token = strconcat (serialno, " ", keyref, NULL);
135 err = gpg_error_from_syserror ();
139 /* fixme: the strcmp should compare only the first two strings. */
140 for (item = nvc_lookup (pk, "Token:");
142 item = nve_next_value (item, "Token:"))
143 if ((s = nve_value (item)) && !strcmp (s, token))
147 /* No token or no token with that value exists. Add a new
148 * one so that keys which have been stored on several cards
149 * are well supported. */
150 err = nvc_add (pk, "Token:", token);
156 /* If a timestamp has been supplied and the key is new write a
157 * creation timestamp. (We douple check that there is no Created
159 if (timestamp && newkey && !nvc_lookup (pk, "Created:"))
161 gnupg_isotime_t timebuf;
163 epoch2isotime (timebuf, timestamp);
164 err = nvc_add (pk, "Created:", timebuf);
170 err = es_fseek (fp, 0, SEEK_SET);
174 err = nvc_write (pk, fp);
176 err = es_fflush (fp);
179 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
184 if (ftruncate (es_fileno (fp), es_ftello (fp)))
186 err = gpg_error_from_syserror ();
187 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
194 err = gpg_error_from_syserror ();
195 log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
202 bump_key_eventcounter ();
207 gnupg_remove (fname);
209 gcry_sexp_release (key);
215 /* Write an S-expression formatted key to our key storage. With FORCE
216 * passed as true an existing key with the given GRIP will get
217 * overwritten. If SERIALNO and KEYREF are given a Token line is
218 * added to the key if the extended format is used. If TIMESTAMP is
219 * not zero and the key doies not yet exists it will be recorded as
222 agent_write_private_key (const unsigned char *grip,
223 const void *buffer, size_t length, int force,
224 const char *serialno, const char *keyref,
229 char hexgrip[40+4+1];
231 bin2hex (grip, 20, hexgrip);
232 strcpy (hexgrip+40, ".key");
234 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
237 /* FIXME: Write to a temp file first so that write failures during
238 key updates won't lead to a key loss. */
240 if (!force && !gnupg_access (fname, F_OK))
242 log_error ("secret key file '%s' already exists\n", fname);
244 return gpg_error (GPG_ERR_EEXIST);
247 fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
250 gpg_error_t tmperr = gpg_error_from_syserror ();
252 if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
254 fp = es_fopen (fname, "wbx,mode=-rw");
256 tmperr = gpg_error_from_syserror ();
260 log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
270 /* See if an existing key is in extended format. */
271 if (es_fread (&first, 1, 1, fp) != 1)
273 rc = gpg_error_from_syserror ();
274 log_error ("error reading first byte from '%s': %s\n",
275 fname, strerror (errno));
281 rc = es_fseek (fp, 0, SEEK_SET);
284 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
292 /* Key is already in the extended format. */
293 return write_extended_private_key (fname, fp, 1, 0, buffer, length,
294 serialno, keyref, timestamp);
296 if (first == '(' && opt.enable_extended_key_format)
298 /* Key is in the old format - but we want the extended format. */
299 return write_extended_private_key (fname, fp, 0, 0, buffer, length,
300 serialno, keyref, timestamp);
304 if (opt.enable_extended_key_format)
305 return write_extended_private_key (fname, fp, 0, 1, buffer, length,
306 serialno, keyref, timestamp);
308 if (es_fwrite (buffer, length, 1, fp) != 1)
310 gpg_error_t tmperr = gpg_error_from_syserror ();
311 log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
313 gnupg_remove (fname);
318 /* When force is given, the file might have to be truncated. */
319 if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
321 gpg_error_t tmperr = gpg_error_from_syserror ();
322 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
324 gnupg_remove (fname);
331 gpg_error_t tmperr = gpg_error_from_syserror ();
332 log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
333 gnupg_remove (fname);
337 bump_key_eventcounter ();
344 agent_update_private_key (const unsigned char *grip, nvc_t pk)
346 char *fname, *fname0;
348 char hexgrip[40+8+1];
351 bin2hex (grip, 20, hexgrip);
352 strcpy (hexgrip+40, ".key.tmp");
354 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
356 fname0 = xstrdup (fname);
359 err = gpg_error_from_syserror ();
363 fname0[strlen (fname)-4] = 0;
365 fp = es_fopen (fname, "wbx,mode=-rw");
368 err = gpg_error_from_syserror ();
370 log_error ("can't create '%s': %s\n", fname, gpg_strerror (err));
375 err = nvc_write (pk, fp);
377 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
381 #ifdef HAVE_W32_SYSTEM
382 /* No atomic mv on W32 systems. */
383 gnupg_remove (fname0);
385 if (rename (fname, fname0))
387 err = gpg_error_from_errno (errno);
388 log_error (_("error renaming '%s' to '%s': %s\n"),
389 fname, fname0, strerror (errno));
396 /* Callback function to try the unprotection from the passphrase query
399 try_unprotect_cb (struct pin_entry_info_s *pi)
401 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
402 ctrl_t ctrl = arg->ctrl;
405 gnupg_isotime_t now, protected_at, tmptime;
408 log_assert (!arg->unprotected_key);
410 arg->change_required = 0;
411 err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
412 &arg->unprotected_key, &dummy);
415 if (!opt.max_passphrase_days || ctrl->in_passwd)
416 return 0; /* No regular passphrase change required. */
420 /* No protection date known - must force passphrase change. */
421 desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
422 "Please change it now."));
424 return gpg_error_from_syserror ();
428 gnupg_get_isotime (now);
429 gnupg_copy_time (tmptime, protected_at);
430 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
433 if (strcmp (now, tmptime) > 0 )
435 /* Passphrase "expired". */
437 (L_("This passphrase has not been changed%%0A"
438 "since %.4s-%.2s-%.2s. Please change it now."),
439 protected_at, protected_at+4, protected_at+6);
441 return gpg_error_from_syserror ();
447 /* Change required. */
448 if (opt.enforce_passphrase_constraints)
450 err = agent_get_confirmation (ctrl, desc,
451 L_("Change passphrase"), NULL, 0);
453 arg->change_required = 1;
457 err = agent_get_confirmation (ctrl, desc,
458 L_("Change passphrase"),
459 L_("I'll change it later"), 0);
461 arg->change_required = 1;
462 else if (gpg_err_code (err) == GPG_ERR_CANCELED
463 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
473 /* Return true if the STRING has an %C or %c expando. */
475 has_comment_expando (const char *string)
483 for (s = string; *s; s++)
487 if (*s == 'c' || *s == 'C')
500 /* Modify a Key description, replacing certain special format
501 characters. List of currently supported replacements:
503 %% - Replaced by a single %
504 %c - Replaced by the content of COMMENT.
505 %C - Same as %c but put into parentheses.
506 %F - Replaced by an ssh style fingerprint computed from KEY.
508 The functions returns 0 on success or an error code. On success a
509 newly allocated string is stored at the address of RESULT.
512 agent_modify_description (const char *in, const char *comment,
513 const gcry_sexp_t key, char **result)
515 size_t comment_length;
521 char *ssh_fpr = NULL;
529 comment_length = strlen (comment);
530 in_len = strlen (in);
532 /* First pass calculates the length, second pass does the actual
534 /* FIXME: This can be simplified by using es_fopenmem. */
537 for (pass=0; pass < 2; pass++)
540 for (i = 0; i < in_len; i++)
554 case 'c': /* Comment. */
557 memcpy (out, comment, comment_length);
558 out += comment_length;
561 out_len += comment_length;
564 case 'C': /* Comment. */
570 memcpy (out, comment, comment_length);
571 out += comment_length;
575 out_len += comment_length + 2;
578 case 'F': /* SSH style fingerprint. */
580 ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
585 out = stpcpy (out, ssh_fpr);
587 out_len += strlen (ssh_fpr);
591 default: /* Invalid special sequences are kept as they are. */
602 else if (in[i] == '%')
615 *result = out = xtrymalloc (out_len + 1);
619 return gpg_error_from_syserror ();
625 log_assert (*result + out_len == out);
628 /* The ssh prompt may sometimes end in
630 * The empty parentheses doesn't look very good. We use this hack
631 * here to remove them as well as the indentation spaces. */
634 if (i > 2 && !strcmp (p + i - 2, "()"))
638 while (p > *result && spacep (p))
647 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
648 should be the hex encoded keygrip of that key to be used with the
649 caching mechanism. DESC_TEXT may be set to override the default
650 description used for the pinentry. If LOOKUP_TTL is given this
651 function is used to lookup the default ttl. If R_PASSPHRASE is not
652 NULL, the function succeeded and the key was protected the used
653 passphrase (entered or from the cache) is stored there; if not NULL
654 will be stored. The caller needs to free the returned
657 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
658 unsigned char **keybuf, const unsigned char *grip,
659 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
662 struct pin_entry_info_s *pi;
663 struct try_unprotect_arg_s arg;
665 unsigned char *result;
670 *r_passphrase = NULL;
672 bin2hex (grip, 20, hexgrip);
674 /* Initially try to get it using a cache nonce. */
679 pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
682 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
697 /* First try to get it from the cache - if there is none or we can't
698 unprotect it, we fall back to ask the user */
699 if (cache_mode != CACHE_MODE_IGNORE)
704 pw = agent_get_cache (ctrl, hexgrip, cache_mode);
707 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
710 if (cache_mode == CACHE_MODE_NORMAL)
711 agent_store_cache_hit (hexgrip);
722 else if (cache_mode == CACHE_MODE_NORMAL)
724 /* The standard use of GPG keys is to have a signing and an
725 encryption subkey. Commonly both use the same
726 passphrase. We try to help the user to enter the
727 passphrase only once by silently trying the last
728 correctly entered passphrase. Checking one additional
729 passphrase should be acceptable; despite the S2K
730 introduced delays. The assumed workflow is:
732 1. Read encrypted message in a MUA and thus enter a
733 passphrase for the encryption subkey.
735 2. Reply to that mail with an encrypted and signed
736 mail, thus entering the passphrase for the signing
739 We can often avoid the passphrase entry in the second
740 step. We do this only in normal mode, so not to
741 interfere with unrelated cache entries. */
742 pw = agent_get_cache (ctrl, NULL, cache_mode);
745 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
746 &result, &resultlen);
761 /* If the pinentry is currently in use, we wait up to 60 seconds
762 for it to close and check the cache again. This solves a common
763 situation where several requests for unprotecting a key have
764 been made but the user is still entering the passphrase for
765 the first request. Because all requests to agent_askpin are
766 serialized they would then pop up one after the other to
767 request the passphrase - despite that the user has already
768 entered it and is then available in the cache. This
769 implementation is not race free but in the worst case the
770 user has to enter the passphrase only once more. */
771 if (pinentry_active_p (ctrl, 0))
774 if (!pinentry_active_p (ctrl, 60))
776 /* We need to give the other thread a chance to actually put
777 it into the cache. */
781 /* Timeout - better call pinentry now the plain way. */
785 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
787 return gpg_error_from_syserror ();
788 pi->max_length = MAX_PASSPHRASE_LEN + 1;
789 pi->min_digits = 0; /* we want a real passphrase */
792 pi->check_cb = try_unprotect_cb;
794 arg.protected_key = *keybuf;
795 arg.unprotected_key = NULL;
796 arg.change_required = 0;
797 pi->check_cb_arg = &arg;
799 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
802 if ((pi->status & PINENTRY_STATUS_PASSWORD_FROM_CACHE))
804 log_error ("Clearing pinentry cache which caused error %s\n",
807 agent_clear_passphrase (ctrl, hexgrip, cache_mode);
812 log_assert (arg.unprotected_key);
813 if (arg.change_required)
815 /* The callback told as that the user should change their
816 passphrase. Present the dialog to do. */
817 size_t canlen, erroff;
820 log_assert (arg.unprotected_key);
821 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
822 rc = gcry_sexp_sscan (&s_skey, &erroff,
823 (char*)arg.unprotected_key, canlen);
826 log_error ("failed to build S-Exp (off=%u): %s\n",
827 (unsigned int)erroff, gpg_strerror (rc));
828 wipememory (arg.unprotected_key, canlen);
829 xfree (arg.unprotected_key);
833 rc = agent_protect_and_store (ctrl, s_skey, NULL);
834 gcry_sexp_release (s_skey);
837 log_error ("changing the passphrase failed: %s\n",
839 wipememory (arg.unprotected_key, canlen);
840 xfree (arg.unprotected_key);
847 /* Passphrase is fine. */
848 agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
849 lookup_ttl? lookup_ttl (hexgrip) : 0);
850 agent_store_cache_hit (hexgrip);
851 if (r_passphrase && *pi->pin)
852 *r_passphrase = xtrystrdup (pi->pin);
855 *keybuf = arg.unprotected_key;
862 /* Read the key identified by GRIP from the private key directory and
863 * return it as an gcrypt S-expression object in RESULT. If R_KEYMETA
864 * is not NULl and the extended key format is used, the meta data
865 * items are stored there. However the "Key:" item is removed from
866 * it. On failure returns an error code and stores NULL at RESULT and
869 read_key_file (const unsigned char *grip, gcry_sexp_t *result, nvc_t *r_keymeta)
876 size_t buflen, erroff;
878 char hexgrip[40+4+1];
885 bin2hex (grip, 20, hexgrip);
886 strcpy (hexgrip+40, ".key");
888 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
890 fp = es_fopen (fname, "rb");
893 err = gpg_error_from_syserror ();
894 if (gpg_err_code (err) != GPG_ERR_ENOENT)
895 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
900 if (es_fread (&first, 1, 1, fp) != 1)
902 err = gpg_error_from_syserror ();
903 log_error ("error reading first byte from '%s': %s\n",
904 fname, gpg_strerror (err));
910 if (es_fseek (fp, 0, SEEK_SET))
912 err = gpg_error_from_syserror ();
913 log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
921 /* Key is in extended format. */
925 err = nvc_parse_private_key (&pk, &line, fp);
929 log_error ("error parsing '%s' line %d: %s\n",
930 fname, line, gpg_strerror (err));
933 err = nvc_get_private_key (pk, result);
935 log_error ("error getting private key from '%s': %s\n",
936 fname, gpg_strerror (err));
938 nvc_delete_named (pk, "Key:");
941 if (!err && r_keymeta)
949 if (fstat (es_fileno (fp), &st))
951 err = gpg_error_from_syserror ();
952 log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
959 buf = xtrymalloc (buflen+1);
962 err = gpg_error_from_syserror ();
963 log_error ("error allocating %zu bytes for '%s': %s\n",
964 buflen, fname, gpg_strerror (err));
972 if (es_fread (buf, buflen, 1, fp) != 1)
974 err = gpg_error_from_syserror ();
975 log_error ("error reading %zu bytes from '%s': %s\n",
976 buflen, fname, gpg_strerror (err));
983 /* Convert the file into a gcrypt S-expression object. */
984 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
990 log_error ("failed to build S-Exp (off=%u): %s\n",
991 (unsigned int)erroff, gpg_strerror (err));
999 /* Remove the key identified by GRIP from the private key directory. */
1001 remove_key_file (const unsigned char *grip)
1003 gpg_error_t err = 0;
1005 char hexgrip[40+4+1];
1007 bin2hex (grip, 20, hexgrip);
1008 strcpy (hexgrip+40, ".key");
1009 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1011 if (gnupg_remove (fname))
1012 err = gpg_error_from_syserror ();
1019 * Prompt a user the card insertion, when it's not available yet.
1022 prompt_for_card (ctrl_t ctrl, const unsigned char *grip,
1023 nvc_t keymeta, const unsigned char *shadow_info)
1027 char *want_sn = NULL;
1031 char *comment_buffer = NULL;
1032 const char *comment = NULL;
1033 int refuse_prompt = 0;
1035 bin2hex (grip, 20, hexgrip);
1041 if ((p = nvc_get_string (keymeta, "Prompt:")) && !strcmp (p, "no"))
1044 if ((p = nvc_get_string (keymeta, "Label:")))
1046 if (strchr (p, '\n')
1047 && (comment_buffer = linefeed_to_percent0A (p)))
1048 comment = comment_buffer;
1054 err = parse_shadow_info (shadow_info, &want_sn, NULL, NULL);
1058 len = want_sn? strlen (want_sn) : 0;
1059 if (len == 32 && !strncmp (want_sn, "D27600012401", 12))
1061 /* This is an OpenPGP card - reformat */
1062 if (!strncmp (want_sn+16, "0006", 4))
1064 /* This is a Yubikey. Print the s/n as it would be printed
1065 * on Yubikey 5. Example: D2760001240100000006120808620000
1069 sn = atoi_4 (want_sn+20) * 10000;
1070 sn += atoi_4 (want_sn+24);
1071 snprintf (want_sn, 32, "%lu %03lu %03lu",
1072 (sn/1000000ul), (sn/1000ul % 1000ul), (sn % 1000ul));
1074 else /* Default is the Zeitcontrol card print format. */
1076 memmove (want_sn, want_sn+16, 4);
1078 memmove (want_sn+5, want_sn+20, 8);
1082 else if (len == 20 && want_sn[19] == '0')
1084 /* We assume that a 20 byte serial number is a standard one
1085 * which has the property to have a zero in the last nibble (Due
1086 * to BCD representation). We don't display this '0' because it
1087 * may confuse the user. */
1093 /* Scan device(s), and check if key for GRIP is available. */
1094 err = agent_card_serialno (ctrl, &serialno, NULL);
1097 struct card_key_info_s *keyinfo;
1100 err = agent_card_keyinfo (ctrl, hexgrip, 0, &keyinfo);
1103 /* Key for GRIP found, use it. */
1104 agent_card_free_keyinfo (keyinfo);
1109 /* Card is not available. Prompt the insertion. */
1112 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
1116 if (asprintf (&desc,
1120 L_("Please insert the card with serial number"),
1121 want_sn ? want_sn : "",
1122 comment? comment:"") < 0)
1123 err = out_of_core ();
1126 err = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
1127 if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK &&
1128 gpg_err_code (err) == GPG_ERR_NO_PIN_ENTRY)
1129 err = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
1139 gcry_free (comment_buffer);
1144 /* Return the secret key as an S-Exp in RESULT after locating it using
1145 the GRIP. Caller should set GRIP=NULL, when a key in a file is
1146 intended to be used for cryptographic operation. In this case,
1147 CTRL->keygrip is used to locate the file, and it may ask a user for
1148 confirmation. If the operation shall be diverted to a token, an
1149 allocated S-expression with the shadow_info part from the file is
1150 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
1151 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
1152 set to present a custom description for the pinentry. LOOKUP_TTL
1153 is an optional function to convey a TTL to the cache manager; we do
1154 not simply pass the TTL value because the value is only needed if
1155 an unprotect action was needed and looking up the TTL may have some
1156 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
1157 given that cache item is first tried to get a passphrase. If
1158 R_PASSPHRASE is not NULL, the function succeeded and the key was
1159 protected the used passphrase (entered or from the cache) is stored
1160 there; if not NULL will be stored. The caller needs to free the
1161 returned passphrase. */
1163 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
1164 const char *desc_text,
1165 const unsigned char *grip, unsigned char **shadow_info,
1166 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
1167 gcry_sexp_t *result, char **r_passphrase,
1168 time_t *r_timestamp)
1174 nvc_t keymeta = NULL;
1175 char *desc_text_buffer = NULL; /* Used in case we extend DESC_TEXT. */
1179 *shadow_info = NULL;
1181 *r_passphrase = NULL;
1183 *r_timestamp = (time_t)(-1);
1185 if (!grip && !ctrl->have_keygrip)
1186 return gpg_error (GPG_ERR_NO_SECKEY);
1188 err = read_key_file (grip? grip : ctrl->keygrip, &s_skey, &keymeta);
1190 /* For use with the protection functions we also need the key as an
1191 canonical encoded S-expression in a buffer. Create this buffer
1193 err = make_canon_sexp (s_skey, &buf, &len);
1196 nvc_release (keymeta);
1197 xfree (desc_text_buffer);
1201 if (r_timestamp && keymeta)
1203 const char *created = nvc_get_string (keymeta, "Created:");
1206 *r_timestamp = isotime2epoch (created);
1209 if (!grip && keymeta)
1211 const char *ask_confirmation = nvc_get_string (keymeta, "Confirm:");
1213 if (ask_confirmation
1214 && ((!strcmp (ask_confirmation, "restricted") && ctrl->restricted)
1215 || !strcmp (ask_confirmation, "yes")))
1217 char hexgrip[40+4+1];
1219 char *comment_buffer = NULL;
1220 const char *comment = NULL;
1222 bin2hex (ctrl->keygrip, 20, hexgrip);
1224 if ((comment = nvc_get_string (keymeta, "Label:")))
1226 if (strchr (comment, '\n')
1227 && (comment_buffer = linefeed_to_percent0A (comment)))
1228 comment = comment_buffer;
1231 prompt = xtryasprintf (L_("Requested the use of key%%0A"
1234 "Do you want to allow this?"),
1235 hexgrip, comment? comment:"");
1237 gcry_free (comment_buffer);
1239 err = agent_get_confirmation (ctrl, prompt,
1240 L_("Allow"), L_("Deny"), 0);
1248 switch (agent_private_key_type (buf))
1250 case PRIVATE_KEY_CLEAR:
1251 break; /* no unprotection needed */
1252 case PRIVATE_KEY_OPENPGP_NONE:
1254 unsigned char *buf_new;
1257 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
1259 log_error ("failed to convert unprotected openpgp key: %s\n",
1260 gpg_strerror (err));
1268 case PRIVATE_KEY_PROTECTED:
1270 char *desc_text_final;
1271 char *comment_buffer = NULL;
1272 const char *comment = NULL;
1274 /* Note, that we will take the comment as a C string for
1275 * display purposes; i.e. all stuff beyond a Nul character is
1276 * ignored. If a "Label" entry is available in the meta data
1277 * this is used instead of the s-expression comment. */
1278 if (keymeta && (comment = nvc_get_string (keymeta, "Label:")))
1280 if (strchr (comment, '\n')
1281 && (comment_buffer = linefeed_to_percent0A (comment)))
1282 comment = comment_buffer;
1283 /* In case DESC_TEXT has no escape pattern for a comment
1285 if (desc_text && !has_comment_expando (desc_text))
1287 desc_text_buffer = strconcat (desc_text, "%0A%C", NULL);
1288 if (desc_text_buffer)
1289 desc_text = desc_text_buffer;
1294 gcry_sexp_t comment_sexp;
1296 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1298 comment_buffer = gcry_sexp_nth_string (comment_sexp, 1);
1299 gcry_sexp_release (comment_sexp);
1300 comment = comment_buffer;
1303 desc_text_final = NULL;
1305 err = agent_modify_description (desc_text, comment, s_skey,
1307 gcry_free (comment_buffer);
1311 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf,
1312 grip? grip : ctrl->keygrip,
1313 cache_mode, lookup_ttl, r_passphrase);
1315 log_error ("failed to unprotect the secret key: %s\n",
1316 gpg_strerror (err));
1319 xfree (desc_text_final);
1322 case PRIVATE_KEY_SHADOWED:
1325 const unsigned char *s;
1326 unsigned char *shadow_type;
1329 err = agent_get_shadow_info_type (buf, &s, &shadow_type);
1332 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
1334 *shadow_info = xtrymalloc (n);
1337 err = out_of_core ();
1342 memcpy (*shadow_info, s, n);
1344 * When it's a key on card (not on tpm2), maks sure
1347 if (strcmp (shadow_type, "t1-v1") == 0 && !grip)
1348 err = prompt_for_card (ctrl, ctrl->keygrip,
1349 keymeta, *shadow_info);
1354 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
1356 xfree (shadow_type);
1359 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
1362 log_error ("invalid private key format\n");
1363 err = gpg_error (GPG_ERR_BAD_SECKEY);
1366 gcry_sexp_release (s_skey);
1373 xfree (*r_passphrase);
1374 *r_passphrase = NULL;
1376 nvc_release (keymeta);
1377 xfree (desc_text_buffer);
1381 err = sexp_sscan_private_key (result, &erroff, buf);
1383 nvc_release (keymeta);
1384 xfree (desc_text_buffer);
1387 log_error ("failed to build S-Exp (off=%u): %s\n",
1388 (unsigned int)erroff, gpg_strerror (err));
1391 xfree (*r_passphrase);
1392 *r_passphrase = NULL;
1400 /* Return the key for the keygrip GRIP. The result is stored at
1401 RESULT. This function extracts the key from the private key
1402 database and returns it as an S-expression object as it is. On
1403 failure an error code is returned and NULL stored at RESULT. */
1405 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1406 gcry_sexp_t *result, nvc_t *r_keymeta)
1415 err = read_key_file (grip, &s_skey, r_keymeta);
1422 /* Return the public key for the keygrip GRIP. The result is stored
1423 at RESULT. This function extracts the public key from the private
1424 key database. On failure an error code is returned and NULL stored
1427 public_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1428 gcry_sexp_t *result, int for_ssh)
1433 nvc_t keymeta = NULL;
1434 const char *algoname, *elems;
1436 gcry_mpi_t array[10];
1437 gcry_sexp_t curve = NULL;
1438 gcry_sexp_t flags = NULL;
1439 gcry_sexp_t uri_sexp, comment_sexp;
1440 const char *uri, *comment;
1441 size_t uri_length, comment_length;
1442 int uri_intlen, comment_intlen;
1445 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1446 for comment + end-of-list. */
1448 gcry_sexp_t list = NULL;
1455 err = read_key_file (grip, &s_skey, for_ssh? &keymeta : NULL);
1461 /* Use-for-ssh: yes */
1465 if (keymeta == NULL)
1466 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1468 if ((p = nvc_get_string (keymeta, "Use-for-ssh:"))
1469 && !strcmp (p, "yes"))
1472 nvc_release (keymeta);
1476 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1479 for (i=0; i < DIM (array); i++)
1482 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1483 array, DIM (array), &curve, &flags);
1486 gcry_sexp_release (s_skey);
1492 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1494 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1498 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1500 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1502 gcry_sexp_release (s_skey);
1506 log_assert (sizeof (size_t) <= sizeof (void*));
1508 init_membuf (&format_mb, 256);
1510 put_membuf_printf (&format_mb, "(public-key(%s%%S%%S", algoname);
1511 args[argidx++] = &curve;
1512 args[argidx++] = &flags;
1513 for (idx=0, s=elems; idx < npkey; idx++)
1515 put_membuf_printf (&format_mb, "(%c %%m)", *s++);
1516 log_assert (argidx < DIM (args));
1517 args[argidx++] = &array[idx];
1519 put_membuf_str (&format_mb, ")");
1522 put_membuf_str (&format_mb, "(uri %b)");
1523 log_assert (argidx+1 < DIM (args));
1524 uri_intlen = (int)uri_length;
1525 args[argidx++] = (void *)&uri_intlen;
1526 args[argidx++] = (void *)&uri;
1530 put_membuf_str (&format_mb, "(comment %b)");
1531 log_assert (argidx+1 < DIM (args));
1532 comment_intlen = (int)comment_length;
1533 args[argidx++] = (void *)&comment_intlen;
1534 args[argidx++] = (void *)&comment;
1536 put_membuf (&format_mb, ")", 2);
1537 log_assert (argidx < DIM (args));
1538 args[argidx] = NULL;
1540 format = get_membuf (&format_mb, NULL);
1543 err = gpg_error_from_syserror ();
1544 for (i=0; array[i]; i++)
1545 gcry_mpi_release (array[i]);
1546 gcry_sexp_release (curve);
1547 gcry_sexp_release (flags);
1548 gcry_sexp_release (uri_sexp);
1549 gcry_sexp_release (comment_sexp);
1553 err = gcry_sexp_build_array (&list, NULL, format, args);
1555 for (i=0; array[i]; i++)
1556 gcry_mpi_release (array[i]);
1557 gcry_sexp_release (curve);
1558 gcry_sexp_release (flags);
1559 gcry_sexp_release (uri_sexp);
1560 gcry_sexp_release (comment_sexp);
1568 agent_public_key_from_file (ctrl_t ctrl,
1569 const unsigned char *grip,
1570 gcry_sexp_t *result)
1572 return public_key_from_file (ctrl, grip, result, 0);
1576 agent_ssh_key_from_file (ctrl_t ctrl,
1577 const unsigned char *grip,
1578 gcry_sexp_t *result)
1580 return public_key_from_file (ctrl, grip, result, 1);
1584 /* Check whether the secret key identified by GRIP is available.
1585 Returns 0 is the key is available. */
1587 agent_key_available (const unsigned char *grip)
1591 char hexgrip[40+4+1];
1593 bin2hex (grip, 20, hexgrip);
1594 strcpy (hexgrip+40, ".key");
1596 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1598 result = !gnupg_access (fname, R_OK)? 0 : -1;
1605 /* Return the information about the secret key specified by the binary
1606 keygrip GRIP. If the key is a shadowed one the shadow information
1607 will be stored at the address R_SHADOW_INFO as an allocated
1610 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1611 int *r_keytype, unsigned char **r_shadow_info,
1612 unsigned char **r_shadow_info_type)
1622 *r_keytype = PRIVATE_KEY_UNKNOWN;
1624 *r_shadow_info = NULL;
1629 err = read_key_file (grip, &sexp, NULL);
1632 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1633 return gpg_error (GPG_ERR_NOT_FOUND);
1637 err = make_canon_sexp (sexp, &buf, &len);
1638 gcry_sexp_release (sexp);
1643 keytype = agent_private_key_type (buf);
1646 case PRIVATE_KEY_CLEAR:
1647 case PRIVATE_KEY_OPENPGP_NONE:
1649 case PRIVATE_KEY_PROTECTED:
1650 /* If we ever require it we could retrieve the comment fields
1653 case PRIVATE_KEY_SHADOWED:
1656 const unsigned char *s;
1659 err = agent_get_shadow_info_type (buf, &s, r_shadow_info_type);
1662 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1664 *r_shadow_info = xtrymalloc (n);
1665 if (!*r_shadow_info)
1666 err = gpg_error_from_syserror ();
1668 memcpy (*r_shadow_info, s, n);
1673 err = gpg_error (GPG_ERR_BAD_SECKEY);
1677 if (!err && r_keytype)
1678 *r_keytype = keytype;
1686 /* Delete the key with GRIP from the disk after having asked for
1687 * confirmation using DESC_TEXT. If FORCE is set the function won't
1688 * require a confirmation via Pinentry or warns if the key is also
1689 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1690 * smartcards) will be affected.
1692 * Common error codes are:
1694 * GPG_ERR_KEY_ON_CARD
1695 * GPG_ERR_NOT_CONFIRMED
1696 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1699 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1700 const unsigned char *grip, int force, int only_stubs)
1703 gcry_sexp_t s_skey = NULL;
1704 unsigned char *buf = NULL;
1706 char *desc_text_final = NULL;
1707 char *comment = NULL;
1708 ssh_control_file_t cf = NULL;
1709 char hexgrip[40+4+1];
1710 char *default_desc = NULL;
1713 err = read_key_file (grip, &s_skey, NULL);
1714 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1715 err = gpg_error (GPG_ERR_NO_SECKEY);
1719 err = make_canon_sexp (s_skey, &buf, &len);
1723 key_type = agent_private_key_type (buf);
1724 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1726 err = gpg_error (GPG_ERR_FORBIDDEN);
1732 case PRIVATE_KEY_CLEAR:
1733 case PRIVATE_KEY_OPENPGP_NONE:
1734 case PRIVATE_KEY_PROTECTED:
1735 bin2hex (grip, 20, hexgrip);
1740 default_desc = xtryasprintf
1741 (L_("Do you really want to delete the key identified by keygrip%%0A"
1742 " %s%%0A %%C%%0A?"), hexgrip);
1743 desc_text = default_desc;
1746 /* Note, that we will take the comment as a C string for
1747 display purposes; i.e. all stuff beyond a Nul character is
1750 gcry_sexp_t comment_sexp;
1752 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1754 comment = gcry_sexp_nth_string (comment_sexp, 1);
1755 gcry_sexp_release (comment_sexp);
1759 err = agent_modify_description (desc_text, comment, s_skey,
1764 err = agent_get_confirmation (ctrl, desc_text_final,
1765 L_("Delete key"), L_("No"), 0);
1769 cf = ssh_open_control_file ();
1772 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1774 err = agent_get_confirmation
1776 L_("Warning: This key is also listed for use with SSH!\n"
1777 "Deleting the key might remove your ability to "
1778 "access remote machines."),
1779 L_("Delete key"), L_("No"), 0);
1785 err = remove_key_file (grip);
1788 case PRIVATE_KEY_SHADOWED:
1789 err = remove_key_file (grip);
1793 log_error ("invalid private key format\n");
1794 err = gpg_error (GPG_ERR_BAD_SECKEY);
1799 ssh_close_control_file (cf);
1800 gcry_free (comment);
1801 xfree (desc_text_final);
1802 xfree (default_desc);
1804 gcry_sexp_release (s_skey);
1809 /* Write an S-expression formatted shadow key to our key storage.
1810 Shadow key is created by an S-expression public key in PKBUF and
1811 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1812 existing key with the given GRIP will get overwritten. */
1814 agent_write_shadow_key (const unsigned char *grip,
1815 const char *serialno, const char *keyid,
1816 const unsigned char *pkbuf, int force)
1819 unsigned char *shadow_info;
1820 unsigned char *shdkey;
1823 /* Just in case some caller did not parse the stuff correctly, skip
1824 * leading spaces. */
1825 while (spacep (serialno))
1827 while (spacep (keyid))
1830 shadow_info = make_shadow_info (serialno, keyid);
1832 return gpg_error_from_syserror ();
1834 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1835 xfree (shadow_info);
1838 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1842 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1843 err = agent_write_private_key (grip, shdkey, len, force, serialno, keyid, 0);
1846 log_error ("error writing key: %s\n", gpg_strerror (err));