* gpg.texi (GPG Configuration Options): Make http_proxy option
[gnupg.git] / g10 / passphrase.c
blobf4015ef74744bd91154d9225f1d5f1ecc38aefe9
1 /* passphrase.c - Get a passphrase
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2006 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 2 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, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <stddef.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <assert.h>
30 #include <errno.h>
31 #ifdef HAVE_LOCALE_H
32 #include <locale.h>
33 #endif
34 #ifdef HAVE_LANGINFO_CODESET
35 #include <langinfo.h>
36 #endif
38 #include "gpg.h"
39 #include "util.h"
40 #include "options.h"
41 #include "ttyio.h"
42 #include "cipher.h"
43 #include "keydb.h"
44 #include "main.h"
45 #include "i18n.h"
46 #include "status.h"
47 #include "call-agent.h"
50 static char *fd_passwd = NULL;
51 static char *next_pw = NULL;
52 static char *last_pw = NULL;
55 /* Hash a passphrase using the supplied s2k. If create is true, create
56 a new salt or what else must be filled into the s2k for a new key.
57 always needs: dek->algo, s2k->mode, s2k->hash_algo. */
58 static void
59 hash_passphrase ( DEK *dek, char *pw, STRING2KEY *s2k, int create )
61 gcry_md_hd_t md;
62 int pass, i;
63 int used = 0;
64 int pwlen = strlen(pw);
66 assert ( s2k->hash_algo );
67 dek->keylen = gcry_cipher_get_algo_keylen (dek->algo);
68 if ( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
69 BUG();
71 if (gcry_md_open (&md, s2k->hash_algo, 1))
72 BUG ();
73 for (pass=0; used < dek->keylen ; pass++ )
75 if ( pass )
77 gcry_md_reset (md);
78 for (i=0; i < pass; i++ ) /* Preset the hash context. */
79 gcry_md_putc (md, 0 );
82 if ( s2k->mode == 1 || s2k->mode == 3 )
84 int len2 = pwlen + 8;
85 ulong count = len2;
87 if ( create && !pass )
89 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
90 if ( s2k->mode == 3 )
91 s2k->count = opt.s2k_count;
94 if ( s2k->mode == 3 )
96 count = S2K_DECODE_COUNT(s2k->count);
97 if ( count < len2 )
98 count = len2;
101 /* A little bit complicated because we need a ulong for count. */
102 while ( count > len2 ) /* maybe iterated+salted */
104 gcry_md_write ( md, s2k->salt, 8 );
105 gcry_md_write ( md, pw, pwlen );
106 count -= len2;
108 if ( count < 8 )
109 gcry_md_write ( md, s2k->salt, count );
110 else
112 gcry_md_write ( md, s2k->salt, 8 );
113 count -= 8;
114 gcry_md_write ( md, pw, count );
117 else
118 gcry_md_write ( md, pw, pwlen );
119 gcry_md_final( md );
121 i = gcry_md_get_algo_dlen ( s2k->hash_algo );
122 if ( i > dek->keylen - used )
123 i = dek->keylen - used;
125 memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
126 used += i;
128 gcry_md_close(md);
134 have_static_passphrase()
136 return !!fd_passwd && opt.batch;
139 /****************
140 * Set the passphrase to be used for the next query and only for the next
141 * one.
143 void
144 set_next_passphrase( const char *s )
146 xfree(next_pw);
147 next_pw = NULL;
148 if ( s )
150 next_pw = xmalloc_secure( strlen(s)+1 );
151 strcpy (next_pw, s );
155 /****************
156 * Get the last passphrase used in passphrase_to_dek.
157 * Note: This removes the passphrase from this modules and
158 * the caller must free the result. May return NULL:
160 char *
161 get_last_passphrase()
163 char *p = last_pw;
164 last_pw = NULL;
165 return p;
168 /* As if we had used the passphrase - make it the last_pw. */
169 void
170 next_to_last_passphrase(void)
172 if (next_pw)
174 last_pw=next_pw;
175 next_pw=NULL;
179 /* Here's an interesting question: since this passphrase was passed in
180 on the command line, is there really any point in using secure
181 memory for it? I'm going with 'yes', since it doesn't hurt, and
182 might help in some small way (swapping). */
184 void
185 set_passphrase_from_string(const char *pass)
187 xfree (fd_passwd);
188 fd_passwd = xmalloc_secure(strlen(pass)+1);
189 strcpy (fd_passwd, pass);
193 void
194 read_passphrase_from_fd( int fd )
196 int i, len;
197 char *pw;
199 if ( !opt.batch )
200 { /* Not used but we have to do a dummy read, so that it won't end
201 up at the begin of the message if the quite usual trick to
202 prepend the passphtrase to the message is used. */
203 char buf[1];
205 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
207 *buf = 0;
208 return;
211 for (pw = NULL, i = len = 100; ; i++ )
213 if (i >= len-1 )
215 char *pw2 = pw;
216 len += 100;
217 pw = xmalloc_secure( len );
218 if( pw2 )
220 memcpy(pw, pw2, i );
221 xfree (pw2);
223 else
224 i=0;
226 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
227 break;
229 pw[i] = 0;
230 if (!opt.batch)
231 tty_printf("\b\b\b \n" );
233 xfree ( fd_passwd );
234 fd_passwd = pw;
239 * Ask the GPG Agent for the passphrase.
240 * Mode 0: Allow cached passphrase
241 * 1: No cached passphrase FIXME: Not really implemented
242 * 2: Ditto, but change the text to "repeat entry"
244 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
245 * NULL, the function does set it to 1 if the user canceled the
246 * operation. If CACHEID is not NULL, it will be used as the cacheID
247 * for the gpg-agent; if is NULL and a key fingerprint can be
248 * computed, this will be used as the cacheid.
250 static char *
251 passphrase_get ( u32 *keyid, int mode, const char *cacheid,
252 const char *tryagain_text,
253 const char *custom_description,
254 const char *custom_prompt, int *canceled)
256 int rc;
257 char *atext = NULL;
258 char *pw = NULL;
259 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
260 byte fpr[MAX_FINGERPRINT_LEN];
261 int have_fpr = 0;
262 char *orig_codeset = NULL;
263 char *my_prompt;
264 char hexfprbuf[20*2+1];
265 const char *my_cacheid;
267 if (canceled)
268 *canceled = 0;
270 #if MAX_FINGERPRINT_LEN < 20
271 #error agent needs a 20 byte fingerprint
272 #endif
274 memset (fpr, 0, MAX_FINGERPRINT_LEN );
275 if( keyid && get_pubkey( pk, keyid ) )
277 if (pk)
278 free_public_key( pk );
279 pk = NULL; /* oops: no key for some reason */
282 #ifdef ENABLE_NLS
283 /* The Assuan agent protocol requires us to transmit utf-8 strings */
284 orig_codeset = bind_textdomain_codeset (PACKAGE, NULL);
285 #ifdef HAVE_LANGINFO_CODESET
286 if (!orig_codeset)
287 orig_codeset = nl_langinfo (CODESET);
288 #endif
289 if (orig_codeset)
290 { /* We only switch when we are able to restore the codeset later. */
291 orig_codeset = xstrdup (orig_codeset);
292 if (!bind_textdomain_codeset (PACKAGE, "utf-8"))
293 orig_codeset = NULL;
295 #endif
297 if (custom_description)
298 atext = native_to_utf8 (custom_description);
299 else if ( !mode && pk && keyid )
301 char *uid;
302 size_t uidlen;
303 const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
304 const char *timestr;
305 char *maink;
307 if ( !algo_name )
308 algo_name = "?";
310 #define KEYIDSTRING _(" (main key ID %s)")
312 maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
313 if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
314 && keyid[1] != keyid[3] )
315 sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
316 else
317 *maink = 0;
319 uid = get_user_id ( keyid, &uidlen );
320 timestr = strtimestamp (pk->timestamp);
322 #undef KEYIDSTRING
324 #define PROMPTSTRING _("You need a passphrase to unlock the secret" \
325 " key for user:\n" \
326 "\"%.*s\"\n" \
327 "%u-bit %s key, ID %s, created %s%s\n" )
329 atext = xmalloc ( 100 + strlen (PROMPTSTRING)
330 + uidlen + 15 + strlen(algo_name) + keystrlen()
331 + strlen (timestr) + strlen (maink) );
332 sprintf (atext, PROMPTSTRING,
333 (int)uidlen, uid,
334 nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
335 maink );
336 xfree (uid);
337 xfree (maink);
339 #undef PROMPTSTRING
342 size_t dummy;
343 fingerprint_from_pk( pk, fpr, &dummy );
344 have_fpr = 1;
348 else if (mode == 2 )
349 atext = xstrdup ( _("Repeat passphrase\n") );
350 else
351 atext = xstrdup ( _("Enter passphrase\n") );
354 if (!mode && cacheid)
355 my_cacheid = cacheid;
356 else if (!mode && have_fpr)
357 my_cacheid = bin2hex (fpr, 20, hexfprbuf);
358 else
359 my_cacheid = NULL;
361 if (tryagain_text)
362 tryagain_text = _(tryagain_text);
364 my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
366 rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext, &pw);
368 xfree (my_prompt);
369 xfree (atext); atext = NULL;
371 if (!rc)
373 else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
375 log_info (_("cancelled by user\n") );
376 if (canceled)
377 *canceled = 1;
379 else
380 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
382 #ifdef ENABLE_NLS
383 if (orig_codeset)
385 bind_textdomain_codeset (PACKAGE, orig_codeset);
386 xfree (orig_codeset);
388 #endif
389 if (pk)
390 free_public_key( pk );
391 if (rc)
393 xfree (pw);
394 return NULL;
396 return pw;
401 * Clear the cached passphrase. If CACHEID is not NULL, it will be
402 * used instead of a cache ID derived from KEYID.
404 void
405 passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
407 int rc;
409 if (!cacheid)
411 PKT_public_key *pk;
412 # if MAX_FINGERPRINT_LEN < 20
413 # error agent needs a 20 byte fingerprint
414 # endif
415 byte fpr[MAX_FINGERPRINT_LEN];
416 char hexfprbuf[2*20+1];
417 size_t dummy;
419 pk = xcalloc (1, sizeof *pk);
420 if ( !keyid || get_pubkey( pk, keyid ) )
422 log_error ("key not found in passphrase_clear_cache\n");
423 free_public_key (pk);
424 return;
426 memset (fpr, 0, MAX_FINGERPRINT_LEN );
427 fingerprint_from_pk ( pk, fpr, &dummy );
428 bin2hex (fpr, 20, hexfprbuf);
429 rc = agent_clear_passphrase (hexfprbuf);
430 free_public_key ( pk );
432 else
433 rc = agent_clear_passphrase (cacheid);
435 if (rc)
436 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
440 /****************
441 * Ask for a passphrase and return that string.
443 char *
444 ask_passphrase (const char *description,
445 const char *tryagain_text,
446 const char *promptid,
447 const char *prompt,
448 const char *cacheid, int *canceled)
450 char *pw = NULL;
452 if (canceled)
453 *canceled = 0;
455 if (!opt.batch && description)
457 if (strchr (description, '%'))
459 char *tmp = unescape_percent_string (description);
460 tty_printf ("\n%s\n", tmp);
461 xfree (tmp);
463 else
464 tty_printf ("\n%s\n",description);
467 if (have_static_passphrase ())
469 pw = xmalloc_secure (strlen(fd_passwd)+1);
470 strcpy (pw, fd_passwd);
472 else
473 pw = passphrase_get (NULL, 0, cacheid,
474 tryagain_text, description, prompt,
475 canceled );
477 if (!pw || !*pw)
478 write_status( STATUS_MISSING_PASSPHRASE );
480 return pw;
484 /* Return a new DEK object Using the string-to-key sepcifier S2K. Use
485 KEYID and PUBKEY_ALGO to prompt the user. Returns NULL is the user
486 selected to cancel the passphrase entry and it CANCELED is not
487 NULL, sets it to true.
489 MODE 0: Allow cached passphrase
490 1: Ignore cached passphrase
491 2: Ditto, but change the text to "repeat entry"
493 DEK *
494 passphrase_to_dek (u32 *keyid, int pubkey_algo,
495 int cipher_algo, STRING2KEY *s2k, int mode,
496 const char *tryagain_text, int *canceled)
498 char *pw = NULL;
499 DEK *dek;
500 STRING2KEY help_s2k;
501 int dummy_canceled;
503 if (!canceled)
504 canceled = &dummy_canceled;
505 *canceled = 0;
507 if ( !s2k )
509 /* This is used for the old rfc1991 mode
510 * Note: This must match the code in encode.c with opt.rfc1991 set */
511 s2k = &help_s2k;
512 s2k->mode = 0;
513 s2k->hash_algo = S2K_DIGEST_ALGO;
516 /* If we do not have a passphrase available in NEXT_PW and status
517 information are request, we print them now. */
518 if ( !next_pw && is_status_enabled() )
520 char buf[50];
522 if ( keyid )
524 u32 used_kid[2];
525 char *us;
527 if ( keyid[2] && keyid[3] )
529 used_kid[0] = keyid[2];
530 used_kid[1] = keyid[3];
532 else
534 used_kid[0] = keyid[0];
535 used_kid[1] = keyid[1];
538 us = get_long_user_id_string ( keyid );
539 write_status_text ( STATUS_USERID_HINT, us );
540 xfree(us);
542 snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
543 (ulong)keyid[0], (ulong)keyid[1],
544 (ulong)used_kid[0], (ulong)used_kid[1],
545 pubkey_algo );
547 write_status_text ( STATUS_NEED_PASSPHRASE, buf );
549 else
551 snprintf (buf, sizeof buf -1, "%d %d %d",
552 cipher_algo, s2k->mode, s2k->hash_algo );
553 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
557 /* If we do have a keyID, we do not have a passphrase available in
558 NEXT_PW, we are not running in batch mode and we do not want to
559 ignore the passphrase cache (mode!=1), print a prompt with
560 information on that key. */
561 if ( keyid && !opt.batch && !next_pw && mode!=1 )
563 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
564 char *p;
566 p = get_user_id_native(keyid);
567 tty_printf ("\n");
568 tty_printf (_("You need a passphrase to unlock the secret key for\n"
569 "user: \"%s\"\n"),p);
570 xfree(p);
572 if ( !get_pubkey( pk, keyid ) )
574 const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
576 tty_printf (_("%u-bit %s key, ID %s, created %s"),
577 nbits_from_pk( pk ), s?s:"?", keystr(keyid),
578 strtimestamp(pk->timestamp) );
579 if ( keyid[2] && keyid[3]
580 && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
582 if ( keystrlen () > 10 )
584 tty_printf ("\n");
585 tty_printf (_(" (subkey on main key ID %s)"),
586 keystr(&keyid[2]) );
588 else
589 tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
591 tty_printf("\n");
594 tty_printf("\n");
595 if (pk)
596 free_public_key( pk );
599 if ( next_pw )
601 /* Simply return the passphrase we already have in NEXT_PW. */
602 pw = next_pw;
603 next_pw = NULL;
605 else if ( have_static_passphrase () )
607 /* Return the passphrase we have stored in FD_PASSWD. */
608 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
609 strcpy ( pw, fd_passwd );
611 else
613 /* Divert to the gpg-agent. */
614 pw = passphrase_get ( keyid, mode == 2? 1: 0, NULL,
615 tryagain_text, NULL, NULL, canceled );
616 if (*canceled)
618 xfree (pw);
619 return NULL;
621 if (!pw)
622 pw = xstrdup ("");
623 if ( *pw && mode == 2 )
625 int i;
626 for(i=0;i<opt.passwd_repeat;i++)
628 char *pw2 = passphrase_get ( keyid, 2, NULL, NULL, NULL,
629 NULL, canceled );
630 if (*canceled)
632 xfree (pw);
633 xfree (pw2);
634 return NULL;
636 if (!pw2)
637 pw2 = xstrdup ("");
638 if ( strcmp(pw, pw2) )
640 xfree(pw2);
641 xfree(pw);
642 return NULL;
644 xfree(pw2);
649 if ( !pw || !*pw )
650 write_status( STATUS_MISSING_PASSPHRASE );
652 /* Hash the passphrase and store it in a newly allocated DEK object.
653 Keep a copy of the passphrase in LAST_PW for use by
654 get_last_passphrase(). */
655 dek = xmalloc_secure_clear ( sizeof *dek );
656 dek->algo = cipher_algo;
657 if ( !*pw && mode == 2 )
658 dek->keylen = 0;
659 else
660 hash_passphrase( dek, pw, s2k, mode==2 );
661 xfree(last_pw);
662 last_pw = pw;
663 return dek;