2008-02-01 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / passphrase.c
blobcf67b7f9f4681c2d97d131d4c176c274dda95bde
1 /* passphrase.c - Get a passphrase
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2006, 2007 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/>.
21 #include <config.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <assert.h>
28 #include <errno.h>
29 #ifdef HAVE_LOCALE_H
30 #include <locale.h>
31 #endif
32 #ifdef HAVE_LANGINFO_CODESET
33 #include <langinfo.h>
34 #endif
36 #include "gpg.h"
37 #include "util.h"
38 #include "options.h"
39 #include "ttyio.h"
40 #include "cipher.h"
41 #include "keydb.h"
42 #include "main.h"
43 #include "i18n.h"
44 #include "status.h"
45 #include "call-agent.h"
48 static char *fd_passwd = NULL;
49 static char *next_pw = NULL;
50 static char *last_pw = NULL;
53 /* Hash a passphrase using the supplied s2k. If create is true, create
54 a new salt or what else must be filled into the s2k for a new key.
55 always needs: dek->algo, s2k->mode, s2k->hash_algo. */
56 static void
57 hash_passphrase ( DEK *dek, char *pw, STRING2KEY *s2k, int create )
59 gcry_md_hd_t md;
60 int pass, i;
61 int used = 0;
62 int pwlen = strlen(pw);
64 assert ( s2k->hash_algo );
65 dek->keylen = gcry_cipher_get_algo_keylen (dek->algo);
66 if ( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
67 BUG();
69 if (gcry_md_open (&md, s2k->hash_algo, 1))
70 BUG ();
71 for (pass=0; used < dek->keylen ; pass++ )
73 if ( pass )
75 gcry_md_reset (md);
76 for (i=0; i < pass; i++ ) /* Preset the hash context. */
77 gcry_md_putc (md, 0 );
80 if ( s2k->mode == 1 || s2k->mode == 3 )
82 int len2 = pwlen + 8;
83 ulong count = len2;
85 if ( create && !pass )
87 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
88 if ( s2k->mode == 3 )
89 s2k->count = opt.s2k_count;
92 if ( s2k->mode == 3 )
94 count = S2K_DECODE_COUNT(s2k->count);
95 if ( count < len2 )
96 count = len2;
99 /* A little bit complicated because we need a ulong for count. */
100 while ( count > len2 ) /* maybe iterated+salted */
102 gcry_md_write ( md, s2k->salt, 8 );
103 gcry_md_write ( md, pw, pwlen );
104 count -= len2;
106 if ( count < 8 )
107 gcry_md_write ( md, s2k->salt, count );
108 else
110 gcry_md_write ( md, s2k->salt, 8 );
111 count -= 8;
112 gcry_md_write ( md, pw, count );
115 else
116 gcry_md_write ( md, pw, pwlen );
117 gcry_md_final( md );
119 i = gcry_md_get_algo_dlen ( s2k->hash_algo );
120 if ( i > dek->keylen - used )
121 i = dek->keylen - used;
123 memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
124 used += i;
126 gcry_md_close(md);
132 have_static_passphrase()
134 return !!fd_passwd && opt.batch;
137 /****************
138 * Set the passphrase to be used for the next query and only for the next
139 * one.
141 void
142 set_next_passphrase( const char *s )
144 xfree(next_pw);
145 next_pw = NULL;
146 if ( s )
148 next_pw = xmalloc_secure( strlen(s)+1 );
149 strcpy (next_pw, s );
153 /****************
154 * Get the last passphrase used in passphrase_to_dek.
155 * Note: This removes the passphrase from this modules and
156 * the caller must free the result. May return NULL:
158 char *
159 get_last_passphrase()
161 char *p = last_pw;
162 last_pw = NULL;
163 return p;
166 /* As if we had used the passphrase - make it the last_pw. */
167 void
168 next_to_last_passphrase(void)
170 if (next_pw)
172 last_pw=next_pw;
173 next_pw=NULL;
177 /* Here's an interesting question: since this passphrase was passed in
178 on the command line, is there really any point in using secure
179 memory for it? I'm going with 'yes', since it doesn't hurt, and
180 might help in some small way (swapping). */
182 void
183 set_passphrase_from_string(const char *pass)
185 xfree (fd_passwd);
186 fd_passwd = xmalloc_secure(strlen(pass)+1);
187 strcpy (fd_passwd, pass);
191 void
192 read_passphrase_from_fd( int fd )
194 int i, len;
195 char *pw;
197 if ( !opt.batch )
198 { /* Not used but we have to do a dummy read, so that it won't end
199 up at the begin of the message if the quite usual trick to
200 prepend the passphtrase to the message is used. */
201 char buf[1];
203 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
205 *buf = 0;
206 return;
209 for (pw = NULL, i = len = 100; ; i++ )
211 if (i >= len-1 )
213 char *pw2 = pw;
214 len += 100;
215 pw = xmalloc_secure( len );
216 if( pw2 )
218 memcpy(pw, pw2, i );
219 xfree (pw2);
221 else
222 i=0;
224 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
225 break;
227 pw[i] = 0;
228 if (!opt.batch)
229 tty_printf("\b\b\b \n" );
231 xfree ( fd_passwd );
232 fd_passwd = pw;
237 * Ask the GPG Agent for the passphrase.
238 * Mode 0: Allow cached passphrase
239 * 1: No cached passphrase FIXME: Not really implemented
240 * 2: Ditto, but change the text to "repeat entry"
242 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
243 * NULL, the function does set it to 1 if the user canceled the
244 * operation. If CACHEID is not NULL, it will be used as the cacheID
245 * for the gpg-agent; if is NULL and a key fingerprint can be
246 * computed, this will be used as the cacheid.
248 static char *
249 passphrase_get ( u32 *keyid, int mode, const char *cacheid,
250 const char *tryagain_text,
251 const char *custom_description,
252 const char *custom_prompt, int *canceled)
254 int rc;
255 char *atext = NULL;
256 char *pw = NULL;
257 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
258 byte fpr[MAX_FINGERPRINT_LEN];
259 int have_fpr = 0;
260 char *orig_codeset;
261 char *my_prompt;
262 char hexfprbuf[20*2+1];
263 const char *my_cacheid;
265 if (canceled)
266 *canceled = 0;
268 #if MAX_FINGERPRINT_LEN < 20
269 #error agent needs a 20 byte fingerprint
270 #endif
272 memset (fpr, 0, MAX_FINGERPRINT_LEN );
273 if( keyid && get_pubkey( pk, keyid ) )
275 if (pk)
276 free_public_key( pk );
277 pk = NULL; /* oops: no key for some reason */
280 orig_codeset = i18n_switchto_utf8 ();
282 if (custom_description)
283 atext = native_to_utf8 (custom_description);
284 else if ( !mode && pk && keyid )
286 char *uid;
287 size_t uidlen;
288 const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
289 const char *timestr;
290 char *maink;
292 if ( !algo_name )
293 algo_name = "?";
295 #define KEYIDSTRING _(" (main key ID %s)")
297 maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
298 if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
299 && keyid[1] != keyid[3] )
300 sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
301 else
302 *maink = 0;
304 uid = get_user_id ( keyid, &uidlen );
305 timestr = strtimestamp (pk->timestamp);
307 #undef KEYIDSTRING
309 #define PROMPTSTRING _("You need a passphrase to unlock the secret" \
310 " key for user:\n" \
311 "\"%.*s\"\n" \
312 "%u-bit %s key, ID %s, created %s%s\n" )
314 atext = xmalloc ( 100 + strlen (PROMPTSTRING)
315 + uidlen + 15 + strlen(algo_name) + keystrlen()
316 + strlen (timestr) + strlen (maink) );
317 sprintf (atext, PROMPTSTRING,
318 (int)uidlen, uid,
319 nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
320 maink );
321 xfree (uid);
322 xfree (maink);
324 #undef PROMPTSTRING
327 size_t dummy;
328 fingerprint_from_pk( pk, fpr, &dummy );
329 have_fpr = 1;
333 else if (mode == 2 )
334 atext = xstrdup ( _("Repeat passphrase\n") );
335 else
336 atext = xstrdup ( _("Enter passphrase\n") );
339 if (!mode && cacheid)
340 my_cacheid = cacheid;
341 else if (!mode && have_fpr)
342 my_cacheid = bin2hex (fpr, 20, hexfprbuf);
343 else
344 my_cacheid = NULL;
346 if (tryagain_text)
347 tryagain_text = _(tryagain_text);
349 my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
351 rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext, &pw);
353 xfree (my_prompt);
354 xfree (atext); atext = NULL;
356 i18n_switchback (orig_codeset);
359 if (!rc)
361 else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
363 log_info (_("cancelled by user\n") );
364 if (canceled)
365 *canceled = 1;
367 else
369 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
370 /* Due to limitations in the API of the upper layers they
371 consider an error as no passphrase entered. This works in
372 most cases but not during key creation where this should
373 definitely not happen and let it continue without requiring a
374 passphrase. Given that now all the upper layers handle a
375 cancel correctly, we simply set the cancel flag now for all
376 errors from the agent. */
377 if (canceled)
378 *canceled = 1;
381 if (pk)
382 free_public_key( pk );
383 if (rc)
385 xfree (pw);
386 return NULL;
388 return pw;
393 * Clear the cached passphrase. If CACHEID is not NULL, it will be
394 * used instead of a cache ID derived from KEYID.
396 void
397 passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
399 int rc;
401 if (!cacheid)
403 PKT_public_key *pk;
404 # if MAX_FINGERPRINT_LEN < 20
405 # error agent needs a 20 byte fingerprint
406 # endif
407 byte fpr[MAX_FINGERPRINT_LEN];
408 char hexfprbuf[2*20+1];
409 size_t dummy;
411 pk = xcalloc (1, sizeof *pk);
412 if ( !keyid || get_pubkey( pk, keyid ) )
414 log_error ("key not found in passphrase_clear_cache\n");
415 free_public_key (pk);
416 return;
418 memset (fpr, 0, MAX_FINGERPRINT_LEN );
419 fingerprint_from_pk ( pk, fpr, &dummy );
420 bin2hex (fpr, 20, hexfprbuf);
421 rc = agent_clear_passphrase (hexfprbuf);
422 free_public_key ( pk );
424 else
425 rc = agent_clear_passphrase (cacheid);
427 if (rc)
428 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
432 /****************
433 * Ask for a passphrase and return that string.
435 char *
436 ask_passphrase (const char *description,
437 const char *tryagain_text,
438 const char *promptid,
439 const char *prompt,
440 const char *cacheid, int *canceled)
442 char *pw = NULL;
444 if (canceled)
445 *canceled = 0;
447 if (!opt.batch && description)
449 if (strchr (description, '%'))
451 char *tmp = unescape_percent_string (description);
452 tty_printf ("\n%s\n", tmp);
453 xfree (tmp);
455 else
456 tty_printf ("\n%s\n",description);
459 if (have_static_passphrase ())
461 pw = xmalloc_secure (strlen(fd_passwd)+1);
462 strcpy (pw, fd_passwd);
464 else
465 pw = passphrase_get (NULL, 0, cacheid,
466 tryagain_text, description, prompt,
467 canceled );
469 if (!pw || !*pw)
470 write_status( STATUS_MISSING_PASSPHRASE );
472 return pw;
476 /* Return a new DEK object Using the string-to-key sepcifier S2K. Use
477 KEYID and PUBKEY_ALGO to prompt the user. Returns NULL is the user
478 selected to cancel the passphrase entry and if CANCELED is not
479 NULL, sets it to true.
481 MODE 0: Allow cached passphrase
482 1: Ignore cached passphrase
483 2: Ditto, but change the text to "repeat entry"
485 DEK *
486 passphrase_to_dek (u32 *keyid, int pubkey_algo,
487 int cipher_algo, STRING2KEY *s2k, int mode,
488 const char *tryagain_text, int *canceled)
490 char *pw = NULL;
491 DEK *dek;
492 STRING2KEY help_s2k;
493 int dummy_canceled;
495 if (!canceled)
496 canceled = &dummy_canceled;
497 *canceled = 0;
499 if ( !s2k )
501 /* This is used for the old rfc1991 mode
502 * Note: This must match the code in encode.c with opt.rfc1991 set */
503 s2k = &help_s2k;
504 s2k->mode = 0;
505 s2k->hash_algo = S2K_DIGEST_ALGO;
508 /* If we do not have a passphrase available in NEXT_PW and status
509 information are request, we print them now. */
510 if ( !next_pw && is_status_enabled() )
512 char buf[50];
514 if ( keyid )
516 u32 used_kid[2];
517 char *us;
519 if ( keyid[2] && keyid[3] )
521 used_kid[0] = keyid[2];
522 used_kid[1] = keyid[3];
524 else
526 used_kid[0] = keyid[0];
527 used_kid[1] = keyid[1];
530 us = get_long_user_id_string ( keyid );
531 write_status_text ( STATUS_USERID_HINT, us );
532 xfree(us);
534 snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
535 (ulong)keyid[0], (ulong)keyid[1],
536 (ulong)used_kid[0], (ulong)used_kid[1],
537 pubkey_algo );
539 write_status_text ( STATUS_NEED_PASSPHRASE, buf );
541 else
543 snprintf (buf, sizeof buf -1, "%d %d %d",
544 cipher_algo, s2k->mode, s2k->hash_algo );
545 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
549 /* If we do have a keyID, we do not have a passphrase available in
550 NEXT_PW, we are not running in batch mode and we do not want to
551 ignore the passphrase cache (mode!=1), print a prompt with
552 information on that key. */
553 if ( keyid && !opt.batch && !next_pw && mode!=1 )
555 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
556 char *p;
558 p = get_user_id_native(keyid);
559 tty_printf ("\n");
560 tty_printf (_("You need a passphrase to unlock the secret key for\n"
561 "user: \"%s\"\n"),p);
562 xfree(p);
564 if ( !get_pubkey( pk, keyid ) )
566 const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
568 tty_printf (_("%u-bit %s key, ID %s, created %s"),
569 nbits_from_pk( pk ), s?s:"?", keystr(keyid),
570 strtimestamp(pk->timestamp) );
571 if ( keyid[2] && keyid[3]
572 && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
574 if ( keystrlen () > 10 )
576 tty_printf ("\n");
577 tty_printf (_(" (subkey on main key ID %s)"),
578 keystr(&keyid[2]) );
580 else
581 tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
583 tty_printf("\n");
586 tty_printf("\n");
587 if (pk)
588 free_public_key( pk );
591 if ( next_pw )
593 /* Simply return the passphrase we already have in NEXT_PW. */
594 pw = next_pw;
595 next_pw = NULL;
597 else if ( have_static_passphrase () )
599 /* Return the passphrase we have stored in FD_PASSWD. */
600 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
601 strcpy ( pw, fd_passwd );
603 else
605 /* Divert to the gpg-agent. */
606 pw = passphrase_get ( keyid, mode == 2? 1: 0, NULL,
607 tryagain_text, NULL, NULL, canceled );
608 if (*canceled)
610 xfree (pw);
611 write_status( STATUS_MISSING_PASSPHRASE );
612 return NULL;
614 if (!pw)
615 pw = xstrdup ("");
616 if ( *pw && mode == 2 )
618 int i;
619 for(i=0;i<opt.passwd_repeat;i++)
621 char *pw2 = passphrase_get ( keyid, 2, NULL, NULL, NULL,
622 NULL, canceled );
623 if (*canceled)
625 xfree (pw);
626 xfree (pw2);
627 write_status( STATUS_MISSING_PASSPHRASE );
628 return NULL;
630 if (!pw2)
631 pw2 = xstrdup ("");
632 if ( strcmp(pw, pw2) )
634 xfree(pw2);
635 xfree(pw);
636 return NULL;
638 xfree(pw2);
643 if ( !pw || !*pw )
644 write_status( STATUS_MISSING_PASSPHRASE );
646 /* Hash the passphrase and store it in a newly allocated DEK object.
647 Keep a copy of the passphrase in LAST_PW for use by
648 get_last_passphrase(). */
649 dek = xmalloc_secure_clear ( sizeof *dek );
650 dek->algo = cipher_algo;
651 if ( !*pw && mode == 2 )
652 dek->keylen = 0;
653 else
654 hash_passphrase( dek, pw, s2k, mode==2 );
655 xfree(last_pw);
656 last_pw = pw;
657 return dek;