1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
|
/* passphrase.c - Get a passphrase
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
* 2005, 2006, 2007, 2009, 2011 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_LANGINFO_CODESET
#include <langinfo.h>
#endif
#include "gpg.h"
#include "../common/util.h"
#include "options.h"
#include "../common/ttyio.h"
#include "keydb.h"
#include "main.h"
#include "../common/i18n.h"
#include "../common/status.h"
#include "call-agent.h"
#include "../common/shareddefs.h"
static char *fd_passwd = NULL;
static char *next_pw = NULL;
static char *last_pw = NULL;
int
have_static_passphrase()
{
return (!!fd_passwd
&& (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
}
/* Return a static passphrase. The returned value is only valid as
long as no other passphrase related function is called. NULL may
be returned if no passphrase has been set; better use
have_static_passphrase first. */
const char *
get_static_passphrase (void)
{
return fd_passwd;
}
/****************
* Set the passphrase to be used for the next query and only for the next
* one.
*/
void
set_next_passphrase( const char *s )
{
xfree(next_pw);
next_pw = NULL;
if ( s )
{
next_pw = xmalloc_secure( strlen(s)+1 );
strcpy (next_pw, s );
}
}
/****************
* Get the last passphrase used in passphrase_to_dek.
* Note: This removes the passphrase from this modules and
* the caller must free the result. May return NULL:
*/
char *
get_last_passphrase()
{
char *p = last_pw;
last_pw = NULL;
return p;
}
/* Here's an interesting question: since this passphrase was passed in
on the command line, is there really any point in using secure
memory for it? I'm going with 'yes', since it doesn't hurt, and
might help in some small way (swapping). */
void
set_passphrase_from_string(const char *pass)
{
xfree (fd_passwd);
fd_passwd = xmalloc_secure(strlen(pass)+1);
strcpy (fd_passwd, pass);
}
void
read_passphrase_from_fd( int fd )
{
int i, len;
char *pw;
if (! gnupg_fd_valid (fd))
log_fatal ("passphrase-fd is invalid: %s\n", strerror (errno));
if ( !opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
{ /* Not used but we have to do a dummy read, so that it won't end
up at the begin of the message if the quite usual trick to
prepend the passphtrase to the message is used. */
char buf[1];
while (!(read (fd, buf, 1) != 1 || *buf == '\n' ))
;
*buf = 0;
return;
}
for (pw = NULL, i = len = 100; ; i++ )
{
if (i >= len-1 )
{
char *pw2 = pw;
len += 100;
pw = xmalloc_secure( len );
if( pw2 )
{
memcpy(pw, pw2, i );
xfree (pw2);
}
else
i=0;
}
if (read( fd, pw+i, 1) != 1 || pw[i] == '\n' )
break;
}
pw[i] = 0;
if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
tty_printf("\b\b\b \n" );
xfree ( fd_passwd );
fd_passwd = pw;
}
/*
* Ask the GPG Agent for the passphrase.
* If NOCACHE is set the symmetric passpharse caching will not be used.
*
* If REPEAT is positive, a new passphrase is requested and the agent
* shall require REPEAT times repetitions of the entered passphrase.
* This is used for symmetric encryption.
*
* Note that TRYAGAIN_TEXT must not be translated. If CANCELED is not
* NULL, the function does set it to 1 if the user canceled the
* operation. If CACHEID is not NULL, it will be used as the cacheID
* for the gpg-agent; if is NULL and a key fingerprint can be
* computed, this will be used as the cacheid.
*
* For FLAGS see passphrase_to_dek;
*/
static char *
passphrase_get (int newsymkey, int nocache, const char *cacheid, int repeat,
const char *tryagain_text, unsigned int flags, int *canceled)
{
int rc;
char *pw = NULL;
char *orig_codeset;
const char *my_cacheid;
const char *desc;
if (canceled)
*canceled = 0;
orig_codeset = i18n_switchto_utf8 ();
if (!nocache && cacheid)
my_cacheid = cacheid;
else
my_cacheid = NULL;
if (tryagain_text)
tryagain_text = _(tryagain_text);
if ((flags & GETPASSWORD_FLAG_SYMDECRYPT))
desc = _("Please enter the passphrase for decryption.");
else
desc = _("Enter passphrase\n");
/* Here we have:
* REPEAT is set in create mode and if opt.passphrase_repeat is set.
* (Thus it is not a clean indication that we want a new passphrase).
* NOCACHE is set in create mode or if --no-symkey-cache is used.
* CACHEID is only set if caching shall be used.
* NEWSYMKEY has been added latter to make it clear that a new key
* is requested. The whole chain of API is a bit too complex since
* we we stripped things out over time; however, there is no time
* for a full state analysis and thus this new parameter.
*/
rc = agent_get_passphrase (my_cacheid, tryagain_text, NULL,
desc,
newsymkey, repeat, nocache, &pw);
i18n_switchback (orig_codeset);
if (!rc)
;
else if (gpg_err_code (rc) == GPG_ERR_CANCELED
|| gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
{
log_info (_("cancelled by user\n") );
if (canceled)
*canceled = 1;
}
else
{
log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
/* Due to limitations in the API of the upper layers they
consider an error as no passphrase entered. This works in
most cases but not during key creation where this should
definitely not happen and let it continue without requiring a
passphrase. Given that now all the upper layers handle a
cancel correctly, we simply set the cancel flag now for all
errors from the agent. */
if (canceled)
*canceled = 1;
write_status_errcode ("get_passphrase", rc);
}
if (rc)
{
xfree (pw);
pw = NULL;
}
return pw;
}
/*
* Clear the cached passphrase with CACHEID.
*/
void
passphrase_clear_cache (const char *cacheid)
{
int rc;
rc = agent_clear_passphrase (cacheid);
if (rc)
log_error (_("problem with the agent: %s\n"), gpg_strerror (rc));
}
#define HAVE_PTHREAD 1
#ifdef HAVE_PTHREAD
#include <pthread.h>
#define MAX_THREADS 8
struct user_defined_threads_ctx
{
int oldest_thread_idx;
int next_thread_idx;
int num_threads_running;
pthread_attr_t attr;
pthread_t thread[MAX_THREADS];
struct job_thread_param
{
gcry_kdf_job_fn_t job;
void *priv;
} work[MAX_THREADS];
};
static void *
job_thread (void *p)
{
struct job_thread_param *param = p;
param->job (param->priv);
pthread_exit (NULL);
}
static int
wait_all_jobs_completion (void *jobs_context)
{
struct user_defined_threads_ctx *ctx = jobs_context;
int i, idx;
int ret;
for (i = 0; i < ctx->num_threads_running; i++)
{
idx = (ctx->oldest_thread_idx + i) % MAX_THREADS;
ret = pthread_join (ctx->thread[idx], NULL);
if (ret)
return -1;
}
/* reset context for next round of parallel work */
ctx->num_threads_running = 0;
ctx->oldest_thread_idx = -1;
ctx->next_thread_idx = 0;
return 0;
}
static int
pthread_jobs_launch_job (void *jobs_context, gcry_kdf_job_fn_t job,
void *job_priv)
{
struct user_defined_threads_ctx *ctx = jobs_context;
int ret;
if (ctx->next_thread_idx == ctx->oldest_thread_idx)
{
/* thread limit reached, join a thread */
ret = pthread_join (ctx->thread[ctx->oldest_thread_idx], NULL);
if (ret)
return -1;
ctx->oldest_thread_idx = (ctx->oldest_thread_idx + 1) % MAX_THREADS;
ctx->num_threads_running--;
}
ctx->work[ctx->next_thread_idx].job = job;
ctx->work[ctx->next_thread_idx].priv = job_priv;
ret = pthread_create (&ctx->thread[ctx->next_thread_idx], &ctx->attr,
job_thread, &ctx->work[ctx->next_thread_idx]);
if (ret)
{
/* could not create new thread. */
(void)wait_all_jobs_completion (jobs_context);
return -1;
}
if (ctx->oldest_thread_idx < 0)
ctx->oldest_thread_idx = ctx->next_thread_idx;
ctx->next_thread_idx = (ctx->next_thread_idx + 1) % MAX_THREADS;
ctx->num_threads_running++;
return 0;
}
#endif
static gpg_error_t
gnupg_kdf_derive (int algo, int subalgo,
const unsigned long *param, unsigned int paramlen,
const unsigned char *pass, size_t passlen,
const unsigned char *salt, size_t saltlen,
const unsigned char *key, size_t keylen,
const unsigned char *ad, size_t adlen,
size_t outlen, unsigned char *out)
{
gpg_error_t err;
gcry_kdf_hd_t hd;
err = gcry_kdf_open (&hd, algo, subalgo, param, paramlen,
pass, passlen, salt, saltlen, key, keylen,
ad, adlen);
if (err)
return err;
if (HAVE_PTHREAD)
{
struct user_defined_threads_ctx jobs_context;
const gcry_kdf_thread_ops_t ops =
{
&jobs_context,
pthread_jobs_launch_job,
wait_all_jobs_completion
};
memset (&jobs_context, 0, sizeof (struct user_defined_threads_ctx));
jobs_context.oldest_thread_idx = -1;
if (pthread_attr_init (&jobs_context.attr))
{
err = gpg_error_from_syserror ();
gcry_kdf_close (hd);
return err;
}
if (pthread_attr_setdetachstate (&jobs_context.attr,
PTHREAD_CREATE_JOINABLE))
{
err = gpg_error_from_syserror ();
pthread_attr_destroy (&jobs_context.attr);
gcry_kdf_close (hd);
return err;
}
err = gcry_kdf_compute (hd, &ops);
pthread_attr_destroy (&jobs_context. attr);
}
else
err = gcry_kdf_compute (hd, NULL);
if (!err)
err = gcry_kdf_final (hd, outlen, out);
gcry_kdf_close (hd);
return err;
}
/* Return a new DEK object using the string-to-key specifier S2K.
* Returns NULL if the user canceled the passphrase entry and if
* CANCELED is not NULL, sets it to true.
*
* If CREATE is true a new passphrase will be created. If NOCACHE is
* true the symmetric key caching will not be used.
* FLAG bits are:
* GETPASSWORD_FLAG_SYMDECRYPT := for symmetric decryption
*/
DEK *
passphrase_to_dek (int cipher_algo, STRING2KEY *s2k,
int create, int nocache,
const char *tryagain_text, unsigned int flags,
int *canceled)
{
char *pw = NULL;
DEK *dek;
STRING2KEY help_s2k;
int dummy_canceled;
char s2k_cacheidbuf[1+32+1];
char *s2k_cacheid = NULL;
if (!canceled)
canceled = &dummy_canceled;
*canceled = 0;
if (opt.no_symkey_cache)
nocache = 1; /* Force no symmetric key caching. */
if ( !s2k )
{
log_assert (create && !nocache);
/* This is used for the old rfc1991 mode
* Note: This must match the code in encode.c with opt.rfc1991 set */
memset (&help_s2k, 0, sizeof (help_s2k));
s2k = &help_s2k;
s2k->u.s.hash_algo = S2K_DIGEST_ALGO;
}
/* Create a new salt or what else to be filled into the s2k for a
new key. */
if (create)
{
if (s2k->mode == 1 || s2k->mode == 3)
{
gcry_randomize (s2k->u.s.salt, 8, GCRY_STRONG_RANDOM);
if ( s2k->mode == 3 )
{
/* We delay the encoding until it is really needed. This is
if we are going to dynamically calibrate it, we need to
call out to gpg-agent and that should not be done during
option processing in main(). */
if (!opt.s2k_count)
opt.s2k_count = encode_s2k_iterations (agent_get_s2k_count ());
s2k->u.s.count = opt.s2k_count;
}
}
else if (s2k->mode == 4)
gcry_randomize (s2k->u.a.salt, 16, GCRY_STRONG_RANDOM);
}
/* If we do not have a passphrase available in NEXT_PW and status
information are request, we print them now. */
if ( !next_pw && is_status_enabled() )
{
char buf[50];
snprintf (buf, sizeof buf, "%d %d %d",
cipher_algo, s2k->mode, s2k->u.s.hash_algo );
write_status_text ( STATUS_NEED_PASSPHRASE_SYM, buf );
}
if ( next_pw )
{
/* Simply return the passphrase we already have in NEXT_PW. */
pw = next_pw;
next_pw = NULL;
}
else if ( have_static_passphrase () )
{
/* Return the passphrase we have stored in FD_PASSWD. */
pw = xmalloc_secure ( strlen(fd_passwd)+1 );
strcpy ( pw, fd_passwd );
}
else
{
if (!nocache)
{
if (s2k->mode == 1 || s2k->mode == 3)
{
memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
*s2k_cacheidbuf = 'S';
bin2hex (s2k->u.s.salt, 8, s2k_cacheidbuf + 1);
s2k_cacheid = s2k_cacheidbuf;
}
else if (s2k->mode == 4)
{
memset (s2k_cacheidbuf, 0, sizeof s2k_cacheidbuf);
*s2k_cacheidbuf = 'S';
bin2hex (s2k->u.a.salt, 16, s2k_cacheidbuf + 1);
s2k_cacheid = s2k_cacheidbuf;
}
}
if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
{
char buf[32];
snprintf (buf, sizeof (buf), "%u", 100);
write_status_text (STATUS_INQUIRE_MAXLEN, buf);
}
/* Divert to the gpg-agent. */
pw = passphrase_get (create, create && nocache, s2k_cacheid,
create? opt.passphrase_repeat : 0,
tryagain_text, flags, canceled);
if (*canceled)
{
xfree (pw);
write_status( STATUS_CANCELED_BY_USER );
return NULL;
}
}
if ( !pw || !*pw )
write_status( STATUS_MISSING_PASSPHRASE );
/* Hash the passphrase and store it in a newly allocated DEK object.
Keep a copy of the passphrase in LAST_PW for use by
get_last_passphrase(). */
dek = xmalloc_secure_clear ( sizeof *dek );
dek->algo = cipher_algo;
if ( (!pw || !*pw) && create)
dek->keylen = 0;
else
{
gpg_error_t err;
dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
if (!(dek->keylen > 0 && dek->keylen <= DIM(dek->key)))
BUG ();
if (s2k->mode == 4)
{
unsigned long param[4];
param[0] = dek->keylen;
param[1] = s2k->u.a.t;
param[2] = (1UL << (s2k->u.a.m & 0x1f));
param[3] = s2k->u.a.p;
err = gnupg_kdf_derive (GCRY_KDF_ARGON2, GCRY_KDF_ARGON2ID,
param, 4, pw, strlen (pw),
s2k->u.a.salt, 16, NULL, 0, NULL, 0,
dek->keylen, dek->key);
}
else
err = gcry_kdf_derive (pw, strlen (pw),
s2k->mode == 3? GCRY_KDF_ITERSALTED_S2K :
s2k->mode == 1? GCRY_KDF_SALTED_S2K :
/* */ GCRY_KDF_SIMPLE_S2K,
s2k->u.s.hash_algo, s2k->u.s.salt, 8,
S2K_DECODE_COUNT(s2k->u.s.count),
dek->keylen, dek->key);
if (err)
{
log_error ("gcry_kdf_derive failed: %s", gpg_strerror (err));
xfree (pw);
xfree (dek);
write_status( STATUS_MISSING_PASSPHRASE );
return NULL;
}
}
if (s2k_cacheid)
memcpy (dek->s2k_cacheid, s2k_cacheid, sizeof dek->s2k_cacheid);
xfree(last_pw);
last_pw = pw;
return dek;
}
/* Emit the USERID_HINT and the NEED_PASSPHRASE status messages.
MAINKEYID may be NULL. */
void
emit_status_need_passphrase (ctrl_t ctrl,
u32 *keyid, u32 *mainkeyid, int pubkey_algo)
{
char buf[50];
char *us;
us = get_long_user_id_string (ctrl, keyid);
write_status_text (STATUS_USERID_HINT, us);
xfree (us);
snprintf (buf, sizeof buf, "%08lX%08lX %08lX%08lX %d 0",
(ulong)keyid[0],
(ulong)keyid[1],
(ulong)(mainkeyid? mainkeyid[0]:keyid[0]),
(ulong)(mainkeyid? mainkeyid[1]:keyid[1]),
pubkey_algo);
write_status_text (STATUS_NEED_PASSPHRASE, buf);
}
/* Return an allocated utf-8 string describing the key PK. If ESCAPED
is true spaces and control characters are percent or plus escaped.
MODE describes the use of the key description; use one of the
FORMAT_KEYDESC_ macros. */
char *
gpg_format_keydesc (ctrl_t ctrl, PKT_public_key *pk, int mode, int escaped)
{
char *uid;
size_t uidlen;
const char *algo_name;
const char *timestr;
char *orig_codeset;
char *maink;
char *desc;
const char *prompt;
const char *trailer = "";
int is_subkey;
if (mode == FORMAT_KEYDESC_KEYGRIP)
{
is_subkey = 0;
algo_name = NULL;
timestr = NULL;
uid = NULL;
}
else
{
is_subkey = (pk->main_keyid[0] && pk->main_keyid[1]
&& pk->keyid[0] != pk->main_keyid[0]
&& pk->keyid[1] != pk->main_keyid[1]);
algo_name = openpgp_pk_algo_name (pk->pubkey_algo);
timestr = strtimestamp (pk->timestamp);
uid = get_user_id (ctrl, is_subkey? pk->main_keyid:pk->keyid,
&uidlen, NULL);
}
orig_codeset = i18n_switchto_utf8 ();
if (is_subkey)
maink = xtryasprintf (_(" (main key ID %s)"), keystr (pk->main_keyid));
else
maink = NULL;
switch (mode)
{
case FORMAT_KEYDESC_NORMAL:
prompt = _("Please enter the passphrase to unlock the"
" OpenPGP secret key:");
break;
case FORMAT_KEYDESC_IMPORT:
prompt = _("Please enter the passphrase to import the"
" OpenPGP secret key:");
break;
case FORMAT_KEYDESC_EXPORT:
if (is_subkey)
prompt = _("Please enter the passphrase to export the"
" OpenPGP secret subkey:");
else
prompt = _("Please enter the passphrase to export the"
" OpenPGP secret key:");
break;
case FORMAT_KEYDESC_DELKEY:
if (is_subkey)
prompt = _("Do you really want to permanently delete the"
" OpenPGP secret subkey key:");
else
prompt = _("Do you really want to permanently delete the"
" OpenPGP secret key:");
trailer = "?";
break;
case FORMAT_KEYDESC_KEYGRIP:
prompt = _("Please enter the passphrase to export the"
" secret key with keygrip:");
break;
default:
prompt = "?";
break;
}
if (mode == FORMAT_KEYDESC_KEYGRIP)
desc = xtryasprintf ("%s\n\n"
" %s\n",
prompt,
"<keygrip>");
else
desc = xtryasprintf (_("%s\n"
"\"%.*s\"\n"
"%u-bit %s key, ID %s,\n"
"created %s%s.\n%s"),
prompt,
(int)uidlen, uid,
nbits_from_pk (pk), algo_name,
keystr (pk->keyid), timestr,
maink?maink:"", trailer);
xfree (maink);
xfree (uid);
i18n_switchback (orig_codeset);
if (escaped)
{
char *tmp = percent_plus_escape (desc);
xfree (desc);
desc = tmp;
}
return desc;
}
|