Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/passphrase.c
Line
Count
Source
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 "../common/util.h"
37
#include "options.h"
38
#include "../common/ttyio.h"
39
#include "keydb.h"
40
#include "main.h"
41
#include "../common/i18n.h"
42
#include "../common/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
static int pw_from_string;
50
51
52
/* Return true if a static passphrase has been set.  The actual return
53
 * value is 1 in the general case and 2 if the passphrase has been set
54
 * from a string (i.e. --passphrase option). */
55
int
56
have_static_passphrase (void)
57
12.5k
{
58
12.5k
  int ret;
59
12.5k
  ret = (!!fd_passwd
60
0
         && (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
61
12.5k
  if (ret && pw_from_string)
62
0
    ret = 2;
63
12.5k
  return ret;
64
12.5k
}
65
66
67
/* Return a static passphrase.  The returned value is only valid as
68
   long as no other passphrase related function is called.  NULL may
69
   be returned if no passphrase has been set; better use
70
   have_static_passphrase first.  */
71
const char *
72
get_static_passphrase (void)
73
0
{
74
0
  return fd_passwd;
75
0
}
76
77
78
/****************
79
 * Set the passphrase to be used for the next query and only for the next
80
 * one.
81
 */
82
void
83
set_next_passphrase( const char *s )
84
0
{
85
0
  xfree(next_pw);
86
0
  next_pw = NULL;
87
0
  if ( s )
88
0
    {
89
0
      next_pw = xmalloc_secure( strlen(s)+1 );
90
0
      strcpy (next_pw, s );
91
0
    }
92
0
}
93
94
/****************
95
 * Get the last passphrase used in passphrase_to_dek.
96
 * Note: This removes the passphrase from this modules and
97
 * the caller must free the result.  May return NULL:
98
 */
99
char *
100
get_last_passphrase (void)
101
0
{
102
0
  char *p = last_pw;
103
0
  last_pw = NULL;
104
0
  return p;
105
0
}
106
107
/* Here's an interesting question: since this passphrase was passed in
108
   on the command line, is there really any point in using secure
109
   memory for it?  I'm going with 'yes', since it doesn't hurt, and
110
   might help in some small way (swapping). */
111
112
void
113
set_passphrase_from_string(const char *pass)
114
0
{
115
0
  xfree (fd_passwd);
116
0
  fd_passwd = xmalloc_secure(strlen(pass)+1);
117
0
  strcpy (fd_passwd, pass);
118
0
  pw_from_string = 1;
119
0
}
120
121
122
void
123
read_passphrase_from_fd( int fd )
124
0
{
125
0
  int i, len;
126
0
  char *pw;
127
128
0
  if (! gnupg_fd_valid (fd))
129
0
    log_fatal ("passphrase-fd is invalid: %s\n", strerror (errno));
130
131
0
  if ( !opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
132
0
    { /* Not used but we have to do a dummy read, so that it won't end
133
         up at the begin of the message if the quite usual trick to
134
         prepend the passphtrase to the message is used. */
135
0
      char buf[1];
136
137
0
      while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
138
0
        ;
139
0
      *buf = 0;
140
0
      return;
141
0
    }
142
143
0
  for (pw = NULL, i = len = 100; ; i++ )
144
0
    {
145
0
      if (i >= len-1 )
146
0
        {
147
0
          char *pw2 = pw;
148
0
          len += 100;
149
0
          pw = xmalloc_secure( len );
150
0
          if( pw2 )
151
0
            {
152
0
              memcpy(pw, pw2, i );
153
0
              xfree (pw2);
154
0
            }
155
0
          else
156
0
            i=0;
157
0
  }
158
0
      if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
159
0
        break;
160
0
    }
161
0
  pw[i] = 0;
162
0
  if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
163
0
    tty_printf("\b\b\b   \n" );
164
165
0
  xfree ( fd_passwd );
166
0
  fd_passwd = pw;
167
0
  pw_from_string = 0;
168
0
}
169
170
171
/*
172
 * Ask the GPG Agent for the passphrase.
173
 * If NOCACHE is set the symmetric passpharse caching will not be used.
174
 *
175
 * If REPEAT is positive, a new passphrase is requested and the agent
176
 * shall require REPEAT times repetitions of the entered passphrase.
177
 * This is used for symmetric encryption.
178
 *
179
 * Note that TRYAGAIN_TEXT must not be translated.  If CANCELED is not
180
 * NULL, the function does set it to 1 if the user canceled the
181
 * operation.  If CACHEID is not NULL, it will be used as the cacheID
182
 * for the gpg-agent; if is NULL and a key fingerprint can be
183
 * computed, this will be used as the cacheid.
184
 *
185
 * For FLAGS see passphrase_to_dek;
186
 */
187
static char *
188
passphrase_get (int newsymkey, int nocache, const char *cacheid, int repeat,
189
                const char *tryagain_text, unsigned int flags, int *canceled)
190
12.5k
{
191
12.5k
  int rc;
192
12.5k
  char *pw = NULL;
193
12.5k
  char *orig_codeset;
194
12.5k
  const char *my_cacheid;
195
12.5k
  const char *desc;
196
197
12.5k
  if (canceled)
198
12.5k
    *canceled = 0;
199
200
12.5k
  orig_codeset = i18n_switchto_utf8 ();
201
202
12.5k
  if (!nocache && cacheid)
203
216
    my_cacheid = cacheid;
204
12.3k
  else
205
12.3k
    my_cacheid = NULL;
206
207
12.5k
  if (tryagain_text)
208
0
    tryagain_text = _(tryagain_text);
209
210
12.5k
  if ((flags & GETPASSWORD_FLAG_SYMDECRYPT))
211
12.5k
    desc = _("Please enter the passphrase for decryption.");
212
0
  else
213
0
    desc = _("Enter passphrase\n");
214
215
  /* Here we have:
216
   * REPEAT is set in create mode and if opt.passphrase_repeat is set.
217
   * (Thus it is not a clean indication that we want a new passphrase).
218
   * NOCACHE is set in create mode or if --no-symkey-cache is used.
219
   * CACHEID is only set if caching shall be used.
220
   * NEWSYMKEY has been added latter to make it clear that a new key
221
   * is requested.  The whole chain of API is a bit too complex since
222
   * we we stripped things out over time; however, there is no time
223
   * for a full state analysis and thus this new parameter.
224
   */
225
12.5k
  rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
226
12.5k
                             desc,
227
12.5k
                             newsymkey, repeat, nocache, &pw);
228
229
12.5k
  i18n_switchback (orig_codeset);
230
231
232
12.5k
  if (!rc)
233
0
    ;
234
12.5k
  else if (gpg_err_code (rc) == GPG_ERR_CANCELED
235
12.5k
            || gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
236
0
    {
237
0
      log_info (_("cancelled by user\n") );
238
0
      if (canceled)
239
0
        *canceled = 1;
240
0
    }
241
12.5k
  else
242
12.5k
    {
243
12.5k
      log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
244
      /* Due to limitations in the API of the upper layers they
245
         consider an error as no passphrase entered.  This works in
246
         most cases but not during key creation where this should
247
         definitely not happen and let it continue without requiring a
248
         passphrase.  Given that now all the upper layers handle a
249
         cancel correctly, we simply set the cancel flag now for all
250
         errors from the agent.  */
251
12.5k
      if (canceled)
252
12.5k
        *canceled = 1;
253
254
12.5k
      write_status_errcode ("get_passphrase", rc);
255
12.5k
    }
256
257
12.5k
  if (rc)
258
12.5k
    {
259
12.5k
      xfree (pw);
260
12.5k
      pw = NULL;
261
12.5k
    }
262
12.5k
  return pw;
263
12.5k
}
264
265
266
/*
267
 * Clear the cached passphrase with CACHEID.
268
 */
269
void
270
passphrase_clear_cache (const char *cacheid)
271
0
{
272
0
  int rc;
273
274
0
  rc = agent_clear_passphrase (cacheid);
275
0
  if (rc)
276
0
    log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
277
0
}
278
279
280
/* Return a new DEK object using the string-to-key specifier S2K.
281
 * Returns NULL if the user canceled the passphrase entry and if
282
 * CANCELED is not NULL, sets it to true.
283
 *
284
 * If CREATE is true a new passphrase will be created.  If NOCACHE is
285
 * true the symmetric key caching will not be used.
286
 * FLAG bits are:
287
 *   GETPASSWORD_FLAG_SYMDECRYPT := for symmetric decryption
288
 */
289
DEK *
290
passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
291
                   int create, int nocache,
292
                   const char *tryagain_text, unsigned int flags,
293
                   int *canceled)
294
12.5k
{
295
12.5k
  char *pw = NULL;
296
12.5k
  DEK *dek;
297
12.5k
  STRING2KEY help_s2k;
298
12.5k
  int dummy_canceled;
299
12.5k
  char s2k_cacheidbuf[1+16+1];
300
12.5k
  char *s2k_cacheid = NULL;
301
302
12.5k
  if (!canceled)
303
1.10k
    canceled = &dummy_canceled;
304
12.5k
  *canceled = 0;
305
306
12.5k
  if (opt.no_symkey_cache)
307
0
    nocache = 1;  /* Force no symmetric key caching.  */
308
309
12.5k
  if ( !s2k )
310
0
    {
311
0
      log_assert (create && !nocache);
312
      /* This is used for the old rfc1991 mode
313
       * Note: This must match the code in encode.c with opt.rfc1991 set */
314
0
      memset (&help_s2k, 0, sizeof (help_s2k));
315
0
      s2k = &help_s2k;
316
0
      s2k->hash_algo = S2K_DIGEST_ALGO;
317
0
    }
318
319
  /* Create a new salt or what else to be filled into the s2k for a
320
     new key.  */
321
12.5k
  if (create && (s2k->mode == 1 || s2k->mode == 3))
322
0
    {
323
0
      gcry_randomize (s2k->salt, 8, GCRY_STRONG_RANDOM);
324
0
      if ( s2k->mode == 3 )
325
0
        {
326
          /* We delay the encoding until it is really needed.  This is
327
             if we are going to dynamically calibrate it, we need to
328
             call out to gpg-agent and that should not be done during
329
             option processing in main().  */
330
0
          if (!opt.s2k_count)
331
0
            opt.s2k_count = encode_s2k_iterations (agent_get_s2k_count ());
332
0
          s2k->count = opt.s2k_count;
333
0
        }
334
0
    }
335
336
  /* If we do not have a passphrase available in NEXT_PW and status
337
     information are request, we print them now. */
338
12.5k
  if ( !next_pw && is_status_enabled() )
339
0
    {
340
0
      char buf[50];
341
342
0
      snprintf (buf, sizeof buf, "%d %d %d",
343
0
                cipher_algo, s2k->mode, s2k->hash_algo );
344
0
      write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
345
0
    }
346
347
12.5k
  if ( next_pw )
348
0
    {
349
      /* Simply return the passphrase we already have in NEXT_PW. */
350
0
      pw = next_pw;
351
0
      next_pw = NULL;
352
0
    }
353
12.5k
  else if ( have_static_passphrase () )
354
0
    {
355
      /* Return the passphrase we have stored in FD_PASSWD. */
356
0
      pw = xmalloc_secure ( strlen(fd_passwd)+1 );
357
0
      strcpy ( pw, fd_passwd );
358
0
    }
359
12.5k
  else
360
12.5k
    {
361
12.5k
      if (!nocache && (s2k->mode == 1 || s2k->mode == 3))
362
216
  {
363
216
    memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
364
216
    *s2k_cacheidbuf = 'S';
365
216
    bin2hex (s2k->salt, 8, s2k_cacheidbuf + 1);
366
216
    s2k_cacheid = s2k_cacheidbuf;
367
216
  }
368
369
12.5k
      if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
370
0
        {
371
0
          char buf[32];
372
373
0
          snprintf (buf, sizeof (buf), "%u", 100);
374
0
          write_status_text (STATUS_INQUIRE_MAXLEN, buf);
375
0
        }
376
377
      /* Divert to the gpg-agent. */
378
12.5k
      pw = passphrase_get (create, create && nocache, s2k_cacheid,
379
12.5k
                           create? opt.passphrase_repeat : 0,
380
12.5k
                           tryagain_text, flags, canceled);
381
12.5k
      if (*canceled)
382
12.5k
        {
383
12.5k
          xfree (pw);
384
12.5k
    write_status( STATUS_CANCELED_BY_USER );
385
12.5k
          return NULL;
386
12.5k
        }
387
12.5k
    }
388
389
0
  if ( !pw || !*pw )
390
0
    write_status( STATUS_MISSING_PASSPHRASE );
391
392
  /* Hash the passphrase and store it in a newly allocated DEK object.
393
     Keep a copy of the passphrase in LAST_PW for use by
394
     get_last_passphrase(). */
395
0
  dek = xmalloc_secure_clear ( sizeof *dek );
396
0
  dek->algo = cipher_algo;
397
0
  if (!pw || !*pw)
398
0
    {
399
0
      if (create)
400
0
        dek->keylen = 0;
401
0
      else
402
0
        {
403
0
          xfree (dek);
404
0
          return NULL;
405
0
        }
406
0
    }
407
0
  else
408
0
    {
409
0
      gpg_error_t err;
410
411
0
      dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
412
0
      if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
413
0
        BUG ();
414
0
      err = gcry_kdf_derive (pw, strlen (pw),
415
0
                             s2k->mode == 3? GCRY_KDF_ITERSALTED_S2K :
416
0
                             s2k->mode == 1? GCRY_KDF_SALTED_S2K :
417
0
                             /* */           GCRY_KDF_SIMPLE_S2K,
418
0
                             s2k->hash_algo, s2k->salt, 8,
419
0
                             S2K_DECODE_COUNT(s2k->count),
420
0
                             dek->keylen, dek->key);
421
0
      if (err)
422
0
        {
423
0
          log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
424
0
          xfree (pw);
425
0
          xfree (dek);
426
0
    write_status( STATUS_MISSING_PASSPHRASE );
427
0
          return NULL;
428
0
        }
429
0
    }
430
0
  if (s2k_cacheid)
431
0
    memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
432
0
  xfree(last_pw);
433
0
  last_pw = pw;
434
0
  return dek;
435
0
}
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 (ctrl_t ctrl,
442
                             u32 *keyid, u32 *mainkeyid, int pubkey_algo)
443
0
{
444
0
  char buf[50];
445
0
  char *us;
446
447
0
  us = get_long_user_id_string (ctrl, keyid);
448
0
  write_status_text (STATUS_USERID_HINT, us);
449
0
  xfree (us);
450
451
0
  snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
452
0
            (ulong)keyid[0],
453
0
            (ulong)keyid[1],
454
0
            (ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
455
0
            (ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
456
0
            pubkey_algo);
457
458
0
  write_status_text (STATUS_NEED_PASSPHRASE, buf);
459
0
}
460
461
462
/* Return an allocated utf-8 string describing the key PK.  If ESCAPED
463
   is true spaces and control characters are percent or plus escaped.
464
   MODE describes the use of the key description; use one of the
465
   FORMAT_KEYDESC_ macros. */
466
char *
467
gpg_format_keydesc (ctrl_t ctrl, PKT_public_key *pk, int mode, int escaped)
468
0
{
469
0
  char *uid;
470
0
  size_t uidlen;
471
0
  const char *algo_name;
472
0
  const char *timestr;
473
0
  char *orig_codeset;
474
0
  char *maink;
475
0
  char *desc;
476
0
  const char *prompt;
477
0
  const char *trailer = "";
478
0
  int is_subkey;
479
480
0
  if (mode == FORMAT_KEYDESC_KEYGRIP)
481
0
    {
482
0
      is_subkey = 0;
483
0
      algo_name = NULL;
484
0
      timestr = NULL;
485
0
      uid = NULL;
486
0
    }
487
0
  else
488
0
    {
489
0
      is_subkey = (pk->main_keyid[0] && pk->main_keyid[1]
490
0
                   && pk->keyid[0] != pk->main_keyid[0]
491
0
                   && pk->keyid[1] != pk->main_keyid[1]);
492
0
      algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
493
0
      timestr = strtimestamp (pk->timestamp);
494
0
      uid = get_user_id (ctrl, is_subkey? pk->main_keyid:pk->keyid,
495
0
                         &uidlen, NULL);
496
0
    }
497
498
0
  orig_codeset = i18n_switchto_utf8 ();
499
500
0
  if (is_subkey)
501
0
    maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
502
0
  else
503
0
    maink = NULL;
504
505
0
  switch (mode)
506
0
    {
507
0
    case FORMAT_KEYDESC_NORMAL:
508
0
      prompt = _("Please enter the passphrase to unlock the"
509
0
                 " OpenPGP secret key:");
510
0
      break;
511
0
    case FORMAT_KEYDESC_IMPORT:
512
0
      prompt = _("Please enter the passphrase to import the"
513
0
                 " OpenPGP secret key:");
514
0
      break;
515
0
    case FORMAT_KEYDESC_EXPORT:
516
0
      if (is_subkey)
517
0
        prompt = _("Please enter the passphrase to export the"
518
0
                   " OpenPGP secret subkey:");
519
0
      else
520
0
        prompt = _("Please enter the passphrase to export the"
521
0
                   " OpenPGP secret key:");
522
0
      break;
523
0
    case FORMAT_KEYDESC_DELKEY:
524
0
      if (is_subkey)
525
0
        prompt = _("Do you really want to permanently delete the"
526
0
                   " OpenPGP secret subkey key:");
527
0
      else
528
0
        prompt = _("Do you really want to permanently delete the"
529
0
                   " OpenPGP secret key:");
530
0
      trailer = "?";
531
0
      break;
532
0
    case FORMAT_KEYDESC_KEYGRIP:
533
0
      prompt = _("Please enter the passphrase to export the"
534
0
                 " secret key with keygrip:");
535
0
      break;
536
0
    default:
537
0
      prompt = "?";
538
0
      break;
539
0
    }
540
541
0
  if (mode == FORMAT_KEYDESC_KEYGRIP)
542
0
    desc = xtryasprintf ("%s\n\n"
543
0
                         "   %s\n",
544
0
                         prompt,
545
0
                         "<keygrip>");
546
0
  else
547
0
    desc = xtryasprintf (_("%s\n"
548
0
                           "\"%.*s\"\n"
549
0
                           "%u-bit %s key, ID %s,\n"
550
0
                           "created %s%s.\n%s"),
551
0
                         prompt,
552
0
                         (int)uidlen, uid,
553
0
                         nbits_from_pk (pk), algo_name,
554
0
                         keystr (pk->keyid), timestr,
555
0
                         maink?maink:"", trailer);
556
0
  xfree (maink);
557
0
  xfree (uid);
558
559
0
  i18n_switchback (orig_codeset);
560
561
0
  if (escaped)
562
0
    {
563
0
      char *tmp = percent_plus_escape (desc);
564
0
      xfree (desc);
565
0
      desc = tmp;
566
0
    }
567
568
0
  return desc;
569
0
}