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 ( !opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
170 { /* Not used but we have to do a dummy read, so that it won't end
171 up at the begin of the message if the quite usual trick to
172 prepend the passphtrase to the message is used. */
175 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
181 for (pw = NULL, i = len = 100; ; i++ )
187 pw = xmalloc_secure( len );
196 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
200 if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
201 tty_printf("\b\b\b \n" );
209 * Ask the GPG Agent for the passphrase.
210 * If NOCACHE is set the symmetric passpharse caching will not be used.
212 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
213 * NULL, the function does set it to 1 if the user canceled the
214 * operation. If CACHEID is not NULL, it will be used as the cacheID
215 * for the gpg-agent; if is NULL and a key fingerprint can be
216 * computed, this will be used as the cacheid.
219 passphrase_get (int nocache, const char *cacheid, int repeat,
220 const char *tryagain_text, int *canceled)
225 const char *my_cacheid;
230 orig_codeset = i18n_switchto_utf8 ();
232 if (!nocache && cacheid)
233 my_cacheid = cacheid;
238 tryagain_text = _(tryagain_text);
240 rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
241 _("Enter passphrase\n"),
242 repeat, nocache, &pw);
244 i18n_switchback (orig_codeset);
249 else if (gpg_err_code (rc) == GPG_ERR_CANCELED
250 || gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
252 log_info (_("cancelled by user\n") );
258 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
259 /* Due to limitations in the API of the upper layers they
260 consider an error as no passphrase entered. This works in
261 most cases but not during key creation where this should
262 definitely not happen and let it continue without requiring a
263 passphrase. Given that now all the upper layers handle a
264 cancel correctly, we simply set the cancel flag now for all
265 errors from the agent. */
269 write_status_errcode ("get_passphrase", rc);
282 * Clear the cached passphrase with CACHEID.
285 passphrase_clear_cache (const char *cacheid)
289 rc = agent_clear_passphrase (cacheid);
291 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
295 /* Return a new DEK object using the string-to-key specifier S2K.
296 * Returns NULL if the user canceled the passphrase entry and if
297 * CANCELED is not NULL, sets it to true.
299 * If CREATE is true a new passphrase sll be created. If NOCACHE is
300 * true the symmetric key caching will not be used. */
302 passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
303 int create, int nocache,
304 const char *tryagain_text, int *canceled)
310 char s2k_cacheidbuf[1+16+1];
311 char *s2k_cacheid = NULL;
314 canceled = &dummy_canceled;
319 log_assert (create && !nocache);
320 /* This is used for the old rfc1991 mode
321 * Note: This must match the code in encode.c with opt.rfc1991 set */
322 memset (&help_s2k, 0, sizeof (help_s2k));
324 s2k->hash_algo = S2K_DIGEST_ALGO;
327 /* Create a new salt or what else to be filled into the s2k for a
329 if (create && (s2k->mode == 1 || s2k->mode == 3))
331 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
332 if ( s2k->mode == 3 )
334 /* We delay the encoding until it is really needed. This is
335 if we are going to dynamically calibrate it, we need to
336 call out to gpg-agent and that should not be done during
337 option processing in main(). */
339 opt.s2k_count = encode_s2k_iterations (0);
340 s2k->count = opt.s2k_count;
344 /* If we do not have a passphrase available in NEXT_PW and status
345 information are request, we print them now. */
346 if ( !next_pw && is_status_enabled() )
350 snprintf (buf, sizeof buf, "%d %d %d",
351 cipher_algo, s2k->mode, s2k->hash_algo );
352 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
357 /* Simply return the passphrase we already have in NEXT_PW. */
361 else if ( have_static_passphrase () )
363 /* Return the passphrase we have stored in FD_PASSWD. */
364 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
365 strcpy ( pw, fd_passwd );
369 if (!nocache && (s2k->mode == 1 || s2k->mode == 3))
371 memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
372 *s2k_cacheidbuf = 'S';
373 bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
374 s2k_cacheid = s2k_cacheidbuf;
377 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
381 snprintf (buf, sizeof (buf), "%u", 100);
382 write_status_text (STATUS_INQUIRE_MAXLEN, buf);
385 /* Divert to the gpg-agent. */
386 pw = passphrase_get (create && nocache, s2k_cacheid,
387 create? opt.passphrase_repeat : 0,
388 tryagain_text, canceled);
392 write_status( STATUS_MISSING_PASSPHRASE );
398 write_status( STATUS_MISSING_PASSPHRASE );
400 /* Hash the passphrase and store it in a newly allocated DEK object.
401 Keep a copy of the passphrase in LAST_PW for use by
402 get_last_passphrase(). */
403 dek = xmalloc_secure_clear ( sizeof *dek );
404 dek->algo = cipher_algo;
405 if ( (!pw || !*pw) && create)
411 dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
412 if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
414 err = gcry_kdf_derive (pw, strlen (pw),
415 s2k->mode == 3? GCRY_KDF_ITERSALTED_S2K :
416 s2k->mode == 1? GCRY_KDF_SALTED_S2K :
417 /* */ GCRY_KDF_SIMPLE_S2K,
418 s2k->hash_algo, s2k->salt, 8,
419 S2K_DECODE_COUNT(s2k->count),
420 dek->keylen, dek->key);
423 log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
426 write_status( STATUS_MISSING_PASSPHRASE );
431 memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
438 /* Emit the USERID_HINT and the NEED_PASSPHRASE status messages.
439 MAINKEYID may be NULL. */
441 emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo)
446 us = get_long_user_id_string (keyid);
447 write_status_text (STATUS_USERID_HINT, us);
450 snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
453 (ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
454 (ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
457 write_status_text (STATUS_NEED_PASSPHRASE, buf);
461 /* Return an allocated utf-8 string describing the key PK. If ESCAPED
462 is true spaces and control characters are percent or plus escaped.
463 MODE describes the use of the key description; use one of the
464 FORMAT_KEYDESC_ macros. */
466 gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped)
470 const char *algo_name;
476 const char *trailer = "";
479 is_subkey = (pk->main_keyid[0] && pk->main_keyid[1]
480 && pk->keyid[0] != pk->main_keyid[0]
481 && pk->keyid[1] != pk->main_keyid[1]);
482 algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
483 timestr = strtimestamp (pk->timestamp);
484 uid = get_user_id (is_subkey? pk->main_keyid:pk->keyid, &uidlen);
486 orig_codeset = i18n_switchto_utf8 ();
489 maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
495 case FORMAT_KEYDESC_NORMAL:
496 prompt = _("Please enter the passphrase to unlock the"
497 " OpenPGP secret key:");
499 case FORMAT_KEYDESC_IMPORT:
500 prompt = _("Please enter the passphrase to import the"
501 " OpenPGP secret key:");
503 case FORMAT_KEYDESC_EXPORT:
505 prompt = _("Please enter the passphrase to export the"
506 " OpenPGP secret subkey:");
508 prompt = _("Please enter the passphrase to export the"
509 " OpenPGP secret key:");
511 case FORMAT_KEYDESC_DELKEY:
513 prompt = _("Do you really want to permanently delete the"
514 " OpenPGP secret subkey key:");
516 prompt = _("Do you really want to permanently delete the"
517 " OpenPGP secret key:");
525 desc = xtryasprintf (_("%s\n"
527 "%u-bit %s key, ID %s,\n"
528 "created %s%s.\n%s"),
531 nbits_from_pk (pk), algo_name,
532 keystr (pk->keyid), timestr,
533 maink?maink:"", trailer);
537 i18n_switchback (orig_codeset);
541 char *tmp = percent_plus_escape (desc);