1 /* passphrase.c - Get a passphrase
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2006, 2007, 2009, 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 <https://www.gnu.org/licenses/>.
31 #ifdef HAVE_LANGINFO_CODESET
43 #include "call-agent.h"
44 #include "../common/shareddefs.h"
46 static char *fd_passwd = NULL;
47 static char *next_pw = NULL;
48 static char *last_pw = NULL;
52 /* Pack an s2k iteration count into the form specified in 2440. If
53 we're in between valid values, round up. With value 0 return the
56 encode_s2k_iterations (int iterations)
67 /* Ask the gpg-agent for a useful iteration count. */
68 err = agent_get_s2k_count (&mycnt);
69 if (err || mycnt < 65536)
71 /* Don't print an error if an older agent is used. */
72 if (err && gpg_err_code (err) != GPG_ERR_ASS_PARAMETER)
73 log_error (_("problem with the agent: %s\n"), gpg_strerror (err));
74 /* Default to 65536 which we used up to 2.0.13. */
77 else if (mycnt >= 65011712)
78 return 255; /* Largest possible value. */
80 return encode_s2k_iterations ((int)mycnt);
83 if (iterations <= 1024)
84 return 0; /* Command line arg compatibility. */
86 if (iterations >= 65011712)
89 /* Need count to be in the range 16-31 */
90 for (count=iterations>>6; count>=32; count>>=1)
93 result = (c<<4)|(count-16);
95 if (S2K_DECODE_COUNT(result) < iterations)
103 have_static_passphrase()
106 && (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
109 /* Return a static passphrase. The returned value is only valid as
110 long as no other passphrase related function is called. NULL may
111 be returned if no passphrase has been set; better use
112 have_static_passphrase first. */
114 get_static_passphrase (void)
121 * Set the passphrase to be used for the next query and only for the next
125 set_next_passphrase( const char *s )
131 next_pw = xmalloc_secure( strlen(s)+1 );
132 strcpy (next_pw, s );
137 * Get the last passphrase used in passphrase_to_dek.
138 * Note: This removes the passphrase from this modules and
139 * the caller must free the result. May return NULL:
142 get_last_passphrase()
149 /* Here's an interesting question: since this passphrase was passed in
150 on the command line, is there really any point in using secure
151 memory for it? I'm going with 'yes', since it doesn't hurt, and
152 might help in some small way (swapping). */
155 set_passphrase_from_string(const char *pass)
158 fd_passwd = xmalloc_secure(strlen(pass)+1);
159 strcpy (fd_passwd, pass);
164 read_passphrase_from_fd( int fd )
169 if (! gnupg_fd_valid (fd))
170 log_fatal ("passphrase-fd is invalid: %s\n", strerror (errno));
172 if ( !opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
173 { /* Not used but we have to do a dummy read, so that it won't end
174 up at the begin of the message if the quite usual trick to
175 prepend the passphtrase to the message is used. */
178 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
184 for (pw = NULL, i = len = 100; ; i++ )
190 pw = xmalloc_secure( len );
199 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
203 if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
204 tty_printf("\b\b\b \n" );
212 * Ask the GPG Agent for the passphrase.
213 * If NOCACHE is set the symmetric passpharse caching will not be used.
215 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
216 * NULL, the function does set it to 1 if the user canceled the
217 * operation. If CACHEID is not NULL, it will be used as the cacheID
218 * for the gpg-agent; if is NULL and a key fingerprint can be
219 * computed, this will be used as the cacheid.
222 passphrase_get (int nocache, const char *cacheid, int repeat,
223 const char *tryagain_text, int *canceled)
228 const char *my_cacheid;
233 orig_codeset = i18n_switchto_utf8 ();
235 if (!nocache && cacheid)
236 my_cacheid = cacheid;
241 tryagain_text = _(tryagain_text);
243 rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
244 _("Enter passphrase\n"),
245 repeat, nocache, &pw);
247 i18n_switchback (orig_codeset);
252 else if (gpg_err_code (rc) == GPG_ERR_CANCELED
253 || gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
255 log_info (_("cancelled by user\n") );
261 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
262 /* Due to limitations in the API of the upper layers they
263 consider an error as no passphrase entered. This works in
264 most cases but not during key creation where this should
265 definitely not happen and let it continue without requiring a
266 passphrase. Given that now all the upper layers handle a
267 cancel correctly, we simply set the cancel flag now for all
268 errors from the agent. */
272 write_status_errcode ("get_passphrase", rc);
285 * Clear the cached passphrase with CACHEID.
288 passphrase_clear_cache (const char *cacheid)
292 rc = agent_clear_passphrase (cacheid);
294 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
298 /* Return a new DEK object using the string-to-key specifier S2K.
299 * Returns NULL if the user canceled the passphrase entry and if
300 * CANCELED is not NULL, sets it to true.
302 * If CREATE is true a new passphrase sll be created. If NOCACHE is
303 * true the symmetric key caching will not be used. */
305 passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
306 int create, int nocache,
307 const char *tryagain_text, int *canceled)
313 char s2k_cacheidbuf[1+16+1];
314 char *s2k_cacheid = NULL;
317 canceled = &dummy_canceled;
322 log_assert (create && !nocache);
323 /* This is used for the old rfc1991 mode
324 * Note: This must match the code in encode.c with opt.rfc1991 set */
325 memset (&help_s2k, 0, sizeof (help_s2k));
327 s2k->hash_algo = S2K_DIGEST_ALGO;
330 /* Create a new salt or what else to be filled into the s2k for a
332 if (create && (s2k->mode == 1 || s2k->mode == 3))
334 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
335 if ( s2k->mode == 3 )
337 /* We delay the encoding until it is really needed. This is
338 if we are going to dynamically calibrate it, we need to
339 call out to gpg-agent and that should not be done during
340 option processing in main(). */
342 opt.s2k_count = encode_s2k_iterations (0);
343 s2k->count = opt.s2k_count;
347 /* If we do not have a passphrase available in NEXT_PW and status
348 information are request, we print them now. */
349 if ( !next_pw && is_status_enabled() )
353 snprintf (buf, sizeof buf, "%d %d %d",
354 cipher_algo, s2k->mode, s2k->hash_algo );
355 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
360 /* Simply return the passphrase we already have in NEXT_PW. */
364 else if ( have_static_passphrase () )
366 /* Return the passphrase we have stored in FD_PASSWD. */
367 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
368 strcpy ( pw, fd_passwd );
372 if (!nocache && (s2k->mode == 1 || s2k->mode == 3))
374 memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
375 *s2k_cacheidbuf = 'S';
376 bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
377 s2k_cacheid = s2k_cacheidbuf;
380 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
384 snprintf (buf, sizeof (buf), "%u", 100);
385 write_status_text (STATUS_INQUIRE_MAXLEN, buf);
388 /* Divert to the gpg-agent. */
389 pw = passphrase_get (create && nocache, s2k_cacheid,
390 create? opt.passphrase_repeat : 0,
391 tryagain_text, canceled);
395 write_status( STATUS_MISSING_PASSPHRASE );
401 write_status( STATUS_MISSING_PASSPHRASE );
403 /* Hash the passphrase and store it in a newly allocated DEK object.
404 Keep a copy of the passphrase in LAST_PW for use by
405 get_last_passphrase(). */
406 dek = xmalloc_secure_clear ( sizeof *dek );
407 dek->algo = cipher_algo;
408 if ( (!pw || !*pw) && create)
414 dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
415 if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
417 err = gcry_kdf_derive (pw, strlen (pw),
418 s2k->mode == 3? GCRY_KDF_ITERSALTED_S2K :
419 s2k->mode == 1? GCRY_KDF_SALTED_S2K :
420 /* */ GCRY_KDF_SIMPLE_S2K,
421 s2k->hash_algo, s2k->salt, 8,
422 S2K_DECODE_COUNT(s2k->count),
423 dek->keylen, dek->key);
426 log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
429 write_status( STATUS_MISSING_PASSPHRASE );
434 memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
441 /* Emit the USERID_HINT and the NEED_PASSPHRASE status messages.
442 MAINKEYID may be NULL. */
444 emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo)
449 us = get_long_user_id_string (keyid);
450 write_status_text (STATUS_USERID_HINT, us);
453 snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
456 (ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
457 (ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
460 write_status_text (STATUS_NEED_PASSPHRASE, buf);
464 /* Return an allocated utf-8 string describing the key PK. If ESCAPED
465 is true spaces and control characters are percent or plus escaped.
466 MODE describes the use of the key description; use one of the
467 FORMAT_KEYDESC_ macros. */
469 gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped)
473 const char *algo_name;
479 const char *trailer = "";
482 is_subkey = (pk->main_keyid[0] && pk->main_keyid[1]
483 && pk->keyid[0] != pk->main_keyid[0]
484 && pk->keyid[1] != pk->main_keyid[1]);
485 algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
486 timestr = strtimestamp (pk->timestamp);
487 uid = get_user_id (is_subkey? pk->main_keyid:pk->keyid, &uidlen);
489 orig_codeset = i18n_switchto_utf8 ();
492 maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
498 case FORMAT_KEYDESC_NORMAL:
499 prompt = _("Please enter the passphrase to unlock the"
500 " OpenPGP secret key:");
502 case FORMAT_KEYDESC_IMPORT:
503 prompt = _("Please enter the passphrase to import the"
504 " OpenPGP secret key:");
506 case FORMAT_KEYDESC_EXPORT:
508 prompt = _("Please enter the passphrase to export the"
509 " OpenPGP secret subkey:");
511 prompt = _("Please enter the passphrase to export the"
512 " OpenPGP secret key:");
514 case FORMAT_KEYDESC_DELKEY:
516 prompt = _("Do you really want to permanently delete the"
517 " OpenPGP secret subkey key:");
519 prompt = _("Do you really want to permanently delete the"
520 " OpenPGP secret key:");
528 desc = xtryasprintf (_("%s\n"
530 "%u-bit %s key, ID %s,\n"
531 "created %s%s.\n%s"),
534 nbits_from_pk (pk), algo_name,
535 keystr (pk->keyid), timestr,
536 maink?maink:"", trailer);
540 i18n_switchback (orig_codeset);
544 char *tmp = percent_plus_escape (desc);