1 /* findkey.c - Locate the secret key
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2007,
3 * 2010, 2011 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
32 #include <pth.h> /* (we use pth_sleep) */
36 #include "../common/ssh-utils.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 chnage the passphrase. */
53 /* Write an S-expression formatted key to our key storage. With FORCE
54 passed as true an existing key with the given GRIP will get
57 agent_write_private_key (const unsigned char *grip,
58 const void *buffer, size_t length, int force)
65 bin2hex (grip, 20, hexgrip);
66 strcpy (hexgrip+40, ".key");
68 fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
70 if (!force && !access (fname, F_OK))
72 log_error ("secret key file `%s' already exists\n", fname);
74 return gpg_error (GPG_ERR_GENERAL);
77 /* In FORCE mode we would like to create FNAME but only if it does
78 not already exist. We cannot make this guarantee just using
79 POSIX (GNU provides the "x" opentype for fopen, however, this is
80 not portable). Thus, we use the more flexible open function and
81 then use fdopen to obtain a stream. */
82 fd = open (fname, force? (O_CREAT | O_TRUNC | O_WRONLY | O_BINARY)
83 : (O_CREAT | O_EXCL | O_WRONLY | O_BINARY),
85 #ifndef HAVE_W32_SYSTEM
93 fp = fdopen (fd, "wb");
104 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
105 log_error ("can't create `%s': %s\n", fname, strerror (errno));
110 if (fwrite (buffer, length, 1, fp) != 1)
112 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
113 log_error ("error writing `%s': %s\n", fname, strerror (errno));
121 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
122 log_error ("error closing `%s': %s\n", fname, strerror (errno));
127 bump_key_eventcounter ();
133 /* Callback function to try the unprotection from the passpharse query
136 try_unprotect_cb (struct pin_entry_info_s *pi)
138 struct try_unprotect_arg_s *arg = pi->check_cb_arg;
141 gnupg_isotime_t now, protected_at, tmptime;
144 assert (!arg->unprotected_key);
146 arg->change_required = 0;
147 err = agent_unprotect (arg->protected_key, pi->pin, protected_at,
148 &arg->unprotected_key, &dummy);
151 if (!opt.max_passphrase_days || arg->ctrl->in_passwd)
152 return 0; /* No regular passphrase change required. */
156 /* No protection date known - must force passphrase change. */
157 desc = xtrystrdup (_("Note: This passphrase has never been changed.%0A"
158 "Please change it now."));
160 return gpg_error_from_syserror ();
164 gnupg_get_isotime (now);
165 gnupg_copy_time (tmptime, protected_at);
166 err = add_days_to_isotime (tmptime, opt.max_passphrase_days);
169 if (strcmp (now, tmptime) > 0 )
171 /* Passphrase "expired". */
173 (_("This passphrase has not been changed%%0A"
174 "since %.4s-%.2s-%.2s. Please change it now."),
175 protected_at, protected_at+4, protected_at+6);
177 return gpg_error_from_syserror ();
183 /* Change required. */
184 if (opt.enforce_passphrase_constraints)
186 err = agent_get_confirmation (arg->ctrl, desc,
187 _("Change passphrase"), NULL, 0);
189 arg->change_required = 1;
193 err = agent_get_confirmation (arg->ctrl, desc,
194 _("Change passphrase"),
195 _("I'll change it later"), 0);
197 arg->change_required = 1;
198 else if (gpg_err_code (err) == GPG_ERR_CANCELED)
208 /* Modify a Key description, replacing certain special format
209 characters. List of currently supported replacements:
211 %% - Replaced by a single %
212 %c - Replaced by the content of COMMENT.
213 %F - Replaced by an ssh style fingerprint computed from KEY.
215 The functions returns 0 on success or an error code. On success a
216 newly allocated string is stored at the address of RESULT.
219 modify_description (const char *in, const char *comment, const gcry_sexp_t key,
222 size_t comment_length;
228 char *ssh_fpr = NULL;
230 comment_length = strlen (comment);
231 in_len = strlen (in);
233 /* First pass calculates the length, second pass does the actual
237 for (pass=0; pass < 2; pass++)
240 for (i = 0; i < in_len; i++)
254 case 'c': /* Comment. */
257 memcpy (out, comment, comment_length);
258 out += comment_length;
261 out_len += comment_length;
264 case 'F': /* SSH style fingerprint. */
266 ssh_get_fingerprint_string (key, &ssh_fpr);
270 out = stpcpy (out, ssh_fpr);
272 out_len += strlen (ssh_fpr);
276 default: /* Invalid special sequences are kept as they are. */
287 else if (in[i] == '%')
300 *result = out = xtrymalloc (out_len + 1);
304 return gpg_error_from_syserror ();
310 assert (*result + out_len == out);
317 /* Unprotect the canconical encoded S-expression key in KEYBUF. GRIP
318 should be the hex encoded keygrip of that key to be used with the
319 caching mechanism. DESC_TEXT may be set to override the default
320 description used for the pinentry. If LOOKUP_TTL is given this
321 function is used to lookup the default ttl. */
323 unprotect (ctrl_t ctrl, const char *desc_text,
324 unsigned char **keybuf, const unsigned char *grip,
325 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl)
327 struct pin_entry_info_s *pi;
328 struct try_unprotect_arg_s arg;
330 unsigned char *result;
334 bin2hex (grip, 20, hexgrip);
336 /* First try to get it from the cache - if there is none or we can't
337 unprotect it, we fall back to ask the user */
338 if (cache_mode != CACHE_MODE_IGNORE)
344 pw = agent_get_cache (hexgrip, cache_mode, &cache_marker);
347 rc = agent_unprotect (*keybuf, pw, NULL, &result, &resultlen);
348 agent_unlock_cache_entry (&cache_marker);
358 /* If the pinentry is currently in use, we wait up to 60 seconds
359 for it to close and check the cache again. This solves a common
360 situation where several requests for unprotecting a key have
361 been made but the user is still entering the passphrase for
362 the first request. Because all requests to agent_askpin are
363 serialized they would then pop up one after the other to
364 request the passphrase - despite that the user has already
365 entered it and is then available in the cache. This
366 implementation is not race free but in the worst case the
367 user has to enter the passphrase only once more. */
368 if (pinentry_active_p (ctrl, 0))
371 if (!pinentry_active_p (ctrl, 60))
373 /* We need to give the other thread a chance to actually put
374 it into the cache. */
378 /* Timeout - better call pinentry now the plain way. */
382 pi = gcry_calloc_secure (1, sizeof (*pi) + 100);
384 return gpg_error_from_syserror ();
385 pi->max_length = 100;
386 pi->min_digits = 0; /* we want a real passphrase */
389 pi->check_cb = try_unprotect_cb;
391 arg.protected_key = *keybuf;
392 arg.unprotected_key = NULL;
393 arg.change_required = 0;
394 pi->check_cb_arg = &arg;
396 rc = agent_askpin (ctrl, desc_text, NULL, NULL, pi);
399 assert (arg.unprotected_key);
400 if (arg.change_required)
402 size_t canlen, erroff;
405 assert (arg.unprotected_key);
406 canlen = gcry_sexp_canon_len (arg.unprotected_key, 0, NULL, NULL);
407 rc = gcry_sexp_sscan (&s_skey, &erroff,
408 (char*)arg.unprotected_key, canlen);
411 log_error ("failed to build S-Exp (off=%u): %s\n",
412 (unsigned int)erroff, gpg_strerror (rc));
413 wipememory (arg.unprotected_key, canlen);
414 xfree (arg.unprotected_key);
418 rc = agent_protect_and_store (ctrl, s_skey);
419 gcry_sexp_release (s_skey);
422 log_error ("changing the passphrase failed: %s\n",
424 wipememory (arg.unprotected_key, canlen);
425 xfree (arg.unprotected_key);
431 agent_put_cache (hexgrip, cache_mode, pi->pin,
432 lookup_ttl? lookup_ttl (hexgrip) : 0);
434 *keybuf = arg.unprotected_key;
441 /* Read the key identified by GRIP from the private key directory and
442 return it as an gcrypt S-expression object in RESULT. On failure
443 returns an error code and stores NULL at RESULT. */
445 read_key_file (const unsigned char *grip, gcry_sexp_t *result)
452 size_t buflen, erroff;
454 char hexgrip[40+4+1];
458 bin2hex (grip, 20, hexgrip);
459 strcpy (hexgrip+40, ".key");
461 fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
462 fp = fopen (fname, "rb");
465 rc = gpg_error_from_syserror ();
466 if (gpg_err_code (rc) != GPG_ERR_ENOENT)
467 log_error ("can't open `%s': %s\n", fname, strerror (errno));
472 if (fstat (fileno(fp), &st))
474 rc = gpg_error_from_syserror ();
475 log_error ("can't stat `%s': %s\n", fname, strerror (errno));
482 buf = xtrymalloc (buflen+1);
483 if (!buf || fread (buf, buflen, 1, fp) != 1)
485 rc = gpg_error_from_syserror ();
486 log_error ("error reading `%s': %s\n", fname, strerror (errno));
493 /* Convert the file into a gcrypt S-expression object. */
494 rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
500 log_error ("failed to build S-Exp (off=%u): %s\n",
501 (unsigned int)erroff, gpg_strerror (rc));
509 /* Return the secret key as an S-Exp in RESULT after locating it using
510 the GRIP. Stores NULL at RESULT if the operation shall be diverted
511 to a token; in this case an allocated S-expression with the
512 shadow_info part from the file is stored at SHADOW_INFO.
513 CACHE_MODE defines now the cache shall be used. DESC_TEXT may be
514 set to present a custom description for the pinentry. LOOKUP_TTL
515 is an optional function to convey a TTL to the cache manager; we do
516 not simply pass the TTL value because the value is only needed if an
517 unprotect action was needed and looking up the TTL may have some
518 overhead (e.g. scanning the sshcontrol file). */
520 agent_key_from_file (ctrl_t ctrl, const char *desc_text,
521 const unsigned char *grip, unsigned char **shadow_info,
522 cache_mode_t cache_mode, lookup_ttl_t lookup_ttl,
527 size_t len, buflen, erroff;
529 int got_shadow_info = 0;
535 rc = read_key_file (grip, &s_skey);
539 /* For use with the protection functions we also need the key as an
540 canonical encoded S-expression in a buffer. Create this buffer
542 rc = make_canon_sexp (s_skey, &buf, &len);
546 switch (agent_private_key_type (buf))
548 case PRIVATE_KEY_CLEAR:
549 break; /* no unprotection needed */
550 case PRIVATE_KEY_PROTECTED:
552 char *desc_text_final;
553 char *comment = NULL;
555 /* Note, that we will take the comment as a C string for
556 display purposes; i.e. all stuff beyond a Nul character is
559 gcry_sexp_t comment_sexp;
561 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
563 comment = gcry_sexp_nth_string (comment_sexp, 1);
564 gcry_sexp_release (comment_sexp);
567 desc_text_final = NULL;
569 rc = modify_description (desc_text, comment? comment:"", s_skey,
575 rc = unprotect (ctrl, desc_text_final, &buf, grip,
576 cache_mode, lookup_ttl);
578 log_error ("failed to unprotect the secret key: %s\n",
582 xfree (desc_text_final);
585 case PRIVATE_KEY_SHADOWED:
588 const unsigned char *s;
591 rc = agent_get_shadow_info (buf, &s);
594 n = gcry_sexp_canon_len (s, 0, NULL,NULL);
596 *shadow_info = xtrymalloc (n);
601 memcpy (*shadow_info, s, n);
607 log_error ("get_shadow_info failed: %s\n", gpg_strerror (rc));
610 rc = gpg_error (GPG_ERR_UNUSABLE_SECKEY);
613 log_error ("invalid private key format\n");
614 rc = gpg_error (GPG_ERR_BAD_SECKEY);
617 gcry_sexp_release (s_skey);
619 if (rc || got_shadow_info)
625 buflen = gcry_sexp_canon_len (buf, 0, NULL, NULL);
626 rc = gcry_sexp_sscan (&s_skey, &erroff, (char*)buf, buflen);
627 wipememory (buf, buflen);
631 log_error ("failed to build S-Exp (off=%u): %s\n",
632 (unsigned int)erroff, gpg_strerror (rc));
641 /* Return the key for the keygrip GRIP. The result is stored at
642 RESULT. This function extracts the key from the private key
643 database and returns it as an S-expression object as it is. On
644 failure an error code is returned and NULL stored at RESULT. */
646 agent_raw_key_from_file (ctrl_t ctrl, const unsigned char *grip,
656 err = read_key_file (grip, &s_skey);
663 /* Return the public key for the keygrip GRIP. The result is stored
664 at RESULT. This function extracts the public key from the private
665 key database. On failure an error code is returned and NULL stored
668 agent_public_key_from_file (ctrl_t ctrl,
669 const unsigned char *grip,
674 const char *algoname;
675 gcry_sexp_t uri_sexp, comment_sexp;
676 const char *uri, *comment;
677 size_t uri_length, comment_length;
679 void *args[4+2+2+1]; /* Size is max. # of elements + 2 for uri + 2
680 for comment + end-of-list. */
682 gcry_sexp_t list, l2;
693 rc = read_key_file (grip, &s_skey);
697 list = gcry_sexp_find_token (s_skey, "shadowed-private-key", 0 );
699 list = gcry_sexp_find_token (s_skey, "protected-private-key", 0 );
701 list = gcry_sexp_find_token (s_skey, "private-key", 0 );
704 log_error ("invalid private key format\n");
705 gcry_sexp_release (s_skey);
706 return gpg_error (GPG_ERR_BAD_SECKEY);
709 l2 = gcry_sexp_cadr (list);
710 gcry_sexp_release (list);
712 name = gcry_sexp_nth_data (list, 0, &n);
713 if (n==3 && !memcmp (name, "rsa", 3))
718 else if (n==3 && !memcmp (name, "dsa", 3))
723 else if (n==3 && !memcmp (name, "elg", 3))
730 log_error ("unknown private key algorithm\n");
731 gcry_sexp_release (list);
732 gcry_sexp_release (s_skey);
733 return gpg_error (GPG_ERR_BAD_SECKEY);
736 /* Allocate an array for the parameters and copy them out of the
737 secret key. FIXME: We should have a generic copy function. */
738 array = xtrycalloc (strlen(elems) + 1, sizeof *array);
741 rc = gpg_error_from_syserror ();
742 gcry_sexp_release (list);
743 gcry_sexp_release (s_skey);
747 for (idx=0, s=elems; *s; s++, idx++ )
749 l2 = gcry_sexp_find_token (list, s, 1);
752 /* Required parameter not found. */
753 for (i=0; i<idx; i++)
754 gcry_mpi_release (array[i]);
756 gcry_sexp_release (list);
757 gcry_sexp_release (s_skey);
758 return gpg_error (GPG_ERR_BAD_SECKEY);
760 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
761 gcry_sexp_release (l2);
764 /* Required parameter is invalid. */
765 for (i=0; i<idx; i++)
766 gcry_mpi_release (array[i]);
768 gcry_sexp_release (list);
769 gcry_sexp_release (s_skey);
770 return gpg_error (GPG_ERR_BAD_SECKEY);
773 gcry_sexp_release (list);
778 uri_sexp = gcry_sexp_find_token (s_skey, "uri", 0);
780 uri = gcry_sexp_nth_data (uri_sexp, 1, &uri_length);
784 comment_sexp = gcry_sexp_find_token (s_skey, "comment", 0);
786 comment = gcry_sexp_nth_data (comment_sexp, 1, &comment_length);
788 gcry_sexp_release (s_skey);
792 /* FIXME: The following thing is pretty ugly code; we should
793 investigate how to make it cleaner. Probably code to handle
794 canonical S-expressions in a memory buffer is better suioted for
795 such a task. After all that is what we do in protect.c. Neeed
796 to find common patterns and write a straightformward API to use
798 assert (sizeof (size_t) <= sizeof (void*));
800 format = xtrymalloc (15+7*strlen (elems)+10+15+1+1);
803 rc = gpg_error_from_syserror ();
804 for (i=0; array[i]; i++)
805 gcry_mpi_release (array[i]);
807 gcry_sexp_release (uri_sexp);
808 gcry_sexp_release (comment_sexp);
813 p = stpcpy (stpcpy (format, "(public-key("), algoname);
814 for (idx=0, s=elems; *s; s++, idx++ )
818 p = stpcpy (p, " %m)");
819 assert (argidx < DIM (args));
820 args[argidx++] = &array[idx];
825 p = stpcpy (p, "(uri %b)");
826 assert (argidx+1 < DIM (args));
827 args[argidx++] = (void *)uri_length;
828 args[argidx++] = (void *)uri;
832 p = stpcpy (p, "(comment %b)");
833 assert (argidx+1 < DIM (args));
834 args[argidx++] = (void *)comment_length;
835 args[argidx++] = (void*)comment;
839 assert (argidx < DIM (args));
842 rc = gcry_sexp_build_array (&list, NULL, format, args);
844 for (i=0; array[i]; i++)
845 gcry_mpi_release (array[i]);
847 gcry_sexp_release (uri_sexp);
848 gcry_sexp_release (comment_sexp);
857 /* Return the secret key as an S-Exp after locating it using the grip.
858 Returns NULL if key is not available. 0 = key is available */
860 agent_key_available (const unsigned char *grip)
864 char hexgrip[40+4+1];
866 bin2hex (grip, 20, hexgrip);
867 strcpy (hexgrip+40, ".key");
869 fname = make_filename (opt.homedir, GNUPG_PRIVATE_KEYS_DIR, hexgrip, NULL);
870 result = !access (fname, R_OK)? 0 : -1;
877 /* Return the information about the secret key specified by the binary
878 keygrip GRIP. If the key is a shadowed one the shadow information
879 will be stored at the address R_SHADOW_INFO as an allocated
882 agent_key_info_from_file (ctrl_t ctrl, const unsigned char *grip,
883 int *r_keytype, unsigned char **r_shadow_info)
893 *r_keytype = PRIVATE_KEY_UNKNOWN;
895 *r_shadow_info = NULL;
900 err = read_key_file (grip, &sexp);
903 if (gpg_err_code (err) == GPG_ERR_ENOENT)
904 return gpg_error (GPG_ERR_NOT_FOUND);
908 err = make_canon_sexp (sexp, &buf, &len);
909 gcry_sexp_release (sexp);
914 keytype = agent_private_key_type (buf);
917 case PRIVATE_KEY_CLEAR:
919 case PRIVATE_KEY_PROTECTED:
920 /* If we ever require it we could retrieve the comment fields
923 case PRIVATE_KEY_SHADOWED:
926 const unsigned char *s;
929 err = agent_get_shadow_info (buf, &s);
932 n = gcry_sexp_canon_len (s, 0, NULL, NULL);
934 *r_shadow_info = xtrymalloc (n);
936 err = gpg_error_from_syserror ();
938 memcpy (*r_shadow_info, s, n);
943 err = gpg_error (GPG_ERR_BAD_SECKEY);
947 if (!err && r_keytype)
948 *r_keytype = keytype;