New gpgsm server option no-encrypt-to.
[gnupg.git] / g10 / passphrase.c
blob84eedc21175fa2f4a0c1499aa39051f51c0a3c10
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.
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 = gcry_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 /* A little bit complicated because we need a ulong for count. */
92 while ( count > len2 ) /* maybe iterated+salted */
94 gcry_md_write ( md, s2k->salt, 8 );
95 gcry_md_write ( md, pw, pwlen );
96 count -= len2;
98 if ( count < 8 )
99 gcry_md_write ( md, s2k->salt, count );
100 else
102 gcry_md_write ( md, s2k->salt, 8 );
103 count -= 8;
104 gcry_md_write ( md, pw, count );
107 else
108 gcry_md_write ( md, pw, pwlen );
109 gcry_md_final( md );
111 i = gcry_md_get_algo_dlen ( s2k->hash_algo );
112 if ( i > dek->keylen - used )
113 i = dek->keylen - used;
115 memcpy (dek->key+used, gcry_md_read (md, s2k->hash_algo), i);
116 used += i;
118 gcry_md_close(md);
124 have_static_passphrase()
126 return !!fd_passwd && opt.batch;
129 /****************
130 * Set the passphrase to be used for the next query and only for the next
131 * one.
133 void
134 set_next_passphrase( const char *s )
136 xfree(next_pw);
137 next_pw = NULL;
138 if ( s )
140 next_pw = xmalloc_secure( strlen(s)+1 );
141 strcpy (next_pw, s );
145 /****************
146 * Get the last passphrase used in passphrase_to_dek.
147 * Note: This removes the passphrase from this modules and
148 * the caller must free the result. May return NULL:
150 char *
151 get_last_passphrase()
153 char *p = last_pw;
154 last_pw = NULL;
155 return p;
158 /* As if we had used the passphrase - make it the last_pw. */
159 void
160 next_to_last_passphrase(void)
162 if (next_pw)
164 last_pw=next_pw;
165 next_pw=NULL;
169 /* Here's an interesting question: since this passphrase was passed in
170 on the command line, is there really any point in using secure
171 memory for it? I'm going with 'yes', since it doesn't hurt, and
172 might help in some small way (swapping). */
174 void
175 set_passphrase_from_string(const char *pass)
177 xfree (fd_passwd);
178 fd_passwd = xmalloc_secure(strlen(pass)+1);
179 strcpy (fd_passwd, pass);
183 void
184 read_passphrase_from_fd( int fd )
186 int i, len;
187 char *pw;
189 if ( !opt.batch )
190 { /* Not used but we have to do a dummy read, so that it won't end
191 up at the begin of the message if the quite usual trick to
192 prepend the passphtrase to the message is used. */
193 char buf[1];
195 while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
197 *buf = 0;
198 return;
201 for (pw = NULL, i = len = 100; ; i++ )
203 if (i >= len-1 )
205 char *pw2 = pw;
206 len += 100;
207 pw = xmalloc_secure( len );
208 if( pw2 )
210 memcpy(pw, pw2, i );
211 xfree (pw2);
213 else
214 i=0;
216 if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
217 break;
219 pw[i] = 0;
220 if (!opt.batch)
221 tty_printf("\b\b\b \n" );
223 xfree ( fd_passwd );
224 fd_passwd = pw;
229 * Ask the GPG Agent for the passphrase.
230 * Mode 0: Allow cached passphrase
231 * 1: No cached passphrase; that is we are asking for a new passphrase
232 * FIXME: Only partially implemented
234 * Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
235 * NULL, the function does set it to 1 if the user canceled the
236 * operation. If CACHEID is not NULL, it will be used as the cacheID
237 * for the gpg-agent; if is NULL and a key fingerprint can be
238 * computed, this will be used as the cacheid.
240 static char *
241 passphrase_get ( u32 *keyid, int mode, const char *cacheid, int repeat,
242 const char *tryagain_text,
243 const char *custom_description,
244 const char *custom_prompt, int *canceled)
246 int rc;
247 char *atext = NULL;
248 char *pw = NULL;
249 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
250 byte fpr[MAX_FINGERPRINT_LEN];
251 int have_fpr = 0;
252 char *orig_codeset;
253 char *my_prompt;
254 char hexfprbuf[20*2+1];
255 const char *my_cacheid;
256 int check = (mode == 1);
258 if (canceled)
259 *canceled = 0;
261 #if MAX_FINGERPRINT_LEN < 20
262 #error agent needs a 20 byte fingerprint
263 #endif
265 memset (fpr, 0, MAX_FINGERPRINT_LEN );
266 if( keyid && get_pubkey( pk, keyid ) )
268 if (pk)
269 free_public_key( pk );
270 pk = NULL; /* oops: no key for some reason */
273 orig_codeset = i18n_switchto_utf8 ();
275 if (custom_description)
276 atext = native_to_utf8 (custom_description);
277 else if ( !mode && pk && keyid )
279 char *uid;
280 size_t uidlen;
281 const char *algo_name = gcry_pk_algo_name ( pk->pubkey_algo );
282 const char *timestr;
283 char *maink;
285 if ( !algo_name )
286 algo_name = "?";
288 #define KEYIDSTRING _(" (main key ID %s)")
290 maink = xmalloc ( strlen (KEYIDSTRING) + keystrlen() + 20 );
291 if( keyid[2] && keyid[3] && keyid[0] != keyid[2]
292 && keyid[1] != keyid[3] )
293 sprintf( maink, KEYIDSTRING, keystr(&keyid[2]) );
294 else
295 *maink = 0;
297 uid = get_user_id ( keyid, &uidlen );
298 timestr = strtimestamp (pk->timestamp);
300 #undef KEYIDSTRING
302 #define PROMPTSTRING _("Please enter the passphrase to unlock the" \
303 " secret key for the OpenPGP certificate:\n" \
304 "\"%.*s\"\n" \
305 "%u-bit %s key, ID %s,\n" \
306 "created %s%s.\n" )
308 atext = xmalloc ( 100 + strlen (PROMPTSTRING)
309 + uidlen + 15 + strlen(algo_name) + keystrlen()
310 + strlen (timestr) + strlen (maink) );
311 sprintf (atext, PROMPTSTRING,
312 (int)uidlen, uid,
313 nbits_from_pk (pk), algo_name, keystr(&keyid[0]), timestr,
314 maink );
315 xfree (uid);
316 xfree (maink);
318 #undef PROMPTSTRING
321 size_t dummy;
322 fingerprint_from_pk( pk, fpr, &dummy );
323 have_fpr = 1;
327 else
328 atext = xstrdup ( _("Enter passphrase\n") );
331 if (!mode && cacheid)
332 my_cacheid = cacheid;
333 else if (!mode && have_fpr)
334 my_cacheid = bin2hex (fpr, 20, hexfprbuf);
335 else
336 my_cacheid = NULL;
338 if (tryagain_text)
339 tryagain_text = _(tryagain_text);
341 my_prompt = custom_prompt ? native_to_utf8 (custom_prompt): NULL;
343 rc = agent_get_passphrase (my_cacheid, tryagain_text, my_prompt, atext,
344 repeat, check, &pw);
346 xfree (my_prompt);
347 xfree (atext); atext = NULL;
349 i18n_switchback (orig_codeset);
352 if (!rc)
354 else if ( gpg_err_code (rc) == GPG_ERR_CANCELED )
356 log_info (_("cancelled by user\n") );
357 if (canceled)
358 *canceled = 1;
360 else
362 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
363 /* Due to limitations in the API of the upper layers they
364 consider an error as no passphrase entered. This works in
365 most cases but not during key creation where this should
366 definitely not happen and let it continue without requiring a
367 passphrase. Given that now all the upper layers handle a
368 cancel correctly, we simply set the cancel flag now for all
369 errors from the agent. */
370 if (canceled)
371 *canceled = 1;
373 write_status_error ("get_passphrase", rc);
376 if (pk)
377 free_public_key( pk );
378 if (rc)
380 xfree (pw);
381 return NULL;
383 return pw;
388 * Clear the cached passphrase. If CACHEID is not NULL, it will be
389 * used instead of a cache ID derived from KEYID.
391 void
392 passphrase_clear_cache ( u32 *keyid, const char *cacheid, int algo )
394 int rc;
396 (void)algo;
398 if (!cacheid)
400 PKT_public_key *pk;
401 # if MAX_FINGERPRINT_LEN < 20
402 # error agent needs a 20 byte fingerprint
403 # endif
404 byte fpr[MAX_FINGERPRINT_LEN];
405 char hexfprbuf[2*20+1];
406 size_t dummy;
408 pk = xcalloc (1, sizeof *pk);
409 if ( !keyid || get_pubkey( pk, keyid ) )
411 log_error ("key not found in passphrase_clear_cache\n");
412 free_public_key (pk);
413 return;
415 memset (fpr, 0, MAX_FINGERPRINT_LEN );
416 fingerprint_from_pk ( pk, fpr, &dummy );
417 bin2hex (fpr, 20, hexfprbuf);
418 rc = agent_clear_passphrase (hexfprbuf);
419 free_public_key ( pk );
421 else
422 rc = agent_clear_passphrase (cacheid);
424 if (rc)
425 log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
429 /* Return a new DEK object Using the string-to-key sepcifier S2K. Use
430 KEYID and PUBKEY_ALGO to prompt the user. Returns NULL is the user
431 selected to cancel the passphrase entry and if CANCELED is not
432 NULL, sets it to true.
434 MODE 0: Allow cached passphrase
435 1: Ignore cached passphrase
436 2: Ditto, but create a new key
437 3: Allow cached passphrase; use the S2K salt as the cache ID
438 4: Ditto, but create a new key
440 DEK *
441 passphrase_to_dek_ext (u32 *keyid, int pubkey_algo,
442 int cipher_algo, STRING2KEY *s2k, int mode,
443 const char *tryagain_text,
444 const char *custdesc, const char *custprompt,
445 int *canceled)
447 char *pw = NULL;
448 DEK *dek;
449 STRING2KEY help_s2k;
450 int dummy_canceled;
452 if (!canceled)
453 canceled = &dummy_canceled;
454 *canceled = 0;
456 if ( !s2k )
458 assert (mode != 3 && mode != 4);
459 /* This is used for the old rfc1991 mode
460 * Note: This must match the code in encode.c with opt.rfc1991 set */
461 s2k = &help_s2k;
462 s2k->mode = 0;
463 s2k->hash_algo = S2K_DIGEST_ALGO;
466 /* Create a new salt or what else to be filled into the s2k for a
467 new key. */
468 if ((mode == 2 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
470 gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
471 if ( s2k->mode == 3 )
472 s2k->count = opt.s2k_count;
475 /* If we do not have a passphrase available in NEXT_PW and status
476 information are request, we print them now. */
477 if ( !next_pw && is_status_enabled() )
479 char buf[50];
481 if ( keyid )
483 u32 used_kid[2];
484 char *us;
486 if ( keyid[2] && keyid[3] )
488 used_kid[0] = keyid[2];
489 used_kid[1] = keyid[3];
491 else
493 used_kid[0] = keyid[0];
494 used_kid[1] = keyid[1];
497 us = get_long_user_id_string ( keyid );
498 write_status_text ( STATUS_USERID_HINT, us );
499 xfree(us);
501 snprintf (buf, sizeof buf -1, "%08lX%08lX %08lX%08lX %d 0",
502 (ulong)keyid[0], (ulong)keyid[1],
503 (ulong)used_kid[0], (ulong)used_kid[1],
504 pubkey_algo );
506 write_status_text ( STATUS_NEED_PASSPHRASE, buf );
508 else
510 snprintf (buf, sizeof buf -1, "%d %d %d",
511 cipher_algo, s2k->mode, s2k->hash_algo );
512 write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
516 /* If we do have a keyID, we do not have a passphrase available in
517 NEXT_PW, we are not running in batch mode and we do not want to
518 ignore the passphrase cache (mode!=1), print a prompt with
519 information on that key. */
520 if ( keyid && !opt.batch && !next_pw && mode!=1 )
522 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
523 char *p;
525 p = get_user_id_native(keyid);
526 tty_printf ("\n");
527 tty_printf (_("You need a passphrase to unlock the secret key for\n"
528 "user: \"%s\"\n"),p);
529 xfree(p);
531 if ( !get_pubkey( pk, keyid ) )
533 const char *s = gcry_pk_algo_name ( pk->pubkey_algo );
535 tty_printf (_("%u-bit %s key, ID %s, created %s"),
536 nbits_from_pk( pk ), s?s:"?", keystr(keyid),
537 strtimestamp(pk->timestamp) );
538 if ( keyid[2] && keyid[3]
539 && keyid[0] != keyid[2] && keyid[1] != keyid[3] )
541 if ( keystrlen () > 10 )
543 tty_printf ("\n");
544 tty_printf (_(" (subkey on main key ID %s)"),
545 keystr(&keyid[2]) );
547 else
548 tty_printf ( _(" (main key ID %s)"), keystr(&keyid[2]) );
550 tty_printf("\n");
553 tty_printf("\n");
554 if (pk)
555 free_public_key( pk );
558 if ( next_pw )
560 /* Simply return the passphrase we already have in NEXT_PW. */
561 pw = next_pw;
562 next_pw = NULL;
564 else if ( have_static_passphrase () )
566 /* Return the passphrase we have stored in FD_PASSWD. */
567 pw = xmalloc_secure ( strlen(fd_passwd)+1 );
568 strcpy ( pw, fd_passwd );
570 else
572 char *cacheid = NULL;
573 char buf[1+16+1];
575 if ((mode == 3 || mode == 4) && (s2k->mode == 1 || s2k->mode == 3))
577 memset (buf, 0, sizeof buf);
578 *buf = 'S';
579 bin2hex (s2k->salt, 8, buf + 1);
580 cacheid = buf;
583 /* Divert to the gpg-agent. */
584 pw = passphrase_get (keyid, mode == 2, cacheid,
585 (mode == 2 || mode == 4)? opt.passwd_repeat : 0,
586 tryagain_text, custdesc, custprompt, canceled);
587 if (*canceled)
589 xfree (pw);
590 write_status( STATUS_MISSING_PASSPHRASE );
591 return NULL;
595 if ( !pw || !*pw )
596 write_status( STATUS_MISSING_PASSPHRASE );
598 /* Hash the passphrase and store it in a newly allocated DEK object.
599 Keep a copy of the passphrase in LAST_PW for use by
600 get_last_passphrase(). */
601 dek = xmalloc_secure_clear ( sizeof *dek );
602 dek->algo = cipher_algo;
603 if ( !*pw && (mode == 2 || mode == 4))
604 dek->keylen = 0;
605 else
606 hash_passphrase (dek, pw, s2k);
607 xfree(last_pw);
608 last_pw = pw;
609 return dek;
613 DEK *
614 passphrase_to_dek (u32 *keyid, int pubkey_algo,
615 int cipher_algo, STRING2KEY *s2k, int mode,
616 const char *tryagain_text, int *canceled)
618 return passphrase_to_dek_ext (keyid, pubkey_algo, cipher_algo,
619 s2k, mode, tryagain_text, NULL, NULL,
620 canceled);