agent/
[gnupg.git] / g10 / passphrase.c
blob9fddebf0e97fa7e08c942366fbea41d5f0c29d12
1 /* passphrase.c - Get a passphrase
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005, 2006, 2007, 2009 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.
54 Always needs: dek->algo, s2k->mode, s2k->hash_algo. */
55 static void
56 hash_passphrase ( DEK *dek, char *pw, STRING2KEY *s2k)
58 gcry_md_hd_t md;
59 int pass, i;
60 int used = 0;
61 int pwlen = strlen(pw);
63 assert ( s2k->hash_algo );
64 dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
65 if ( !(dek->keylen > 0 && dek->keylen <= DIM(dek->key)) )
66 BUG();
68 if (gcry_md_open (&md, s2k->hash_algo, 1))
69 BUG ();
70 for (pass=0; used < dek->keylen ; pass++ )
72 if ( pass )
74 gcry_md_reset (md);
75 for (i=0; i < pass; i++ ) /* Preset the hash context. */
76 gcry_md_putc (md, 0 );
79 if ( s2k->mode == 1 || s2k->mode == 3 )
81 int len2 = pwlen + 8;
82 ulong count = len2;
84 if ( s2k->mode == 3 )
86 count = S2K_DECODE_COUNT(s2k->count);
87 if ( count < len2 )
88 count = len2;
91 /* Fixme: To avoid DoS attacks by sending an sym-encrypted
92 packet with a very high S2K count, we should either cap
93 the iteration count or CPU seconds based timeout. */
95 /* A little bit complicated because we need a ulong for count. */
96 while ( count > len2 ) /* maybe iterated+salted */
98 gcry_md_write ( md, s2k->salt, 8 );
99 gcry_md_write ( md, pw, pwlen );
100 count -= len2;
102 if ( count < 8 )
103 gcry_md_write ( md, s2k->salt, count );
104 else
106 gcry_md_write ( md, s2k->salt, 8 );
107 count -= 8;
108 gcry_md_write ( md, pw, count );
111 else
112 gcry_md_write ( md, pw, pwlen );
113 gcry_md_final( md );
115 i = gcry_md_get_algo_dlen ( s2k->hash_algo );
116 if ( i > dek->keylen - used )
117 i = dek->keylen - used;
119 memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
120 used += i;
122 gcry_md_close(md);
128 have_static_passphrase()
130 return !!fd_passwd && opt.batch;
133 /****************
134 * Set the passphrase to be used for the next query and only for the next
135 * one.
137 void
138 set_next_passphrase( const char *s )
140 xfree(next_pw);
141 next_pw = NULL;
142 if ( s )
144 next_pw = xmalloc_secure( strlen(s)+1 );
145 strcpy (next_pw, s );
149 /****************
150 * Get the last passphrase used in passphrase_to_dek.
151 * Note: This removes the passphrase from this modules and
152 * the caller must free the result. May return NULL:
154 char *
155 get_last_passphrase()
157 char *p = last_pw;
158 last_pw = NULL;
159 return p;
162 /* As if we had used the passphrase - make it the last_pw. */
163 void
164 next_to_last_passphrase(void)
166 if (next_pw)
168 last_pw=next_pw;
169 next_pw=NULL;
173 /* Here's an interesting question: since this passphrase was passed in
174 on the command line, is there really any point in using secure
175 memory for it? I'm going with 'yes', since it doesn't hurt, and
176 might help in some small way (swapping). */
178 void
179 set_passphrase_from_string(const char *pass)
181 xfree (fd_passwd);
182 fd_passwd = xmalloc_secure(strlen(pass)+1);
183 strcpy (fd_passwd, pass);
187 void
188 read_passphrase_from_fd( int fd )
190 int i, len;
191 char *pw;
193 if ( !opt.batch )
194 { /* Not used but we have to do a dummy read, so that it won't end
195 up at the begin of the message if the quite usual trick to
196 prepend the passphtrase to the message is used. */
197 char buf[1];
199 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
201 *buf = 0;
202 return;
205 for (pw = NULL, i = len = 100; ; i++ )
207 if (i >= len-1 )
209 char *pw2 = pw;
210 len += 100;
211 pw = xmalloc_secure( len );
212 if( pw2 )
214 memcpy(pw, pw2, i );
215 xfree (pw2);
217 else
218 i=0;
220 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
221 break;
223 pw[i] = 0;
224 if (!opt.batch)
225 tty_printf("\b\b\b \n" );
227 xfree ( fd_passwd );
228 fd_passwd = pw;
233 * Ask the GPG Agent for the passphrase.
234 * Mode 0: Allow cached passphrase
235 * 1: No cached passphrase; that is we are asking for a new passphrase
236 * FIXME: Only partially implemented
238 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
239 * NULL, the function does set it to 1 if the user canceled the
240 * operation. If CACHEID is not NULL, it will be used as the cacheID
241 * for the gpg-agent; if is NULL and a key fingerprint can be
242 * computed, this will be used as the cacheid.
244 static char *
245 passphrase_get ( u32 *keyid, int mode, const char *cacheid, int repeat,
246 const char *tryagain_text,
247 const char *custom_description,
248 const char *custom_prompt, int *canceled)
250 int rc;
251 char *atext = NULL;
252 char *pw = NULL;
253 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
254 byte fpr[MAX_FINGERPRINT_LEN];
255 int have_fpr = 0;
256 char *orig_codeset;
257 char *my_prompt;
258 char hexfprbuf[20*2+1];
259 const char *my_cacheid;
260 int check = (mode == 1);
262 if (canceled)
263 *canceled = 0;
265 #if MAX_FINGERPRINT_LEN < 20
266 #error agent needs a 20 byte fingerprint
267 #endif
269 memset (fpr, 0, MAX_FINGERPRINT_LEN );
270 if( keyid && get_pubkey( pk, keyid ) )
272 if (pk)
273 free_public_key( pk );
274 pk = NULL; /* oops: no key for some reason */
277 orig_codeset = i18n_switchto_utf8 ();
279 if (custom_description)
280 atext = native_to_utf8 (custom_description);
281 else if ( !mode && pk && keyid )
283 char *uid;
284 size_t uidlen;
285 const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
286 const char *timestr;
287 char *maink;
289 if ( !algo_name )
290 algo_name = "?";
292 #define KEYIDSTRING _(" (main key ID %s)")
294 maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
295 if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
296 && keyid[1] != keyid[3] )
297 sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
298 else
299 *maink = 0;
301 uid = get_user_id ( keyid, &uidlen );
302 timestr = strtimestamp (pk->timestamp);
304 #undef KEYIDSTRING
306 #define PROMPTSTRING _("Please enter the passphrase to unlock the" \
307 " secret key for the OpenPGP certificate:\n" \
308 "\"%.*s\"\n" \
309 "%u-bit %s key, ID %s,\n" \
310 "created %s%s.\n" )
312 atext = xmalloc ( 100 + strlen (PROMPTSTRING)
313 + uidlen + 15 + strlen(algo_name) + keystrlen()
314 + strlen (timestr) + strlen (maink) );
315 sprintf (atext, PROMPTSTRING,
316 (int)uidlen, uid,
317 nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
318 maink );
319 xfree (uid);
320 xfree (maink);
322 #undef PROMPTSTRING
325 size_t dummy;
326 fingerprint_from_pk( pk, fpr, &dummy );
327 have_fpr = 1;
331 else
332 atext = xstrdup ( _("Enter passphrase\n") );
335 if (!mode && cacheid)
336 my_cacheid = cacheid;
337 else if (!mode && have_fpr)
338 my_cacheid = bin2hex (fpr, 20, hexfprbuf);
339 else
340 my_cacheid = NULL;
342 if (tryagain_text)
343 tryagain_text = _(tryagain_text);
345 my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
347 rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext,
348 repeat, check, &pw);
350 xfree (my_prompt);
351 xfree (atext); atext = NULL;
353 i18n_switchback (orig_codeset);
356 if (!rc)
358 else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
360 log_info (_("cancelled by user\n") );
361 if (canceled)
362 *canceled = 1;
364 else
366 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
367 /* Due to limitations in the API of the upper layers they
368 consider an error as no passphrase entered. This works in
369 most cases but not during key creation where this should
370 definitely not happen and let it continue without requiring a
371 passphrase. Given that now all the upper layers handle a
372 cancel correctly, we simply set the cancel flag now for all
373 errors from the agent. */
374 if (canceled)
375 *canceled = 1;
377 write_status_error ("get_passphrase", rc);
380 if (pk)
381 free_public_key( pk );
382 if (rc)
384 xfree (pw);
385 return NULL;
387 return pw;
392 * Clear the cached passphrase. If CACHEID is not NULL, it will be
393 * used instead of a cache ID derived from KEYID.
395 void
396 passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
398 int rc;
400 (void)algo;
402 if (!cacheid)
404 PKT_public_key *pk;
405 # if MAX_FINGERPRINT_LEN < 20
406 # error agent needs a 20 byte fingerprint
407 # endif
408 byte fpr[MAX_FINGERPRINT_LEN];
409 char hexfprbuf[2*20+1];
410 size_t dummy;
412 pk = xcalloc (1, sizeof *pk);
413 if ( !keyid || get_pubkey( pk, keyid ) )
415 log_error ("key not found in passphrase_clear_cache\n");
416 free_public_key (pk);
417 return;
419 memset (fpr, 0, MAX_FINGERPRINT_LEN );
420 fingerprint_from_pk ( pk, fpr, &dummy );
421 bin2hex (fpr, 20, hexfprbuf);
422 rc = agent_clear_passphrase (hexfprbuf);
423 free_public_key ( pk );
425 else
426 rc = agent_clear_passphrase (cacheid);
428 if (rc)
429 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
433 /* Return a new DEK object Using the string-to-key sepcifier S2K. Use
434 KEYID and PUBKEY_ALGO to prompt the user. Returns NULL is the user
435 selected to cancel the passphrase entry and if CANCELED is not
436 NULL, sets it to true.
438 MODE 0: Allow cached passphrase
439 1: Ignore cached passphrase
440 2: Ditto, but create a new key
441 3: Allow cached passphrase; use the S2K salt as the cache ID
442 4: Ditto, but create a new key
444 DEK *
445 passphrase_to_dek_ext (u32 *keyid, int pubkey_algo,
446 int cipher_algo, STRING2KEY *s2k, int mode,
447 const char *tryagain_text,
448 const char *custdesc, const char *custprompt,
449 int *canceled)
451 char *pw = NULL;
452 DEK *dek;
453 STRING2KEY help_s2k;
454 int dummy_canceled;
455 char s2k_cacheidbuf[1+16+1], *s2k_cacheid = NULL;
457 if (!canceled)
458 canceled = &dummy_canceled;
459 *canceled = 0;
461 if ( !s2k )
463 assert (mode != 3 && mode != 4);
464 /* This is used for the old rfc1991 mode
465 * Note: This must match the code in encode.c with opt.rfc1991 set */
466 s2k = &help_s2k;
467 s2k->mode = 0;
468 s2k->hash_algo = S2K_DIGEST_ALGO;
471 /* Create a new salt or what else to be filled into the s2k for a
472 new key. */
473 if ((mode == 2 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
475 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
476 if ( s2k->mode == 3 )
477 s2k->count = opt.s2k_count;
480 /* If we do not have a passphrase available in NEXT_PW and status
481 information are request, we print them now. */
482 if ( !next_pw && is_status_enabled() )
484 char buf[50];
486 if ( keyid )
488 u32 used_kid[2];
489 char *us;
491 if ( keyid[2] && keyid[3] )
493 used_kid[0] = keyid[2];
494 used_kid[1] = keyid[3];
496 else
498 used_kid[0] = keyid[0];
499 used_kid[1] = keyid[1];
502 us = get_long_user_id_string ( keyid );
503 write_status_text ( STATUS_USERID_HINT, us );
504 xfree(us);
506 snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
507 (ulong)keyid[0], (ulong)keyid[1],
508 (ulong)used_kid[0], (ulong)used_kid[1],
509 pubkey_algo );
511 write_status_text ( STATUS_NEED_PASSPHRASE, buf );
513 else
515 snprintf (buf, sizeof buf -1, "%d %d %d",
516 cipher_algo, s2k->mode, s2k->hash_algo );
517 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
521 /* If we do have a keyID, we do not have a passphrase available in
522 NEXT_PW, we are not running in batch mode and we do not want to
523 ignore the passphrase cache (mode!=1), print a prompt with
524 information on that key. */
525 if ( keyid && !opt.batch && !next_pw && mode!=1 )
527 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
528 char *p;
530 p = get_user_id_native(keyid);
531 tty_printf ("\n");
532 tty_printf (_("You need a passphrase to unlock the secret key for\n"
533 "user: \"%s\"\n"),p);
534 xfree(p);
536 if ( !get_pubkey( pk, keyid ) )
538 const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
540 tty_printf (_("%u-bit %s key, ID %s, created %s"),
541 nbits_from_pk( pk ), s?s:"?", keystr(keyid),
542 strtimestamp(pk->timestamp) );
543 if ( keyid[2] && keyid[3]
544 && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
546 if ( keystrlen () > 10 )
548 tty_printf ("\n");
549 tty_printf (_(" (subkey on main key ID %s)"),
550 keystr(&keyid[2]) );
552 else
553 tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
555 tty_printf("\n");
558 tty_printf("\n");
559 if (pk)
560 free_public_key( pk );
563 if ( next_pw )
565 /* Simply return the passphrase we already have in NEXT_PW. */
566 pw = next_pw;
567 next_pw = NULL;
569 else if ( have_static_passphrase () )
571 /* Return the passphrase we have stored in FD_PASSWD. */
572 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
573 strcpy ( pw, fd_passwd );
575 else
577 if ((mode == 3 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
579 memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
580 *s2k_cacheidbuf = 'S';
581 bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
582 s2k_cacheid = s2k_cacheidbuf;
585 /* Divert to the gpg-agent. */
586 pw = passphrase_get (keyid, mode == 2, s2k_cacheid,
587 (mode == 2 || mode == 4)? opt.passwd_repeat : 0,
588 tryagain_text, custdesc, custprompt, canceled);
589 if (*canceled)
591 xfree (pw);
592 write_status( STATUS_MISSING_PASSPHRASE );
593 return NULL;
597 if ( !pw || !*pw )
598 write_status( STATUS_MISSING_PASSPHRASE );
600 /* Hash the passphrase and store it in a newly allocated DEK object.
601 Keep a copy of the passphrase in LAST_PW for use by
602 get_last_passphrase(). */
603 dek = xmalloc_secure_clear ( sizeof *dek );
604 dek->algo = cipher_algo;
605 if ( (!pw || !*pw) && (mode == 2 || mode == 4))
606 dek->keylen = 0;
607 else
608 hash_passphrase (dek, pw, s2k);
609 if (s2k_cacheid)
610 memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
611 xfree(last_pw);
612 last_pw = pw;
613 return dek;
617 DEK *
618 passphrase_to_dek (u32 *keyid, int pubkey_algo,
619 int cipher_algo, STRING2KEY *s2k, int mode,
620 const char *tryagain_text, int *canceled)
622 return passphrase_to_dek_ext (keyid, pubkey_algo, cipher_algo,
623 s2k, mode, tryagain_text, NULL, NULL,
624 canceled);