chiark / gitweb /
g10: avoid warning when --disable-tofu
[gnupg2.git] / g10 / passphrase.c
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.
4  *
5  * This file is part of GnuPG.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
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 <errno.h>
28 #ifdef HAVE_LOCALE_H
29 #include <locale.h>
30 #endif
31 #ifdef HAVE_LANGINFO_CODESET
32 #include <langinfo.h>
33 #endif
34
35 #include "gpg.h"
36 #include "util.h"
37 #include "options.h"
38 #include "ttyio.h"
39 #include "keydb.h"
40 #include "main.h"
41 #include "i18n.h"
42 #include "status.h"
43 #include "call-agent.h"
44 #include "../common/shareddefs.h"
45
46 static char *fd_passwd = NULL;
47 static char *next_pw = NULL;
48 static char *last_pw = NULL;
49
50
51
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
54    old default.  */
55 unsigned char
56 encode_s2k_iterations (int iterations)
57 {
58   gpg_error_t err;
59   unsigned char c=0;
60   unsigned char result;
61   unsigned int count;
62
63   if (!iterations)
64     {
65       unsigned long mycnt;
66
67       /* Ask the gpg-agent for a useful iteration count.  */
68       err = agent_get_s2k_count (&mycnt);
69       if (err || mycnt < 65536)
70         {
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.  */
75           return 96;
76         }
77       else if (mycnt >= 65011712)
78         return 255; /* Largest possible value.  */
79       else
80         return encode_s2k_iterations ((int)mycnt);
81     }
82
83   if (iterations <= 1024)
84     return 0;  /* Command line arg compatibility.  */
85
86   if (iterations >= 65011712)
87     return 255;
88
89   /* Need count to be in the range 16-31 */
90   for (count=iterations>>6; count>=32; count>>=1)
91     c++;
92
93   result = (c<<4)|(count-16);
94
95   if (S2K_DECODE_COUNT(result) < iterations)
96     result++;
97
98   return result;
99 }
100
101
102 int
103 have_static_passphrase()
104 {
105   return (!!fd_passwd
106           && (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
107 }
108
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.  */
113 const char *
114 get_static_passphrase (void)
115 {
116   return fd_passwd;
117 }
118
119
120 /****************
121  * Set the passphrase to be used for the next query and only for the next
122  * one.
123  */
124 void
125 set_next_passphrase( const char *s )
126 {
127   xfree(next_pw);
128   next_pw = NULL;
129   if ( s )
130     {
131       next_pw = xmalloc_secure( strlen(s)+1 );
132       strcpy (next_pw, s );
133     }
134 }
135
136 /****************
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:
140  */
141 char *
142 get_last_passphrase()
143 {
144   char *p = last_pw;
145   last_pw = NULL;
146   return p;
147 }
148
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). */
153
154 void
155 set_passphrase_from_string(const char *pass)
156 {
157   xfree (fd_passwd);
158   fd_passwd = xmalloc_secure(strlen(pass)+1);
159   strcpy (fd_passwd, pass);
160 }
161
162
163 void
164 read_passphrase_from_fd( int fd )
165 {
166   int i, len;
167   char *pw;
168
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. */
173       char buf[1];
174
175       while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
176         ;
177       *buf = 0;
178       return;
179     }
180
181   for (pw = NULL, i = len = 100; ; i++ )
182     {
183       if (i >= len-1 )
184         {
185           char *pw2 = pw;
186           len += 100;
187           pw = xmalloc_secure( len );
188           if( pw2 )
189             {
190               memcpy(pw, pw2, i );
191               xfree (pw2);
192             }
193           else
194             i=0;
195         }
196       if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
197         break;
198     }
199   pw[i] = 0;
200   if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
201     tty_printf("\b\b\b   \n" );
202
203   xfree ( fd_passwd );
204   fd_passwd = pw;
205 }
206
207
208 /*
209  * Ask the GPG Agent for the passphrase.
210  * If NOCACHE is set the symmetric passpharse caching will not be used.
211  *
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.
217  */
218 static char *
219 passphrase_get (int nocache, const char *cacheid, int repeat,
220                 const char *tryagain_text, int *canceled)
221 {
222   int rc;
223   char *pw = NULL;
224   char *orig_codeset;
225   const char *my_cacheid;
226
227   if (canceled)
228     *canceled = 0;
229
230   orig_codeset = i18n_switchto_utf8 ();
231
232   if (!nocache && cacheid)
233     my_cacheid = cacheid;
234   else
235     my_cacheid = NULL;
236
237   if (tryagain_text)
238     tryagain_text = _(tryagain_text);
239
240   rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
241                              _("Enter passphrase\n"),
242                              repeat, nocache, &pw);
243
244   i18n_switchback (orig_codeset);
245
246
247   if (!rc)
248     ;
249   else if (gpg_err_code (rc) == GPG_ERR_CANCELED
250             || gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
251     {
252       log_info (_("cancelled by user\n") );
253       if (canceled)
254         *canceled = 1;
255     }
256   else
257     {
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.  */
266       if (canceled)
267         *canceled = 1;
268
269       write_status_errcode ("get_passphrase", rc);
270     }
271
272   if (rc)
273     {
274       xfree (pw);
275       pw = NULL;
276     }
277   return pw;
278 }
279
280
281 /*
282  * Clear the cached passphrase with CACHEID.
283  */
284 void
285 passphrase_clear_cache (const char *cacheid)
286 {
287   int rc;
288
289   rc = agent_clear_passphrase (cacheid);
290   if (rc)
291     log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
292 }
293
294
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.
298  *
299  * If CREATE is true a new passphrase sll be created.  If NOCACHE is
300  * true the symmetric key caching will not be used.  */
301 DEK *
302 passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
303                    int create, int nocache,
304                    const char *tryagain_text, int *canceled)
305 {
306   char *pw = NULL;
307   DEK *dek;
308   STRING2KEY help_s2k;
309   int dummy_canceled;
310   char s2k_cacheidbuf[1+16+1];
311   char *s2k_cacheid = NULL;
312
313   if (!canceled)
314     canceled = &dummy_canceled;
315   *canceled = 0;
316
317   if ( !s2k )
318     {
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));
323       s2k = &help_s2k;
324       s2k->hash_algo = S2K_DIGEST_ALGO;
325     }
326
327   /* Create a new salt or what else to be filled into the s2k for a
328      new key.  */
329   if (create && (s2k->mode == 1 || s2k->mode == 3))
330     {
331       gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
332       if ( s2k->mode == 3 )
333         {
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().  */
338           if (!opt.s2k_count)
339             opt.s2k_count = encode_s2k_iterations (0);
340           s2k->count = opt.s2k_count;
341         }
342     }
343
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() )
347     {
348       char buf[50];
349
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 );
353     }
354
355   if ( next_pw )
356     {
357       /* Simply return the passphrase we already have in NEXT_PW. */
358       pw = next_pw;
359       next_pw = NULL;
360     }
361   else if ( have_static_passphrase () )
362     {
363       /* Return the passphrase we have stored in FD_PASSWD. */
364       pw = xmalloc_secure ( strlen(fd_passwd)+1 );
365       strcpy ( pw, fd_passwd );
366     }
367   else
368     {
369       if (!nocache && (s2k->mode == 1 || s2k->mode == 3))
370         {
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;
375         }
376
377       if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
378         {
379           char buf[32];
380
381           snprintf (buf, sizeof (buf), "%u", 100);
382           write_status_text (STATUS_INQUIRE_MAXLEN, buf);
383         }
384
385       /* Divert to the gpg-agent. */
386       pw = passphrase_get (create && nocache, s2k_cacheid,
387                            create? opt.passphrase_repeat : 0,
388                            tryagain_text, canceled);
389       if (*canceled)
390         {
391           xfree (pw);
392           write_status( STATUS_MISSING_PASSPHRASE );
393           return NULL;
394         }
395     }
396
397   if ( !pw || !*pw )
398     write_status( STATUS_MISSING_PASSPHRASE );
399
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)
406     dek->keylen = 0;
407   else
408     {
409       gpg_error_t err;
410
411       dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
412       if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
413         BUG ();
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);
421       if (err)
422         {
423           log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
424           xfree (pw);
425           xfree (dek);
426           write_status( STATUS_MISSING_PASSPHRASE );
427           return NULL;
428         }
429     }
430   if (s2k_cacheid)
431     memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
432   xfree(last_pw);
433   last_pw = pw;
434   return dek;
435 }
436
437
438 /* Emit the USERID_HINT and the NEED_PASSPHRASE status messages.
439    MAINKEYID may be NULL. */
440 void
441 emit_status_need_passphrase (u32 *keyid, u32 *mainkeyid, int pubkey_algo)
442 {
443   char buf[50];
444   char *us;
445
446   us = get_long_user_id_string (keyid);
447   write_status_text (STATUS_USERID_HINT, us);
448   xfree (us);
449
450   snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
451             (ulong)keyid[0],
452             (ulong)keyid[1],
453             (ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
454             (ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
455             pubkey_algo);
456
457   write_status_text (STATUS_NEED_PASSPHRASE, buf);
458 }
459
460
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. */
465 char *
466 gpg_format_keydesc (PKT_public_key *pk, int mode, int escaped)
467 {
468   char *uid;
469   size_t uidlen;
470   const char *algo_name;
471   const char *timestr;
472   char *orig_codeset;
473   char *maink;
474   char *desc;
475   const char *prompt;
476   const char *trailer = "";
477   int is_subkey;
478
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);
485
486   orig_codeset = i18n_switchto_utf8 ();
487
488   if (is_subkey)
489     maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
490   else
491     maink = NULL;
492
493   switch (mode)
494     {
495     case FORMAT_KEYDESC_NORMAL:
496       prompt = _("Please enter the passphrase to unlock the"
497                  " OpenPGP secret key:");
498       break;
499     case FORMAT_KEYDESC_IMPORT:
500       prompt = _("Please enter the passphrase to import the"
501                  " OpenPGP secret key:");
502       break;
503     case FORMAT_KEYDESC_EXPORT:
504       if (is_subkey)
505         prompt = _("Please enter the passphrase to export the"
506                    " OpenPGP secret subkey:");
507       else
508         prompt = _("Please enter the passphrase to export the"
509                    " OpenPGP secret key:");
510       break;
511     case FORMAT_KEYDESC_DELKEY:
512       if (is_subkey)
513         prompt = _("Do you really want to permanently delete the"
514                    " OpenPGP secret subkey key:");
515       else
516         prompt = _("Do you really want to permanently delete the"
517                    " OpenPGP secret key:");
518       trailer = "?";
519       break;
520     default:
521       prompt = "?";
522       break;
523     }
524
525   desc = xtryasprintf (_("%s\n"
526                          "\"%.*s\"\n"
527                          "%u-bit %s key, ID %s,\n"
528                          "created %s%s.\n%s"),
529                        prompt,
530                        (int)uidlen, uid,
531                        nbits_from_pk (pk), algo_name,
532                        keystr (pk->keyid), timestr,
533                        maink?maink:"", trailer);
534   xfree (maink);
535   xfree (uid);
536
537   i18n_switchback (orig_codeset);
538
539   if (escaped)
540     {
541       char *tmp = percent_plus_escape (desc);
542       xfree (desc);
543       desc = tmp;
544     }
545
546   return desc;
547 }