1 /* findkey.c - Locate the secret key
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007,
3 * 2010, 2011 Free Software Foundation, Inc.
4 * Copyright (C) 2014 Werner Koch
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
33 #include <npth.h> /* (we use pth_sleep) */
36 #include "../common/i18n.h"
37 #include "../common/ssh-utils.h"
38 #include "../common/name-value.h"
44 /* Helper to pass data to the check callback of the unprotect function. */
45 struct try_unprotect_arg_s
48 const unsigned char *protected_key;
49 unsigned char *unprotected_key;
50 int change_required; /* Set by the callback to indicate that the
51 user should change the passphrase. */
55 /* Note: Ownership of FNAME and FP are moved to this function. */
57 write_extended_private_key (char *fname, estream_t fp, int update,
58 const void *buf, size_t len)
62 gcry_sexp_t key = NULL;
69 err = nvc_parse_private_key (&pk, &line, fp);
70 if (err && gpg_err_code (err) != GPG_ERR_ENOENT)
72 log_error ("error parsing '%s' line %d: %s\n",
73 fname, line, gpg_strerror (err));
79 pk = nvc_new_private_key ();
82 err = gpg_error_from_syserror ();
88 err = gcry_sexp_sscan (&key, NULL, buf, len);
92 err = nvc_set_private_key (pk, key);
96 err = es_fseek (fp, 0, SEEK_SET);
100 err = nvc_write (pk, fp);
103 log_error ("error writing '%s': %s\n", fname, gpg_strerror (err));
108 if (ftruncate (es_fileno (fp), es_ftello (fp)))
110 err = gpg_error_from_syserror ();
111 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (err));
118 err = gpg_error_from_syserror ();
119 log_error ("error closing '%s': %s\n", fname, gpg_strerror (err));
126 bump_key_eventcounter ();
131 gnupg_remove (fname);
133 gcry_sexp_release (key);
138 /* Write an S-expression formatted key to our key storage. With FORCE
139 passed as true an existing key with the given GRIP will get
142 agent_write_private_key (const unsigned char *grip,
143 const void *buffer, size_t length, int force)
147 char hexgrip[40+4+1];
149 bin2hex (grip, 20, hexgrip);
150 strcpy (hexgrip+40, ".key");
152 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
155 /* FIXME: Write to a temp file first so that write failures during
156 key updates won't lead to a key loss. */
158 if (!force && !access (fname, F_OK))
160 log_error ("secret key file '%s' already exists\n", fname);
162 return gpg_error (GPG_ERR_EEXIST);
165 fp = es_fopen (fname, force? "rb+,mode=-rw" : "wbx,mode=-rw");
168 gpg_error_t tmperr = gpg_error_from_syserror ();
170 if (force && gpg_err_code (tmperr) == GPG_ERR_ENOENT)
172 fp = es_fopen (fname, "wbx,mode=-rw");
174 tmperr = gpg_error_from_syserror ();
178 log_error ("can't create '%s': %s\n", fname, gpg_strerror (tmperr));
188 /* See if an existing key is in extended format. */
189 if (es_fread (&first, 1, 1, fp) != 1)
191 rc = gpg_error_from_syserror ();
192 log_error ("error reading first byte from '%s': %s\n",
193 fname, strerror (errno));
199 rc = es_fseek (fp, 0, SEEK_SET);
202 log_error ("error seeking in '%s': %s\n", fname, strerror (errno));
210 /* Key is already in the extended format. */
211 return write_extended_private_key (fname, fp, 1, buffer, length);
213 if (first == '(' && opt.enable_extended_key_format)
215 /* Key is in the old format - but we want the extended format. */
216 return write_extended_private_key (fname, fp, 0, buffer, length);
220 if (opt.enable_extended_key_format)
221 return write_extended_private_key (fname, fp, 0, buffer, length);
223 if (es_fwrite (buffer, length, 1, fp) != 1)
225 gpg_error_t tmperr = gpg_error_from_syserror ();
226 log_error ("error writing '%s': %s\n", fname, gpg_strerror (tmperr));
228 gnupg_remove (fname);
233 /* When force is given, the file might have to be truncated. */
234 if (force && ftruncate (es_fileno (fp), es_ftello (fp)))
236 gpg_error_t tmperr = gpg_error_from_syserror ();
237 log_error ("error truncating '%s': %s\n", fname, gpg_strerror (tmperr));
239 gnupg_remove (fname);
246 gpg_error_t tmperr = gpg_error_from_syserror ();
247 log_error ("error closing '%s': %s\n", fname, gpg_strerror (tmperr));
248 gnupg_remove (fname);
252 bump_key_eventcounter ();
258 /* Callback function to try the unprotection from the passphrase query
261 try_unprotect_cb (struct pin_entry_info_s *pi)
263 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
264 ctrl_t ctrl = arg->ctrl;
267 gnupg_isotime_t now, protected_at, tmptime;
270 assert (!arg->unprotected_key);
272 arg->change_required = 0;
273 err = agent_unprotect (ctrl, arg->protected_key, pi->pin, protected_at,
274 &arg->unprotected_key, &dummy);
277 if (!opt.max_passphrase_days || ctrl->in_passwd)
278 return 0; /* No regular passphrase change required. */
282 /* No protection date known - must force passphrase change. */
283 desc = xtrystrdup (L_("Note: This passphrase has never been changed.%0A"
284 "Please change it now."));
286 return gpg_error_from_syserror ();
290 gnupg_get_isotime (now);
291 gnupg_copy_time (tmptime, protected_at);
292 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
295 if (strcmp (now, tmptime) > 0 )
297 /* Passphrase "expired". */
299 (L_("This passphrase has not been changed%%0A"
300 "since %.4s-%.2s-%.2s. Please change it now."),
301 protected_at, protected_at+4, protected_at+6);
303 return gpg_error_from_syserror ();
309 /* Change required. */
310 if (opt.enforce_passphrase_constraints)
312 err = agent_get_confirmation (ctrl, desc,
313 L_("Change passphrase"), NULL, 0);
315 arg->change_required = 1;
319 err = agent_get_confirmation (ctrl, desc,
320 L_("Change passphrase"),
321 L_("I'll change it later"), 0);
323 arg->change_required = 1;
324 else if (gpg_err_code (err) == GPG_ERR_CANCELED
325 || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
335 /* Modify a Key description, replacing certain special format
336 characters. List of currently supported replacements:
338 %% - Replaced by a single %
339 %c - Replaced by the content of COMMENT.
340 %C - Same as %c but put into parentheses.
341 %F - Replaced by an ssh style fingerprint computed from KEY.
343 The functions returns 0 on success or an error code. On success a
344 newly allocated string is stored at the address of RESULT.
347 agent_modify_description (const char *in, const char *comment,
348 const gcry_sexp_t key, char **result)
350 size_t comment_length;
356 char *ssh_fpr = NULL;
364 comment_length = strlen (comment);
365 in_len = strlen (in);
367 /* First pass calculates the length, second pass does the actual
369 /* FIXME: This can be simplified by using es_fopenmem. */
372 for (pass=0; pass < 2; pass++)
375 for (i = 0; i < in_len; i++)
389 case 'c': /* Comment. */
392 memcpy (out, comment, comment_length);
393 out += comment_length;
396 out_len += comment_length;
399 case 'C': /* Comment. */
405 memcpy (out, comment, comment_length);
406 out += comment_length;
410 out_len += comment_length + 2;
413 case 'F': /* SSH style fingerprint. */
415 ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest,
420 out = stpcpy (out, ssh_fpr);
422 out_len += strlen (ssh_fpr);
426 default: /* Invalid special sequences are kept as they are. */
437 else if (in[i] == '%')
450 *result = out = xtrymalloc (out_len + 1);
454 return gpg_error_from_syserror ();
460 log_assert (*result + out_len == out);
463 /* The ssh prompt may sometimes end in
465 * The empty parentheses doesn't look very good. We use this hack
466 * here to remove them as well as the indentation spaces. */
469 if (i > 2 && !strcmp (p + i - 2, "()"))
473 while (p > *result && spacep (p))
482 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
483 should be the hex encoded keygrip of that key to be used with the
484 caching mechanism. DESC_TEXT may be set to override the default
485 description used for the pinentry. If LOOKUP_TTL is given this
486 function is used to lookup the default ttl. If R_PASSPHRASE is not
487 NULL, the function succeeded and the key was protected the used
488 passphrase (entered or from the cache) is stored there; if not NULL
489 will be stored. The caller needs to free the returned
492 unprotect (ctrl_t ctrl, const char *cache_nonce, const char *desc_text,
493 unsigned char **keybuf, const unsigned char *grip,
494 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
497 struct pin_entry_info_s *pi;
498 struct try_unprotect_arg_s arg;
500 unsigned char *result;
505 *r_passphrase = NULL;
507 bin2hex (grip, 20, hexgrip);
509 /* Initially try to get it using a cache nonce. */
514 pw = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
517 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
532 /* First try to get it from the cache - if there is none or we can't
533 unprotect it, we fall back to ask the user */
534 if (cache_mode != CACHE_MODE_IGNORE)
539 pw = agent_get_cache (ctrl, hexgrip, cache_mode);
542 rc = agent_unprotect (ctrl, *keybuf, pw, NULL, &result, &resultlen);
545 if (cache_mode == CACHE_MODE_NORMAL)
546 agent_store_cache_hit (hexgrip);
557 else if (cache_mode == CACHE_MODE_NORMAL)
559 /* The standard use of GPG keys is to have a signing and an
560 encryption subkey. Commonly both use the same
561 passphrase. We try to help the user to enter the
562 passphrase only once by silently trying the last
563 correctly entered passphrase. Checking one additional
564 passphrase should be acceptable; despite the S2K
565 introduced delays. The assumed workflow is:
567 1. Read encrypted message in a MUA and thus enter a
568 passphrase for the encryption subkey.
570 2. Reply to that mail with an encrypted and signed
571 mail, thus entering the passphrase for the signing
574 We can often avoid the passphrase entry in the second
575 step. We do this only in normal mode, so not to
576 interfere with unrelated cache entries. */
577 pw = agent_get_cache (ctrl, NULL, cache_mode);
580 rc = agent_unprotect (ctrl, *keybuf, pw, NULL,
581 &result, &resultlen);
596 /* If the pinentry is currently in use, we wait up to 60 seconds
597 for it to close and check the cache again. This solves a common
598 situation where several requests for unprotecting a key have
599 been made but the user is still entering the passphrase for
600 the first request. Because all requests to agent_askpin are
601 serialized they would then pop up one after the other to
602 request the passphrase - despite that the user has already
603 entered it and is then available in the cache. This
604 implementation is not race free but in the worst case the
605 user has to enter the passphrase only once more. */
606 if (pinentry_active_p (ctrl, 0))
609 if (!pinentry_active_p (ctrl, 60))
611 /* We need to give the other thread a chance to actually put
612 it into the cache. */
616 /* Timeout - better call pinentry now the plain way. */
620 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
622 return gpg_error_from_syserror ();
623 pi->max_length = MAX_PASSPHRASE_LEN + 1;
624 pi->min_digits = 0; /* we want a real passphrase */
627 pi->check_cb = try_unprotect_cb;
629 arg.protected_key = *keybuf;
630 arg.unprotected_key = NULL;
631 arg.change_required = 0;
632 pi->check_cb_arg = &arg;
634 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi, hexgrip, cache_mode);
637 assert (arg.unprotected_key);
638 if (arg.change_required)
640 /* The callback told as that the user should change their
641 passphrase. Present the dialog to do. */
642 size_t canlen, erroff;
645 assert (arg.unprotected_key);
646 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
647 rc = gcry_sexp_sscan (&s_skey, &erroff,
648 (char*)arg.unprotected_key, canlen);
651 log_error ("failed to build S-Exp (off=%u): %s\n",
652 (unsigned int)erroff, gpg_strerror (rc));
653 wipememory (arg.unprotected_key, canlen);
654 xfree (arg.unprotected_key);
658 rc = agent_protect_and_store (ctrl, s_skey, NULL);
659 gcry_sexp_release (s_skey);
662 log_error ("changing the passphrase failed: %s\n",
664 wipememory (arg.unprotected_key, canlen);
665 xfree (arg.unprotected_key);
672 /* Passphrase is fine. */
673 agent_put_cache (ctrl, hexgrip, cache_mode, pi->pin,
674 lookup_ttl? lookup_ttl (hexgrip) : 0);
675 agent_store_cache_hit (hexgrip);
676 if (r_passphrase && *pi->pin)
677 *r_passphrase = xtrystrdup (pi->pin);
680 *keybuf = arg.unprotected_key;
687 /* Read the key identified by GRIP from the private key directory and
688 return it as an gcrypt S-expression object in RESULT. On failure
689 returns an error code and stores NULL at RESULT. */
691 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
698 size_t buflen, erroff;
700 char hexgrip[40+4+1];
705 bin2hex (grip, 20, hexgrip);
706 strcpy (hexgrip+40, ".key");
708 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
710 fp = es_fopen (fname, "rb");
713 err = gpg_error_from_syserror ();
714 if (gpg_err_code (err) != GPG_ERR_ENOENT)
715 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
720 if (es_fread (&first, 1, 1, fp) != 1)
722 err = gpg_error_from_syserror ();
723 log_error ("error reading first byte from '%s': %s\n",
724 fname, gpg_strerror (err));
730 if (es_fseek (fp, 0, SEEK_SET))
732 err = gpg_error_from_syserror ();
733 log_error ("error seeking in '%s': %s\n", fname, gpg_strerror (err));
741 /* Key is in extended format. */
745 err = nvc_parse_private_key (&pk, &line, fp);
749 log_error ("error parsing '%s' line %d: %s\n",
750 fname, line, gpg_strerror (err));
753 err = nvc_get_private_key (pk, result);
756 log_error ("error getting private key from '%s': %s\n",
757 fname, gpg_strerror (err));
764 if (fstat (es_fileno (fp), &st))
766 err = gpg_error_from_syserror ();
767 log_error ("can't stat '%s': %s\n", fname, gpg_strerror (err));
774 buf = xtrymalloc (buflen+1);
777 err = gpg_error_from_syserror ();
778 log_error ("error allocating %zu bytes for '%s': %s\n",
779 buflen, fname, gpg_strerror (err));
787 if (es_fread (buf, buflen, 1, fp) != 1)
789 err = gpg_error_from_syserror ();
790 log_error ("error reading %zu bytes from '%s': %s\n",
791 buflen, fname, gpg_strerror (err));
798 /* Convert the file into a gcrypt S-expression object. */
799 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
805 log_error ("failed to build S-Exp (off=%u): %s\n",
806 (unsigned int)erroff, gpg_strerror (err));
814 /* Remove the key identified by GRIP from the private key directory. */
816 remove_key_file (const unsigned char *grip)
820 char hexgrip[40+4+1];
822 bin2hex (grip, 20, hexgrip);
823 strcpy (hexgrip+40, ".key");
824 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
826 if (gnupg_remove (fname))
827 err = gpg_error_from_syserror ();
833 /* Return the secret key as an S-Exp in RESULT after locating it using
834 the GRIP. If the operation shall be diverted to a token, an
835 allocated S-expression with the shadow_info part from the file is
836 stored at SHADOW_INFO; if not NULL will be stored at SHADOW_INFO.
837 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
838 set to present a custom description for the pinentry. LOOKUP_TTL
839 is an optional function to convey a TTL to the cache manager; we do
840 not simply pass the TTL value because the value is only needed if
841 an unprotect action was needed and looking up the TTL may have some
842 overhead (e.g. scanning the sshcontrol file). If a CACHE_NONCE is
843 given that cache item is first tried to get a passphrase. If
844 R_PASSPHRASE is not NULL, the function succeeded and the key was
845 protected the used passphrase (entered or from the cache) is stored
846 there; if not NULL will be stored. The caller needs to free the
847 returned passphrase. */
849 agent_key_from_file (ctrl_t ctrl, const char *cache_nonce,
850 const char *desc_text,
851 const unsigned char *grip, unsigned char **shadow_info,
852 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
853 gcry_sexp_t *result, char **r_passphrase)
857 size_t len, buflen, erroff;
864 *r_passphrase = NULL;
866 err = read_key_file (grip, &s_skey);
869 if (gpg_err_code (err) == GPG_ERR_ENOENT)
870 err = gpg_error (GPG_ERR_NO_SECKEY);
874 /* For use with the protection functions we also need the key as an
875 canonical encoded S-expression in a buffer. Create this buffer
877 err = make_canon_sexp (s_skey, &buf, &len);
881 switch (agent_private_key_type (buf))
883 case PRIVATE_KEY_CLEAR:
884 break; /* no unprotection needed */
885 case PRIVATE_KEY_OPENPGP_NONE:
887 unsigned char *buf_new;
890 err = agent_unprotect (ctrl, buf, "", NULL, &buf_new, &buf_newlen);
892 log_error ("failed to convert unprotected openpgp key: %s\n",
901 case PRIVATE_KEY_PROTECTED:
903 char *desc_text_final;
904 char *comment = NULL;
906 /* Note, that we will take the comment as a C string for
907 display purposes; i.e. all stuff beyond a Nul character is
910 gcry_sexp_t comment_sexp;
912 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
914 comment = gcry_sexp_nth_string (comment_sexp, 1);
915 gcry_sexp_release (comment_sexp);
918 desc_text_final = NULL;
920 err = agent_modify_description (desc_text, comment, s_skey,
926 err = unprotect (ctrl, cache_nonce, desc_text_final, &buf, grip,
927 cache_mode, lookup_ttl, r_passphrase);
929 log_error ("failed to unprotect the secret key: %s\n",
933 xfree (desc_text_final);
936 case PRIVATE_KEY_SHADOWED:
939 const unsigned char *s;
942 err = agent_get_shadow_info (buf, &s);
945 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
947 *shadow_info = xtrymalloc (n);
949 err = out_of_core ();
952 memcpy (*shadow_info, s, n);
957 log_error ("get_shadow_info failed: %s\n", gpg_strerror (err));
960 err = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
963 log_error ("invalid private key format\n");
964 err = gpg_error (GPG_ERR_BAD_SECKEY);
967 gcry_sexp_release (s_skey);
974 xfree (*r_passphrase);
975 *r_passphrase = NULL;
980 buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
981 err = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
982 wipememory (buf, buflen);
986 log_error ("failed to build S-Exp (off=%u): %s\n",
987 (unsigned int)erroff, gpg_strerror (err));
990 xfree (*r_passphrase);
991 *r_passphrase = NULL;
1001 /* Return the string name from the S-expression S_KEY as well as a
1002 string describing the names of the parameters. ALGONAMESIZE and
1003 ELEMSSIZE give the allocated size of the provided buffers. The
1004 buffers may be NULL if not required. If R_LIST is not NULL the top
1005 level list will be stored there; the caller needs to release it in
1008 key_parms_from_sexp (gcry_sexp_t s_key, gcry_sexp_t *r_list,
1009 char *r_algoname, size_t algonamesize,
1010 char *r_elems, size_t elemssize)
1012 gcry_sexp_t list, l2;
1013 const char *name, *algoname, *elems;
1019 list = gcry_sexp_find_token (s_key, "shadowed-private-key", 0 );
1021 list = gcry_sexp_find_token (s_key, "protected-private-key", 0 );
1023 list = gcry_sexp_find_token (s_key, "private-key", 0 );
1026 log_error ("invalid private key format\n");
1027 return gpg_error (GPG_ERR_BAD_SECKEY);
1030 l2 = gcry_sexp_cadr (list);
1031 gcry_sexp_release (list);
1033 name = gcry_sexp_nth_data (list, 0, &n);
1034 if (n==3 && !memcmp (name, "rsa", 3))
1039 else if (n==3 && !memcmp (name, "dsa", 3))
1044 else if (n==3 && !memcmp (name, "ecc", 3))
1049 else if (n==5 && !memcmp (name, "ecdsa", 5))
1054 else if (n==4 && !memcmp (name, "ecdh", 4))
1059 else if (n==3 && !memcmp (name, "elg", 3))
1066 log_error ("unknown private key algorithm\n");
1067 gcry_sexp_release (list);
1068 return gpg_error (GPG_ERR_BAD_SECKEY);
1073 if (strlen (algoname) >= algonamesize)
1074 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1075 strcpy (r_algoname, algoname);
1079 if (strlen (elems) >= elemssize)
1080 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
1081 strcpy (r_elems, elems);
1087 gcry_sexp_release (list);
1093 /* Return true if KEYPARMS holds an EdDSA key. */
1095 is_eddsa (gcry_sexp_t keyparms)
1103 list = gcry_sexp_find_token (keyparms, "flags", 0);
1104 for (i = list ? gcry_sexp_length (list)-1 : 0; i > 0; i--)
1106 s = gcry_sexp_nth_data (list, i, &n);
1108 continue; /* Not a data element. */
1110 if (n == 5 && !memcmp (s, "eddsa", 5))
1116 gcry_sexp_release (list);
1121 /* Return the public key algorithm number if S_KEY is a DSA style key.
1122 If it is not a DSA style key, return 0. */
1124 agent_is_dsa_key (gcry_sexp_t s_key)
1133 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1134 return 0; /* Error - assume it is not an DSA key. */
1136 if (!strcmp (algoname, "dsa"))
1137 result = GCRY_PK_DSA;
1138 else if (!strcmp (algoname, "ecc"))
1140 if (is_eddsa (list))
1143 result = GCRY_PK_ECDSA;
1145 else if (!strcmp (algoname, "ecdsa"))
1146 result = GCRY_PK_ECDSA;
1150 gcry_sexp_release (list);
1155 /* Return true if S_KEY is an EdDSA key as used with curve Ed25519. */
1157 agent_is_eddsa_key (gcry_sexp_t s_key)
1166 if (key_parms_from_sexp (s_key, &list, algoname, sizeof algoname, NULL, 0))
1167 return 0; /* Error - assume it is not an EdDSA key. */
1169 if (!strcmp (algoname, "ecc") && is_eddsa (list))
1171 else if (!strcmp (algoname, "eddsa")) /* backward compatibility. */
1176 gcry_sexp_release (list);
1181 /* Return the key for the keygrip GRIP. The result is stored at
1182 RESULT. This function extracts the key from the private key
1183 database and returns it as an S-expression object as it is. On
1184 failure an error code is returned and NULL stored at RESULT. */
1186 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
1187 gcry_sexp_t *result)
1196 err = read_key_file (grip, &s_skey);
1203 /* Return the public key for the keygrip GRIP. The result is stored
1204 at RESULT. This function extracts the public key from the private
1205 key database. On failure an error code is returned and NULL stored
1208 agent_public_key_from_file (ctrl_t ctrl,
1209 const unsigned char *grip,
1210 gcry_sexp_t *result)
1215 const char *algoname, *elems;
1217 gcry_mpi_t array[10];
1218 gcry_sexp_t curve = NULL;
1219 gcry_sexp_t flags = NULL;
1220 gcry_sexp_t uri_sexp, comment_sexp;
1221 const char *uri, *comment;
1222 size_t uri_length, comment_length;
1224 void *args[2+7+2+2+1]; /* Size is 2 + max. # of elements + 2 for uri + 2
1225 for comment + end-of-list. */
1227 gcry_sexp_t list = NULL;
1234 err = read_key_file (grip, &s_skey);
1238 for (i=0; i < DIM (array); i++)
1241 err = extract_private_key (s_skey, 0, &algoname, &npkey, NULL, &elems,
1242 array, DIM (array), &curve, &flags);
1245 gcry_sexp_release (s_skey);
1251 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
1253 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
1257 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1259 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
1261 gcry_sexp_release (s_skey);
1265 /* FIXME: The following thing is pretty ugly code; we should
1266 investigate how to make it cleaner. Probably code to handle
1267 canonical S-expressions in a memory buffer is better suited for
1268 such a task. After all that is what we do in protect.c. Need
1269 to find common patterns and write a straightformward API to use
1271 assert (sizeof (size_t) <= sizeof (void*));
1273 format = xtrymalloc (15+4+7*npkey+10+15+1+1);
1276 err = gpg_error_from_syserror ();
1277 for (i=0; array[i]; i++)
1278 gcry_mpi_release (array[i]);
1279 gcry_sexp_release (curve);
1280 gcry_sexp_release (flags);
1281 gcry_sexp_release (uri_sexp);
1282 gcry_sexp_release (comment_sexp);
1287 p = stpcpy (stpcpy (format, "(public-key("), algoname);
1288 p = stpcpy (p, "%S%S"); /* curve name and flags. */
1289 args[argidx++] = &curve;
1290 args[argidx++] = &flags;
1291 for (idx=0, s=elems; idx < npkey; idx++)
1295 p = stpcpy (p, " %m)");
1296 assert (argidx < DIM (args));
1297 args[argidx++] = &array[idx];
1302 p = stpcpy (p, "(uri %b)");
1303 assert (argidx+1 < DIM (args));
1304 args[argidx++] = (void *)&uri_length;
1305 args[argidx++] = (void *)&uri;
1309 p = stpcpy (p, "(comment %b)");
1310 assert (argidx+1 < DIM (args));
1311 args[argidx++] = (void *)&comment_length;
1312 args[argidx++] = (void*)&comment;
1316 assert (argidx < DIM (args));
1317 args[argidx] = NULL;
1319 err = gcry_sexp_build_array (&list, NULL, format, args);
1321 for (i=0; array[i]; i++)
1322 gcry_mpi_release (array[i]);
1323 gcry_sexp_release (curve);
1324 gcry_sexp_release (flags);
1325 gcry_sexp_release (uri_sexp);
1326 gcry_sexp_release (comment_sexp);
1335 /* Check whether the secret key identified by GRIP is available.
1336 Returns 0 is the key is available. */
1338 agent_key_available (const unsigned char *grip)
1342 char hexgrip[40+4+1];
1344 bin2hex (grip, 20, hexgrip);
1345 strcpy (hexgrip+40, ".key");
1347 fname = make_filename (gnupg_homedir (), GNUPG_PRIVATE_KEYS_DIR,
1349 result = !access (fname, R_OK)? 0 : -1;
1356 /* Return the information about the secret key specified by the binary
1357 keygrip GRIP. If the key is a shadowed one the shadow information
1358 will be stored at the address R_SHADOW_INFO as an allocated
1361 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
1362 int *r_keytype, unsigned char **r_shadow_info)
1372 *r_keytype = PRIVATE_KEY_UNKNOWN;
1374 *r_shadow_info = NULL;
1379 err = read_key_file (grip, &sexp);
1382 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1383 return gpg_error (GPG_ERR_NOT_FOUND);
1387 err = make_canon_sexp (sexp, &buf, &len);
1388 gcry_sexp_release (sexp);
1393 keytype = agent_private_key_type (buf);
1396 case PRIVATE_KEY_CLEAR:
1397 case PRIVATE_KEY_OPENPGP_NONE:
1399 case PRIVATE_KEY_PROTECTED:
1400 /* If we ever require it we could retrieve the comment fields
1403 case PRIVATE_KEY_SHADOWED:
1406 const unsigned char *s;
1409 err = agent_get_shadow_info (buf, &s);
1412 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
1414 *r_shadow_info = xtrymalloc (n);
1415 if (!*r_shadow_info)
1416 err = gpg_error_from_syserror ();
1418 memcpy (*r_shadow_info, s, n);
1423 err = gpg_error (GPG_ERR_BAD_SECKEY);
1427 if (!err && r_keytype)
1428 *r_keytype = keytype;
1436 /* Delete the key with GRIP from the disk after having asked for
1437 * confirmation using DESC_TEXT. If FORCE is set the function won't
1438 * require a confirmation via Pinentry or warns if the key is also
1439 * used by ssh. If ONLY_STUBS is set only stub keys (references to
1440 * smartcards) will be affected.
1442 * Common error codes are:
1444 * GPG_ERR_KEY_ON_CARD
1445 * GPG_ERR_NOT_CONFIRMED
1446 * GPG_ERR_FORBIDDEN - Not a stub key and ONLY_STUBS requested.
1449 agent_delete_key (ctrl_t ctrl, const char *desc_text,
1450 const unsigned char *grip, int force, int only_stubs)
1453 gcry_sexp_t s_skey = NULL;
1454 unsigned char *buf = NULL;
1456 char *desc_text_final = NULL;
1457 char *comment = NULL;
1458 ssh_control_file_t cf = NULL;
1459 char hexgrip[40+4+1];
1460 char *default_desc = NULL;
1463 err = read_key_file (grip, &s_skey);
1464 if (gpg_err_code (err) == GPG_ERR_ENOENT)
1465 err = gpg_error (GPG_ERR_NO_SECKEY);
1469 err = make_canon_sexp (s_skey, &buf, &len);
1473 key_type = agent_private_key_type (buf);
1474 if (only_stubs && key_type != PRIVATE_KEY_SHADOWED)
1476 err = gpg_error (GPG_ERR_FORBIDDEN);
1482 case PRIVATE_KEY_CLEAR:
1483 case PRIVATE_KEY_OPENPGP_NONE:
1484 case PRIVATE_KEY_PROTECTED:
1485 bin2hex (grip, 20, hexgrip);
1490 default_desc = xtryasprintf
1491 (L_("Do you really want to delete the key identified by keygrip%%0A"
1492 " %s%%0A %%C%%0A?"), hexgrip);
1493 desc_text = default_desc;
1496 /* Note, that we will take the comment as a C string for
1497 display purposes; i.e. all stuff beyond a Nul character is
1500 gcry_sexp_t comment_sexp;
1502 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
1504 comment = gcry_sexp_nth_string (comment_sexp, 1);
1505 gcry_sexp_release (comment_sexp);
1509 err = agent_modify_description (desc_text, comment, s_skey,
1514 err = agent_get_confirmation (ctrl, desc_text_final,
1515 L_("Delete key"), L_("No"), 0);
1519 cf = ssh_open_control_file ();
1522 if (!ssh_search_control_file (cf, hexgrip, NULL, NULL, NULL))
1524 err = agent_get_confirmation
1526 L_("Warning: This key is also listed for use with SSH!\n"
1527 "Deleting the key might remove your ability to "
1528 "access remote machines."),
1529 L_("Delete key"), L_("No"), 0);
1535 err = remove_key_file (grip);
1538 case PRIVATE_KEY_SHADOWED:
1539 err = remove_key_file (grip);
1543 log_error ("invalid private key format\n");
1544 err = gpg_error (GPG_ERR_BAD_SECKEY);
1549 ssh_close_control_file (cf);
1550 gcry_free (comment);
1551 xfree (desc_text_final);
1552 xfree (default_desc);
1554 gcry_sexp_release (s_skey);
1559 /* Write an S-expression formatted shadow key to our key storage.
1560 Shadow key is created by an S-expression public key in PKBUF and
1561 card's SERIALNO and the IDSTRING. With FORCE passed as true an
1562 existing key with the given GRIP will get overwritten. */
1564 agent_write_shadow_key (const unsigned char *grip,
1565 const char *serialno, const char *keyid,
1566 const unsigned char *pkbuf, int force)
1569 unsigned char *shadow_info;
1570 unsigned char *shdkey;
1573 shadow_info = make_shadow_info (serialno, keyid);
1575 return gpg_error_from_syserror ();
1577 err = agent_shadow_key (pkbuf, shadow_info, &shdkey);
1578 xfree (shadow_info);
1581 log_error ("shadowing the key failed: %s\n", gpg_strerror (err));
1585 len = gcry_sexp_canon_len (shdkey, 0, NULL, NULL);
1586 err = agent_write_private_key (grip, shdkey, len, force);
1589 log_error ("error writing key: %s\n", gpg_strerror (err));