1 /* genkey.c - Generate a keypair
2 * Copyright (C) 2002, 2003, 2004, 2007, 2010 Free Software Foundation, Inc.
3 * Copyright (C) 2015 g10 Code GmbH.
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 <https://www.gnu.org/licenses/>.
29 #include "../common/i18n.h"
30 #include "../common/exechelp.h"
31 #include "../common/sysutils.h"
34 store_key (gcry_sexp_t private, const char *passphrase, int force,
35 unsigned long s2k_count, time_t timestamp)
40 unsigned char grip[20];
42 if ( !gcry_pk_get_keygrip (private, grip) )
44 log_error ("can't calculate keygrip\n");
45 return gpg_error (GPG_ERR_GENERAL);
48 len = gcry_sexp_sprint (private, GCRYSEXP_FMT_CANON, NULL, 0);
50 buf = gcry_malloc_secure (len);
52 return out_of_core ();
53 len = gcry_sexp_sprint (private, GCRYSEXP_FMT_CANON, buf, len);
60 rc = agent_protect (buf, passphrase, &p, &len, s2k_count);
70 rc = agent_write_private_key (grip, buf, len, force,
71 NULL, NULL, NULL, timestamp);
77 /* Count the number of non-alpha characters in S. Control characters
78 and non-ascii characters are not considered. */
80 nonalpha_count (const char *s)
85 if (isascii (*s) && ( isdigit (*s) || ispunct (*s) ))
92 /* Check PW against a list of pattern. Return 0 if PW does not match
93 these pattern. If CHECK_CONSTRAINTS_NEW_SYMKEY is set in flags and
94 --check-sym-passphrase-pattern has been configured, use the pattern
95 file from that option. */
97 do_check_passphrase_pattern (ctrl_t ctrl, const char *pw, unsigned int flags)
100 const char *pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CHECK_PATTERN);
101 estream_t stream_to_check_pattern = NULL;
102 const char *argv[10];
110 pattern = opt.check_passphrase_pattern;
111 if ((flags & CHECK_CONSTRAINTS_NEW_SYMKEY)
112 && opt.check_sym_passphrase_pattern)
113 pattern = opt.check_sym_passphrase_pattern;
115 return 1; /* Oops - Assume password should not be used */
117 if (strchr (pattern, '/') || strchr (pattern, '\\')
118 || (*pattern == '~' && pattern[1] == '/'))
119 patternfname = make_absfilename_try (pattern, NULL);
121 patternfname = make_filename_try (gnupg_sysconfdir (), pattern, NULL);
124 log_error ("error making filename from '%s': %s\n",
125 pattern, gpg_strerror (gpg_error_from_syserror ()));
126 return 1; /* Do not pass the check. */
129 /* Make debugging a broken config easier by printing a useful error
131 if (gnupg_access (patternfname, F_OK))
133 log_error ("error accessing '%s': %s\n",
134 patternfname, gpg_strerror (gpg_error_from_syserror ()));
135 xfree (patternfname);
136 return 1; /* Do not pass the check. */
140 argv[i++] = "--null";
142 argv[i++] = patternfname,
144 log_assert (i < sizeof argv);
146 if (gnupg_spawn_process (pgmname, argv, NULL, 0,
147 &stream_to_check_pattern, NULL, NULL, &pid))
148 result = 1; /* Execute error - assume password should no be used. */
151 es_set_binary (stream_to_check_pattern);
152 if (es_fwrite (pw, strlen (pw), 1, stream_to_check_pattern) != 1)
154 err = gpg_error_from_syserror ();
155 log_error (_("error writing to pipe: %s\n"), gpg_strerror (err));
156 result = 1; /* Error - assume password should not be used. */
159 es_fflush (stream_to_check_pattern);
160 es_fclose (stream_to_check_pattern);
161 if (gnupg_wait_process (pgmname, pid, 1, NULL))
162 result = 1; /* Helper returned an error - probably a match. */
164 result = 0; /* Success; i.e. no match. */
165 gnupg_release_process (pid);
168 xfree (patternfname);
174 take_this_one_anyway (ctrl_t ctrl, const char *desc, const char *anyway_btn)
176 return agent_get_confirmation (ctrl, desc,
177 anyway_btn, L_("Enter new passphrase"), 0);
181 /* Check whether the passphrase PW is suitable. Returns 0 if the
182 * passphrase is suitable and true if it is not and the user should be
183 * asked to provide a different one. If FAILED_CONSTRAINT is set, a
184 * message describing the problem is returned at FAILED_CONSTRAINT.
186 * CHECK_CONSTRAINTS_NOT_EMPTY
187 * Do not allow an empty passphrase
188 * CHECK_CONSTRAINTS_NEW_SYMKEY
189 * Hint that the passphrase is used for a new symmetric key.
192 check_passphrase_constraints (ctrl_t ctrl, const char *pw, unsigned int flags,
193 char **failed_constraint)
196 unsigned int minlen = opt.min_passphrase_len;
197 unsigned int minnonalpha = opt.min_passphrase_nonalpha;
201 int no_empty = !!(flags & CHECK_CONSTRAINTS_NOT_EMPTY);
203 if (ctrl && ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
209 /* The first check is to warn about an empty passphrase. */
212 const char *desc = (opt.enforce_passphrase_constraints || no_empty?
213 L_("You have not entered a passphrase!%0A"
214 "An empty passphrase is not allowed.") :
215 L_("You have not entered a passphrase - "
216 "this is in general a bad idea!%0A"
217 "Please confirm that you do not want to "
218 "have any protection on your key."));
221 if (failed_constraint)
223 if (opt.enforce_passphrase_constraints || no_empty)
224 *failed_constraint = xstrdup (desc);
226 err = take_this_one_anyway (ctrl, desc,
227 L_("Yes, protection is not needed"));
233 /* Now check the constraints and collect the error messages unless
234 in silent mode which returns immediately. */
235 if (utf8_charcount (pw, -1) < minlen )
237 if (!failed_constraint)
239 err = gpg_error (GPG_ERR_INV_PASSPHRASE);
244 ( ngettext ("A passphrase should be at least %u character long.",
245 "A passphrase should be at least %u characters long.",
249 err = gpg_error_from_syserror ();
254 if (nonalpha_count (pw) < minnonalpha )
256 if (!failed_constraint)
258 err = gpg_error (GPG_ERR_INV_PASSPHRASE);
263 ( ngettext ("A passphrase should contain at least %u digit or%%0A"
264 "special character.",
265 "A passphrase should contain at least %u digits or%%0A"
266 "special characters.",
267 minnonalpha), minnonalpha );
270 err = gpg_error_from_syserror ();
275 /* If configured check the passphrase against a list of known words
276 and pattern. The actual test is done by an external program.
277 The warning message is generic to give the user no hint on how to
278 circumvent this list. */
280 && (opt.check_passphrase_pattern || opt.check_sym_passphrase_pattern)
281 && do_check_passphrase_pattern (ctrl, pw, flags))
283 if (!failed_constraint)
285 err = gpg_error (GPG_ERR_INV_PASSPHRASE);
290 (L_("A passphrase may not be a known term or match%%0A"
291 "certain pattern."));
294 err = gpg_error_from_syserror ();
299 if (failed_constraint && (msg1 || msg2 || msg3))
305 (L_("Warning: You have entered an insecure passphrase."),
307 msg1? msg1 : "", msg1? "%0A" : "",
308 msg2? msg2 : "", msg2? "%0A" : "",
309 msg3? msg3 : "", msg3? "%0A" : "",
313 err = gpg_error_from_syserror ();
316 /* Strip a trailing "%0A". */
318 if (n > 3 && !strcmp (msg + n - 3, "%0A"))
322 if (opt.enforce_passphrase_constraints)
323 *failed_constraint = msg;
326 err = take_this_one_anyway (ctrl, msg, L_("Take this one anyway"));
339 /* Callback function to compare the first entered PIN with the one
340 currently being entered. */
342 reenter_compare_cb (struct pin_entry_info_s *pi)
344 const char *pin1 = pi->check_cb_arg;
346 if (!strcmp (pin1, pi->pin))
348 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
352 /* Ask the user for a new passphrase using PROMPT. On success the
353 function returns 0 and store the passphrase at R_PASSPHRASE; if the
354 user opted not to use a passphrase NULL will be stored there. The
355 user needs to free the returned string. In case of an error and
356 error code is returned and NULL stored at R_PASSPHRASE. */
358 agent_ask_new_passphrase (ctrl_t ctrl, const char *prompt,
362 const char *text1 = prompt;
363 const char *text2 = L_("Please re-enter this passphrase");
364 char *initial_errtext = NULL;
365 struct pin_entry_info_s *pi, *pi2;
367 *r_passphrase = NULL;
369 if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK)
372 unsigned char *buffer;
374 err = pinentry_loopback (ctrl, "NEW_PASSPHRASE", &buffer, &size,
381 *r_passphrase = buffer;
384 *r_passphrase = NULL;
389 pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
391 return gpg_error_from_syserror ();
392 pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1);
395 err = gpg_error_from_syserror ();
399 pi->max_length = MAX_PASSPHRASE_LEN + 1;
401 pi->with_qualitybar = 0;
403 pi2->max_length = MAX_PASSPHRASE_LEN + 1;
405 pi2->check_cb = reenter_compare_cb;
406 pi2->check_cb_arg = pi->pin;
409 err = agent_askpin (ctrl, text1, NULL, initial_errtext, pi, NULL, 0);
410 xfree (initial_errtext);
411 initial_errtext = NULL;
414 if (check_passphrase_constraints (ctrl, pi->pin, 0, &initial_errtext))
416 pi->failed_tries = 0;
417 pi2->failed_tries = 0;
420 /* Unless the passphrase is empty or the pinentry told us that
421 it already did the repetition check, ask to confirm it. */
422 if (*pi->pin && !pi->repeat_okay)
424 err = agent_askpin (ctrl, text2, NULL, NULL, pi2, NULL, 0);
425 if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE)
426 { /* The re-entered one did not match and the user did not
428 initial_errtext = xtrystrdup (L_("does not match - try again"));
431 err = gpg_error_from_syserror ();
436 if (!err && *pi->pin)
438 /* User wants a passphrase. */
439 *r_passphrase = xtrystrdup (pi->pin);
441 err = gpg_error_from_syserror ();
444 xfree (initial_errtext);
452 /* Generate a new keypair according to the parameters given in
453 KEYPARAM. If CACHE_NONCE is given first try to lookup a passphrase
454 using the cache nonce. If NO_PROTECTION is true the key will not
455 be protected by a passphrase. If OVERRIDE_PASSPHRASE is true that
456 passphrase will be used for the new key. If TIMESTAMP is not zero
457 it will be recorded as creation date of the key (unless extended
458 format is disabled) . */
460 agent_genkey (ctrl_t ctrl, const char *cache_nonce, time_t timestamp,
461 const char *keyparam, size_t keyparamlen, int no_protection,
462 const char *override_passphrase, int preset, membuf_t *outbuf)
464 gcry_sexp_t s_keyparam, s_key, s_private, s_public;
465 char *passphrase_buffer = NULL;
466 const char *passphrase;
471 rc = gcry_sexp_sscan (&s_keyparam, NULL, keyparam, keyparamlen);
474 log_error ("failed to convert keyparam: %s\n", gpg_strerror (rc));
475 return gpg_error (GPG_ERR_INV_DATA);
478 /* Get the passphrase now, cause key generation may take a while. */
479 if (override_passphrase)
480 passphrase = override_passphrase;
481 else if (no_protection || !cache_nonce)
485 passphrase_buffer = agent_get_cache (ctrl, cache_nonce, CACHE_MODE_NONCE);
486 passphrase = passphrase_buffer;
489 if (passphrase || no_protection)
493 rc = agent_ask_new_passphrase (ctrl,
494 L_("Please enter the passphrase to%0A"
495 "protect your new key"),
499 gcry_sexp_release (s_keyparam);
502 passphrase = passphrase_buffer;
505 rc = gcry_pk_genkey (&s_key, s_keyparam );
506 gcry_sexp_release (s_keyparam);
509 log_error ("key generation failed: %s\n", gpg_strerror (rc));
510 xfree (passphrase_buffer);
514 /* break out the parts */
515 s_private = gcry_sexp_find_token (s_key, "private-key", 0);
518 log_error ("key generation failed: invalid return value\n");
519 gcry_sexp_release (s_key);
520 xfree (passphrase_buffer);
521 return gpg_error (GPG_ERR_INV_DATA);
523 s_public = gcry_sexp_find_token (s_key, "public-key", 0);
526 log_error ("key generation failed: invalid return value\n");
527 gcry_sexp_release (s_private);
528 gcry_sexp_release (s_key);
529 xfree (passphrase_buffer);
530 return gpg_error (GPG_ERR_INV_DATA);
532 gcry_sexp_release (s_key); s_key = NULL;
534 /* store the secret key */
536 log_debug ("storing private key\n");
537 rc = store_key (s_private, passphrase, 0, ctrl->s2k_count, timestamp);
543 gcry_create_nonce (tmpbuf, 12);
544 cache_nonce = bin2hex (tmpbuf, 12, NULL);
548 && !agent_put_cache (ctrl, cache_nonce, CACHE_MODE_NONCE,
549 passphrase, ctrl->cache_ttl_opt_preset))
550 agent_write_status (ctrl, "CACHE_NONCE", cache_nonce, NULL);
551 if (preset && !no_protection)
553 unsigned char grip[20];
555 if (gcry_pk_get_keygrip (s_private, grip))
557 bin2hex(grip, 20, hexgrip);
558 rc = agent_put_cache (ctrl, hexgrip, CACHE_MODE_ANY, passphrase,
559 ctrl->cache_ttl_opt_preset);
563 xfree (passphrase_buffer);
564 passphrase_buffer = NULL;
566 gcry_sexp_release (s_private);
569 gcry_sexp_release (s_public);
573 /* return the public key */
575 log_debug ("returning public key\n");
576 len = gcry_sexp_sprint (s_public, GCRYSEXP_FMT_CANON, NULL, 0);
578 buf = xtrymalloc (len);
581 gpg_error_t tmperr = out_of_core ();
582 gcry_sexp_release (s_private);
583 gcry_sexp_release (s_public);
586 len = gcry_sexp_sprint (s_public, GCRYSEXP_FMT_CANON, buf, len);
588 put_membuf (outbuf, buf, len);
589 gcry_sexp_release (s_public);
597 /* Apply a new passphrase to the key S_SKEY and store it. If
598 PASSPHRASE_ADDR and *PASSPHRASE_ADDR are not NULL, use that
599 passphrase. If PASSPHRASE_ADDR is not NULL store a newly entered
600 passphrase at that address. */
602 agent_protect_and_store (ctrl_t ctrl, gcry_sexp_t s_skey,
603 char **passphrase_addr)
607 if (passphrase_addr && *passphrase_addr)
609 /* Take an empty string as request not to protect the key. */
610 err = store_key (s_skey, **passphrase_addr? *passphrase_addr:NULL, 1,
619 xfree (*passphrase_addr);
620 *passphrase_addr = NULL;
622 err = agent_ask_new_passphrase (ctrl,
623 L_("Please enter the new passphrase"),
626 err = store_key (s_skey, pass, 1, ctrl->s2k_count, 0);
627 if (!err && passphrase_addr)
628 *passphrase_addr = pass;