Coverage Report

Created: 2026-08-13 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/keygen.c
Line
Count
Source
1
/* keygen.c - Generate a key pair
2
 * Copyright (C) 1998-2007, 2009-2011  Free Software Foundation, Inc.
3
 * Copyright (C) 2014, 2015, 2016, 2017, 2018  Werner Koch
4
 * Copyright (C) 2020, 2024 g10 Code GmbH
5
 *
6
 * This file is part of GnuPG.
7
 *
8
 * GnuPG is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * GnuPG is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
#include <config.h>
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
#include <ctype.h>
27
#include <errno.h>
28
#include <sys/types.h>
29
#include <sys/stat.h>
30
#include <unistd.h>
31
32
#include "gpg.h"
33
#include "../common/util.h"
34
#include "main.h"
35
#include "packet.h"
36
#include "../common/ttyio.h"
37
#include "options.h"
38
#include "keydb.h"
39
#include "trustdb.h"
40
#include "../common/status.h"
41
#include "../common/i18n.h"
42
#include "keyserver-internal.h"
43
#include "call-agent.h"
44
#include "pkglue.h"
45
#include "../common/shareddefs.h"
46
#include "../common/host2net.h"
47
#include "../common/mbox-util.h"
48
49
50
/* The default algorithms.  If you change them, you should ensure the
51
 * value is inside the bounds enforced by ask_keysize and gen_xxx.
52
 * See also get_keysize_range which encodes the allowed ranges.  The
53
 * default answer in ask_algo also needs to be adjusted.  For Kyber
54
 * keep the values set in generate_subkeypair in sync.  */
55
0
#define DEFAULT_STD_KEY_PARAM  "ed25519/cert,sign+cv25519/encr"
56
0
#define FUTURE_STD_KEY_PARAM   "ed25519/cert,sign+cv25519/encr"
57
0
#define PQC_STD_KEY_PARAM_PRI  "bp384/cert,sign"
58
0
#define PQC_STD_KEY_PARAM_SUB  "kyber768_bp256/encr"
59
0
#define PQC_STD_KEY_PARAM      PQC_STD_KEY_PARAM_PRI "+" PQC_STD_KEY_PARAM_SUB
60
61
/* When generating keys using the streamlined key generation dialog,
62
   use this as a default expiration interval.  */
63
const char *default_expiration_interval = "3y";
64
65
/* Flag bits used during key generation.  */
66
0
#define KEYGEN_FLAG_NO_PROTECTION 1
67
0
#define KEYGEN_FLAG_TRANSIENT_KEY 2
68
0
#define KEYGEN_FLAG_CREATE_V5_KEY 4
69
70
/* Maximum number of supported algorithm preferences.  */
71
0
#define MAX_PREFS 30
72
73
enum para_name {
74
  pKEYTYPE,
75
  pKEYLENGTH,
76
  pKEYCURVE,
77
  pKEYUSAGE,
78
  pSUBKEYTYPE,
79
  pSUBKEYLENGTH,
80
  pSUBKEYCURVE,
81
  pSUBKEYUSAGE,
82
  pAUTHKEYTYPE,
83
  pNAMEREAL,
84
  pNAMEEMAIL,
85
  pNAMECOMMENT,
86
  pPREFERENCES,
87
  pREVOKER,
88
  pUSERID,
89
  pCREATIONDATE,
90
  pKEYCREATIONDATE, /* Same in seconds since epoch.  */
91
  pEXPIREDATE,
92
  pKEYEXPIRE, /* in n seconds */
93
  pSUBKEYCREATIONDATE,
94
  pSUBKEYEXPIREDATE,
95
  pSUBKEYEXPIRE, /* in n seconds */
96
  pAUTHKEYCREATIONDATE,  /* Not yet used.  */
97
  pPASSPHRASE,
98
  pSERIALNO,
99
  pCARDBACKUPKEY,
100
  pHANDLE,
101
  pKEYSERVER,
102
  pKEYGRIP,
103
  pSUBKEYGRIP,
104
  pADSK,        /* this uses u.adsk  */
105
  pVERSION,     /* Desired version of the key packet.  */
106
  pSUBVERSION,  /* Ditto for the subpacket.  */
107
  pCARDKEY      /* The keygrips have been taken from active card (bool).  */
108
};
109
110
struct para_data_s {
111
    struct para_data_s *next;
112
    int lnr;
113
    enum para_name key;
114
    union {
115
        u32 expire;
116
        u32 creation;
117
        int abool;
118
        unsigned int usage;
119
        struct revocation_key revkey;
120
        PKT_public_key *adsk;  /* used with key == pADSK */
121
        char value[1];
122
    } u;
123
};
124
125
struct output_control_s
126
{
127
  int lnr;
128
  int dryrun;
129
  unsigned int keygen_flags;
130
  int use_files;
131
  struct {
132
    char  *fname;
133
    char  *newfname;
134
    IOBUF stream;
135
    armor_filter_context_t *afx;
136
  } pub;
137
};
138
139
140
/* An object to help communicating with the actual key generation
141
 * code. */
142
struct common_gen_cb_parm_s
143
{
144
  /* This variable set to the result of agent_genkey.  The callback
145
   * may take a copy of this so that the result can be used after we
146
   * are back from the deep key generation call stack.  */
147
  gcry_sexp_t genkey_result;
148
  /* For a dual algorithms the result of the second algorithm
149
   * (e.g. Kyber). */
150
  gcry_sexp_t genkey_result2;
151
};
152
typedef struct common_gen_cb_parm_s *common_gen_cb_parm_t;
153
154
155
/* A communication object to help adding certain notations to a key
156
 * binding signature.  */
157
struct opaque_data_usage_and_pk
158
{
159
  unsigned int usage;
160
  const char *cpl_notation;
161
  PKT_public_key *pk;
162
};
163
164
165
/* FIXME: These globals vars are ugly.  And using MAX_PREFS even for
166
 * aeads is useless, given that we don't expects more than a very few
167
 * algorithms.  */
168
static int prefs_initialized = 0;
169
static byte sym_prefs[MAX_PREFS];
170
static int nsym_prefs;
171
static byte hash_prefs[MAX_PREFS];
172
static int nhash_prefs;
173
static byte zip_prefs[MAX_PREFS];
174
static int nzip_prefs;
175
static byte aead_prefs[MAX_PREFS];
176
static int naead_prefs;
177
static int mdc_available;
178
static int ks_modify;
179
static int aead_available;
180
181
static void release_parameter_list (struct para_data_s *r);
182
static struct para_data_s *prepare_adsk (ctrl_t ctrl, const char *name);
183
static gpg_error_t parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
184
                                     const char *algostr, const char *usagestr,
185
                                     const char *expirestr,
186
                                     int *r_algo, unsigned int *r_usage,
187
                                     u32 *r_expire, unsigned int *r_nbits,
188
                                     const char **r_curve, int *r_version,
189
                                            char **r_keygrip, u32 *r_keytime);
190
static void do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
191
                                 struct output_control_s *outctrl, int card );
192
static int write_keyblock (iobuf_t out, kbnode_t node);
193
static gpg_error_t gen_card_key (int keyno, int algo, int is_primary,
194
                                 kbnode_t pub_root, u32 *timestamp,
195
                                 u32 expireval, int *keygen_flags);
196
static unsigned int get_keysize_range (int algo,
197
                                       unsigned int *min, unsigned int *max);
198
static void do_add_notation (PKT_signature *sig,
199
                             const char *name, const char *value,
200
                             int critical);
201
202
203

204
/* Return the algo string for a default new key.  */
205
const char *
206
get_default_pubkey_algo (void)
207
0
{
208
0
  if (opt.def_new_key_algo)
209
0
    {
210
0
      if (*opt.def_new_key_algo && !strchr (opt.def_new_key_algo, ':'))
211
0
        return opt.def_new_key_algo;
212
      /* To avoid checking that option every time we delay that until
213
       * here.  The only thing we really need to make sure is that
214
       * there is no colon in the string so that the --gpgconf-list
215
       * command won't mess up its output.  */
216
0
      log_info (_("invalid value for option '%s'\n"), "--default-new-key-algo");
217
0
    }
218
0
  return DEFAULT_STD_KEY_PARAM;
219
0
}
220
221
222
/* Depending on the USE some public key algorithms need to be changed.
223
 * In particular this is the case for standard EC curves which may
224
 * have either ECDSA or ECDH as their algo.  The function returns the
225
 * new algo if demanded by USE. IF the function can't decide the algo
226
 * is returned as is and it is expected that a letter error check will
227
 * kick in.  If no change is required ALGO is returned as is.  */
228
static int
229
adjust_algo_for_ecdh_ecdsa (int algo, unsigned int use, const char *curve)
230
0
{
231
0
  int needalgo;
232
233
0
  if (algo != PUBKEY_ALGO_ECDSA && algo != PUBKEY_ALGO_ECDH)
234
0
    return algo; /* Not an algo we need to adjust.  */
235
236
0
  if (!curve || !*curve)
237
0
    return algo;  /* No curve given and thus we can't decide.  */
238
0
  if (!openpgp_is_curve_supported (curve, &needalgo, NULL))
239
0
    return algo;  /* Curve not supported - can't decide.  */
240
0
  if (needalgo)
241
0
    return algo;  /* No need to map the X{25519,488} curves because we
242
                   * would also need to change the curve.  */
243
244
0
  if (algo == PUBKEY_ALGO_ECDH
245
0
      && (use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT)))
246
0
    return PUBKEY_ALGO_ECDSA;  /* Switch to the signing variant.  */
247
248
0
  if (algo == PUBKEY_ALGO_ECDSA
249
0
      && (use & (PUBKEY_USAGE_ENC)))
250
0
    return PUBKEY_ALGO_ECDH;  /* Switch to the encryption variant.  */
251
252
0
  return algo;  /* Return as is.  */
253
0
}
254
255
256
static void
257
print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
258
0
{
259
0
  byte array[MAX_FINGERPRINT_LEN], *s;
260
0
  char *buf, *p;
261
0
  size_t i, n;
262
263
0
  if (!handle)
264
0
    handle = "";
265
266
0
  buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
267
268
0
  p = buf;
269
0
  if (letter || pk)
270
0
    {
271
0
      *p++ = letter;
272
0
      if (pk)
273
0
        {
274
0
          *p++ = ' ';
275
0
          fingerprint_from_pk (pk, array, &n);
276
0
          s = array;
277
          /* Fixme: Use bin2hex */
278
0
          for (i=0; i < n ; i++, s++, p += 2)
279
0
            snprintf (p, 3, "%02X", *s);
280
0
        }
281
0
    }
282
0
  if (*handle)
283
0
    {
284
0
      *p++ = ' ';
285
0
      for (i=0; handle[i] && i < 100; i++)
286
0
        *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
287
0
    }
288
0
  *p = 0;
289
0
  write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
290
0
                     buf);
291
0
  xfree (buf);
292
0
}
293
294
static void
295
print_status_key_not_created (const char *handle)
296
0
{
297
0
  print_status_key_created (0, NULL, handle);
298
0
}
299
300
301
302
static gpg_error_t
303
write_uid (kbnode_t root, const char *s)
304
0
{
305
0
  PACKET *pkt = NULL;
306
0
  size_t n = strlen (s);
307
308
0
  if (n > MAX_UID_PACKET_LENGTH - 10)
309
0
    return gpg_error (GPG_ERR_INV_USER_ID);
310
311
0
  pkt = xmalloc_clear (sizeof *pkt);
312
0
  pkt->pkttype = PKT_USER_ID;
313
0
  pkt->pkt.user_id = xmalloc_clear (sizeof *pkt->pkt.user_id + n);
314
0
  pkt->pkt.user_id->len = n;
315
0
  pkt->pkt.user_id->ref = 1;
316
0
  strcpy (pkt->pkt.user_id->name, s);
317
0
  add_kbnode (root, new_kbnode (pkt));
318
0
  return 0;
319
0
}
320
321
static void
322
do_add_key_flags (PKT_signature *sig, unsigned int use)
323
0
{
324
0
  byte buf[2] = { 0, 0 };
325
326
  /* The spec says that all primary keys MUST be able to certify. */
327
0
  if ( sig->sig_class != 0x18 )
328
0
    buf[0] |= 0x01;
329
330
0
  if (use & PUBKEY_USAGE_SIG)
331
0
    buf[0] |= 0x02;
332
0
  if (use & PUBKEY_USAGE_ENC)
333
0
    buf[0] |= 0x04 | 0x08;
334
0
  if (use & PUBKEY_USAGE_AUTH)
335
0
    buf[0] |= 0x20;
336
0
  if (use & PUBKEY_USAGE_GROUP)
337
0
    buf[0] |= 0x80;
338
339
0
  if (use & PUBKEY_USAGE_RENC)
340
0
    buf[1] |= 0x04;
341
0
  if (use & PUBKEY_USAGE_TIME)
342
0
    buf[1] |= 0x08;
343
344
0
  build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, buf[1]? 2:1);
345
0
}
346
347
348
int
349
keygen_add_key_expire (PKT_signature *sig, void *opaque)
350
0
{
351
0
  PKT_public_key *pk = opaque;
352
0
  byte buf[8];
353
0
  u32  u;
354
355
0
  if (pk->expiredate)
356
0
    {
357
0
      if (pk->expiredate > pk->timestamp)
358
0
        u = pk->expiredate - pk->timestamp;
359
0
      else
360
0
        u = 1;
361
362
0
      buf[0] = (u >> 24) & 0xff;
363
0
      buf[1] = (u >> 16) & 0xff;
364
0
      buf[2] = (u >>  8) & 0xff;
365
0
      buf[3] = u & 0xff;
366
0
      build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
367
0
    }
368
0
  else
369
0
    {
370
      /* Make sure we don't leave a key expiration subpacket lying
371
         around */
372
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
373
0
    }
374
375
0
  return 0;
376
0
}
377
378
379
/* Add the key usage (i.e. key flags) in SIG from the public keys
380
 * pubkey_usage field.  OPAQUE has the public key.  */
381
int
382
keygen_add_key_flags (PKT_signature *sig, void *opaque)
383
0
{
384
0
  PKT_public_key *pk = opaque;
385
386
0
  do_add_key_flags (sig, pk->pubkey_usage);
387
0
  return 0;
388
0
}
389
390
391
int
392
keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
393
0
{
394
0
  keygen_add_key_flags (sig, opaque);
395
0
  return keygen_add_key_expire (sig, opaque);
396
0
}
397
398
399
/* This is only used to write the key binding signature.  It is not
400
 * used for the primary key.  */
401
static int
402
keygen_add_key_flags_from_oduap (PKT_signature *sig, void *opaque)
403
0
{
404
0
  struct opaque_data_usage_and_pk *oduap = opaque;
405
406
0
  do_add_key_flags (sig, oduap->usage);
407
0
  if (oduap->cpl_notation)
408
0
    do_add_notation (sig, "cpl@gnupg.org", oduap->cpl_notation, 0);
409
0
  return keygen_add_key_expire (sig, oduap->pk);
410
0
}
411
412
413
static int
414
set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
415
0
{
416
0
    int i;
417
418
0
    for (i=0; i < *nbuf; i++ )
419
0
      if (buf[i] == val)
420
0
  {
421
0
    log_info (_("preference '%s' duplicated\n"), item);
422
0
    return -1;
423
0
        }
424
425
0
    if (*nbuf >= MAX_PREFS)
426
0
      {
427
0
  if(type==1)
428
0
    log_info(_("too many cipher preferences\n"));
429
0
  else if(type==2)
430
0
    log_info(_("too many digest preferences\n"));
431
0
  else if(type==3)
432
0
    log_info(_("too many compression preferences\n"));
433
0
  else if(type==4)
434
0
    log_info(_("too many AEAD preferences\n"));
435
0
  else
436
0
    BUG();
437
438
0
        return -1;
439
0
      }
440
441
0
    buf[(*nbuf)++] = val;
442
0
    return 0;
443
0
}
444
445
/*
446
 * Parse the supplied string and use it to set the standard
447
 * preferences.  The string may be in a form like the one printed by
448
 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
449
 * cipher/hash/compress names.  Use NULL to set the default
450
 * preferences.  Returns: 0 = okay
451
 * PERSONAL is either 0 or one PREFTYPE_*
452
 */
453
int
454
keygen_set_std_prefs (const char *string,int personal)
455
0
{
456
0
    byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS], aead[MAX_PREFS];
457
0
    int nsym=0, nhash=0, nzip=0, naead=0, val, rc=0;
458
0
    int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
459
0
    char dummy_string[25*4+1]; /* Enough for 25 items. */
460
461
0
    if (!string || !ascii_strcasecmp (string, "default"))
462
0
      {
463
0
  if (opt.def_preference_list)
464
0
    string=opt.def_preference_list;
465
0
  else
466
0
    {
467
0
            int any_compress = 0;
468
0
      dummy_string[0]='\0';
469
470
            /* The rationale why we use the order AES256,192,128 is
471
               for compatibility reasons with PGP.  If gpg would
472
               define AES128 first, we would get the somewhat
473
               confusing situation:
474
475
                 gpg -r pgpkey -r gpgkey  ---gives--> AES256
476
                 gpg -r gpgkey -r pgpkey  ---gives--> AES
477
478
               Note that by using --personal-cipher-preferences it is
479
               possible to prefer AES128.
480
            */
481
482
      /* Make sure we do not add more than a total of 15 items
483
       * here, as we could overflow the size of dummy_string.
484
       * Note further that we try to add AES/3DES despite that
485
       * they are anyway implictly used by LibrePGP/rfc4880.  */
486
0
      if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
487
0
        strcat(dummy_string,"S9 ");
488
0
      if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
489
0
        strcat(dummy_string,"S8 ");
490
0
      if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
491
0
        strcat(dummy_string,"S7 "); /* AES-128 - LibrePGP default. */
492
0
      if ( !openpgp_cipher_test_algo (CIPHER_ALGO_3DES) )
493
0
              strcat(dummy_string,"S2 "); /* 3DES - RFC4880 default. */
494
495
0
            if (!openpgp_aead_test_algo (AEAD_ALGO_OCB))
496
0
        strcat(dummy_string,"A2 ");
497
498
0
            if (personal)
499
0
              {
500
                /* The default internal hash algo order is:
501
                 *  SHA-256, SHA-384, SHA-512, SHA-224, SHA-1.
502
                 */
503
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
504
0
                  strcat (dummy_string, "H8 ");
505
506
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
507
0
                  strcat (dummy_string, "H9 ");
508
509
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
510
0
                  strcat (dummy_string, "H10 ");
511
0
              }
512
0
            else
513
0
              {
514
                /* The default advertised hash algo order is:
515
                 *  SHA-512, SHA-384, SHA-256, SHA-224, SHA-1.
516
                 */
517
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
518
0
                  strcat (dummy_string, "H10 ");
519
520
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
521
0
                  strcat (dummy_string, "H9 ");
522
523
0
                if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
524
0
                  strcat (dummy_string, "H8 ");
525
0
              }
526
527
0
            if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
528
0
        strcat (dummy_string, "H11 ");
529
530
0
      strcat (dummy_string, "H2 "); /* SHA-1 */
531
532
0
      if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
533
0
              {
534
0
                strcat(dummy_string,"Z2 ");
535
0
                any_compress = 1;
536
0
              }
537
538
0
      if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
539
0
              {
540
0
                strcat(dummy_string,"Z3 ");
541
0
                any_compress = 1;
542
0
              }
543
544
0
      if(!check_compress_algo(COMPRESS_ALGO_ZIP))
545
0
              {
546
0
                strcat(dummy_string,"Z1 ");
547
0
                any_compress = 1;
548
0
              }
549
550
            /* In case we have no compress algo at all, declare that
551
               we prefer no compression.  */
552
0
            if (!any_compress)
553
0
              strcat(dummy_string,"Z0 ");
554
555
            /* Remove the trailing space.  */
556
0
            if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
557
0
              dummy_string[strlen (dummy_string)-1] = 0;
558
559
0
      string=dummy_string;
560
0
    }
561
0
      }
562
0
    else if (!ascii_strcasecmp (string, "none"))
563
0
        string = "";
564
565
0
    if(strlen(string))
566
0
      {
567
0
  char *prefstringbuf;
568
0
        char *tok, *prefstring;
569
0
        int any_cipher=0, any_digest=0, any_compress=0, any_aead=0;
570
0
        int err_cipher=0, err_digest=0, err_compress=0, err_aead=0;
571
572
        /* We need a writable string. */
573
0
  prefstring = prefstringbuf = xstrdup (string);
574
575
0
  while((tok=strsep(&prefstring," ,")))
576
0
    {
577
0
            if (!*tok)
578
0
              ;
579
0
      else if((val=string_to_cipher_algo (tok)))
580
0
        {
581
0
    if(set_one_pref(val,1,tok,sym,&nsym))
582
0
      err_cipher = 1;
583
0
                else
584
0
                  any_cipher = 1;
585
0
        }
586
0
      else if((val=string_to_digest_algo (tok)))
587
0
        {
588
0
    if(set_one_pref(val,2,tok,hash,&nhash))
589
0
      err_digest = 1;
590
0
                else
591
0
                  any_digest = 1;
592
0
        }
593
0
      else if((val=string_to_compress_algo(tok))>-1)
594
0
        {
595
0
    if(set_one_pref(val,3,tok,zip,&nzip))
596
0
      err_compress = 1;
597
0
                else
598
0
                  any_compress = 1;
599
0
        }
600
0
      else if ((val=string_to_aead_algo (tok)))
601
0
        {
602
0
    if (set_one_pref (val, 4, tok, aead, &naead))
603
0
      err_aead = 1;
604
0
                else
605
0
                  any_aead = 1;
606
0
        }
607
0
      else if (!ascii_strcasecmp(tok, "mdc")
608
0
                     || !ascii_strcasecmp(tok, "[mdc]"))
609
0
        mdc=1;
610
0
      else if (!ascii_strcasecmp(tok, "no-mdc")
611
0
                     || !ascii_strcasecmp(tok, "[no-mdc]"))
612
0
        mdc=0;
613
0
      else if (!ascii_strcasecmp(tok, "ks-modify")
614
0
                     || !ascii_strcasecmp(tok, "[ks-modify]"))
615
0
        modify=1;
616
0
      else if (!ascii_strcasecmp(tok,"no-ks-modify")
617
0
                     || !ascii_strcasecmp(tok,"[no-ks-modify]"))
618
0
        modify=0;
619
0
      else if (!ascii_strcasecmp(tok,"aead")
620
0
                     || !ascii_strcasecmp(tok,"[aead]"))
621
0
              {
622
                /* Ignore because this is set from the preferences but
623
                 * shown in the in the preferences/features list.  */
624
0
              }
625
0
      else
626
0
        {
627
0
    log_info (_("invalid item '%s' in preference string\n"),tok);
628
0
    rc=-1;
629
0
        }
630
0
    }
631
632
        /* We return an error only if we have seen a parsing error for
633
         * one class but did not add any algorithm of that class.
634
         * Note that the set_one_pref functions already print log_info
635
         * diagnostics so that the user is made aware of the problems.
636
         * But tjhis way things work better even if an algorithm has
637
         * been disabled at the Libgcrypt level.  */
638
0
        if (!rc && ((err_cipher && !any_cipher)
639
0
                    || (err_digest && !any_digest)
640
0
                    || (err_compress && !any_compress)
641
0
                    || (err_aead && !any_aead)))
642
0
          rc = 1;
643
644
0
  xfree (prefstringbuf);
645
0
      }
646
647
0
    if(!rc)
648
0
      {
649
0
  if(personal)
650
0
    {
651
0
      if(personal==PREFTYPE_SYM)
652
0
        {
653
0
    xfree(opt.personal_cipher_prefs);
654
655
0
    if(nsym==0)
656
0
      opt.personal_cipher_prefs=NULL;
657
0
    else
658
0
      {
659
0
        int i;
660
661
0
        opt.personal_cipher_prefs=
662
0
          xmalloc(sizeof(prefitem_t *)*(nsym+1));
663
664
0
        for (i=0; i<nsym; i++)
665
0
          {
666
0
      opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
667
0
      opt.personal_cipher_prefs[i].value = sym[i];
668
0
          }
669
670
0
        opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
671
0
        opt.personal_cipher_prefs[i].value = 0;
672
0
      }
673
0
        }
674
0
      else if(personal==PREFTYPE_HASH)
675
0
        {
676
0
    xfree(opt.personal_digest_prefs);
677
678
0
    if(nhash==0)
679
0
      opt.personal_digest_prefs=NULL;
680
0
    else
681
0
      {
682
0
        int i;
683
684
0
        opt.personal_digest_prefs=
685
0
          xmalloc(sizeof(prefitem_t *)*(nhash+1));
686
687
0
        for (i=0; i<nhash; i++)
688
0
          {
689
0
      opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
690
0
      opt.personal_digest_prefs[i].value = hash[i];
691
0
          }
692
693
0
        opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
694
0
        opt.personal_digest_prefs[i].value = 0;
695
0
      }
696
0
        }
697
0
      else if(personal==PREFTYPE_ZIP)
698
0
        {
699
0
    xfree(opt.personal_compress_prefs);
700
701
0
    if(nzip==0)
702
0
      opt.personal_compress_prefs=NULL;
703
0
    else
704
0
      {
705
0
        int i;
706
707
0
        opt.personal_compress_prefs=
708
0
          xmalloc(sizeof(prefitem_t *)*(nzip+1));
709
710
0
        for (i=0; i<nzip; i++)
711
0
          {
712
0
      opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
713
0
      opt.personal_compress_prefs[i].value = zip[i];
714
0
          }
715
716
0
        opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
717
0
        opt.personal_compress_prefs[i].value = 0;
718
0
      }
719
0
        }
720
0
    }
721
0
  else
722
0
    {
723
0
      memcpy (sym_prefs,  sym,  (nsym_prefs=nsym));
724
0
      memcpy (hash_prefs, hash, (nhash_prefs=nhash));
725
0
      memcpy (zip_prefs,  zip,  (nzip_prefs=nzip));
726
0
      memcpy (aead_prefs, aead,  (naead_prefs=naead));
727
0
      mdc_available = mdc;
728
0
            aead_available = !!naead;
729
0
      ks_modify = modify;
730
0
      prefs_initialized = 1;
731
0
    }
732
0
      }
733
734
0
    return rc;
735
0
}
736
737
738
/* Return a fake user ID containing the preferences.  Caller must
739
   free. */
740
PKT_user_id *
741
keygen_get_std_prefs(void)
742
0
{
743
0
  int i,j=0;
744
0
  PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
745
746
0
  if(!prefs_initialized)
747
0
    keygen_set_std_prefs(NULL,0);
748
749
0
  uid->ref=1;
750
751
0
  uid->prefs = xmalloc ((sizeof(prefitem_t *)*
752
0
                         (nsym_prefs+naead_prefs+nhash_prefs+nzip_prefs+1)));
753
754
0
  for(i=0;i<nsym_prefs;i++,j++)
755
0
    {
756
0
      uid->prefs[j].type=PREFTYPE_SYM;
757
0
      uid->prefs[j].value=sym_prefs[i];
758
0
    }
759
760
0
  for (i=0; i < naead_prefs; i++, j++)
761
0
    {
762
0
      uid->prefs[j].type = PREFTYPE_AEAD;
763
0
      uid->prefs[j].value = aead_prefs[i];
764
0
    }
765
766
0
  for(i=0;i<nhash_prefs;i++,j++)
767
0
    {
768
0
      uid->prefs[j].type=PREFTYPE_HASH;
769
0
      uid->prefs[j].value=hash_prefs[i];
770
0
    }
771
772
0
  for(i=0;i<nzip_prefs;i++,j++)
773
0
    {
774
0
      uid->prefs[j].type=PREFTYPE_ZIP;
775
0
      uid->prefs[j].value=zip_prefs[i];
776
0
    }
777
778
0
  uid->prefs[j].type=PREFTYPE_NONE;
779
0
  uid->prefs[j].value=0;
780
781
0
  uid->flags.mdc = mdc_available;
782
0
  uid->flags.aead = aead_available;
783
0
  uid->flags.ks_modify = ks_modify;
784
785
0
  return uid;
786
0
}
787
788
static void
789
add_feature_mdc (PKT_signature *sig,int enabled)
790
0
{
791
0
    const byte *s;
792
0
    size_t n;
793
0
    int i;
794
0
    char *buf;
795
796
0
    s = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n );
797
    /* Already set or cleared */
798
0
    if (s && n &&
799
0
  ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
800
0
      return;
801
802
0
    if (!s || !n) { /* create a new one */
803
0
        n = 1;
804
0
        buf = xmalloc_clear (n);
805
0
    }
806
0
    else {
807
0
        buf = xmalloc (n);
808
0
        memcpy (buf, s, n);
809
0
    }
810
811
0
    if(enabled)
812
0
      buf[0] |= 0x01; /* MDC feature */
813
0
    else
814
0
      buf[0] &= ~0x01;
815
816
    /* Are there any bits set? */
817
0
    for(i=0;i<n;i++)
818
0
      if(buf[i]!=0)
819
0
  break;
820
821
0
    if(i==n)
822
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
823
0
    else
824
0
      build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
825
826
0
    xfree (buf);
827
0
}
828
829
830
static void
831
add_feature_aead (PKT_signature *sig, int enabled)
832
0
{
833
0
  const byte *s;
834
0
  size_t n;
835
0
  int i;
836
0
  char *buf;
837
838
0
  s = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n );
839
0
  if (s && n && ((enabled && (s[0] & 0x02)) || (!enabled && !(s[0] & 0x02))))
840
0
    return; /* Already set or cleared */
841
842
0
  if (!s || !n)
843
0
    { /* Create a new one */
844
0
      n = 1;
845
0
      buf = xmalloc_clear (n);
846
0
    }
847
0
  else
848
0
    {
849
0
      buf = xmalloc (n);
850
0
      memcpy (buf, s, n);
851
0
    }
852
853
0
  if (enabled)
854
0
    buf[0] |= 0x02; /* AEAD supported */
855
0
  else
856
0
    buf[0] &= ~0x02;
857
858
  /* Are there any bits set? */
859
0
  for (i=0; i < n; i++)
860
0
    if (buf[i])
861
0
      break;
862
863
0
  if (i == n)
864
0
    delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
865
0
  else
866
0
    build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
867
868
0
  xfree (buf);
869
0
}
870
871
872
static void
873
add_feature_v5 (PKT_signature *sig, int enabled)
874
0
{
875
0
  const byte *s;
876
0
  size_t n;
877
0
  int i;
878
0
  char *buf;
879
880
0
  s = parse_sig_subpkt (sig, 1, SIGSUBPKT_FEATURES, &n );
881
0
  if (s && n && ((enabled && (s[0] & 0x04)) || (!enabled && !(s[0] & 0x04))))
882
0
    return; /* Already set or cleared */
883
884
0
  if (!s || !n)
885
0
    { /* Create a new one */
886
0
      n = 1;
887
0
      buf = xmalloc_clear (n);
888
0
    }
889
0
  else
890
0
    {
891
0
      buf = xmalloc (n);
892
0
      memcpy (buf, s, n);
893
0
    }
894
895
0
  if (enabled)
896
0
    buf[0] |= 0x04; /* v5 key supported */
897
0
  else
898
0
    buf[0] &= ~0x04;
899
900
  /* Are there any bits set? */
901
0
  for (i=0; i < n; i++)
902
0
    if (buf[i])
903
0
      break;
904
905
0
  if (i == n)
906
0
    delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
907
0
  else
908
0
    build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
909
910
0
  xfree (buf);
911
0
}
912
913
914
static void
915
add_keyserver_modify (PKT_signature *sig,int enabled)
916
0
{
917
0
  const byte *s;
918
0
  size_t n;
919
0
  int i;
920
0
  char *buf;
921
922
  /* The keyserver modify flag is a negative flag (i.e. no-modify) */
923
0
  enabled=!enabled;
924
925
0
  s = parse_sig_subpkt (sig, 1, SIGSUBPKT_KS_FLAGS, &n );
926
  /* Already set or cleared */
927
0
  if (s && n &&
928
0
      ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
929
0
    return;
930
931
0
  if (!s || !n) { /* create a new one */
932
0
    n = 1;
933
0
    buf = xmalloc_clear (n);
934
0
  }
935
0
  else {
936
0
    buf = xmalloc (n);
937
0
    memcpy (buf, s, n);
938
0
  }
939
940
0
  if(enabled)
941
0
    buf[0] |= 0x80; /* no-modify flag */
942
0
  else
943
0
    buf[0] &= ~0x80;
944
945
  /* Are there any bits set? */
946
0
  for(i=0;i<n;i++)
947
0
    if(buf[i]!=0)
948
0
      break;
949
950
0
  if(i==n)
951
0
    delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
952
0
  else
953
0
    build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
954
955
0
  xfree (buf);
956
0
}
957
958
959
int
960
keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
961
0
{
962
0
  (void)opaque;
963
964
0
  if (!prefs_initialized)
965
0
    keygen_set_std_prefs (NULL, 0);
966
967
0
  if (nsym_prefs)
968
0
    build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
969
0
  else
970
0
    {
971
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
972
0
      delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
973
0
    }
974
975
0
  if (naead_prefs)
976
0
    build_sig_subpkt (sig, SIGSUBPKT_PREF_AEAD, aead_prefs, naead_prefs);
977
0
  else
978
0
    {
979
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_AEAD);
980
0
      delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_AEAD);
981
0
    }
982
983
0
  if (nhash_prefs)
984
0
    build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
985
0
  else
986
0
    {
987
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
988
0
      delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
989
0
    }
990
991
0
  if (nzip_prefs)
992
0
    build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
993
0
  else
994
0
    {
995
0
      delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
996
0
      delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
997
0
    }
998
999
  /* Make sure that the MDC feature flag is set if needed.  */
1000
0
  add_feature_mdc (sig,mdc_available);
1001
0
  add_feature_aead (sig, aead_available);
1002
0
  add_feature_v5 (sig, 1);
1003
0
  add_keyserver_modify (sig,ks_modify);
1004
0
  keygen_add_keyserver_url(sig,NULL);
1005
1006
0
  return 0;
1007
0
}
1008
1009
1010
/****************
1011
 * Add preference to the self signature packet.
1012
 * This is only called for packets with version > 3.
1013
 */
1014
int
1015
keygen_add_std_prefs (PKT_signature *sig, void *opaque)
1016
0
{
1017
0
  PKT_public_key *pk = opaque;
1018
1019
0
  do_add_key_flags (sig, pk->pubkey_usage);
1020
0
  keygen_add_key_expire (sig, opaque );
1021
0
  keygen_upd_std_prefs (sig, opaque);
1022
0
  keygen_add_keyserver_url (sig,NULL);
1023
1024
0
  return 0;
1025
0
}
1026
1027
int
1028
keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
1029
0
{
1030
0
  const char *url=opaque;
1031
1032
0
  if(!url)
1033
0
    url=opt.def_keyserver_url;
1034
1035
0
  if(url)
1036
0
    build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
1037
0
  else
1038
0
    delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
1039
1040
0
  return 0;
1041
0
}
1042
1043
1044
/* This function is used to add a notations to a signature.  In
1045
 * general the caller should have cleared exiting notations before
1046
 * adding new ones.  For example by calling:
1047
 *
1048
 *  delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
1049
 *  delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
1050
 *
1051
 * Only human readable notaions may be added.  NAME and value are
1052
 * expected to be UTF-* strings.
1053
 */
1054
static void
1055
do_add_notation (PKT_signature *sig, const char *name, const char *value,
1056
                 int critical)
1057
0
{
1058
0
  unsigned char *buf;
1059
0
  unsigned int n1,n2;
1060
1061
0
  n1 = strlen (name);
1062
0
  n2 = strlen (value);
1063
1064
0
  buf = xmalloc (8 + n1 + n2);
1065
1066
0
  buf[0] = 0x80; /* human readable.  */
1067
0
  buf[1] = buf[2] = buf[3] = 0;
1068
0
  buf[4] = n1 >> 8;
1069
0
  buf[5] = n1;
1070
0
  buf[6] = n2 >> 8;
1071
0
  buf[7] = n2;
1072
0
  memcpy (buf+8, name, n1);
1073
0
  memcpy (buf+8+n1, value, n2);
1074
0
  build_sig_subpkt (sig,
1075
0
                    (SIGSUBPKT_NOTATION|(critical?SIGSUBPKT_FLAG_CRITICAL:0)),
1076
0
                    buf, 8+n1+n2 );
1077
0
  xfree (buf);
1078
0
}
1079
1080
1081
int
1082
keygen_add_notations(PKT_signature *sig,void *opaque)
1083
0
{
1084
0
  struct notation *notation;
1085
1086
  /* We always start clean */
1087
0
  delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
1088
0
  delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
1089
0
  sig->flags.notation=0;
1090
1091
0
  for(notation=opaque;notation;notation=notation->next)
1092
0
    if(!notation->flags.ignore)
1093
0
      {
1094
0
  unsigned char *buf;
1095
0
  unsigned int n1,n2;
1096
1097
0
  n1=strlen(notation->name);
1098
0
  if(notation->altvalue)
1099
0
    n2=strlen(notation->altvalue);
1100
0
  else if(notation->bdat)
1101
0
    n2=notation->blen;
1102
0
  else
1103
0
    n2=strlen(notation->value);
1104
1105
0
  buf = xmalloc( 8 + n1 + n2 );
1106
1107
  /* human readable or not */
1108
0
  buf[0] = notation->bdat?0:0x80;
1109
0
  buf[1] = buf[2] = buf[3] = 0;
1110
0
  buf[4] = n1 >> 8;
1111
0
  buf[5] = n1;
1112
0
  buf[6] = n2 >> 8;
1113
0
  buf[7] = n2;
1114
0
  memcpy(buf+8, notation->name, n1 );
1115
0
  if(notation->altvalue)
1116
0
    memcpy(buf+8+n1, notation->altvalue, n2 );
1117
0
  else if(notation->bdat)
1118
0
    memcpy(buf+8+n1, notation->bdat, n2 );
1119
0
  else
1120
0
    memcpy(buf+8+n1, notation->value, n2 );
1121
0
  build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
1122
0
        (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
1123
0
        buf, 8+n1+n2 );
1124
0
  xfree(buf);
1125
0
      }
1126
1127
0
  return 0;
1128
0
}
1129
1130
1131
int
1132
keygen_add_revkey (PKT_signature *sig, void *opaque)
1133
0
{
1134
0
  struct revocation_key *revkey = opaque;
1135
0
  byte buf[2+MAX_FINGERPRINT_LEN];
1136
1137
0
  log_assert (revkey->fprlen <= MAX_FINGERPRINT_LEN);
1138
0
  buf[0] = revkey->class;
1139
0
  buf[1] = revkey->algid;
1140
0
  memcpy (buf + 2, revkey->fpr, revkey->fprlen);
1141
0
  memset (buf + 2 + revkey->fprlen, 0, sizeof (revkey->fpr) - revkey->fprlen);
1142
1143
0
  build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+revkey->fprlen);
1144
1145
  /* All sigs with revocation keys set are nonrevocable.  */
1146
0
  sig->flags.revocable = 0;
1147
0
  buf[0] = 0;
1148
0
  build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
1149
1150
0
  parse_revkeys (sig);
1151
1152
0
  return 0;
1153
0
}
1154
1155
1156
1157
/* Create a back-signature.  If TIMESTAMP is not NULL, use it for the
1158
   signature creation time.  */
1159
gpg_error_t
1160
make_backsig (ctrl_t ctrl, PKT_signature *sig, PKT_public_key *pk,
1161
              PKT_public_key *sub_pk, PKT_public_key *sub_psk,
1162
              u32 timestamp, const char *cache_nonce)
1163
0
{
1164
0
  gpg_error_t err;
1165
0
  PKT_signature *backsig;
1166
1167
0
  cache_public_key (sub_pk);
1168
1169
0
  err = make_keysig_packet (ctrl, &backsig, pk, NULL, sub_pk, sub_psk, 0x19,
1170
0
                            timestamp, 0, NULL, NULL, cache_nonce);
1171
0
  if (err)
1172
0
    log_error ("make_keysig_packet failed for backsig: %s\n",
1173
0
               gpg_strerror (err));
1174
0
  else
1175
0
    {
1176
      /* Get it into a binary packed form. */
1177
0
      IOBUF backsig_out = iobuf_temp();
1178
0
      PACKET backsig_pkt;
1179
1180
0
      init_packet (&backsig_pkt);
1181
0
      backsig_pkt.pkttype = PKT_SIGNATURE;
1182
0
      backsig_pkt.pkt.signature = backsig;
1183
0
      err = build_packet (backsig_out, &backsig_pkt);
1184
0
      free_packet (&backsig_pkt, NULL);
1185
0
      if (err)
1186
0
  log_error ("build_packet failed for backsig: %s\n", gpg_strerror (err));
1187
0
      else
1188
0
  {
1189
0
    size_t pktlen = 0;
1190
0
    byte *buf = iobuf_get_temp_buffer (backsig_out);
1191
1192
    /* Remove the packet header. */
1193
0
    if(buf[0]&0x40)
1194
0
      {
1195
0
        if (buf[1] < 192)
1196
0
    {
1197
0
      pktlen = buf[1];
1198
0
      buf += 2;
1199
0
    }
1200
0
        else if(buf[1] < 224)
1201
0
    {
1202
0
      pktlen = (buf[1]-192)*256;
1203
0
      pktlen += buf[2]+192;
1204
0
      buf += 3;
1205
0
    }
1206
0
        else if (buf[1] == 255)
1207
0
    {
1208
0
                  pktlen = buf32_to_size_t (buf+2);
1209
0
      buf += 6;
1210
0
    }
1211
0
        else
1212
0
    BUG ();
1213
0
      }
1214
0
    else
1215
0
      {
1216
0
        int mark = 1;
1217
1218
0
        switch (buf[0]&3)
1219
0
    {
1220
0
    case 3:
1221
0
      BUG ();
1222
0
      break;
1223
1224
0
    case 2:
1225
0
      pktlen  = (size_t)buf[mark++] << 24;
1226
0
      pktlen |= buf[mark++] << 16;
1227
      /* fall through */
1228
0
    case 1:
1229
0
      pktlen |= buf[mark++] << 8;
1230
      /* fall through */
1231
0
    case 0:
1232
0
      pktlen |= buf[mark++];
1233
0
    }
1234
1235
0
        buf += mark;
1236
0
      }
1237
1238
    /* Now make the binary blob into a subpacket.  */
1239
0
    build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
1240
1241
0
    iobuf_close (backsig_out);
1242
0
  }
1243
0
    }
1244
1245
0
  return err;
1246
0
}
1247
1248
1249
/* This function should be called to make sure that
1250
 * opt.def_new_key_adsks has no duplicates and that tehre is no '!'
1251
 * suffix.  We don't do this during normal option processing because
1252
 * this list is only needed for a very few operations.  Callingit
1253
 * twice does not harm.  Users of the option list should skip empty
1254
 * items.  */
1255
void
1256
keygen_prepare_new_key_adsks (void)
1257
0
{
1258
0
  strlist_t sl, slr;
1259
0
  char *p;
1260
1261
0
  for (sl = opt.def_new_key_adsks; sl; sl = sl->next)
1262
0
    {
1263
0
      if (!*sl->d)
1264
0
        continue;
1265
0
      p = strchr (sl->d, '!');
1266
0
      if (p)
1267
0
        *p = 0;
1268
0
      for (slr = opt.def_new_key_adsks; slr != sl; slr = slr->next)
1269
0
        if (!ascii_strcasecmp (sl->d, slr->d))
1270
0
          {
1271
0
            *sl->d = 0; /* clear fpr to mark this as a duplicate.  */
1272
0
            break;
1273
0
          }
1274
0
    }
1275
0
}
1276
1277
1278
/* Append all default ADSKs to the KEYBLOCK but ignore those which are
1279
 * already on that keyblock.  Returns 0 if any key has been added;
1280
 * GPG_ERR_FALSE if no key was added or any other error code.  */
1281
gpg_error_t
1282
append_all_default_adsks (ctrl_t ctrl, kbnode_t keyblock)
1283
0
{
1284
0
  gpg_error_t err = 0;
1285
0
  int any_done = 0;
1286
0
  strlist_t sl;
1287
0
  struct para_data_s *para;
1288
0
  byte adskfpr[MAX_FINGERPRINT_LEN];
1289
0
  size_t adskfprlen;
1290
0
  u32 sigtimestamp = make_timestamp ();
1291
1292
0
  keygen_prepare_new_key_adsks ();
1293
0
  for (sl = opt.def_new_key_adsks; sl && !err; sl = sl->next)
1294
0
    {
1295
0
      if (!*sl->d)
1296
0
        continue;
1297
0
      para = prepare_adsk (ctrl, sl->d);
1298
0
      if (para)
1299
0
        {
1300
0
          fingerprint_from_pk (para->u.adsk, adskfpr, &adskfprlen);
1301
0
          if (!has_key_with_fingerprint (keyblock, adskfpr, adskfprlen))
1302
0
            {
1303
              /* Fixme: We should use a cache nonce so that only one
1304
               * pinentry pops up.  */
1305
0
              err = append_adsk_to_key (ctrl, keyblock, para->u.adsk,
1306
0
                                        sigtimestamp, NULL);
1307
0
              if (!err)
1308
0
                any_done = 1;
1309
0
            }
1310
0
          release_parameter_list (para);
1311
0
        }
1312
0
    }
1313
1314
0
  if (!err && !any_done)
1315
0
    err = gpg_error (GPG_ERR_FALSE);
1316
1317
0
  return err;
1318
0
}
1319
1320
1321
/* Write a direct key signature to the first key in ROOT using the key
1322
   PSK.  REVKEY is describes the direct key signature and TIMESTAMP is
1323
   the timestamp to set on the signature.  */
1324
static gpg_error_t
1325
write_direct_sig (ctrl_t ctrl, kbnode_t root, PKT_public_key *psk,
1326
                  struct revocation_key *revkey, u32 timestamp,
1327
                  const char *cache_nonce)
1328
0
{
1329
0
  gpg_error_t err;
1330
0
  PACKET *pkt;
1331
0
  PKT_signature *sig;
1332
0
  KBNODE node;
1333
0
  PKT_public_key *pk;
1334
1335
0
  if (opt.verbose)
1336
0
    log_info (_("writing direct signature\n"));
1337
1338
  /* Get the pk packet from the pub_tree. */
1339
0
  node = find_kbnode (root, PKT_PUBLIC_KEY);
1340
0
  if (!node)
1341
0
    BUG ();
1342
0
  pk = node->pkt->pkt.public_key;
1343
1344
  /* We have to cache the key, so that the verification of the
1345
     signature creation is able to retrieve the public key.  */
1346
0
  cache_public_key (pk);
1347
1348
  /* Make the signature.  */
1349
0
  err = make_keysig_packet (ctrl, &sig, pk, NULL,NULL, psk, 0x1F,
1350
0
                            timestamp, 0,
1351
0
                            keygen_add_revkey, revkey, cache_nonce);
1352
0
  if (err)
1353
0
    {
1354
0
      log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err) );
1355
0
      return err;
1356
0
    }
1357
1358
0
  pkt = xmalloc_clear (sizeof *pkt);
1359
0
  pkt->pkttype = PKT_SIGNATURE;
1360
0
  pkt->pkt.signature = sig;
1361
0
  add_kbnode (root, new_kbnode (pkt));
1362
0
  return err;
1363
0
}
1364
1365
1366
1367
/* Write a self-signature to the first user id in ROOT using the key
1368
   PSK.  USE and TIMESTAMP give the extra data we need for the
1369
   signature.  */
1370
static gpg_error_t
1371
write_selfsigs (ctrl_t ctrl, kbnode_t root, PKT_public_key *psk,
1372
    unsigned int use, u32 timestamp, const char *cache_nonce)
1373
0
{
1374
0
  gpg_error_t err;
1375
0
  PACKET *pkt;
1376
0
  PKT_signature *sig;
1377
0
  PKT_user_id *uid;
1378
0
  KBNODE node;
1379
0
  PKT_public_key *pk;
1380
1381
0
  if (opt.verbose)
1382
0
    log_info (_("writing self signature\n"));
1383
1384
  /* Get the uid packet from the list. */
1385
0
  node = find_kbnode (root, PKT_USER_ID);
1386
0
  if (!node)
1387
0
    BUG(); /* No user id packet in tree.  */
1388
0
  uid = node->pkt->pkt.user_id;
1389
1390
  /* Get the pk packet from the pub_tree. */
1391
0
  node = find_kbnode (root, PKT_PUBLIC_KEY);
1392
0
  if (!node)
1393
0
    BUG();
1394
0
  pk = node->pkt->pkt.public_key;
1395
1396
  /* The usage has not yet been set - do it now. */
1397
0
  pk->pubkey_usage = use;
1398
1399
  /* We have to cache the key, so that the verification of the
1400
     signature creation is able to retrieve the public key.  */
1401
0
  cache_public_key (pk);
1402
1403
  /* Make the signature.  */
1404
0
  err = make_keysig_packet (ctrl, &sig, pk, uid, NULL, psk, 0x13,
1405
0
                            timestamp, 0,
1406
0
                            keygen_add_std_prefs, pk, cache_nonce);
1407
0
  if (err)
1408
0
    {
1409
0
      log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
1410
0
      return err;
1411
0
    }
1412
1413
0
  pkt = xmalloc_clear (sizeof *pkt);
1414
0
  pkt->pkttype = PKT_SIGNATURE;
1415
0
  pkt->pkt.signature = sig;
1416
0
  add_kbnode (root, new_kbnode (pkt));
1417
1418
0
  return err;
1419
0
}
1420
1421
1422
/* Append a key binding signature to the last subkey in KEYBLOCK.
1423
 * PRI_PSK is the key used to create (sign) the key binding signature
1424
 * this is usuallay the primary key.  SUB_PSK is a key used to create
1425
 * a back-signature; this is required if the PUBKEY_USAGE_SIG
1426
 * capability is passed in USE (which gives the key usage).  TIMESTAMP
1427
 * is the signature creation time with 0 meaning "now".  CACHE_NONCE
1428
 * is passed to the agent to indentify the passphrase cache slot.  */
1429
static int
1430
write_keybinding (ctrl_t ctrl, kbnode_t keyblock,
1431
                  PKT_public_key *pri_psk, PKT_public_key *sub_psk,
1432
                  unsigned int use, u32 timestamp, const char *cache_nonce)
1433
0
{
1434
0
  gpg_error_t err;
1435
0
  PACKET *pkt;
1436
0
  PKT_signature *sig;
1437
0
  KBNODE node;
1438
0
  PKT_public_key *pri_pk, *sub_pk;
1439
0
  struct opaque_data_usage_and_pk oduap;
1440
1441
0
  if (opt.verbose)
1442
0
    log_info(_("writing key binding signature\n"));
1443
1444
  /* Get the primary pk packet from the tree.  */
1445
0
  node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1446
0
  if (!node)
1447
0
    BUG();
1448
0
  pri_pk = node->pkt->pkt.public_key;
1449
1450
  /* We have to cache the key, so that the verification of the
1451
   * signature creation is able to retrieve the public key.  */
1452
0
  cache_public_key (pri_pk);
1453
1454
  /* Find the last subkey. */
1455
0
  sub_pk = NULL;
1456
0
  for (node = keyblock; node; node = node->next )
1457
0
    {
1458
0
      if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1459
0
        sub_pk = node->pkt->pkt.public_key;
1460
0
    }
1461
0
  if (!sub_pk)
1462
0
    BUG();
1463
1464
  /* Make the signature.  */
1465
0
  oduap.usage = use;
1466
0
  if ((use & PUBKEY_USAGE_ENC)
1467
0
      && opt.compliance == CO_DE_VS
1468
      /* The required libgcrypt 1.11 won't yet claim a compliant RNG.  */
1469
0
      && gnupg_rng_is_compliant (CO_DE_VS))
1470
0
    oduap.cpl_notation = "de-vs";
1471
0
  else
1472
0
    oduap.cpl_notation = NULL;
1473
0
  oduap.pk = sub_pk;
1474
0
  err = make_keysig_packet (ctrl, &sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
1475
0
                            timestamp, 0,
1476
0
                            keygen_add_key_flags_from_oduap, &oduap,
1477
0
                            cache_nonce);
1478
0
  if (err)
1479
0
    {
1480
0
      log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
1481
0
      return err;
1482
0
    }
1483
1484
  /* Make a backsig.  */
1485
0
  if (use & PUBKEY_USAGE_SIG)
1486
0
    {
1487
0
      err = make_backsig (ctrl,
1488
0
                          sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
1489
0
      if (err)
1490
0
        return err;
1491
0
    }
1492
1493
0
  pkt = xmalloc_clear ( sizeof *pkt );
1494
0
  pkt->pkttype = PKT_SIGNATURE;
1495
0
  pkt->pkt.signature = sig;
1496
0
  add_kbnode (keyblock, new_kbnode (pkt) );
1497
0
  return err;
1498
0
}
1499
1500
1501
/* Returns true if SEXP specified the curve ED448 or X448.  */
1502
static int
1503
curve_is_448 (gcry_sexp_t sexp)
1504
0
{
1505
0
  gcry_sexp_t list, l2;
1506
0
  char *curve;
1507
0
  int result;
1508
1509
0
  list = gcry_sexp_find_token (sexp, "public-key", 0);
1510
0
  if (!list)
1511
0
    return 0;  /* Not a public key.  */
1512
0
  l2 = gcry_sexp_cadr (list);
1513
0
  gcry_sexp_release (list);
1514
0
  list = l2;
1515
0
  if (!list)
1516
0
    return 0; /* Bad public key.  */
1517
1518
0
  l2 = gcry_sexp_find_token (list, "curve", 0);
1519
0
  gcry_sexp_release (list);
1520
0
  if (!l2)
1521
0
    return 0; /* No curve parameter.  */
1522
0
  curve = gcry_sexp_nth_string (l2, 1);
1523
0
  gcry_sexp_release (l2);
1524
0
  if (!curve)
1525
0
    return 0; /* Bad curve parameter.  */
1526
0
  result = (!ascii_strcasecmp (curve, "X448")
1527
0
            || !ascii_strcasecmp (curve, "Ed448")
1528
0
            || !ascii_strcasecmp (curve, "cv448"));
1529
0
  xfree (curve);
1530
0
  return result;
1531
0
}
1532
1533
1534
/* Extract the parameters in OpenPGP format from SEXP and put them
1535
 * into the caller provided ARRAY.  SEXP2 is used to provide the
1536
 * parameters for dual algorithm (e.g. Kyber).  */
1537
static gpg_error_t
1538
ecckey_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1539
                  gcry_sexp_t sexp2, int algo, int pkversion)
1540
0
{
1541
0
  gpg_error_t err;
1542
0
  gcry_sexp_t list, l2;
1543
0
  char *curve = NULL;
1544
0
  int i;
1545
0
  const char *oidstr;
1546
0
  unsigned int nbits;
1547
1548
0
  array[0] = NULL;
1549
0
  array[1] = NULL;
1550
0
  array[2] = NULL;
1551
1552
0
  list = gcry_sexp_find_token (sexp, "public-key", 0);
1553
0
  if (!list)
1554
0
    return gpg_error (GPG_ERR_INV_OBJ);
1555
0
  l2 = gcry_sexp_cadr (list);
1556
0
  gcry_sexp_release (list);
1557
0
  list = l2;
1558
0
  if (!list)
1559
0
    return gpg_error (GPG_ERR_NO_OBJ);
1560
1561
0
  l2 = gcry_sexp_find_token (list, "curve", 0);
1562
0
  if (!l2)
1563
0
    {
1564
0
      err = gpg_error (GPG_ERR_NO_OBJ);
1565
0
      goto leave;
1566
0
    }
1567
0
  curve = gcry_sexp_nth_string (l2, 1);
1568
0
  if (!curve)
1569
0
    {
1570
0
      err = gpg_error (GPG_ERR_NO_OBJ);
1571
0
      goto leave;
1572
0
    }
1573
0
  gcry_sexp_release (l2);
1574
0
  oidstr = openpgp_curve_to_oid (curve, &nbits, NULL, pkversion > 4);
1575
0
  if (!oidstr)
1576
0
    {
1577
      /* That can't happen because we used one of the curves
1578
         gpg_curve_to_oid knows about.  */
1579
0
      err = gpg_error (GPG_ERR_INV_OBJ);
1580
0
      goto leave;
1581
0
    }
1582
1583
0
  err = openpgp_oid_from_str (oidstr, &array[0]);
1584
0
  if (err)
1585
0
    goto leave;
1586
1587
0
  err = sexp_extract_param_sos (list, "q", &array[1]);
1588
0
  if (err)
1589
0
    goto leave;
1590
1591
0
  gcry_sexp_release (list);
1592
0
  list = NULL;
1593
1594
0
  if (algo == PUBKEY_ALGO_KYBER)
1595
0
    {
1596
0
      if (!sexp2)
1597
0
        {
1598
0
          err = gpg_error (GPG_ERR_MISSING_VALUE);
1599
0
          goto leave;
1600
0
        }
1601
1602
0
      list = gcry_sexp_find_token (sexp2, "public-key", 0);
1603
0
      if (!list)
1604
0
        {
1605
0
          err = gpg_error (GPG_ERR_INV_OBJ);
1606
0
          goto leave;
1607
0
        }
1608
0
      l2 = gcry_sexp_cadr (list);
1609
0
      gcry_sexp_release (list);
1610
0
      list = l2;
1611
0
      if (!list)
1612
0
        {
1613
0
          err = gpg_error (GPG_ERR_NO_OBJ);
1614
0
          goto leave;
1615
0
        }
1616
1617
0
      l2 = gcry_sexp_find_token (list, "p", 1);
1618
0
      if (!l2)
1619
0
        {
1620
0
          err = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1621
0
          goto leave;
1622
0
        }
1623
0
      array[2] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_OPAQUE);
1624
0
      gcry_sexp_release (l2);
1625
0
      if (!array[2])
1626
0
        {
1627
0
          err = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1628
0
          goto leave;
1629
0
        }
1630
0
    }
1631
0
  else if (algo == PUBKEY_ALGO_ECDH)
1632
0
    {
1633
0
      array[2] = pk_ecdh_default_params (nbits);
1634
0
      if (!array[2])
1635
0
        {
1636
0
          err = gpg_error_from_syserror ();
1637
0
          goto leave;
1638
0
        }
1639
0
    }
1640
1641
0
 leave:
1642
0
  xfree (curve);
1643
0
  gcry_sexp_release (list);
1644
0
  if (err)
1645
0
    {
1646
0
      for (i=0; i < 3; i++)
1647
0
        {
1648
0
          gcry_mpi_release (array[i]);
1649
0
          array[i] = NULL;
1650
0
        }
1651
0
    }
1652
0
  return err;
1653
0
}
1654
1655
1656
/* Extract key parameters from SEXP and store them in ARRAY.  ELEMS is
1657
   a string where each character denotes a parameter name.  TOPNAME is
1658
   the name of the top element above the elements.  */
1659
static int
1660
key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1661
               const char *topname, const char *elems)
1662
0
{
1663
0
  gcry_sexp_t list, l2;
1664
0
  const char *s;
1665
0
  int i, idx;
1666
0
  int rc = 0;
1667
1668
0
  list = gcry_sexp_find_token (sexp, topname, 0);
1669
0
  if (!list)
1670
0
    return gpg_error (GPG_ERR_INV_OBJ);
1671
0
  l2 = gcry_sexp_cadr (list);
1672
0
  gcry_sexp_release (list);
1673
0
  list = l2;
1674
0
  if (!list)
1675
0
    return gpg_error (GPG_ERR_NO_OBJ);
1676
1677
0
  for (idx=0,s=elems; *s; s++, idx++)
1678
0
    {
1679
0
      l2 = gcry_sexp_find_token (list, s, 1);
1680
0
      if (!l2)
1681
0
        {
1682
0
          rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1683
0
          goto leave;
1684
0
        }
1685
0
      array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1686
0
      gcry_sexp_release (l2);
1687
0
      if (!array[idx])
1688
0
        {
1689
0
          rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1690
0
          goto leave;
1691
0
        }
1692
0
    }
1693
0
  gcry_sexp_release (list);
1694
1695
0
 leave:
1696
0
  if (rc)
1697
0
    {
1698
0
      for (i=0; i<idx; i++)
1699
0
        {
1700
0
          gcry_mpi_release (array[i]);
1701
0
          array[i] = NULL;
1702
0
        }
1703
0
      gcry_sexp_release (list);
1704
0
    }
1705
0
  return rc;
1706
0
}
1707
1708
1709
/* Create a keyblock using the given KEYGRIP.  ALGO is the OpenPGP
1710
 * algorithm of that keygrip.  If CARDKEY is true the key is expected
1711
 * to already live on the active card.  */
1712
static int
1713
do_create_from_keygrip (ctrl_t ctrl, int algo,
1714
                        const char *hexkeygrip, int cardkey,
1715
                        kbnode_t pub_root, u32 timestamp, u32 expireval,
1716
                        int is_subkey, int *keygen_flags)
1717
0
{
1718
0
  int err;
1719
0
  PACKET *pkt;
1720
0
  PKT_public_key *pk;
1721
0
  gcry_sexp_t s_key;
1722
0
  gcry_sexp_t s_key2 = NULL;
1723
0
  const char *algoelem;
1724
0
  char *hexkeygrip_buffer = NULL;
1725
0
  char *hexkeygrip2 = NULL;
1726
1727
0
  if (hexkeygrip[0] == '&')
1728
0
    hexkeygrip++;
1729
0
  if (strchr (hexkeygrip, ','))
1730
0
    {
1731
0
      hexkeygrip_buffer = xtrystrdup (hexkeygrip);
1732
0
      if (!hexkeygrip_buffer)
1733
0
        return gpg_error_from_syserror ();
1734
0
      hexkeygrip = hexkeygrip_buffer;
1735
0
      hexkeygrip2 = strchr (hexkeygrip_buffer, ',');
1736
0
      if (hexkeygrip2)
1737
0
        *hexkeygrip2++ = 0;
1738
0
    }
1739
1740
1741
0
  switch (algo)
1742
0
    {
1743
0
    case PUBKEY_ALGO_RSA:       algoelem = "ne"; break;
1744
0
    case PUBKEY_ALGO_DSA:       algoelem = "pqgy"; break;
1745
0
    case PUBKEY_ALGO_ELGAMAL_E: algoelem = "pgy"; break;
1746
0
    case PUBKEY_ALGO_ECDH:
1747
0
    case PUBKEY_ALGO_ECDSA:     algoelem = ""; break;
1748
0
    case PUBKEY_ALGO_EDDSA:     algoelem = ""; break;
1749
0
    case PUBKEY_ALGO_KYBER:     algoelem = ""; break;
1750
0
    default:
1751
0
      xfree (hexkeygrip_buffer);
1752
0
      return gpg_error (GPG_ERR_INTERNAL);
1753
0
    }
1754
1755
  /* Ask the agent for the public key matching HEXKEYGRIP.  */
1756
0
  if (cardkey)
1757
0
    {
1758
0
      err = agent_scd_readkey (ctrl, hexkeygrip, &s_key, NULL);
1759
0
      if (err)
1760
0
        {
1761
0
          xfree (hexkeygrip_buffer);
1762
0
          return err;
1763
0
        }
1764
0
    }
1765
0
  else
1766
0
    {
1767
0
      unsigned char *public;
1768
1769
0
      err = agent_readkey (ctrl, 0, hexkeygrip, &public);
1770
0
      if (err)
1771
0
        {
1772
0
          xfree (hexkeygrip_buffer);
1773
0
          return err;
1774
0
        }
1775
0
      err = gcry_sexp_sscan (&s_key, NULL, public,
1776
0
                               gcry_sexp_canon_len (public, 0, NULL, NULL));
1777
0
      xfree (public);
1778
0
      if (err)
1779
0
        {
1780
0
          xfree (hexkeygrip_buffer);
1781
0
          return err;
1782
0
        }
1783
0
      if (hexkeygrip2)
1784
0
        {
1785
0
          err = agent_readkey (ctrl, 0, hexkeygrip2, &public);
1786
0
          if (err)
1787
0
            {
1788
0
              gcry_sexp_release (s_key);
1789
0
              xfree (hexkeygrip_buffer);
1790
0
              return err;
1791
0
            }
1792
0
          err = gcry_sexp_sscan (&s_key2, NULL, public,
1793
0
                                 gcry_sexp_canon_len (public, 0, NULL, NULL));
1794
0
          xfree (public);
1795
0
          if (err)
1796
0
            {
1797
0
              gcry_sexp_release (s_key);
1798
0
              xfree (hexkeygrip_buffer);
1799
0
              return err;
1800
0
            }
1801
0
        }
1802
0
    }
1803
1804
  /* For X448 and Kyber we force the use of v5 packets.  */
1805
0
  if (curve_is_448 (s_key) || algo == PUBKEY_ALGO_KYBER)
1806
0
    *keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
1807
1808
  /* Build a public key packet.  */
1809
0
  pk = xtrycalloc (1, sizeof *pk);
1810
0
  if (!pk)
1811
0
    {
1812
0
      err = gpg_error_from_syserror ();
1813
0
      gcry_sexp_release (s_key);
1814
0
      gcry_sexp_release (s_key2);
1815
0
      xfree (hexkeygrip_buffer);
1816
0
      return err;
1817
0
    }
1818
1819
0
  pk->timestamp = timestamp;
1820
0
  pk->version = (*keygen_flags & KEYGEN_FLAG_CREATE_V5_KEY)? 5 : 4;
1821
0
  if (expireval)
1822
0
    pk->expiredate = pk->timestamp + expireval;
1823
0
  pk->pubkey_algo = algo;
1824
1825
0
  if (algo == PUBKEY_ALGO_KYBER)
1826
0
    err = ecckey_from_sexp (pk->pkey, s_key, s_key2, algo, pk->version);
1827
0
  else if (algo == PUBKEY_ALGO_ECDSA
1828
0
      || algo == PUBKEY_ALGO_EDDSA
1829
0
      || algo == PUBKEY_ALGO_ECDH )
1830
0
    err = ecckey_from_sexp (pk->pkey, s_key, NULL, algo, pk->version);
1831
0
  else
1832
0
    err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1833
0
  if (err)
1834
0
    {
1835
0
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1836
0
      gcry_sexp_release (s_key);
1837
0
      gcry_sexp_release (s_key2);
1838
0
      free_public_key (pk);
1839
0
      xfree (hexkeygrip_buffer);
1840
0
      return err;
1841
0
    }
1842
0
  gcry_sexp_release (s_key);
1843
0
  gcry_sexp_release (s_key2);
1844
1845
0
  pkt = xtrycalloc (1, sizeof *pkt);
1846
0
  if (!pkt)
1847
0
    {
1848
0
      err = gpg_error_from_syserror ();
1849
0
      free_public_key (pk);
1850
0
      xfree (hexkeygrip_buffer);
1851
0
      return err;
1852
0
    }
1853
1854
0
  pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1855
0
  pkt->pkt.public_key = pk;
1856
0
  add_kbnode (pub_root, new_kbnode (pkt));
1857
1858
0
  xfree (hexkeygrip_buffer);
1859
0
  return 0;
1860
0
}
1861
1862
1863
/* Common code for the key generation function gen_xxx.  The optional
1864
 * (COMMON_GEN_CB,COMMON_GEN_CB_PARM) can be used as communication
1865
 * object.  A KEYPARMS2 forces the use of a composite key (e.g. Kyber+ECC).
1866
 */
1867
static int
1868
common_gen (const char *keyparms, const char *keyparms2,
1869
            int algo, const char *algoelem,
1870
            kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
1871
            int keygen_flags, const char *passphrase,
1872
            char **cache_nonce_addr, char **passwd_nonce_addr,
1873
            gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
1874
            common_gen_cb_parm_t common_gen_cb_parm)
1875
0
{
1876
0
  int err;
1877
0
  PACKET *pkt;
1878
0
  PKT_public_key *pk;
1879
0
  gcry_sexp_t s_key;
1880
0
  gcry_sexp_t s_key2 = NULL;
1881
1882
0
  err = agent_genkey (NULL, cache_nonce_addr, passwd_nonce_addr, keyparms,
1883
0
                      !!(keygen_flags & KEYGEN_FLAG_NO_PROTECTION),
1884
0
                      passphrase, timestamp,
1885
0
                      &s_key);
1886
0
  if (err)
1887
0
    {
1888
0
      log_error ("agent_genkey failed: %s\n", gpg_strerror (err) );
1889
0
      return err;
1890
0
    }
1891
1892
0
  if (keyparms2)
1893
0
    {
1894
0
      unsigned char tmpgrip[KEYGRIP_LEN];
1895
0
      char hexgrip1[2*KEYGRIP_LEN+1];
1896
0
      char hexgrip2[2*KEYGRIP_LEN+1];
1897
1898
0
      err = agent_genkey (NULL, NULL, NULL, keyparms2,
1899
0
                          1 /* No protection */,
1900
0
                          NULL, timestamp,
1901
0
                          &s_key2);
1902
0
      if (err)
1903
0
        {
1904
0
          log_error ("agent_genkey failed for second algo: %s\n",
1905
0
                     gpg_strerror (err) );
1906
0
          gcry_sexp_release (s_key);
1907
0
          return err;
1908
0
        }
1909
1910
0
      if (!gcry_pk_get_keygrip (s_key, tmpgrip))
1911
0
        {
1912
0
          log_error ("error computing keygrip for generated key\n");
1913
0
          gcry_sexp_release (s_key);
1914
0
          gcry_sexp_release (s_key2);
1915
0
          return gpg_error (GPG_ERR_GENERAL);
1916
0
        }
1917
0
      bin2hex (tmpgrip, KEYGRIP_LEN, hexgrip1);
1918
0
      if (!gcry_pk_get_keygrip (s_key2, tmpgrip))
1919
0
        {
1920
0
          log_error ("error computing keygrip for generated key\n");
1921
0
          gcry_sexp_release (s_key);
1922
0
          gcry_sexp_release (s_key2);
1923
0
          return gpg_error (GPG_ERR_GENERAL);
1924
0
        }
1925
0
      bin2hex (tmpgrip, KEYGRIP_LEN, hexgrip2);
1926
0
      err = agent_crosslink_keys (NULL, hexgrip1, hexgrip2);
1927
0
      if (err)
1928
0
        {
1929
0
          log_error ("error setting link attributes for generated keys\n");
1930
0
          gcry_sexp_release (s_key);
1931
0
          gcry_sexp_release (s_key2);
1932
0
          return gpg_error (GPG_ERR_GENERAL);
1933
0
        }
1934
0
    }
1935
1936
0
  if (common_gen_cb && common_gen_cb_parm)
1937
0
    {
1938
0
      common_gen_cb_parm->genkey_result = s_key;
1939
0
      common_gen_cb_parm->genkey_result2 = s_key2;
1940
0
      err = common_gen_cb (common_gen_cb_parm);
1941
0
      common_gen_cb_parm->genkey_result = NULL;
1942
0
      common_gen_cb_parm->genkey_result2 = NULL;
1943
0
      if (err)
1944
0
        {
1945
0
          gcry_sexp_release (s_key);
1946
0
          gcry_sexp_release (s_key2);
1947
0
          return err;
1948
0
        }
1949
0
    }
1950
1951
0
  pk = xtrycalloc (1, sizeof *pk);
1952
0
  if (!pk)
1953
0
    {
1954
0
      err = gpg_error_from_syserror ();
1955
0
      gcry_sexp_release (s_key);
1956
0
      return err;
1957
0
    }
1958
1959
0
  pk->timestamp = timestamp;
1960
0
  pk->version = (keygen_flags & KEYGEN_FLAG_CREATE_V5_KEY)? 5 : 4;
1961
0
  if (expireval)
1962
0
    pk->expiredate = pk->timestamp + expireval;
1963
0
  pk->pubkey_algo = algo;
1964
1965
0
  if (algo == PUBKEY_ALGO_KYBER)
1966
0
    err = ecckey_from_sexp (pk->pkey, s_key, s_key2, algo, pk->version);
1967
0
  else if (algo == PUBKEY_ALGO_ECDSA
1968
0
           || algo == PUBKEY_ALGO_EDDSA
1969
0
           || algo == PUBKEY_ALGO_ECDH )
1970
0
    err = ecckey_from_sexp (pk->pkey, s_key, NULL, algo, pk->version);
1971
0
  else
1972
0
    err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1973
0
  if (err)
1974
0
    {
1975
0
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1976
0
      gcry_sexp_release (s_key);
1977
0
      free_public_key (pk);
1978
0
      return err;
1979
0
    }
1980
0
  gcry_sexp_release (s_key);
1981
0
  gcry_sexp_release (s_key2);
1982
1983
0
  pkt = xtrycalloc (1, sizeof *pkt);
1984
0
  if (!pkt)
1985
0
    {
1986
0
      err = gpg_error_from_syserror ();
1987
0
      free_public_key (pk);
1988
0
      return err;
1989
0
    }
1990
1991
0
  pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1992
0
  pkt->pkt.public_key = pk;
1993
0
  add_kbnode (pub_root, new_kbnode (pkt));
1994
1995
0
  return 0;
1996
0
}
1997
1998
1999
/*
2000
 * Generate an Elgamal key.
2001
 */
2002
static int
2003
gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
2004
         u32 timestamp, u32 expireval, int is_subkey,
2005
         int keygen_flags, const char *passphrase,
2006
         char **cache_nonce_addr, char **passwd_nonce_addr,
2007
         gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
2008
         common_gen_cb_parm_t common_gen_cb_parm)
2009
0
{
2010
0
  int err;
2011
0
  char *keyparms;
2012
0
  char nbitsstr[35];
2013
2014
0
  log_assert (is_ELGAMAL (algo));
2015
2016
0
  if (nbits < 1024)
2017
0
    {
2018
0
      nbits = 2048;
2019
0
      log_info (_("keysize invalid; using %u bits\n"), nbits );
2020
0
    }
2021
0
  else if (nbits > 4096)
2022
0
    {
2023
0
      nbits = 4096;
2024
0
      log_info (_("keysize invalid; using %u bits\n"), nbits );
2025
0
    }
2026
2027
0
  if ((nbits % 32))
2028
0
    {
2029
0
      nbits = ((nbits + 31) / 32) * 32;
2030
0
      log_info (_("keysize rounded up to %u bits\n"), nbits );
2031
0
    }
2032
2033
  /* Note that we use transient-key only if no-protection has also
2034
     been enabled.  */
2035
0
  snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
2036
0
  keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
2037
0
                           algo == GCRY_PK_ELG_E ? "openpgp-elg" :
2038
0
                           algo == GCRY_PK_ELG   ? "elg" : "x-oops" ,
2039
0
                           strlen (nbitsstr), nbitsstr,
2040
0
                           ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2041
0
                            && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2042
0
                           "(transient-key)" : "" );
2043
0
  if (!keyparms)
2044
0
    err = gpg_error_from_syserror ();
2045
0
  else
2046
0
    {
2047
0
      err = common_gen (keyparms, NULL, algo, "pgy",
2048
0
                        pub_root, timestamp, expireval, is_subkey,
2049
0
                        keygen_flags, passphrase,
2050
0
                        cache_nonce_addr, passwd_nonce_addr,
2051
0
                        common_gen_cb, common_gen_cb_parm);
2052
0
      xfree (keyparms);
2053
0
    }
2054
2055
0
  return err;
2056
0
}
2057
2058
2059
/*
2060
 * Generate an DSA key
2061
 */
2062
static gpg_error_t
2063
gen_dsa (unsigned int nbits, KBNODE pub_root,
2064
         u32 timestamp, u32 expireval, int is_subkey,
2065
         int keygen_flags, const char *passphrase,
2066
         char **cache_nonce_addr, char **passwd_nonce_addr,
2067
         gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
2068
         common_gen_cb_parm_t common_gen_cb_parm)
2069
0
{
2070
0
  int err;
2071
0
  unsigned int qbits;
2072
0
  char *keyparms;
2073
0
  char nbitsstr[35];
2074
0
  char qbitsstr[35];
2075
2076
0
  if (nbits < 768)
2077
0
    {
2078
0
      nbits = 2048;
2079
0
      log_info(_("keysize invalid; using %u bits\n"), nbits );
2080
0
    }
2081
0
  else if ( nbits > 3072 )
2082
0
    {
2083
0
      nbits = 3072;
2084
0
      log_info(_("keysize invalid; using %u bits\n"), nbits );
2085
0
    }
2086
2087
0
  if( (nbits % 64) )
2088
0
    {
2089
0
      nbits = ((nbits + 63) / 64) * 64;
2090
0
      log_info(_("keysize rounded up to %u bits\n"), nbits );
2091
0
    }
2092
2093
  /* To comply with FIPS rules we round up to the next value unless in
2094
     expert mode.  */
2095
0
  if (!opt.expert && nbits > 1024 && (nbits % 1024))
2096
0
    {
2097
0
      nbits = ((nbits + 1023) / 1024) * 1024;
2098
0
      log_info(_("keysize rounded up to %u bits\n"), nbits );
2099
0
    }
2100
2101
  /*
2102
    Figure out a q size based on the key size.  FIPS 180-3 says:
2103
2104
    L = 1024, N = 160
2105
    L = 2048, N = 224
2106
    L = 2048, N = 256
2107
    L = 3072, N = 256
2108
2109
    2048/256 is an odd pair since there is also a 2048/224 and
2110
    3072/256.  Matching sizes is not a very exact science.
2111
2112
    We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
2113
    but less than 2048, and 160 for 1024 (DSA1).
2114
  */
2115
2116
0
  if (nbits > 2047)
2117
0
    qbits = 256;
2118
0
  else if ( nbits > 1024)
2119
0
    qbits = 224;
2120
0
  else
2121
0
    qbits = 160;
2122
2123
0
  if (qbits != 160 )
2124
0
    log_info (_("WARNING: some OpenPGP programs can't"
2125
0
                " handle a DSA key with this digest size\n"));
2126
2127
0
  snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
2128
0
  snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
2129
0
  keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
2130
0
                           strlen (nbitsstr), nbitsstr,
2131
0
                           strlen (qbitsstr), qbitsstr,
2132
0
                           ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2133
0
                            && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2134
0
                           "(transient-key)" : "" );
2135
0
  if (!keyparms)
2136
0
    err = gpg_error_from_syserror ();
2137
0
  else
2138
0
    {
2139
0
      err = common_gen (keyparms, NULL, PUBKEY_ALGO_DSA, "pqgy",
2140
0
                        pub_root, timestamp, expireval, is_subkey,
2141
0
                        keygen_flags, passphrase,
2142
0
                        cache_nonce_addr, passwd_nonce_addr,
2143
0
                        common_gen_cb, common_gen_cb_parm);
2144
0
      xfree (keyparms);
2145
0
    }
2146
2147
0
  return err;
2148
0
}
2149
2150
2151
2152
/*
2153
 * Generate an ECC key.
2154
 * Note that KEYGEN_FLAGS might be updated by this function to
2155
 * indicate the forced creation of a v5 key.
2156
 */
2157
static gpg_error_t
2158
gen_ecc (int algo, const char *curve, kbnode_t pub_root,
2159
         u32 timestamp, u32 expireval, int is_subkey,
2160
         int *keygen_flags, const char *passphrase,
2161
         char **cache_nonce_addr, char **passwd_nonce_addr,
2162
         gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
2163
         common_gen_cb_parm_t common_gen_cb_parm)
2164
0
{
2165
0
  gpg_error_t err;
2166
0
  char *keyparms;
2167
2168
0
  log_assert (algo == PUBKEY_ALGO_ECDSA
2169
0
              || algo == PUBKEY_ALGO_EDDSA
2170
0
              || algo == PUBKEY_ALGO_ECDH);
2171
2172
0
  if (!curve || !*curve)
2173
0
    return gpg_error (GPG_ERR_UNKNOWN_CURVE);
2174
2175
  /* Map the displayed short forms of some curves to their canonical
2176
   * names. */
2177
0
  if (!ascii_strcasecmp (curve, "cv25519"))
2178
0
    curve = "Curve25519";
2179
0
  else if (!ascii_strcasecmp (curve, "ed25519"))
2180
0
    curve = "Ed25519";
2181
0
  else if (!ascii_strcasecmp (curve, "cv448"))
2182
0
    curve = "X448";
2183
0
  else if (!ascii_strcasecmp (curve, "ed448"))
2184
0
    curve = "Ed448";
2185
2186
  /* Note that we use the "comp" flag with EdDSA to request the use of
2187
     a 0x40 compression prefix octet.  */
2188
0
  if (algo == PUBKEY_ALGO_EDDSA && !strcmp (curve, "Ed25519"))
2189
0
    {
2190
0
      keyparms = xtryasprintf
2191
0
        ("(genkey(ecc(curve %zu:%s)(flags eddsa comp%s)))",
2192
0
         strlen (curve), curve,
2193
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2194
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2195
0
          " transient-key" : ""));
2196
0
    }
2197
0
  else if (algo == PUBKEY_ALGO_EDDSA && !strcmp (curve, "Ed448"))
2198
0
    {
2199
0
      *keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
2200
0
      keyparms = xtryasprintf
2201
0
        ("(genkey(ecc(curve %zu:%s)(flags comp%s)))",
2202
0
         strlen (curve), curve,
2203
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2204
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2205
0
          " transient-key" : ""));
2206
0
    }
2207
0
  else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "Curve25519"))
2208
0
    {
2209
0
      keyparms = xtryasprintf
2210
0
        ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
2211
0
       strlen (curve), curve,
2212
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2213
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2214
0
          " transient-key" : ""));
2215
0
    }
2216
0
  else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "X448"))
2217
0
    {
2218
0
      *keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
2219
0
      keyparms = xtryasprintf
2220
0
        ("(genkey(ecc(curve %zu:%s)(flags comp%s)))",
2221
0
         strlen (curve), curve,
2222
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2223
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2224
0
          " transient-key" : ""));
2225
0
    }
2226
0
  else
2227
0
    {
2228
0
      keyparms = xtryasprintf
2229
0
        ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
2230
0
         strlen (curve), curve,
2231
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2232
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2233
0
          " transient-key" : ""));
2234
0
    }
2235
2236
0
  if (!keyparms)
2237
0
    err = gpg_error_from_syserror ();
2238
0
  else
2239
0
    {
2240
0
      err = common_gen (keyparms, NULL, algo, "",
2241
0
                        pub_root, timestamp, expireval, is_subkey,
2242
0
                        *keygen_flags, passphrase,
2243
0
                        cache_nonce_addr, passwd_nonce_addr,
2244
0
                        common_gen_cb, common_gen_cb_parm);
2245
0
      xfree (keyparms);
2246
0
    }
2247
2248
0
  return err;
2249
0
}
2250
2251
2252
/* Generate a dual ECC+Kyber key.  Note that KEYGEN_FLAGS will be
2253
 * updated by this function to indicate the forced creation of a v5
2254
 * key.  */
2255
static gpg_error_t
2256
gen_kyber (int algo, unsigned int nbits, const char *curve, kbnode_t pub_root,
2257
         u32 timestamp, u32 expireval, int is_subkey,
2258
         int *keygen_flags, const char *passphrase,
2259
         char **cache_nonce_addr, char **passwd_nonce_addr,
2260
         gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
2261
         common_gen_cb_parm_t common_gen_cb_parm)
2262
0
{
2263
0
  gpg_error_t err;
2264
0
  char *keyparms1;
2265
0
  const char *keyparms2;
2266
2267
0
  log_assert (algo == PUBKEY_ALGO_KYBER);
2268
2269
0
  if (nbits == 768)
2270
0
    keyparms2 = "(genkey(kyber768))";
2271
0
  else if (nbits == 1024)
2272
0
    keyparms2 = "(genkey(kyber1024))";
2273
0
  else
2274
0
    return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
2275
2276
0
  if (!curve || !*curve)
2277
0
    return gpg_error (GPG_ERR_UNKNOWN_CURVE);
2278
2279
0
  *keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
2280
2281
0
  if (!strcmp (curve, "Curve25519") || !ascii_strcasecmp (curve, "cv25519"))
2282
0
    {
2283
0
      curve = "Curve25519";
2284
0
      keyparms1 = xtryasprintf
2285
0
        ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
2286
0
         strlen (curve), curve,
2287
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2288
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2289
0
          " transient-key" : ""));
2290
0
    }
2291
0
  else if (!strcmp (curve, "X448") || !ascii_strcasecmp (curve, "cv448"))
2292
0
    {
2293
0
      curve = "X448";
2294
0
      keyparms1 = xtryasprintf
2295
0
        ("(genkey(ecc(curve %zu:%s)(flags comp%s)))",
2296
0
         strlen (curve), curve,
2297
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2298
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2299
0
          " transient-key" : ""));
2300
0
    }
2301
0
  else  /* Should we use the compressed format?  Check smartcard support.  */
2302
0
    {
2303
0
      keyparms1 = xtryasprintf
2304
0
        ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
2305
0
         strlen (curve), curve,
2306
0
         (((*keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2307
0
           && (*keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2308
0
          " transient-key" : ""));
2309
0
    }
2310
2311
0
  if (!keyparms1)
2312
0
    err = gpg_error_from_syserror ();
2313
0
  else
2314
0
    {
2315
0
      err = common_gen (keyparms1, keyparms2, algo, "",
2316
0
                        pub_root, timestamp, expireval, is_subkey,
2317
0
                        *keygen_flags, passphrase,
2318
0
                        cache_nonce_addr, passwd_nonce_addr,
2319
0
                        common_gen_cb, common_gen_cb_parm);
2320
0
      xfree (keyparms1);
2321
0
    }
2322
2323
0
  return err;
2324
0
}
2325
2326
2327
/*
2328
 * Generate an RSA key.
2329
 */
2330
static int
2331
gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
2332
         u32 timestamp, u32 expireval, int is_subkey,
2333
         int keygen_flags, const char *passphrase,
2334
         char **cache_nonce_addr, char **passwd_nonce_addr,
2335
         gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
2336
         common_gen_cb_parm_t common_gen_cb_parm)
2337
0
{
2338
0
  int err;
2339
0
  char *keyparms;
2340
0
  char nbitsstr[35];
2341
0
  const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
2342
2343
0
  log_assert (is_RSA(algo));
2344
2345
0
  if (!nbits)
2346
0
    nbits = get_keysize_range (algo, NULL, NULL);
2347
2348
0
  if (nbits < 1024)
2349
0
    {
2350
0
      nbits = 3072;
2351
0
      log_info (_("keysize invalid; using %u bits\n"), nbits );
2352
0
    }
2353
0
  else if (nbits > maxsize)
2354
0
    {
2355
0
      nbits = maxsize;
2356
0
      log_info (_("keysize invalid; using %u bits\n"), nbits );
2357
0
    }
2358
2359
0
  if ((nbits % 32))
2360
0
    {
2361
0
      nbits = ((nbits + 31) / 32) * 32;
2362
0
      log_info (_("keysize rounded up to %u bits\n"), nbits );
2363
0
    }
2364
2365
0
  snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
2366
0
  keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
2367
0
                           strlen (nbitsstr), nbitsstr,
2368
0
                           ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
2369
0
                            && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
2370
0
                           "(transient-key)" : "" );
2371
0
  if (!keyparms)
2372
0
    err = gpg_error_from_syserror ();
2373
0
  else
2374
0
    {
2375
0
      err = common_gen (keyparms, NULL, algo, "ne",
2376
0
                        pub_root, timestamp, expireval, is_subkey,
2377
0
                        keygen_flags, passphrase,
2378
0
                        cache_nonce_addr, passwd_nonce_addr,
2379
0
                        common_gen_cb, common_gen_cb_parm);
2380
0
      xfree (keyparms);
2381
0
    }
2382
2383
0
  return err;
2384
0
}
2385
2386
2387
/****************
2388
 * check valid days:
2389
 * return 0 on error or the multiplier
2390
 */
2391
static int
2392
check_valid_days( const char *s )
2393
0
{
2394
0
    if( !digitp(s) )
2395
0
  return 0;
2396
0
    for( s++; *s; s++)
2397
0
  if( !digitp(s) )
2398
0
      break;
2399
0
    if( !*s )
2400
0
  return 1;
2401
0
    if( s[1] )
2402
0
  return 0; /* e.g. "2323wc" */
2403
0
    if( *s == 'd' || *s == 'D' )
2404
0
  return 1;
2405
0
    if( *s == 'w' || *s == 'W' )
2406
0
  return 7;
2407
0
    if( *s == 'm' || *s == 'M' )
2408
0
  return 30;
2409
0
    if( *s == 'y' || *s == 'Y' )
2410
0
  return 365;
2411
0
    return 0;
2412
0
}
2413
2414
2415
static void
2416
print_key_flags(int flags)
2417
0
{
2418
0
  if(flags&PUBKEY_USAGE_SIG)
2419
0
    tty_printf("%s ",_("Sign"));
2420
2421
0
  if(flags&PUBKEY_USAGE_CERT)
2422
0
    tty_printf("%s ",_("Certify"));
2423
2424
0
  if(flags&PUBKEY_USAGE_ENC)
2425
0
    tty_printf("%s ",_("Encrypt"));
2426
2427
0
  if(flags&PUBKEY_USAGE_AUTH)
2428
0
    tty_printf("%s ",_("Authenticate"));
2429
2430
0
  if(flags&PUBKEY_USAGE_RENC)
2431
0
    tty_printf("%s ", "RENC");
2432
0
}
2433
2434
2435
/* Ask for the key flags and return them.  CURRENT gives the current
2436
 * usage which should normally be given as 0.  MASK gives the allowed
2437
 * flags.  */
2438
unsigned int
2439
ask_key_flags_with_mask (int algo, int subkey, unsigned int current,
2440
                         unsigned int mask)
2441
0
{
2442
  /* TRANSLATORS: Please use only plain ASCII characters for the
2443
   * translation.  If this is not possible use single digits.  The
2444
   * string needs to 8 bytes long. Here is a description of the
2445
   * functions:
2446
   *
2447
   *   s = Toggle signing capability
2448
   *   e = Toggle encryption capability
2449
   *   a = Toggle authentication capability
2450
   *   q = Finish
2451
   */
2452
0
  const char *togglers = _("SsEeAaQq");
2453
0
  char *answer = NULL;
2454
0
  const char *s;
2455
0
  unsigned int possible;
2456
2457
0
  if ( strlen(togglers) != 8 )
2458
0
    {
2459
0
      tty_printf ("NOTE: Bad translation at %s:%d. "
2460
0
                  "Please report.\n", __FILE__, __LINE__);
2461
0
      togglers = "11223300";
2462
0
    }
2463
2464
  /* restrict the mask to the actual useful bits.  */
2465
2466
  /* Mask the possible usage flags.  This is for example used for a
2467
   * card based key.  For ECDH we need to allows additional usages if
2468
   * they are provided.  RENC is not directly poissible here but see
2469
   * below for a workaround. */
2470
0
  possible = (openpgp_pk_algo_usage (algo) & mask);
2471
0
  possible &= ~PUBKEY_USAGE_RENC;
2472
0
  possible &= ~PUBKEY_USAGE_GROUP;
2473
0
  if (algo == PUBKEY_ALGO_ECDH)
2474
0
    possible |= (current & (PUBKEY_USAGE_ENC
2475
0
                            |PUBKEY_USAGE_CERT
2476
0
                            |PUBKEY_USAGE_SIG
2477
0
                            |PUBKEY_USAGE_AUTH));
2478
2479
  /* However, only primary keys may certify. */
2480
0
  if (subkey)
2481
0
    possible &= ~PUBKEY_USAGE_CERT;
2482
2483
  /* Preload the current set with the possible set, without
2484
   * authentication if CURRENT is 0.  If CURRENT is non-zero we mask
2485
   * with all possible usages.  */
2486
0
  if (current)
2487
0
    current &= possible;
2488
0
  else
2489
0
    current = (possible&~PUBKEY_USAGE_AUTH);
2490
2491
0
  for (;;)
2492
0
    {
2493
0
      tty_printf("\n");
2494
0
      tty_printf(_("Possible actions for this %s key: "),
2495
0
                 (algo == PUBKEY_ALGO_ECDH
2496
0
                  || algo == PUBKEY_ALGO_ECDSA
2497
0
                  || algo == PUBKEY_ALGO_EDDSA)
2498
0
                 ? "ECC" : openpgp_pk_algo_name (algo));
2499
0
      print_key_flags(possible);
2500
0
      tty_printf("\n");
2501
0
      tty_printf(_("Current allowed actions: "));
2502
0
      print_key_flags(current);
2503
0
      tty_printf("\n\n");
2504
2505
0
      if(possible&PUBKEY_USAGE_SIG)
2506
0
  tty_printf(_("   (%c) Toggle the sign capability\n"),
2507
0
       togglers[0]);
2508
0
      if(possible&PUBKEY_USAGE_ENC)
2509
0
  tty_printf(_("   (%c) Toggle the encrypt capability\n"),
2510
0
       togglers[2]);
2511
0
      if(possible&PUBKEY_USAGE_AUTH)
2512
0
  tty_printf(_("   (%c) Toggle the authenticate capability\n"),
2513
0
       togglers[4]);
2514
2515
0
      tty_printf(_("   (%c) Finished\n"),togglers[6]);
2516
0
      tty_printf("\n");
2517
2518
0
      xfree(answer);
2519
0
      answer = cpr_get("keygen.flags",_("Your selection? "));
2520
0
      cpr_kill_prompt();
2521
2522
0
      if (*answer == '=')
2523
0
        {
2524
          /* Hack to allow direct entry of the capabilities.  */
2525
0
          current = 0;
2526
0
          for (s=answer+1; *s; s++)
2527
0
            {
2528
0
              if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
2529
0
                current |= PUBKEY_USAGE_SIG;
2530
0
              else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
2531
0
                current |= PUBKEY_USAGE_ENC;
2532
0
              else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
2533
0
                current |= PUBKEY_USAGE_AUTH;
2534
0
              else if (!subkey && *s == 'c')
2535
0
                {
2536
                  /* Accept 'c' for the primary key because USAGE_CERT
2537
                     will be set anyway.  This is for folks who
2538
                     want to experiment with a cert-only primary key.  */
2539
0
                  current |= PUBKEY_USAGE_CERT;
2540
0
                }
2541
0
              else if ((*s == 'r' || *s == 'R') && (possible&PUBKEY_USAGE_ENC))
2542
0
                {
2543
                  /* Allow to set RENC or an encryption capable key.
2544
                   * This is on purpose not shown in the menu.  */
2545
0
                  current |= PUBKEY_USAGE_RENC;
2546
0
                }
2547
0
            }
2548
0
          break;
2549
0
        }
2550
0
      else if (strlen(answer)>1)
2551
0
  tty_printf(_("Invalid selection.\n"));
2552
0
      else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
2553
0
  break;
2554
0
      else if((*answer==togglers[0] || *answer==togglers[1])
2555
0
        && possible&PUBKEY_USAGE_SIG)
2556
0
  {
2557
0
    if(current&PUBKEY_USAGE_SIG)
2558
0
      current&=~PUBKEY_USAGE_SIG;
2559
0
    else
2560
0
      current|=PUBKEY_USAGE_SIG;
2561
0
  }
2562
0
      else if((*answer==togglers[2] || *answer==togglers[3])
2563
0
        && possible&PUBKEY_USAGE_ENC)
2564
0
  {
2565
0
    if(current&PUBKEY_USAGE_ENC)
2566
0
      current&=~PUBKEY_USAGE_ENC;
2567
0
    else
2568
0
      current|=PUBKEY_USAGE_ENC;
2569
0
  }
2570
0
      else if((*answer==togglers[4] || *answer==togglers[5])
2571
0
        && possible&PUBKEY_USAGE_AUTH)
2572
0
  {
2573
0
    if(current&PUBKEY_USAGE_AUTH)
2574
0
      current&=~PUBKEY_USAGE_AUTH;
2575
0
    else
2576
0
      current|=PUBKEY_USAGE_AUTH;
2577
0
  }
2578
0
      else
2579
0
  tty_printf(_("Invalid selection.\n"));
2580
0
    }
2581
2582
0
  xfree(answer);
2583
2584
0
  return current;
2585
0
}
2586
2587
2588
unsigned int
2589
ask_key_flags (int algo, int subkey, unsigned int current)
2590
0
{
2591
0
  return ask_key_flags_with_mask (algo, subkey, current, ~0);
2592
0
}
2593
2594
2595
/* Check whether we have a key for the key with HEXGRIP.  Returns 0 if
2596
   there is no such key or the OpenPGP algo number for the key.  */
2597
static int
2598
check_keygrip (ctrl_t ctrl, const char *hexgrip)
2599
0
{
2600
0
  gpg_error_t err;
2601
0
  unsigned char *public;
2602
0
  size_t publiclen;
2603
0
  int algo;
2604
2605
0
  if (hexgrip[0] == '&')
2606
0
    hexgrip++;
2607
2608
0
  err = agent_readkey (ctrl, 0, hexgrip, &public);
2609
0
  if (err)
2610
0
    return 0;
2611
0
  publiclen = gcry_sexp_canon_len (public, 0, NULL, NULL);
2612
2613
0
  algo = get_pk_algo_from_canon_sexp (public, publiclen);
2614
0
  xfree (public);
2615
2616
0
  return map_gcry_pk_to_openpgp (algo);
2617
0
}
2618
2619
2620
2621
/* Ask for an algorithm.  The function returns the algorithm id to
2622
 * create. If ADDMODE is false the function won't show an option to
2623
 * create the primary and subkey combined and won't set R_USAGE
2624
 * either.  If a combined algorithm has been selected, the subkey
2625
 * algorithm is stored at R_SUBKEY_ALGO.  If R_KEYGRIP is given, the
2626
 * user has the choice to enter the keygrip of an existing key.  That
2627
 * keygrip is then stored at this address.  The caller needs to free
2628
 * it.  If R_CARDKEY is not NULL and the keygrip has been taken from
2629
 * an active card, true is stored there; if R_KEYTIME is not NULL the
2630
 * creation time of that key is then stored there.  */
2631
static int
2632
ask_algo (ctrl_t ctrl, int addmode, int *r_subkey_algo, unsigned int *r_usage,
2633
          char **r_keygrip, int *r_cardkey, u32 *r_keytime)
2634
0
{
2635
0
  gpg_error_t err;
2636
0
  char *keygrip = NULL;
2637
0
  u32 keytime = 0;
2638
0
  char *answer = NULL;
2639
0
  int cardkey = 0;
2640
0
  int algo;
2641
0
  int dummy_algo;
2642
2643
0
  if (!r_subkey_algo)
2644
0
    r_subkey_algo = &dummy_algo;
2645
2646
0
  tty_printf (_("Please select what kind of key you want:\n"));
2647
2648
0
#if GPG_USE_RSA
2649
0
  if (!addmode)
2650
0
    tty_printf (_("   (%d) RSA and RSA%s\n"), 1, "");
2651
0
#endif
2652
2653
0
  if (!addmode && opt.compliance != CO_DE_VS)
2654
0
    tty_printf (_("   (%d) DSA and Elgamal%s\n"), 2, "");
2655
2656
0
  if (opt.compliance != CO_DE_VS)
2657
0
    tty_printf (_("   (%d) DSA (sign only)%s\n"), 3, "");
2658
0
#if GPG_USE_RSA
2659
0
  tty_printf (_("   (%d) RSA (sign only)%s\n"), 4, "");
2660
0
#endif
2661
2662
0
  if (addmode)
2663
0
    {
2664
0
      if (opt.compliance != CO_DE_VS)
2665
0
        tty_printf (_("   (%d) Elgamal (encrypt only)%s\n"), 5, "");
2666
0
#if GPG_USE_RSA
2667
0
      tty_printf (_("   (%d) RSA (encrypt only)%s\n"), 6, "");
2668
0
#endif
2669
0
    }
2670
0
  if (opt.expert)
2671
0
    {
2672
0
      if (opt.compliance != CO_DE_VS)
2673
0
        tty_printf (_("   (%d) DSA (set your own capabilities)%s\n"), 7, "");
2674
0
#if GPG_USE_RSA
2675
0
      tty_printf (_("   (%d) RSA (set your own capabilities)%s\n"), 8, "");
2676
0
#endif
2677
0
    }
2678
2679
0
#if GPG_USE_ECDSA || GPG_USE_ECDH || GPG_USE_EDDSA
2680
0
  if (!addmode)
2681
0
    tty_printf (_("   (%d) ECC (sign and encrypt)%s\n"), 9, _(" *default*") );
2682
0
  tty_printf (_("  (%d) ECC (sign only)\n"), 10 );
2683
0
  if (opt.expert)
2684
0
    tty_printf (_("  (%d) ECC (set your own capabilities)%s\n"), 11, "");
2685
0
  if (addmode)
2686
0
    tty_printf (_("  (%d) ECC (encrypt only)%s\n"), 12, "");
2687
0
#endif
2688
2689
0
  if (opt.expert && r_keygrip)
2690
0
    tty_printf (_("  (%d) Existing key%s\n"), 13, "");
2691
0
  if (r_keygrip)
2692
0
    tty_printf (_("  (%d) Existing key from card%s\n"), 14, "");
2693
2694
  /* Reserve 15 for Dilithium primary + Kyber subkey.  */
2695
0
  if (!addmode)
2696
0
    tty_printf (_("  (%d) ECC and Kyber%s\n"), 16, "");
2697
0
  if (addmode)
2698
0
    tty_printf (_("  (%d) Kyber (encrypt only)%s\n"), 17, "");
2699
2700
0
  for (;;)
2701
0
    {
2702
0
      *r_usage = 0;
2703
0
      *r_subkey_algo = 0;
2704
0
      xfree (answer);
2705
0
      answer = cpr_get ("keygen.algo", _("Your selection? "));
2706
0
      cpr_kill_prompt ();
2707
0
      algo = *answer? atoi (answer) : 9;  /* Default algo is 9 */
2708
2709
0
      if (opt.compliance == CO_DE_VS
2710
0
          && (algo == 2 || algo == 3 || algo == 5 || algo == 7))
2711
0
        {
2712
0
          tty_printf (_("Invalid selection.\n"));
2713
0
        }
2714
0
      else if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
2715
0
        {
2716
0
          algo = PUBKEY_ALGO_RSA;
2717
0
          *r_subkey_algo = PUBKEY_ALGO_RSA;
2718
0
          break;
2719
0
  }
2720
0
      else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
2721
0
        {
2722
0
          algo = PUBKEY_ALGO_DSA;
2723
0
          *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
2724
0
          break;
2725
0
  }
2726
0
      else if (algo == 3 || !strcmp (answer, "dsa"))
2727
0
        {
2728
0
          algo = PUBKEY_ALGO_DSA;
2729
0
          *r_usage = PUBKEY_USAGE_SIG;
2730
0
          break;
2731
0
  }
2732
0
      else if (algo == 4 || !strcmp (answer, "rsa/s"))
2733
0
        {
2734
0
          algo = PUBKEY_ALGO_RSA;
2735
0
          *r_usage = PUBKEY_USAGE_SIG;
2736
0
          break;
2737
0
  }
2738
0
      else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
2739
0
        {
2740
0
          algo = PUBKEY_ALGO_ELGAMAL_E;
2741
0
          *r_usage = PUBKEY_USAGE_ENC;
2742
0
          break;
2743
0
  }
2744
0
      else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
2745
0
        {
2746
0
          algo = PUBKEY_ALGO_RSA;
2747
0
          *r_usage = PUBKEY_USAGE_ENC;
2748
0
          break;
2749
0
  }
2750
0
      else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
2751
0
        {
2752
0
          algo = PUBKEY_ALGO_DSA;
2753
0
          *r_usage = ask_key_flags (algo, addmode, 0);
2754
0
          break;
2755
0
  }
2756
0
      else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
2757
0
        {
2758
0
          algo = PUBKEY_ALGO_RSA;
2759
0
          *r_usage = ask_key_flags (algo, addmode, 0);
2760
0
          break;
2761
0
  }
2762
0
      else if ((algo == 9 || !strcmp (answer, "ecc+ecc"))
2763
0
               && !addmode)
2764
0
        {
2765
0
          algo = PUBKEY_ALGO_ECDSA;
2766
0
          *r_subkey_algo = PUBKEY_ALGO_ECDH;
2767
0
          break;
2768
0
  }
2769
0
      else if ((algo == 10 || !strcmp (answer, "ecc/s")))
2770
0
        {
2771
0
          algo = PUBKEY_ALGO_ECDSA;
2772
0
          *r_usage = PUBKEY_USAGE_SIG;
2773
0
          break;
2774
0
  }
2775
0
      else if ((algo == 11 || !strcmp (answer, "ecc/*")) && opt.expert)
2776
0
        {
2777
0
          algo = PUBKEY_ALGO_ECDSA;
2778
0
          *r_usage = ask_key_flags (algo, addmode, 0);
2779
0
          break;
2780
0
  }
2781
0
      else if ((algo == 12 || !strcmp (answer, "ecc/e"))
2782
0
               && addmode)
2783
0
        {
2784
0
          algo = PUBKEY_ALGO_ECDH;
2785
0
          *r_usage = PUBKEY_USAGE_ENC;
2786
0
          break;
2787
0
  }
2788
0
      else if ((algo == 13 || !strcmp (answer, "keygrip"))
2789
0
               && opt.expert && r_keygrip)
2790
0
        {
2791
0
          for (;;)
2792
0
            {
2793
0
              xfree (answer);
2794
0
              answer = cpr_get ("keygen.keygrip", _("Enter the keygrip: "));
2795
0
              cpr_kill_prompt ();
2796
0
              trim_spaces (answer);
2797
0
              if (!*answer)
2798
0
                {
2799
0
                  xfree (answer);
2800
0
                  answer = NULL;
2801
0
                  continue;
2802
0
                }
2803
2804
0
              if (strlen (answer) == 40+1+40 && answer[40]==',')
2805
0
                {
2806
0
                  int algo1, algo2;
2807
2808
0
                  answer[40] = 0;
2809
0
                  algo1 = check_keygrip (ctrl, answer);
2810
0
                  algo2 = check_keygrip (ctrl, answer+41);
2811
0
                  answer[40] = ',';
2812
0
                  if (algo1 == PUBKEY_ALGO_ECDH && algo2 == PUBKEY_ALGO_KYBER)
2813
0
                    {
2814
0
                      algo = PUBKEY_ALGO_KYBER;
2815
0
                      break;
2816
0
                    }
2817
0
                  else if (!algo1 || !algo2)
2818
0
                    tty_printf (_("No key with this keygrip\n"));
2819
0
                  else
2820
0
                    tty_printf ("Invalid combination for dual algo (%d,%d)\n",
2821
0
                                algo1, algo2);
2822
0
                }
2823
0
              else if (strlen (answer) != 40 &&
2824
0
                       !(answer[0] == '&' && strlen (answer+1) == 40))
2825
0
                tty_printf
2826
0
                  (_("Not a valid keygrip (expecting 40 hex digits)\n"));
2827
0
              else if (!(algo = check_keygrip (ctrl, answer)) )
2828
0
                tty_printf (_("No key with this keygrip\n"));
2829
0
              else
2830
0
                break; /* Okay.  */
2831
0
            }
2832
0
          xfree (keygrip);
2833
0
          keygrip = answer;
2834
0
          answer = NULL;
2835
0
          *r_usage = ask_key_flags (algo, addmode, 0);
2836
0
          break;
2837
0
  }
2838
0
      else if ((algo == 14 || !strcmp (answer, "cardkey")) && r_keygrip)
2839
0
        {
2840
0
          char *serialno;
2841
0
          keypair_info_t keypairlist, kpi;
2842
0
          int count, selection;
2843
2844
0
          err = agent_scd_serialno (&serialno, NULL);
2845
0
          if (err)
2846
0
            {
2847
0
              tty_printf (_("error reading the card: %s\n"),
2848
0
                          gpg_strerror (err));
2849
0
              goto ask_again;
2850
0
            }
2851
0
          tty_printf (_("Serial number of the card: %s\n"), serialno);
2852
0
          xfree (serialno);
2853
2854
0
          err = agent_scd_keypairinfo (ctrl, NULL, &keypairlist);
2855
0
          if (err)
2856
0
            {
2857
0
              tty_printf (_("error reading the card: %s\n"),
2858
0
                          gpg_strerror (err));
2859
0
              goto ask_again;
2860
0
            }
2861
2862
0
          do
2863
0
            {
2864
0
              char *authkeyref, *encrkeyref, *signkeyref;
2865
2866
0
              agent_scd_getattr_one ("$AUTHKEYID", &authkeyref);
2867
0
              agent_scd_getattr_one ("$ENCRKEYID", &encrkeyref);
2868
0
              agent_scd_getattr_one ("$SIGNKEYID", &signkeyref);
2869
2870
0
              tty_printf (_("Available keys:\n"));
2871
0
              for (count=1, kpi=keypairlist; kpi; kpi = kpi->next, count++)
2872
0
                {
2873
0
                  gcry_sexp_t s_pkey;
2874
0
                  char *algostr = NULL;
2875
0
                  enum gcry_pk_algos algoid = 0;
2876
0
                  const char *keyref = kpi->idstr;
2877
0
                  int any = 0;
2878
2879
0
                  if (!keyref)
2880
0
                    continue;
2881
2882
0
                  if (agent_scd_readkey (ctrl, keyref, &s_pkey, NULL))
2883
0
                    continue;
2884
2885
0
                  algostr = pubkey_algo_string (s_pkey, &algoid);
2886
0
                  gcry_sexp_release (s_pkey);
2887
2888
                  /* We need to tweak the algo in case GCRY_PK_ECC is
2889
                   * returned because pubkey_algo_string is not aware
2890
                   * of the OpenPGP algo mapping.  We need to
2891
                   * distinguish between ECDH and ECDSA but we can do
2892
                   * that only if we got usage flags.
2893
                   * Note: Keep this in sync with parse_key_parameter_part.
2894
                   */
2895
0
                  if (algoid == GCRY_PK_ECC && algostr)
2896
0
                    {
2897
0
                      if (!strcmp (algostr, "ed25519"))
2898
0
                        kpi->algo = PUBKEY_ALGO_EDDSA;
2899
0
                      else if (!strcmp (algostr, "ed448"))
2900
0
                        kpi->algo = PUBKEY_ALGO_EDDSA;
2901
0
                      else if (!strcmp (algostr, "cv25519"))
2902
0
                        kpi->algo = PUBKEY_ALGO_ECDH;
2903
0
                      else if (!strcmp (algostr, "cv448"))
2904
0
                        kpi->algo = PUBKEY_ALGO_ECDH;
2905
0
                      else if ((kpi->usage & GCRY_PK_USAGE_ENCR))
2906
0
                        kpi->algo = PUBKEY_ALGO_ECDH;
2907
0
                      else
2908
0
                        kpi->algo = PUBKEY_ALGO_ECDSA;
2909
0
                    }
2910
0
                  else
2911
0
                    kpi->algo = map_gcry_pk_to_openpgp (algoid);
2912
2913
0
                  tty_printf ("   (%d) %s %s %s",
2914
0
                              count, kpi->keygrip, keyref, algostr);
2915
0
                  if ((kpi->usage & GCRY_PK_USAGE_CERT))
2916
0
                    {
2917
0
                      tty_printf ("%scert", any?",":" (");
2918
0
                      any = 1;
2919
0
                    }
2920
0
                  if ((kpi->usage & GCRY_PK_USAGE_SIGN))
2921
0
                    {
2922
0
                      tty_printf ("%ssign%s", any?",":" (",
2923
0
                                  (signkeyref && keyref
2924
0
                                   && !strcmp (signkeyref, keyref))? "*":"");
2925
0
                      any = 1;
2926
0
                    }
2927
0
                  if ((kpi->usage & GCRY_PK_USAGE_AUTH))
2928
0
                    {
2929
0
                      tty_printf ("%sauth%s", any?",":" (",
2930
0
                                  (authkeyref && keyref
2931
0
                                   && !strcmp (authkeyref, keyref))? "*":"");
2932
0
                      any = 1;
2933
0
                    }
2934
0
                  if ((kpi->usage & GCRY_PK_USAGE_ENCR))
2935
0
                    {
2936
0
                      tty_printf ("%sencr%s", any?",":" (",
2937
0
                                  (encrkeyref && keyref
2938
0
                                   && !strcmp (encrkeyref, keyref))? "*":"");
2939
0
                      any = 1;
2940
0
                    }
2941
0
                  tty_printf ("%s\n", any?")":"");
2942
0
                  xfree (algostr);
2943
0
                }
2944
2945
0
              xfree (answer);
2946
0
              answer = cpr_get ("keygen.cardkey", _("Your selection? "));
2947
0
              cpr_kill_prompt ();
2948
0
              trim_spaces (answer);
2949
0
              selection = atoi (answer);
2950
0
              xfree (authkeyref);
2951
0
              xfree (encrkeyref);
2952
0
              xfree (signkeyref);
2953
0
            }
2954
0
          while (!(selection > 0 && selection < count));
2955
2956
0
          for (count=1,kpi=keypairlist; kpi; kpi = kpi->next, count++)
2957
0
            if (count == selection)
2958
0
              break;
2959
0
          if (!kpi || !kpi->algo)
2960
0
            {
2961
              /* Just in case no good key.  */
2962
0
              free_keypair_info (keypairlist);
2963
0
              goto ask_again;
2964
0
            }
2965
2966
0
          xfree (keygrip);
2967
0
          keygrip = xstrdup (kpi->keygrip);
2968
0
          cardkey = 1;
2969
0
          algo = kpi->algo;
2970
0
          keytime = kpi->keytime;
2971
2972
          /* In expert mode allow to change the usage flags.  */
2973
0
          if (opt.expert)
2974
0
            *r_usage = ask_key_flags_with_mask (algo, addmode,
2975
0
                                                kpi->usage, kpi->usage);
2976
0
          else
2977
0
            {
2978
0
              *r_usage = kpi->usage;
2979
0
              if (addmode)
2980
0
                *r_usage &= ~GCRY_PK_USAGE_CERT;
2981
0
            }
2982
0
          free_keypair_info (keypairlist);
2983
0
          break;
2984
0
  }
2985
0
      else if ((algo == 16 || !strcmp (answer, "ecc+kyber")) && !addmode)
2986
0
        {
2987
0
          algo = PUBKEY_ALGO_ECDSA;
2988
0
          *r_subkey_algo = PUBKEY_ALGO_KYBER;
2989
0
          break;
2990
0
  }
2991
0
      else if ((algo == 17 || !strcmp (answer, "kyber")) && addmode)
2992
0
        {
2993
0
          algo = PUBKEY_ALGO_KYBER;
2994
0
          *r_usage = PUBKEY_USAGE_ENC;
2995
0
          break;
2996
0
  }
2997
0
      else
2998
0
        tty_printf (_("Invalid selection.\n"));
2999
3000
0
    ask_again:
3001
0
      ;
3002
0
    }
3003
3004
0
  xfree(answer);
3005
0
  if (r_keygrip)
3006
0
    *r_keygrip = keygrip;
3007
0
  if (r_cardkey)
3008
0
    *r_cardkey = cardkey;
3009
0
  if (r_keytime)
3010
0
    *r_keytime = keytime;
3011
0
  return algo;
3012
0
}
3013
3014
3015
static unsigned int
3016
get_keysize_range (int algo, unsigned int *min, unsigned int *max)
3017
0
{
3018
0
  unsigned int def;
3019
0
  unsigned int dummy1, dummy2;
3020
3021
0
  if (!min)
3022
0
    min = &dummy1;
3023
0
  if (!max)
3024
0
    max = &dummy2;
3025
3026
0
  switch(algo)
3027
0
    {
3028
0
    case PUBKEY_ALGO_DSA:
3029
0
      *min = opt.expert? 768 : 1024;
3030
0
      *max=3072;
3031
0
      def=2048;
3032
0
      break;
3033
3034
0
    case PUBKEY_ALGO_ECDSA:
3035
0
    case PUBKEY_ALGO_ECDH:
3036
0
      *min=256;
3037
0
      *max=521;
3038
0
      def=256;
3039
0
      break;
3040
3041
0
    case PUBKEY_ALGO_EDDSA:
3042
0
      *min=255;
3043
0
      *max=441;
3044
0
      def=255;
3045
0
      break;
3046
3047
0
    case PUBKEY_ALGO_KYBER:
3048
0
      *min = 768;
3049
0
      *max = 1024;
3050
0
      def = 768;
3051
0
      break;
3052
3053
0
    default:
3054
0
      *min = opt.compliance == CO_DE_VS ? 2048: 1024;
3055
0
      *max = 4096;
3056
0
      def = 3072;
3057
0
      break;
3058
0
    }
3059
3060
0
  return def;
3061
0
}
3062
3063
3064
/* Return a fixed up keysize depending on ALGO.  */
3065
static unsigned int
3066
fixup_keysize (unsigned int nbits, int algo, int silent)
3067
0
{
3068
0
  unsigned int orig_nbits = nbits;
3069
3070
0
  if (algo == PUBKEY_ALGO_DSA && (nbits % 64))
3071
0
    {
3072
0
      nbits = ((nbits + 63) / 64) * 64;
3073
0
    }
3074
0
  else if (algo == PUBKEY_ALGO_EDDSA)
3075
0
    {
3076
0
      if (nbits < 256)
3077
0
        nbits = 255;
3078
0
      else
3079
0
        nbits = 441;
3080
0
    }
3081
0
  else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
3082
0
    {
3083
0
      if (nbits < 256)
3084
0
        nbits = 256;
3085
0
      else if (nbits < 384)
3086
0
        nbits = 384;
3087
0
      else
3088
0
        nbits = 521;
3089
0
    }
3090
0
  else if (algo == PUBKEY_ALGO_KYBER)
3091
0
    {
3092
      /* (in reality the numbers are not bits) */
3093
0
      if (nbits < 768)
3094
0
        nbits = 768;
3095
0
      else if (nbits > 1024)
3096
0
        nbits = 1024;
3097
0
    }
3098
0
  else if ((nbits % 32))
3099
0
    {
3100
0
      nbits = ((nbits + 31) / 32) * 32;
3101
0
    }
3102
3103
0
  if (!silent && orig_nbits != nbits)
3104
0
    tty_printf (_("rounded to %u bits\n"), nbits);
3105
3106
0
  return nbits;
3107
0
}
3108
3109
3110
/* Ask for the key size.  ALGO is the algorithm.  If PRIMARY_KEYSIZE
3111
   is not 0, the function asks for the size of the encryption
3112
   subkey. */
3113
static unsigned
3114
ask_keysize (int algo, unsigned int primary_keysize)
3115
0
{
3116
0
  unsigned int nbits;
3117
0
  unsigned int min, def, max;
3118
0
  int for_subkey = !!primary_keysize;
3119
0
  int autocomp = 0;
3120
3121
0
  def = get_keysize_range (algo, &min, &max);
3122
3123
0
  if (primary_keysize && !opt.expert)
3124
0
    {
3125
      /* Deduce the subkey size from the primary key size.  */
3126
0
      if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
3127
0
        nbits = 3072; /* For performance reasons we don't support more
3128
                         than 3072 bit DSA.  However we won't see this
3129
                         case anyway because DSA can't be used as an
3130
                         encryption subkey ;-). */
3131
0
      else
3132
0
        nbits = primary_keysize;
3133
0
      autocomp = 1;
3134
0
      goto leave;
3135
0
    }
3136
3137
0
  tty_printf(_("%s keys may be between %u and %u bits long.\n"),
3138
0
       openpgp_pk_algo_name (algo), min, max);
3139
3140
0
  for (;;)
3141
0
    {
3142
0
      char *prompt, *answer;
3143
3144
0
      if (for_subkey)
3145
0
        prompt = xasprintf (_("What keysize do you want "
3146
0
                              "for the subkey? (%u) "), def);
3147
0
      else
3148
0
        prompt = xasprintf (_("What keysize do you want? (%u) "), def);
3149
0
      answer = cpr_get ("keygen.size", prompt);
3150
0
      cpr_kill_prompt ();
3151
0
      nbits = *answer? atoi (answer): def;
3152
0
      xfree(prompt);
3153
0
      xfree(answer);
3154
3155
0
      if(nbits<min || nbits>max)
3156
0
  tty_printf(_("%s keysizes must be in the range %u-%u\n"),
3157
0
       openpgp_pk_algo_name (algo), min, max);
3158
0
      else
3159
0
  break;
3160
0
    }
3161
3162
0
  tty_printf (_("Requested keysize is %u bits\n"), nbits);
3163
3164
0
 leave:
3165
0
  nbits = fixup_keysize (nbits, algo, autocomp);
3166
0
  return nbits;
3167
0
}
3168
3169
3170
/* Ask for the curve.  ALGO is the selected algorithm which this
3171
   function may adjust.  Returns a const string of the name of the
3172
   curve.  */
3173
const char *
3174
ask_curve (int *algo, int *subkey_algo, const char *current)
3175
0
{
3176
  /* NB: We always use a complete algo list so that we have stable
3177
     numbers in the menu regardless on how Gpg was configured.  */
3178
0
  struct {
3179
0
    const char *name;
3180
0
    const char* eddsa_curve; /* Corresponding EdDSA curve.  */
3181
0
    const char *pretty_name;
3182
0
    unsigned int supported : 1;   /* Supported by gpg.     */
3183
0
    unsigned int de_vs : 1;       /* Allowed in CO_DE_VS.  */
3184
0
    unsigned int expert_only : 1; /* Only with --expert    */
3185
0
    unsigned int no_listing : 1;  /* Do not show in the menu    */
3186
0
    unsigned int available : 1;   /* Available in Libycrypt (runtime checked) */
3187
0
  } curves[] = {
3188
0
#if GPG_USE_ECDSA || GPG_USE_ECDH
3189
0
# define MY_USE_ECDSADH 1
3190
#else
3191
# define MY_USE_ECDSADH 0
3192
#endif
3193
0
    { "Curve25519",      "Ed25519", "Curve 25519", !!GPG_USE_EDDSA, 0,0,0,0 },
3194
0
    { "X448",            "Ed448",   "Curve 448",   !!GPG_USE_EDDSA, 0,1,0,0 },
3195
0
    { "NIST P-256",      NULL, NULL,               MY_USE_ECDSADH,  0,1,0,0 },
3196
0
    { "NIST P-384",      NULL, NULL,               MY_USE_ECDSADH,  0,0,0,0 },
3197
0
    { "NIST P-521",      NULL, NULL,               MY_USE_ECDSADH,  0,1,0,0 },
3198
0
    { "brainpoolP256r1", NULL, "Brainpool P-256",  MY_USE_ECDSADH,  1,0,0,0 },
3199
0
    { "brainpoolP384r1", NULL, "Brainpool P-384",  MY_USE_ECDSADH,  1,1,0,0 },
3200
0
    { "brainpoolP512r1", NULL, "Brainpool P-512",  MY_USE_ECDSADH,  1,1,0,0 },
3201
0
    { "secp256k1",       NULL, NULL,               MY_USE_ECDSADH,  0,1,1,0 },
3202
0
  };
3203
0
#undef MY_USE_ECDSADH
3204
0
  int idx;
3205
0
  char *answer;
3206
0
  const char *result = NULL;
3207
0
  gcry_sexp_t keyparms;
3208
3209
0
  tty_printf (_("Please select which elliptic curve you want:\n"));
3210
3211
0
  keyparms = NULL;
3212
0
  for (idx=0; idx < DIM(curves); idx++)
3213
0
    {
3214
0
      int rc;
3215
3216
0
      curves[idx].available = 0;
3217
0
      if (!curves[idx].supported)
3218
0
        continue;
3219
3220
0
      if (opt.compliance==CO_DE_VS)
3221
0
        {
3222
0
          if (!curves[idx].de_vs)
3223
0
            continue; /* Not allowed.  */
3224
0
        }
3225
0
      else if (!opt.expert && curves[idx].expert_only)
3226
0
        continue;
3227
3228
      /* We need to switch from the ECDH name of the curve to the
3229
         EDDSA name of the curve if we want a signing key.  */
3230
0
      gcry_sexp_release (keyparms);
3231
0
      rc = gcry_sexp_build (&keyparms, NULL,
3232
0
                            "(public-key(ecc(curve %s)))",
3233
0
                            curves[idx].eddsa_curve? curves[idx].eddsa_curve
3234
0
                            /**/                   : curves[idx].name);
3235
0
      if (rc)
3236
0
        continue;
3237
0
      if (!gcry_pk_get_curve (keyparms, 0, NULL))
3238
0
        continue;
3239
0
      if (subkey_algo && curves[idx].eddsa_curve)
3240
0
        {
3241
          /* Both Curve 25519 (or 448) keys are to be created.  Check that
3242
             Libgcrypt also supports the real Curve25519 (or 448).  */
3243
0
          gcry_sexp_release (keyparms);
3244
0
          rc = gcry_sexp_build (&keyparms, NULL,
3245
0
                                "(public-key(ecc(curve %s)))",
3246
0
                                 curves[idx].name);
3247
0
          if (rc)
3248
0
            continue;
3249
0
          if (!gcry_pk_get_curve (keyparms, 0, NULL))
3250
0
            continue;
3251
0
        }
3252
3253
0
      curves[idx].available = 1;
3254
0
      if (!curves[idx].no_listing)
3255
0
        tty_printf ("   (%d) %s%s\n", idx + 1,
3256
0
                    curves[idx].pretty_name?
3257
0
                    curves[idx].pretty_name:curves[idx].name,
3258
0
                    idx == 0? _(" *default*"):"");
3259
0
    }
3260
0
  gcry_sexp_release (keyparms);
3261
3262
3263
0
  for (;;)
3264
0
    {
3265
0
      answer = cpr_get ("keygen.curve", _("Your selection? "));
3266
0
      cpr_kill_prompt ();
3267
0
      idx = *answer? atoi (answer) : 1;
3268
0
      if (!*answer && current)
3269
0
        {
3270
0
          xfree(answer);
3271
0
          return NULL;
3272
0
        }
3273
0
      else if (*answer && (!idx || (idx > 0 && idx <= DIM (curves)
3274
0
                                    && curves[idx-1].no_listing)))
3275
0
        {
3276
          /* See whether the user entered the name of the curve.  */
3277
0
          for (idx=0; idx < DIM(curves); idx++)
3278
0
            {
3279
0
              if (!opt.expert && curves[idx].expert_only)
3280
0
                continue;
3281
0
              if (!stricmp (curves[idx].name, answer)
3282
0
                  || (curves[idx].pretty_name
3283
0
                      && !stricmp (curves[idx].pretty_name, answer)))
3284
0
                break;
3285
0
            }
3286
0
          if (idx == DIM(curves))
3287
0
            idx = -1;
3288
0
        }
3289
0
      else
3290
0
        idx--;
3291
0
      xfree(answer);
3292
0
      answer = NULL;
3293
0
      if (idx < 0 || idx >= DIM (curves) || !curves[idx].available)
3294
0
        tty_printf (_("Invalid selection.\n"));
3295
0
      else
3296
0
        {
3297
          /* If the user selected a signing algorithm and Curve25519
3298
             we need to set the algo to EdDSA and update the curve name.
3299
             If switching away from EdDSA, we need to set the algo back
3300
             to ECDSA. */
3301
0
          if (*algo == PUBKEY_ALGO_ECDSA || *algo == PUBKEY_ALGO_EDDSA)
3302
0
            {
3303
0
              if (curves[idx].eddsa_curve)
3304
0
                {
3305
0
                  if (subkey_algo && *subkey_algo == PUBKEY_ALGO_ECDSA)
3306
0
                    *subkey_algo = PUBKEY_ALGO_EDDSA;
3307
0
                  *algo = PUBKEY_ALGO_EDDSA;
3308
0
                  result = curves[idx].eddsa_curve;
3309
0
                }
3310
0
              else
3311
0
                {
3312
0
                  if (subkey_algo && *subkey_algo == PUBKEY_ALGO_EDDSA)
3313
0
                    *subkey_algo = PUBKEY_ALGO_ECDSA;
3314
0
                  *algo = PUBKEY_ALGO_ECDSA;
3315
0
                  result = curves[idx].name;
3316
0
                }
3317
0
            }
3318
0
          else
3319
0
            result = curves[idx].name;
3320
0
          break;
3321
0
        }
3322
0
    }
3323
3324
0
  if (!result)
3325
0
    result = curves[0].name;
3326
3327
0
  return result;
3328
0
}
3329
3330
3331
/* Ask for the Kyber variant.  Returns a const algo string like
3332
 * kyber768_bp256 or NULL on error.  */
3333
const char *
3334
ask_kyber_variant (void)
3335
0
{
3336
0
  struct {
3337
0
    const char *desc;           /* e.g. "Kyber 768 (bp256)" */
3338
0
    const char *variant;        /* e.g. "kyber768_bp256"    */
3339
0
    unsigned int de_vs : 1;     /* Allowed in CO_DE_VS.     */
3340
0
  } table[] = {
3341
0
    { "Kyber 768 (bp256)",   "kyber768_bp256", 1 },
3342
0
    { "Kyber 1024 (bp384)",  "kyber1024_bp384", 1 },
3343
0
    { "Kyber 768 (X25519)",  "kyber768_cv25519", 0 },
3344
0
    { "Kyber 1024 (X448)",   "kyber1024_cv448", 0 },
3345
0
  };
3346
0
  int idx;
3347
0
  char *answer;
3348
0
  const char *result = NULL;
3349
3350
0
  tty_printf (_("Please select the %s variant you want:\n"), "Kyber");
3351
3352
0
  for (idx=0; idx < DIM(table); idx++)
3353
0
    {
3354
0
      if (opt.compliance==CO_DE_VS)
3355
0
        {
3356
0
          if (!table[idx].de_vs)
3357
0
            continue; /* Not allowed.  */
3358
0
        }
3359
3360
0
      tty_printf ("   (%d) %s%s\n", idx + 1,
3361
0
                  table[idx].desc,
3362
0
                  idx == 0? _(" *default*"):"");
3363
0
    }
3364
3365
0
  for (;;)
3366
0
    {
3367
0
      answer = cpr_get ("keygen.kyber_variant", _("Your selection? "));
3368
0
      cpr_kill_prompt ();
3369
0
      idx = *answer? atoi (answer) : 1 /* default */;
3370
0
      if (*answer && !idx)
3371
0
        {
3372
          /* See whether the user entered the name of the algo.  */
3373
0
          for (idx=0; idx < DIM(table); idx++)
3374
0
            {
3375
0
              if (!stricmp (table[idx].variant, answer))
3376
0
                break;
3377
0
            }
3378
0
          if (idx == DIM(table))
3379
0
            idx = -1;
3380
0
        }
3381
0
      else
3382
0
        idx--;  /* Map back to 0 based index.  */
3383
0
      xfree(answer);
3384
0
      answer = NULL;
3385
0
      if (idx < 0 || idx >= DIM (table)
3386
0
          || (opt.compliance==CO_DE_VS && !table[idx].de_vs))
3387
0
        tty_printf (_("Invalid selection.\n"));
3388
0
      else
3389
0
        {
3390
0
          result = table[idx].variant;
3391
0
          break;
3392
0
        }
3393
0
    }
3394
3395
0
  if (!result)
3396
0
    result = table[0].variant;
3397
3398
0
  return result;
3399
0
}
3400
3401
3402
/****************
3403
 * Parse an expire string and return its value in seconds.
3404
 * Returns (u32)-1 on error.
3405
 * This isn't perfect since scan_isodatestr returns unix time, and
3406
 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
3407
 * Because of this, we only permit setting expirations up to 2106, but
3408
 * OpenPGP could theoretically allow up to 2242.  I think we'll all
3409
 * just cope for the next few years until we get a 64-bit time_t or
3410
 * similar.
3411
 */
3412
static u32
3413
parse_expire_string_with_ct (const char *string, u32 creation_time)
3414
0
{
3415
0
  int mult;
3416
0
  u32 seconds;
3417
0
  u32 abs_date = 0;
3418
0
  time_t tt;
3419
0
  uint64_t tmp64;
3420
0
  u32 curtime;
3421
3422
0
  if (creation_time == (u32)-1)
3423
0
    curtime = make_timestamp ();
3424
0
  else
3425
0
    curtime = creation_time;
3426
3427
0
  if (!string || !*string || !strcmp (string, "none")
3428
0
      || !strcmp (string, "never") || !strcmp (string, "-"))
3429
0
    seconds = 0;
3430
0
  else if (!strncmp (string, "seconds=", 8))
3431
0
    seconds = scan_secondsstr (string+8);
3432
0
  else if ((abs_date = scan_isodatestr(string))
3433
0
           && (abs_date+86400/2) > curtime)
3434
0
    seconds = (abs_date+86400/2) - curtime;
3435
0
  else if ((tt = isotime2epoch_u64 (string)) != (uint64_t)(-1))
3436
0
    {
3437
0
      tmp64 = tt - curtime;
3438
0
      if (tmp64 >= (u32)(-1))
3439
0
        seconds = (u32)(-1) - 1;  /* cap value.  */
3440
0
      else
3441
0
        seconds = (u32)tmp64;
3442
0
    }
3443
0
  else if ((mult = check_valid_days (string)))
3444
0
    {
3445
0
      tmp64 = scan_secondsstr (string) * 86400L * mult;
3446
0
      if (tmp64 >= (u32)(-1))
3447
0
        seconds = (u32)(-1) - 1;  /* cap value.  */
3448
0
      else
3449
0
        seconds = (u32)tmp64;
3450
0
    }
3451
0
  else
3452
0
    seconds = (u32)(-1);
3453
3454
0
  return seconds;
3455
0
}
3456
3457
u32
3458
parse_expire_string ( const char *string )
3459
0
{
3460
0
  return parse_expire_string_with_ct (string, (u32)-1);
3461
0
}
3462
3463
3464
/* Parse a Creation-Date string which is either "1986-04-26" or
3465
   "19860426T042640".  Returns 0 on error. */
3466
static u32
3467
parse_creation_string (const char *string)
3468
0
{
3469
0
  u32 seconds;
3470
3471
0
  if (!*string)
3472
0
    seconds = 0;
3473
0
  else if ( !strncmp (string, "seconds=", 8) )
3474
0
    seconds = scan_secondsstr (string+8);
3475
0
  else if ( !(seconds = scan_isodatestr (string)))
3476
0
    {
3477
0
      uint64_t tmp = isotime2epoch_u64 (string);
3478
0
      if (tmp == (uint64_t)(-1))
3479
0
        seconds = 0;
3480
0
      else if (tmp > (u32)(-1))
3481
0
        seconds = 0;
3482
0
      else
3483
0
        seconds = tmp;
3484
0
    }
3485
0
  return seconds;
3486
0
}
3487
3488
3489
/* object == 0 for a key, and 1 for a sig */
3490
u32
3491
ask_expire_interval(int object,const char *def_expire)
3492
0
{
3493
0
    u32 interval;
3494
0
    char *answer;
3495
3496
0
    switch(object)
3497
0
      {
3498
0
      case 0:
3499
0
  if(def_expire)
3500
0
    BUG();
3501
0
  tty_printf(_("Please specify how long the key should be valid.\n"
3502
0
         "         0 = key does not expire\n"
3503
0
         "      <n>  = key expires in n days\n"
3504
0
         "      <n>w = key expires in n weeks\n"
3505
0
         "      <n>m = key expires in n months\n"
3506
0
         "      <n>y = key expires in n years\n"));
3507
0
  break;
3508
3509
0
      case 1:
3510
0
  if(!def_expire)
3511
0
    BUG();
3512
0
  tty_printf(_("Please specify how long the signature should be valid.\n"
3513
0
         "         0 = signature does not expire\n"
3514
0
         "      <n>  = signature expires in n days\n"
3515
0
         "      <n>w = signature expires in n weeks\n"
3516
0
         "      <n>m = signature expires in n months\n"
3517
0
         "      <n>y = signature expires in n years\n"));
3518
0
  break;
3519
3520
0
      default:
3521
0
  BUG();
3522
0
      }
3523
3524
    /* Note: The elgamal subkey for DSA has no expiration date because
3525
     * it must be signed with the DSA key and this one has the expiration
3526
     * date */
3527
3528
0
    answer = NULL;
3529
0
    for(;;)
3530
0
      {
3531
0
  u32 curtime;
3532
3533
0
  xfree(answer);
3534
0
  if(object==0)
3535
0
    answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
3536
0
  else
3537
0
    {
3538
0
      char *prompt;
3539
3540
0
      prompt = xasprintf (_("Signature is valid for? (%s) "), def_expire);
3541
0
      answer = cpr_get("siggen.valid",prompt);
3542
0
      xfree(prompt);
3543
3544
0
      if(*answer=='\0')
3545
0
              {
3546
0
                xfree (answer);
3547
0
          answer = xstrdup (def_expire);
3548
0
              }
3549
0
    }
3550
0
  cpr_kill_prompt();
3551
0
  trim_spaces(answer);
3552
0
        curtime = make_timestamp ();
3553
0
  interval = parse_expire_string( answer );
3554
0
  if( interval == (u32)-1 )
3555
0
    {
3556
0
      tty_printf(_("invalid value\n"));
3557
0
      continue;
3558
0
    }
3559
3560
0
  if( !interval )
3561
0
    {
3562
0
            tty_printf((object==0)
3563
0
                       ? _("Key does not expire at all\n")
3564
0
                       : _("Signature does not expire at all\n"));
3565
0
    }
3566
0
  else
3567
0
    {
3568
0
      tty_printf(object==0
3569
0
           ? _("Key expires at %s\n")
3570
0
           : _("Signature expires at %s\n"),
3571
0
           asctimestamp((ulong)(curtime + interval) ) );
3572
#if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
3573
      if ( (time_t)((ulong)(curtime+interval)) < 0 )
3574
        tty_printf (_("Your system can't display dates beyond 2038.\n"
3575
                            "However, it will be correctly handled up to"
3576
                            " 2106.\n"));
3577
            else
3578
#endif /*SIZEOF_TIME_T*/
3579
0
              if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
3580
0
                {
3581
0
                  tty_printf (_("invalid value\n"));
3582
0
                  continue;
3583
0
                }
3584
0
    }
3585
3586
0
  if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
3587
0
               _("Is this correct? (y/N) ")) )
3588
0
    break;
3589
0
      }
3590
3591
0
    xfree(answer);
3592
0
    return interval;
3593
0
}
3594
3595
u32
3596
ask_expiredate (void)
3597
0
{
3598
0
    u32 x = ask_expire_interval(0,NULL);
3599
0
    return x? make_timestamp() + x : 0;
3600
0
}
3601
3602
3603
3604
static PKT_user_id *
3605
uid_from_string (const char *string)
3606
0
{
3607
0
  size_t n;
3608
0
  PKT_user_id *uid;
3609
3610
0
  n = strlen (string);
3611
0
  uid = xmalloc_clear (sizeof *uid + n);
3612
0
  uid->len = n;
3613
0
  strcpy (uid->name, string);
3614
0
  uid->ref = 1;
3615
0
  return uid;
3616
0
}
3617
3618
3619
/* Return true if the user id UID already exists in the keyblock.  */
3620
static int
3621
uid_already_in_keyblock (kbnode_t keyblock, const char *uid)
3622
0
{
3623
0
  PKT_user_id *uidpkt = uid_from_string (uid);
3624
0
  kbnode_t node;
3625
0
  int result = 0;
3626
3627
0
  for (node=keyblock; node && !result; node=node->next)
3628
0
    if (!is_deleted_kbnode (node)
3629
0
        && node->pkt->pkttype == PKT_USER_ID
3630
0
        && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
3631
0
      result = 1;
3632
0
  free_user_id (uidpkt);
3633
0
  return result;
3634
0
}
3635
3636
3637
/* Ask for a user ID.  With a MODE of 1 an extra help prompt is
3638
   printed for use during a new key creation.  If KEYBLOCK is not NULL
3639
   the function prevents the creation of an already existing user
3640
   ID.  IF FULL is not set some prompts are not shown.  */
3641
static char *
3642
ask_user_id (int mode, int full, KBNODE keyblock)
3643
0
{
3644
0
    char *answer;
3645
0
    char *aname, *acomment, *amail, *uid;
3646
3647
0
    if ( !mode )
3648
0
      {
3649
        /* TRANSLATORS: This is the new string telling the user what
3650
           gpg is now going to do (i.e. ask for the parts of the user
3651
           ID).  Note that if you do not translate this string, a
3652
           different string will be used, which might still have
3653
           a correct translation.  */
3654
0
  const char *s1 =
3655
0
          N_("\n"
3656
0
             "GnuPG needs to construct a user ID to identify your key.\n"
3657
0
             "\n");
3658
0
        const char *s2 = _(s1);
3659
3660
0
        if (!strcmp (s1, s2))
3661
0
          {
3662
            /* There is no translation for the string thus we to use
3663
               the old info text.  gettext has no way to tell whether
3664
               a translation is actually available, thus we need to
3665
               to compare again. */
3666
            /* TRANSLATORS: This string is in general not anymore used
3667
               but you should keep your existing translation.  In case
3668
               the new string is not translated this old string will
3669
               be used. */
3670
0
            const char *s3 = N_("\n"
3671
0
"You need a user ID to identify your key; "
3672
0
                                        "the software constructs the user ID\n"
3673
0
"from the Real Name, Comment and Email Address in this form:\n"
3674
0
"    \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
3675
0
            const char *s4 = _(s3);
3676
0
            if (strcmp (s3, s4))
3677
0
              s2 = s3; /* A translation exists - use it. */
3678
0
          }
3679
0
        tty_printf ("%s", s2) ;
3680
0
      }
3681
0
    uid = aname = acomment = amail = NULL;
3682
0
    for(;;) {
3683
0
  char *p;
3684
0
  int fail=0;
3685
3686
0
  if( !aname ) {
3687
0
      for(;;) {
3688
0
    xfree(aname);
3689
0
    aname = cpr_get("keygen.name",_("Real name: "));
3690
0
    trim_spaces(aname);
3691
0
    cpr_kill_prompt();
3692
3693
0
    if( opt.allow_freeform_uid )
3694
0
        break;
3695
3696
0
    if( strpbrk( aname, "<>" ) )
3697
0
                  {
3698
0
        tty_printf(_("Invalid character in name\n"));
3699
0
        tty_printf(_("The characters '%s' and '%s' may not "
3700
0
                                 "appear in name\n"), "<", ">");
3701
0
                  }
3702
0
    else
3703
0
        break;
3704
0
      }
3705
0
  }
3706
0
  if( !amail ) {
3707
0
      for(;;) {
3708
0
    xfree(amail);
3709
0
    amail = cpr_get("keygen.email",_("Email address: "));
3710
0
    trim_spaces(amail);
3711
0
    cpr_kill_prompt();
3712
0
    if( !*amail || opt.allow_freeform_uid )
3713
0
        break;   /* no email address is okay */
3714
0
    else if ( !is_valid_mailbox (amail) )
3715
0
                    tty_printf(_("Not a valid email address\n"));
3716
0
    else
3717
0
        break;
3718
0
      }
3719
0
  }
3720
0
  if (!acomment) {
3721
0
          if (full) {
3722
0
      for(;;) {
3723
0
    xfree(acomment);
3724
0
    acomment = cpr_get("keygen.comment",_("Comment: "));
3725
0
    trim_spaces(acomment);
3726
0
    cpr_kill_prompt();
3727
0
    if( !*acomment )
3728
0
        break;   /* no comment is okay */
3729
0
    else if( strpbrk( acomment, "()" ) )
3730
0
        tty_printf(_("Invalid character in comment\n"));
3731
0
    else
3732
0
        break;
3733
0
      }
3734
0
          }
3735
0
          else {
3736
0
            xfree (acomment);
3737
0
            acomment = xstrdup ("");
3738
0
          }
3739
0
  }
3740
3741
3742
0
  xfree(uid);
3743
0
  uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
3744
0
        if (!*aname && *amail && !*acomment && !random_is_faked ())
3745
0
          { /* Empty name and comment but with mail address.  Use
3746
               simplified form with only the non-angle-bracketed mail
3747
               address.  */
3748
0
            p = stpcpy (p, amail);
3749
0
          }
3750
0
        else
3751
0
          {
3752
0
            p = stpcpy (p, aname );
3753
0
            if (*acomment)
3754
0
              p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
3755
0
            if (*amail)
3756
0
              p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
3757
0
          }
3758
3759
  /* Append a warning if the RNG is switched into fake mode.  */
3760
0
        if ( random_is_faked ()  )
3761
0
          strcpy(p, " (insecure!)" );
3762
3763
  /* print a note in case that UTF8 mapping has to be done */
3764
0
  for(p=uid; *p; p++ ) {
3765
0
      if( *p & 0x80 ) {
3766
0
    tty_printf(_("You are using the '%s' character set.\n"),
3767
0
         get_native_charset() );
3768
0
    break;
3769
0
      }
3770
0
  }
3771
3772
0
  tty_printf(_("You selected this USER-ID:\n    \"%s\"\n\n"), uid);
3773
3774
0
  if( !*amail && !opt.allow_freeform_uid
3775
0
      && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
3776
0
      fail = 1;
3777
0
            tty_printf(_("Please don't put the email address "
3778
0
                         "into the real name or the comment\n") );
3779
0
  }
3780
3781
0
        if (!fail && keyblock)
3782
0
          {
3783
0
            if (uid_already_in_keyblock (keyblock, uid))
3784
0
              {
3785
0
                tty_printf (_("Such a user ID already exists on this key!\n"));
3786
0
                fail = 1;
3787
0
              }
3788
0
          }
3789
3790
0
  for(;;) {
3791
            /* TRANSLATORS: These are the allowed answers in
3792
               lower and uppercase.  Below you will find the matching
3793
               string which should be translated accordingly and the
3794
               letter changed to match the one in the answer string.
3795
3796
                 n = Change name
3797
                 c = Change comment
3798
                 e = Change email
3799
                 o = Okay (ready, continue)
3800
                 q = Quit
3801
             */
3802
0
      const char *ansstr = _("NnCcEeOoQq");
3803
3804
0
      if( strlen(ansstr) != 10 )
3805
0
    BUG();
3806
0
      if( cpr_enabled() ) {
3807
0
                answer = xstrdup (ansstr + (fail?8:6));
3808
0
    answer[1] = 0;
3809
0
      }
3810
0
            else if (full) {
3811
0
    answer = cpr_get("keygen.userid.cmd", fail?
3812
0
      _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
3813
0
      _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
3814
0
    cpr_kill_prompt();
3815
0
            }
3816
0
            else {
3817
0
    answer = cpr_get("keygen.userid.cmd", fail?
3818
0
      _("Change (N)ame, (E)mail, or (Q)uit? ") :
3819
0
      _("Change (N)ame, (E)mail, or (O)kay/(Q)uit? "));
3820
0
    cpr_kill_prompt();
3821
0
      }
3822
0
      if( strlen(answer) > 1 )
3823
0
    ;
3824
0
      else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
3825
0
    xfree(aname); aname = NULL;
3826
0
    break;
3827
0
      }
3828
0
      else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
3829
0
    xfree(acomment); acomment = NULL;
3830
0
    break;
3831
0
      }
3832
0
      else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
3833
0
    xfree(amail); amail = NULL;
3834
0
    break;
3835
0
      }
3836
0
      else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
3837
0
    if( fail ) {
3838
0
        tty_printf(_("Please correct the error first\n"));
3839
0
    }
3840
0
    else {
3841
0
        xfree(aname); aname = NULL;
3842
0
        xfree(acomment); acomment = NULL;
3843
0
        xfree(amail); amail = NULL;
3844
0
        break;
3845
0
    }
3846
0
      }
3847
0
      else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
3848
0
    xfree(aname); aname = NULL;
3849
0
    xfree(acomment); acomment = NULL;
3850
0
    xfree(amail); amail = NULL;
3851
0
    xfree(uid); uid = NULL;
3852
0
    break;
3853
0
      }
3854
0
      xfree(answer);
3855
0
  }
3856
0
  xfree(answer);
3857
0
  if (!amail && !acomment)
3858
0
      break;
3859
0
  xfree(uid); uid = NULL;
3860
0
    }
3861
0
    if( uid ) {
3862
0
  char *p = native_to_utf8( uid );
3863
0
  xfree( uid );
3864
0
  uid = p;
3865
0
    }
3866
0
    return uid;
3867
0
}
3868
3869
3870
/* Basic key generation.  Here we divert to the actual generation
3871
 * routines based on the requested algorithm.  KEYGEN_FLAGS might be
3872
 * updated by this function.  */
3873
static int
3874
do_create (int algo, unsigned int nbits, const char *curve, kbnode_t pub_root,
3875
           u32 timestamp, u32 expiredate, int is_subkey,
3876
           int *keygen_flags, const char *passphrase,
3877
           char **cache_nonce_addr, char **passwd_nonce_addr,
3878
           gpg_error_t (*common_gen_cb)(common_gen_cb_parm_t),
3879
           common_gen_cb_parm_t common_gen_cb_parm)
3880
0
{
3881
0
  gpg_error_t err;
3882
3883
  /* Fixme: The entropy collecting message should be moved to a
3884
     libgcrypt progress handler.  */
3885
0
  if (!opt.batch)
3886
0
    tty_printf (_(
3887
0
"We need to generate a lot of random bytes. It is a good idea to perform\n"
3888
0
"some other action (type on the keyboard, move the mouse, utilize the\n"
3889
0
"disks) during the prime generation; this gives the random number\n"
3890
0
"generator a better chance to gain enough entropy.\n") );
3891
3892
0
  if (algo == PUBKEY_ALGO_ELGAMAL_E)
3893
0
    err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
3894
0
                   *keygen_flags, passphrase,
3895
0
                   cache_nonce_addr, passwd_nonce_addr,
3896
0
                   common_gen_cb, common_gen_cb_parm);
3897
0
  else if (algo == PUBKEY_ALGO_DSA)
3898
0
    err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
3899
0
                   *keygen_flags, passphrase,
3900
0
                   cache_nonce_addr, passwd_nonce_addr,
3901
0
                   common_gen_cb, common_gen_cb_parm);
3902
0
  else if (algo == PUBKEY_ALGO_ECDSA
3903
0
           || algo == PUBKEY_ALGO_EDDSA
3904
0
           || algo == PUBKEY_ALGO_ECDH)
3905
0
    err = gen_ecc (algo, curve, pub_root, timestamp, expiredate, is_subkey,
3906
0
                   keygen_flags, passphrase,
3907
0
                   cache_nonce_addr, passwd_nonce_addr,
3908
0
                   common_gen_cb, common_gen_cb_parm);
3909
0
  else if (algo == PUBKEY_ALGO_KYBER)
3910
0
    err = gen_kyber (algo, nbits, curve,
3911
0
                   pub_root, timestamp, expiredate, is_subkey,
3912
0
                   keygen_flags, passphrase,
3913
0
                   cache_nonce_addr, passwd_nonce_addr,
3914
0
                   common_gen_cb, common_gen_cb_parm);
3915
0
  else if (algo == PUBKEY_ALGO_RSA)
3916
0
    err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
3917
0
                   *keygen_flags, passphrase,
3918
0
                   cache_nonce_addr, passwd_nonce_addr,
3919
0
                   common_gen_cb, common_gen_cb_parm);
3920
0
  else
3921
0
    BUG();
3922
3923
0
  return err;
3924
0
}
3925
3926
3927
/* Generate a new user id packet or return NULL if canceled.  If
3928
   KEYBLOCK is not NULL the function prevents the creation of an
3929
   already existing user ID.  If UIDSTR is not NULL the user is not
3930
   asked but UIDSTR is used to create the user id packet; if the user
3931
   id already exists NULL is returned.  UIDSTR is expected to be utf-8
3932
   encoded and should have already been checked for a valid length
3933
   etc.  */
3934
PKT_user_id *
3935
generate_user_id (KBNODE keyblock, const char *uidstr)
3936
0
{
3937
0
  PKT_user_id *uid;
3938
0
  char *p;
3939
3940
0
  if (uidstr)
3941
0
    {
3942
0
      if (uid_already_in_keyblock (keyblock, uidstr))
3943
0
        return NULL;  /* Already exists.  */
3944
0
      uid = uid_from_string (uidstr);
3945
0
    }
3946
0
  else
3947
0
    {
3948
0
      p = ask_user_id (1, 1, keyblock);
3949
0
      if (!p)
3950
0
        return NULL;  /* Canceled. */
3951
0
      uid = uid_from_string (p);
3952
0
      xfree (p);
3953
0
    }
3954
0
  return uid;
3955
0
}
3956
3957
3958
/* Helper for parse_key_parameter_part_parameter_string for one part of the
3959
 * specification string; i.e.  ALGO/FLAGS.  If STRING is NULL or empty
3960
 * success is returned.  On error an error code is returned.  Note
3961
 * that STRING may be modified by this function.  NULL may be passed
3962
 * for any parameter.  FOR_SUBKEY shall be true if this is used as a
3963
 * subkey.  If CLEAR_CERT is set a default CERT usage will be cleared;
3964
 * this is useful if for example the default algorithm is used for a
3965
 * subkey.  If R_KEYVERSION is not NULL it will receive the version of
3966
 * the key; this is currently 4 but can be changed with the flag "v5"
3967
 * to create a v5 key.  If R_KEYTIME is not NULL and the key has been
3968
 * taken from active OpenPGP card, its creation time is stored
3969
 * there.  */
3970
static gpg_error_t
3971
parse_key_parameter_part (ctrl_t ctrl,
3972
                          char *string, int for_subkey, int clear_cert,
3973
                          int *r_algo, unsigned int *r_size,
3974
                          unsigned int *r_keyuse,
3975
                          char const **r_curve, int *r_keyversion,
3976
                          char **r_keygrip, u32 *r_keytime)
3977
0
{
3978
0
  gpg_error_t err;
3979
0
  char *flags;
3980
0
  int algo;
3981
0
  char *endp;
3982
0
  const char *curve = NULL;
3983
0
  int ecdh_or_ecdsa = 0;
3984
0
  unsigned int size;
3985
0
  int keyuse;
3986
0
  int keyversion = 0;           /* Not specified.  */
3987
0
  int i;
3988
0
  const char *s;
3989
0
  int from_card = 0;
3990
0
  char *keygrip = NULL;
3991
0
  u32 keytime = 0;
3992
0
  int is_448 = 0;
3993
0
  int is_pqc = 0;
3994
3995
0
  if (!string || !*string)
3996
0
    return 0; /* Success.  */
3997
3998
0
  flags = strchr (string, '/');
3999
0
  if (flags)
4000
0
    *flags++ = 0;
4001
4002
0
  algo = 0;
4003
0
  if (!ascii_strcasecmp (string, "card"))
4004
0
    from_card = 1;
4005
0
  else if (strlen (string) >= 3 && (digitp (string+3) || !string[3]))
4006
0
    {
4007
0
      if (!ascii_memcasecmp (string, "rsa", 3))
4008
0
        algo = PUBKEY_ALGO_RSA;
4009
0
      else if (!ascii_memcasecmp (string, "dsa", 3))
4010
0
        algo = PUBKEY_ALGO_DSA;
4011
0
      else if (!ascii_memcasecmp (string, "elg", 3))
4012
0
        algo = PUBKEY_ALGO_ELGAMAL_E;
4013
0
    }
4014
4015
0
  if (from_card)
4016
0
    ; /* We need the flags before we can figure out the key to use.  */
4017
0
  else if (algo)
4018
0
    {
4019
      /* This is one of the algos parsed above (rsa, dsa, or elg).  */
4020
0
      if (!string[3])
4021
0
        size = get_keysize_range (algo, NULL, NULL);
4022
0
      else
4023
0
        {
4024
0
          size = strtoul (string+3, &endp, 10);
4025
0
          if (size < 512 || size > 16384 || *endp)
4026
0
            return gpg_error (GPG_ERR_INV_VALUE);
4027
0
        }
4028
0
    }
4029
0
  else if (!ascii_strcasecmp (string, "kyber")
4030
0
           || !ascii_strcasecmp (string, "kyber768"))
4031
0
    {
4032
      /* Get the curve and check that it can technically be used
4033
       * (i.e. everything except the EdXXXX curves.  */
4034
0
      curve = openpgp_is_curve_supported ("brainpoolP256r1", &algo, NULL);
4035
0
      if (!curve || algo == PUBKEY_ALGO_EDDSA)
4036
0
        return gpg_error (GPG_ERR_UNKNOWN_CURVE);
4037
0
      algo = PUBKEY_ALGO_KYBER;
4038
0
      size = 768;
4039
0
      is_pqc = 1;
4040
0
    }
4041
0
  else if (!ascii_strcasecmp (string, "kyber1024"))
4042
0
    {
4043
      /* Get the curve and check that it can technically be used
4044
       * (i.e. everything except the EdXXXX curves.  */
4045
0
      curve = openpgp_is_curve_supported ("brainpoolP384r1", &algo, NULL);
4046
0
      if (!curve || algo == PUBKEY_ALGO_EDDSA)
4047
0
        return gpg_error (GPG_ERR_UNKNOWN_CURVE);
4048
0
      algo = PUBKEY_ALGO_KYBER;
4049
0
      size = 1024;
4050
0
      is_pqc = 1;
4051
0
    }
4052
0
  else if (!ascii_strncasecmp (string,    "ky768_", 6)
4053
0
           || !ascii_strncasecmp (string, "ky1024_", 7)
4054
0
           || !ascii_strncasecmp (string, "kyber768_", 9)
4055
0
           || !ascii_strncasecmp (string, "kyber1024_", 10)
4056
0
           )
4057
0
    {
4058
      /* Get the curve and check that it can technically be used
4059
       * (i.e. everything except the EdXXXX curves.  */
4060
0
      s = strchr (string, '_');
4061
0
      log_assert (s);
4062
0
      s++;
4063
0
      curve = openpgp_is_curve_supported (s, &algo, NULL);
4064
0
      if (!curve || algo == PUBKEY_ALGO_EDDSA)
4065
0
        return gpg_error (GPG_ERR_UNKNOWN_CURVE);
4066
0
      algo = PUBKEY_ALGO_KYBER;
4067
0
      size = strstr (string, "768_")? 768 : 1024;
4068
0
      is_pqc = 1;
4069
0
    }
4070
0
  else if (!ascii_strcasecmp (string, "dil3"))
4071
0
    {
4072
0
      algo = PUBKEY_ALGO_DIL3_25519;
4073
0
      is_pqc = 1;
4074
0
    }
4075
0
  else if (!ascii_strcasecmp (string, "dil5"))
4076
0
    {
4077
0
      algo = PUBKEY_ALGO_DIL5_448;
4078
0
      is_pqc = 1;
4079
0
    }
4080
0
  else if (!ascii_strcasecmp (string, "sphinx")
4081
0
           || !ascii_strcasecmp (string, "sphinx_sha2"))
4082
0
    {
4083
0
      algo = PUBKEY_ALGO_SPHINX_SHA2;
4084
0
      is_pqc = 1;
4085
0
    }
4086
0
  else if ((curve = openpgp_is_curve_supported (string, &algo, &size)))
4087
0
    {
4088
0
      if (!algo)
4089
0
        {
4090
0
          algo = PUBKEY_ALGO_ECDH; /* Default ECC algorithm.  */
4091
0
          ecdh_or_ecdsa = 1;       /* We may need to switch the algo.  */
4092
0
        }
4093
0
      if (curve && (!strcmp (curve, "X448") || !strcmp (curve, "Ed448")))
4094
0
        is_448 = 1;
4095
0
    }
4096
0
  else
4097
0
    return gpg_error (GPG_ERR_UNKNOWN_CURVE);
4098
4099
  /* Parse the flags.  */
4100
0
  keyuse = 0;
4101
0
  if (flags)
4102
0
    {
4103
0
      char **tokens = NULL;
4104
4105
0
      tokens = strtokenize (flags, ",");
4106
0
      if (!tokens)
4107
0
        return gpg_error_from_syserror ();
4108
4109
0
      for (i=0; (s = tokens[i]); i++)
4110
0
        {
4111
0
          if (!*s)
4112
0
            ;
4113
0
          else if (!ascii_strcasecmp (s, "sign"))
4114
0
            keyuse |= PUBKEY_USAGE_SIG;
4115
0
          else if (!ascii_strcasecmp (s, "encrypt")
4116
0
                   || !ascii_strcasecmp (s, "encr"))
4117
0
            keyuse |= PUBKEY_USAGE_ENC;
4118
0
          else if (!ascii_strcasecmp (s, "auth"))
4119
0
            keyuse |= PUBKEY_USAGE_AUTH;
4120
0
          else if (!ascii_strcasecmp (s, "cert"))
4121
0
            keyuse |= PUBKEY_USAGE_CERT;
4122
0
          else if (!ascii_strcasecmp (s, "ecdsa") && !from_card)
4123
0
            {
4124
0
              if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
4125
0
                algo = PUBKEY_ALGO_ECDSA;
4126
0
              else
4127
0
                {
4128
0
                  xfree (tokens);
4129
0
                  return gpg_error (GPG_ERR_INV_FLAG);
4130
0
                }
4131
0
              ecdh_or_ecdsa = 0;
4132
0
            }
4133
0
          else if (!ascii_strcasecmp (s, "ecdh") && !from_card)
4134
0
            {
4135
0
              if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
4136
0
                algo = PUBKEY_ALGO_ECDH;
4137
0
              else
4138
0
                {
4139
0
                  xfree (tokens);
4140
0
                  return gpg_error (GPG_ERR_INV_FLAG);
4141
0
                }
4142
0
              ecdh_or_ecdsa = 0;
4143
0
            }
4144
0
          else if (!ascii_strcasecmp (s, "eddsa") && !from_card)
4145
0
            {
4146
              /* Not required but we allow it for consistency.  */
4147
0
              if (algo == PUBKEY_ALGO_EDDSA)
4148
0
                ;
4149
0
              else
4150
0
                {
4151
0
                  xfree (tokens);
4152
0
                  return gpg_error (GPG_ERR_INV_FLAG);
4153
0
                }
4154
0
            }
4155
0
          else if (!ascii_strcasecmp (s, "v5"))
4156
0
            keyversion = 5;
4157
0
          else if (!ascii_strcasecmp (s, "v4"))
4158
0
            keyversion = 4;
4159
0
          else
4160
0
            {
4161
0
              xfree (tokens);
4162
0
              return gpg_error (GPG_ERR_UNKNOWN_FLAG);
4163
0
            }
4164
0
        }
4165
4166
0
      xfree (tokens);
4167
0
    }
4168
4169
  /* If not yet decided switch between ecdh and ecdsa unless we want
4170
   * to read the algo from the current card.  */
4171
0
  if (from_card)
4172
0
    {
4173
0
      keypair_info_t keypairlist, kpi;
4174
0
      char *reqkeyref;
4175
4176
0
      if (!keyuse)
4177
0
        keyuse = (for_subkey? PUBKEY_USAGE_ENC
4178
0
                  /* */     : (PUBKEY_USAGE_CERT|PUBKEY_USAGE_SIG));
4179
4180
      /* Access the card to make sure we have one and to show the S/N.  */
4181
0
      {
4182
0
        char *serialno;
4183
4184
0
        err = agent_scd_serialno (&serialno, NULL);
4185
0
        if (err)
4186
0
          {
4187
0
            log_error (_("error reading the card: %s\n"), gpg_strerror (err));
4188
0
            return err;
4189
0
          }
4190
0
        if (!opt.quiet)
4191
0
          log_info (_("Serial number of the card: %s\n"), serialno);
4192
0
        xfree (serialno);
4193
0
      }
4194
4195
0
      err = agent_scd_keypairinfo (ctrl, NULL, &keypairlist);
4196
0
      if (err)
4197
0
        {
4198
0
          log_error (_("error reading the card: %s\n"), gpg_strerror (err));
4199
0
          return err;
4200
0
        }
4201
0
      agent_scd_getattr_one ((keyuse & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_CERT))
4202
0
                             ? "$SIGNKEYID":"$ENCRKEYID", &reqkeyref);
4203
4204
0
      algo = 0; /* Should already be the case.  */
4205
0
      for (kpi=keypairlist; kpi && !algo; kpi = kpi->next)
4206
0
        {
4207
0
          gcry_sexp_t s_pkey;
4208
0
          char *algostr = NULL;
4209
0
          enum gcry_pk_algos algoid = 0;
4210
0
          const char *keyref = kpi->idstr;
4211
4212
0
          if (!reqkeyref)
4213
0
            continue; /* Card does not provide the info (skip all).  */
4214
4215
0
          if (!keyref)
4216
0
            continue; /* Ooops.  */
4217
0
          if (strcmp (reqkeyref, keyref))
4218
0
            continue;  /* This is not the requested keyref.  */
4219
4220
0
          if ((keyuse & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_CERT))
4221
0
              && (kpi->usage & (GCRY_PK_USAGE_SIGN|GCRY_PK_USAGE_CERT)))
4222
0
            ; /* Okay */
4223
0
          else if ((keyuse & PUBKEY_USAGE_ENC)
4224
0
                   && (kpi->usage & GCRY_PK_USAGE_ENCR))
4225
0
            ; /* Okay */
4226
0
          else
4227
0
            continue; /* Not usable for us.  */
4228
4229
0
          if (agent_scd_readkey (ctrl, keyref, &s_pkey, NULL))
4230
0
            continue;  /* Could not read the key.  */
4231
4232
0
          algostr = pubkey_algo_string (s_pkey, &algoid);
4233
0
          gcry_sexp_release (s_pkey);
4234
4235
          /* Map to OpenPGP algo number.
4236
           * We need to tweak the algo in case GCRY_PK_ECC is
4237
           * returned because pubkey_algo_string is not aware
4238
           * of the OpenPGP algo mapping.  We need to
4239
           * distinguish between ECDH and ECDSA but we can do
4240
           * that only if we got usage flags.
4241
           * Note: Keep this in sync with ask_algo.  */
4242
0
          if (algoid == GCRY_PK_ECC && algostr)
4243
0
            {
4244
0
              if (!strcmp (algostr, "ed25519"))
4245
0
                algo = PUBKEY_ALGO_EDDSA;
4246
0
              else if (!strcmp (algostr, "ed448"))
4247
0
                {
4248
0
                  algo = PUBKEY_ALGO_EDDSA;
4249
0
                  is_448 = 1;
4250
0
                }
4251
0
              else if (!strcmp (algostr, "cv25519"))
4252
0
                algo = PUBKEY_ALGO_ECDH;
4253
0
              else if (!strcmp (algostr, "cv448"))
4254
0
                {
4255
0
                  algo = PUBKEY_ALGO_ECDH;
4256
0
                  is_448 = 1;
4257
0
                }
4258
0
              else if ((kpi->usage & GCRY_PK_USAGE_ENCR))
4259
0
                algo = PUBKEY_ALGO_ECDH;
4260
0
              else
4261
0
                algo = PUBKEY_ALGO_ECDSA;
4262
0
            }
4263
0
          else
4264
0
            algo = map_gcry_pk_to_openpgp (algoid);
4265
4266
0
          xfree (algostr);
4267
0
          xfree (keygrip);
4268
0
          keygrip = xtrystrdup (kpi->keygrip);
4269
0
          if (!keygrip)
4270
0
            {
4271
0
              err = gpg_error_from_syserror ();
4272
0
              xfree (reqkeyref);
4273
0
              free_keypair_info (keypairlist);
4274
0
              return err;
4275
0
            }
4276
0
          keytime = kpi->keytime;
4277
0
        }
4278
4279
0
      xfree (reqkeyref);
4280
0
      free_keypair_info (keypairlist);
4281
0
      if (!algo || !keygrip)
4282
0
        {
4283
0
          err = gpg_error (GPG_ERR_PUBKEY_ALGO);
4284
0
          log_error ("no usable key on the card: %s\n", gpg_strerror (err));
4285
0
          xfree (keygrip);
4286
0
          return err;
4287
0
        }
4288
0
    }
4289
0
  else if (ecdh_or_ecdsa && keyuse)
4290
0
    algo = (keyuse & PUBKEY_USAGE_ENC)? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
4291
0
  else if (ecdh_or_ecdsa)
4292
0
    algo = for_subkey? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
4293
4294
  /* Set or fix key usage.  */
4295
0
  if (!keyuse)
4296
0
    {
4297
0
      if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
4298
0
          || algo == PUBKEY_ALGO_DSA)
4299
0
        keyuse = PUBKEY_USAGE_SIG;
4300
0
      else if (algo == PUBKEY_ALGO_RSA)
4301
0
        keyuse = for_subkey? PUBKEY_USAGE_ENC : PUBKEY_USAGE_SIG;
4302
0
      else
4303
0
        keyuse = PUBKEY_USAGE_ENC;
4304
0
    }
4305
0
  else if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
4306
0
           || algo == PUBKEY_ALGO_DSA)
4307
0
    {
4308
0
      keyuse &= ~PUBKEY_USAGE_ENC; /* Forbid encryption.  */
4309
0
    }
4310
0
  else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ELGAMAL_E)
4311
0
    {
4312
0
      keyuse = PUBKEY_USAGE_ENC;   /* Allow only encryption.  */
4313
0
    }
4314
4315
  /* Make sure a primary key can certify.  */
4316
0
  if (!for_subkey)
4317
0
    keyuse |= PUBKEY_USAGE_CERT;
4318
4319
  /* But if requested remove th cert usage.  */
4320
0
  if (clear_cert)
4321
0
    keyuse &= ~PUBKEY_USAGE_CERT;
4322
4323
  /* Check that usage is actually possible.  */
4324
0
  if (/**/((keyuse & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
4325
0
           && !pubkey_get_nsig (algo))
4326
0
       || ((keyuse & PUBKEY_USAGE_ENC)
4327
0
           && !pubkey_get_nenc (algo))
4328
0
       || (for_subkey && (keyuse & PUBKEY_USAGE_CERT)))
4329
0
    {
4330
0
      xfree (keygrip);
4331
0
      return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
4332
0
    }
4333
4334
  /* Ed448, X448 and the PQC algos must only be used as v5 keys.  */
4335
0
  if (is_448 || is_pqc)
4336
0
    {
4337
0
      if (keyversion == 4)
4338
0
        log_info (_("WARNING: v4 is specified, but overridden by v5.\n"));
4339
4340
0
      keyversion = 5;
4341
0
    }
4342
0
  else if (keyversion == 0)
4343
0
    keyversion = 4;
4344
4345
  /* Return values.  */
4346
0
  if (r_algo)
4347
0
    *r_algo = algo;
4348
0
  if (r_size)
4349
0
    {
4350
0
      unsigned int min, def, max;
4351
4352
      /* Make sure the keysize is in the allowed range.  */
4353
0
      def = get_keysize_range (algo, &min, &max);
4354
0
      if (!size)
4355
0
        size = def;
4356
0
      else if (size < min)
4357
0
        size = min;
4358
0
      else if (size > max)
4359
0
        size = max;
4360
4361
0
      *r_size = fixup_keysize (size, algo, 1);
4362
0
    }
4363
4364
0
  if (r_keyuse)
4365
0
    *r_keyuse = keyuse;
4366
0
  if (r_curve)
4367
0
    *r_curve = curve;
4368
0
  if (r_keyversion)
4369
0
    *r_keyversion = keyversion;
4370
4371
0
  if (r_keygrip)
4372
0
    *r_keygrip = keygrip;
4373
0
  else
4374
0
    xfree (keygrip);
4375
4376
0
  if (r_keytime)
4377
0
    *r_keytime = keytime;
4378
4379
0
  return 0;
4380
0
}
4381
4382
4383
/* Parse and return the standard key generation parameter.
4384
 * The string is expected to be in this format:
4385
 *
4386
 *   ALGO[/FLAGS][+SUBALGO[/FLAGS]]
4387
 *
4388
 * Here ALGO is a string in the same format as printed by the
4389
 * keylisting.  For example:
4390
 *
4391
 *   rsa3072 := RSA with 3072 bit.
4392
 *   dsa2048 := DSA with 2048 bit.
4393
 *   elg2048 := Elgamal with 2048 bit.
4394
 *   ed25519 := EDDSA using curve Ed25519.
4395
 *   ed448   := EDDSA using curve Ed448.
4396
 *   cv25519 := ECDH using curve Curve25519.
4397
 *   cv448   := ECDH using curve X448.
4398
 *   nistp256:= ECDSA or ECDH using curve NIST P-256
4399
 *   kyber   := Kyber with the default parameters
4400
 *   ky768_bp384 := Kyber-768 with BrainpoolP256r1 as second algo
4401
 *
4402
 * All strings with an unknown prefix are considered an elliptic
4403
 * curve.  Curves which have no implicit algorithm require that FLAGS
4404
 * is given to select whether ECDSA or ECDH is used; this can either
4405
 * be done using an algorithm keyword or usage keywords.
4406
 *
4407
 * FLAGS is a comma delimited string of keywords:
4408
 *
4409
 *   cert := Allow usage Certify
4410
 *   sign := Allow usage Sign
4411
 *   encr := Allow usage Encrypt
4412
 *   auth := Allow usage Authentication
4413
 *   encrypt := Alias for "encr"
4414
 *   ecdsa := Use algorithm ECDSA.
4415
 *   eddsa := Use algorithm EdDSA.
4416
 *   ecdh  := Use algorithm ECDH.
4417
 *   v5    := Create version 5 key
4418
 *
4419
 * There are several defaults and fallbacks depending on the
4420
 * algorithm.  PART can be used to select which part of STRING is
4421
 * used:
4422
 *   -1 := Both parts
4423
 *    0 := Only the part of the primary key
4424
 *    1 := If there is one part parse that one, if there are
4425
 *         two parts parse the part which best matches the
4426
 *         SUGGESTED_USE or in case that can't be evaluated the second part.
4427
 *         Always return using the args for the primary key (R_ALGO,....).
4428
 *
4429
 */
4430
gpg_error_t
4431
parse_key_parameter_string (ctrl_t ctrl,
4432
                            const char *string, int part,
4433
                            unsigned int suggested_use,
4434
                            int *r_algo, unsigned int *r_size,
4435
                            unsigned int *r_keyuse,
4436
                            char const **r_curve,
4437
                            int *r_version,
4438
                            char **r_keygrip,
4439
                            u32 *r_keytime,
4440
                            int *r_subalgo, unsigned int *r_subsize,
4441
                            unsigned int *r_subkeyuse,
4442
                            char const **r_subcurve,
4443
                            int *r_subversion,
4444
                            char **r_subkeygrip,
4445
                            u32 *r_subkeytime)
4446
0
{
4447
0
  gpg_error_t err = 0;
4448
0
  char *primary, *secondary;
4449
4450
0
  if (r_algo)
4451
0
    *r_algo = 0;
4452
0
  if (r_size)
4453
0
    *r_size = 0;
4454
0
  if (r_keyuse)
4455
0
    *r_keyuse = 0;
4456
0
  if (r_curve)
4457
0
    *r_curve = NULL;
4458
0
  if (r_version)
4459
0
    *r_version = 4;
4460
0
  if (r_keygrip)
4461
0
    *r_keygrip = NULL;
4462
0
  if (r_keytime)
4463
0
    *r_keytime = 0;
4464
0
  if (r_subalgo)
4465
0
    *r_subalgo = 0;
4466
0
  if (r_subsize)
4467
0
    *r_subsize = 0;
4468
0
  if (r_subkeyuse)
4469
0
    *r_subkeyuse = 0;
4470
0
  if (r_subcurve)
4471
0
    *r_subcurve = NULL;
4472
0
  if (r_subversion)
4473
0
    *r_subversion = 4;
4474
0
  if (r_subkeygrip)
4475
0
    *r_subkeygrip = NULL;
4476
0
  if (r_subkeytime)
4477
0
    *r_subkeytime = 0;
4478
4479
0
  if (!string || !*string
4480
0
      || !ascii_strcasecmp (string, "default") || !strcmp (string, "-"))
4481
0
    string = get_default_pubkey_algo ();
4482
0
  else if (!ascii_strcasecmp (string, "future-default")
4483
0
           || !ascii_strcasecmp (string, "futuredefault"))
4484
0
    string = FUTURE_STD_KEY_PARAM;
4485
0
  else if (!ascii_strcasecmp (string, "pqc"))
4486
0
    string = PQC_STD_KEY_PARAM;
4487
0
  else if (!ascii_strcasecmp (string, "card"))
4488
0
    string = "card/cert,sign+card/encr";
4489
4490
0
  primary = xstrdup (string);
4491
0
  secondary = strchr (primary, '+');
4492
0
  if (secondary)
4493
0
    *secondary++ = 0;
4494
0
  if (part == -1 || part == 0)
4495
0
    {
4496
0
      err = parse_key_parameter_part (ctrl, primary,
4497
0
                                      0, 0, r_algo, r_size,
4498
0
                                      r_keyuse, r_curve, r_version,
4499
0
                                      r_keygrip, r_keytime);
4500
0
      if (!err && part == -1)
4501
0
        err = parse_key_parameter_part (ctrl, secondary,
4502
0
                                        1, 0, r_subalgo, r_subsize,
4503
0
                                        r_subkeyuse, r_subcurve, r_subversion,
4504
0
                                        r_subkeygrip, r_subkeytime);
4505
0
    }
4506
0
  else if (part == 1)
4507
0
    {
4508
      /* If we have SECONDARY, use that part.  If there is only one
4509
       * part consider this to be the subkey algo.  In case a
4510
       * SUGGESTED_USE has been given and the usage of the secondary
4511
       * part does not match SUGGESTED_USE try again using the primary
4512
       * part.  Note that when falling back to the primary key we need
4513
       * to force clearing the cert usage. */
4514
0
      if (secondary)
4515
0
        {
4516
0
          err = parse_key_parameter_part (ctrl, secondary,
4517
0
                                          1, 0,
4518
0
                                          r_algo, r_size, r_keyuse, r_curve,
4519
0
                                          r_version, r_keygrip, r_keytime);
4520
0
          if (!err && suggested_use && r_keyuse && !(suggested_use & *r_keyuse))
4521
0
            err = parse_key_parameter_part (ctrl, primary,
4522
0
                                            1, 1 /*(clear cert)*/,
4523
0
                                            r_algo, r_size, r_keyuse, r_curve,
4524
0
                                            r_version, r_keygrip, r_keytime);
4525
0
        }
4526
0
      else
4527
0
        err = parse_key_parameter_part (ctrl, primary,
4528
0
                                        1, 0,
4529
0
                                        r_algo, r_size, r_keyuse, r_curve,
4530
0
                                        r_version, r_keygrip, r_keytime);
4531
0
    }
4532
4533
0
  xfree (primary);
4534
4535
0
  return err;
4536
0
}
4537
4538
4539
4540
/* Append R to the linked list PARA.  */
4541
static void
4542
append_to_parameter (struct para_data_s *para, struct para_data_s *r)
4543
0
{
4544
0
  log_assert (para);
4545
0
  while (para->next)
4546
0
    para = para->next;
4547
0
  para->next = r;
4548
0
}
4549
4550
/* Release the parameter list R.  */
4551
static void
4552
release_parameter_list (struct para_data_s *r)
4553
0
{
4554
0
  struct para_data_s *r2;
4555
4556
0
  for (; r ; r = r2)
4557
0
    {
4558
0
      r2 = r->next;
4559
0
      if (r->key == pPASSPHRASE && *r->u.value)
4560
0
        wipememory (r->u.value, strlen (r->u.value));
4561
0
      else if (r->key == pADSK)
4562
0
        free_public_key (r->u.adsk);
4563
4564
0
      xfree (r);
4565
0
    }
4566
0
}
4567
4568
/* Return the N-th parameter of name KEY from PARA.  An IDX of 0
4569
 * returns the first and so on.  */
4570
static struct para_data_s *
4571
get_parameter_idx (struct para_data_s *para, enum para_name key,
4572
                   unsigned int idx)
4573
0
{
4574
0
  struct para_data_s *r;
4575
4576
0
  for(r = para; r; r = r->next)
4577
0
    if (r->key == key)
4578
0
      {
4579
0
        if (!idx)
4580
0
          return r;
4581
0
        idx--;
4582
0
      }
4583
0
  return NULL;
4584
0
}
4585
4586
/* Return the first parameter of name KEY from PARA.  */
4587
static struct para_data_s *
4588
get_parameter (struct para_data_s *para, enum para_name key)
4589
0
{
4590
0
  return get_parameter_idx (para, key, 0);
4591
0
}
4592
4593
static const char *
4594
get_parameter_value( struct para_data_s *para, enum para_name key )
4595
0
{
4596
0
    struct para_data_s *r = get_parameter( para, key );
4597
0
    return (r && *r->u.value)? r->u.value : NULL;
4598
0
}
4599
4600
4601
/* This is similar to get_parameter_value but also returns the empty
4602
   string.  This is required so that quick_generate_keypair can use an
4603
   empty Passphrase to specify no-protection.  */
4604
static const char *
4605
get_parameter_passphrase (struct para_data_s *para)
4606
0
{
4607
0
  struct para_data_s *r = get_parameter (para, pPASSPHRASE);
4608
0
  return r ? r->u.value : NULL;
4609
0
}
4610
4611
4612
static int
4613
get_parameter_algo (ctrl_t ctrl, struct para_data_s *para, enum para_name key,
4614
                    int *r_default)
4615
0
{
4616
0
  int i;
4617
0
  struct para_data_s *r = get_parameter( para, key );
4618
4619
0
  if (r_default)
4620
0
    *r_default = 0;
4621
4622
0
  if (!r)
4623
0
    return -1;
4624
4625
  /* Note that we need to handle the ECC algorithms specified as
4626
     strings directly because Libgcrypt folds them all to ECC.  */
4627
0
  if (!ascii_strcasecmp (r->u.value, "default"))
4628
0
    {
4629
      /* Note: If you change this default algo, remember to change it
4630
       * also in gpg.c:gpgconf_list.  */
4631
      /* FIXME: We only allow the algo here and have a separate thing
4632
       * for the curve etc.  That is a ugly but demanded for backward
4633
       * compatibility with the batch key generation.  It would be
4634
       * better to make full use of parse_key_parameter_string.  */
4635
0
      parse_key_parameter_string (ctrl, NULL, 0, 0,
4636
0
                                  &i, NULL, NULL, NULL, NULL, NULL, NULL,
4637
0
                                  NULL, NULL, NULL, NULL, NULL, NULL, NULL);
4638
0
      if (r_default)
4639
0
        *r_default = 1;
4640
0
    }
4641
0
  else if (digitp (r->u.value))
4642
0
    i = atoi( r->u.value );
4643
0
  else if (!strcmp (r->u.value, "ELG-E")
4644
0
           || !strcmp (r->u.value, "ELG"))
4645
0
    i = PUBKEY_ALGO_ELGAMAL_E;
4646
0
  else if (!ascii_strcasecmp (r->u.value, "EdDSA"))
4647
0
    i = PUBKEY_ALGO_EDDSA;
4648
0
  else if (!ascii_strcasecmp (r->u.value, "ECDSA"))
4649
0
    i = PUBKEY_ALGO_ECDSA;
4650
0
  else if (!ascii_strcasecmp (r->u.value, "ECDH"))
4651
0
    i = PUBKEY_ALGO_ECDH;
4652
0
  else if (!ascii_strcasecmp (r->u.value, "KYBER"))
4653
0
    i = PUBKEY_ALGO_KYBER;
4654
0
  else
4655
0
    i = map_gcry_pk_to_openpgp (gcry_pk_map_name (r->u.value));
4656
4657
0
  if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
4658
0
    i = 0; /* we don't want to allow generation of these algorithms */
4659
0
  return i;
4660
0
}
4661
4662
4663
/* Parse a usage string.  The usage keywords "auth", "sign", "encr"
4664
 * may be delimited by space, tab, or comma.  On error -1 is returned
4665
 * instead of the usage flags.  */
4666
static int
4667
parse_usagestr (const char *usagestr)
4668
0
{
4669
0
  gpg_error_t err;
4670
0
  char **tokens = NULL;
4671
0
  const char *s;
4672
0
  int i;
4673
0
  unsigned int use = 0;
4674
4675
0
  tokens = strtokenize (usagestr, " \t,");
4676
0
  if (!tokens)
4677
0
    {
4678
0
      err = gpg_error_from_syserror ();
4679
0
      log_error ("strtokenize failed: %s\n", gpg_strerror (err));
4680
0
      return -1;
4681
0
    }
4682
4683
0
  for (i=0; (s = tokens[i]); i++)
4684
0
    {
4685
0
      if (!*s)
4686
0
        ;
4687
0
      else if (!ascii_strcasecmp (s, "sign"))
4688
0
        use |= PUBKEY_USAGE_SIG;
4689
0
      else if (!ascii_strcasecmp (s, "encrypt")
4690
0
                || !ascii_strcasecmp (s, "encr"))
4691
0
        use |= PUBKEY_USAGE_ENC;
4692
0
      else if (!ascii_strcasecmp (s, "auth"))
4693
0
        use |= PUBKEY_USAGE_AUTH;
4694
0
      else if (!ascii_strcasecmp (s, "cert"))
4695
0
        use |= PUBKEY_USAGE_CERT;
4696
0
      else if (!ascii_strcasecmp (s, "renc"))
4697
0
        use |= PUBKEY_USAGE_RENC;
4698
0
      else if (!ascii_strcasecmp (s, "time"))
4699
0
        use |= PUBKEY_USAGE_TIME;
4700
0
      else if (!ascii_strcasecmp (s, "group"))
4701
0
        use |= PUBKEY_USAGE_GROUP;
4702
0
      else
4703
0
        {
4704
0
          xfree (tokens);
4705
0
          return -1; /* error */
4706
0
        }
4707
0
    }
4708
4709
0
  xfree (tokens);
4710
0
  return use;
4711
0
}
4712
4713
4714
/*
4715
 * Parse the usage parameter and set the keyflags.  Returns -1 on
4716
 * error, 0 for no usage given or 1 for usage available.
4717
 */
4718
static int
4719
parse_parameter_usage (const char *fname,
4720
                       struct para_data_s *para, enum para_name key)
4721
0
{
4722
0
  struct para_data_s *r = get_parameter( para, key );
4723
0
  int i;
4724
4725
0
  if (!r)
4726
0
    return 0; /* none (this is an optional parameter)*/
4727
4728
0
  i = parse_usagestr (r->u.value);
4729
0
  if (i == -1)
4730
0
    {
4731
0
      log_error ("%s:%d: invalid usage list\n", fname, r->lnr );
4732
0
      return -1; /* error */
4733
0
    }
4734
4735
0
  r->u.usage = i;
4736
0
  return 1;
4737
0
}
4738
4739
4740
/* Parse the revocation key specified by NAME, check that the public
4741
 * key exists (so that we can get the required public key algorithm),
4742
 * and return a parameter with the revocation key information.  On
4743
 * error print a diagnostic and return NULL.  */
4744
static struct para_data_s *
4745
prepare_desig_revoker (ctrl_t ctrl, const char *name)
4746
0
{
4747
0
  gpg_error_t err;
4748
0
  struct para_data_s *para = NULL;
4749
0
  KEYDB_SEARCH_DESC desc;
4750
0
  int sensitive = 0;
4751
0
  struct revocation_key revkey;
4752
0
  PKT_public_key *revoker_pk = NULL;
4753
0
  size_t fprlen;
4754
4755
0
  if (!ascii_strncasecmp (name, "sensitive:", 10) && !spacep (name+10))
4756
0
    {
4757
0
      name += 10;
4758
0
      sensitive = 1;
4759
0
    }
4760
4761
0
  if (classify_user_id (name, &desc, 1)
4762
0
      || desc.mode != KEYDB_SEARCH_MODE_FPR)
4763
0
    {
4764
0
      log_info (_("\"%s\" is not a fingerprint\n"), name);
4765
0
      err = gpg_error (GPG_ERR_INV_NAME);
4766
0
      goto leave;
4767
0
    }
4768
4769
0
  revoker_pk = xcalloc (1, sizeof *revoker_pk);
4770
0
  revoker_pk->req_usage = PUBKEY_USAGE_CERT;
4771
0
  err = get_pubkey_byname (ctrl, GET_PUBKEY_TRY_LDAP,
4772
0
                           NULL, revoker_pk, name, NULL, NULL, 1);
4773
0
  if (err)
4774
0
    goto leave;
4775
4776
0
  fingerprint_from_pk (revoker_pk, revkey.fpr, &fprlen);
4777
0
  if (fprlen != 20 && fprlen != 32)
4778
0
    {
4779
0
      log_info (_("cannot appoint a PGP 2.x style key as a "
4780
0
                  "designated revoker\n"));
4781
0
      err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
4782
0
      goto leave;
4783
0
    }
4784
0
  revkey.fprlen = fprlen;
4785
0
  revkey.class = 0x80;
4786
0
  if (sensitive)
4787
0
    revkey.class |= 0x40;
4788
0
  revkey.algid = revoker_pk->pubkey_algo;
4789
4790
0
  para = xcalloc (1, sizeof *para);
4791
0
  para->key = pREVOKER;
4792
0
  memcpy (&para->u.revkey, &revkey, sizeof revkey);
4793
4794
0
 leave:
4795
0
  if (err)
4796
0
    log_error ("invalid revocation key '%s': %s\n", name, gpg_strerror (err));
4797
0
  free_public_key (revoker_pk);
4798
0
  return para;
4799
0
}
4800
4801
4802
/* Parse an ADSK specified by NAME, check that the public key exists
4803
 * and return a parameter with the adsk information.  On error print a
4804
 * diagnostic and return NULL.  */
4805
static struct para_data_s *
4806
prepare_adsk (ctrl_t ctrl, const char *name)
4807
0
{
4808
0
  gpg_error_t err;
4809
0
  char *namebuffer = NULL;
4810
0
  struct para_data_s *para = NULL;
4811
0
  KEYDB_SEARCH_DESC desc;
4812
0
  PKT_public_key *adsk_pk = NULL;
4813
0
  char *p;
4814
4815
0
  if (classify_user_id (name, &desc, 1)
4816
0
      || desc.mode != KEYDB_SEARCH_MODE_FPR)
4817
0
    {
4818
0
      log_info (_("\"%s\" is not a fingerprint\n"), name);
4819
0
      err = gpg_error (GPG_ERR_INV_NAME);
4820
0
      goto leave;
4821
0
    }
4822
4823
  /* Force searching for that exact fingerprint.  */
4824
0
  if (!strchr (name, '!'))
4825
0
    {
4826
0
      namebuffer = xstrconcat (name, "!", NULL);
4827
0
      name = namebuffer;
4828
0
    }
4829
4830
0
  adsk_pk = xcalloc (1, sizeof *adsk_pk);
4831
0
  adsk_pk->req_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_RENC;
4832
0
  err = get_pubkey_byname (ctrl, GET_PUBKEY_TRY_LDAP,
4833
0
                           NULL, adsk_pk, name, NULL, NULL, 1);
4834
0
  if (err)
4835
0
    goto leave;
4836
4837
0
  para = xcalloc (1, sizeof *para);
4838
0
  para->key = pADSK;
4839
0
  para->u.adsk = adsk_pk;
4840
0
  adsk_pk = NULL;
4841
4842
0
 leave:
4843
0
  if (err)
4844
0
    {
4845
0
      if (namebuffer && (p=strchr (namebuffer, '!')))
4846
0
        *p = 0; /* Strip the ! for the diagnostic.  */
4847
0
      write_status_error ("add_adsk", err);
4848
0
      log_error ("invalid ADSK '%s' specified: %s\n", name, gpg_strerror (err));
4849
0
    }
4850
0
  free_public_key (adsk_pk);
4851
0
  xfree (namebuffer);
4852
0
  return para;
4853
0
}
4854
4855
4856
/* Parse a pREVOKER parameter into its dedicated parts.  */
4857
static int
4858
parse_revocation_key (const char *fname,
4859
          struct para_data_s *para, enum para_name key)
4860
0
{
4861
0
  struct para_data_s *r = get_parameter( para, key );
4862
0
  struct revocation_key revkey;
4863
0
  char *pn;
4864
0
  int i;
4865
4866
0
  if( !r )
4867
0
    return 0; /* none (this is an optional parameter) */
4868
4869
0
  pn = r->u.value;
4870
4871
0
  revkey.class=0x80;
4872
0
  revkey.algid=atoi(pn);
4873
0
  if(!revkey.algid)
4874
0
    goto fail;
4875
4876
  /* Skip to the fpr */
4877
0
  while(*pn && *pn!=':')
4878
0
    pn++;
4879
4880
0
  if(*pn!=':')
4881
0
    goto fail;
4882
4883
0
  pn++;
4884
4885
0
  for(i=0;i<MAX_FINGERPRINT_LEN && *pn && !spacep (pn);i++,pn+=2)
4886
0
    {
4887
0
      int c=hextobyte(pn);
4888
0
      if(c==-1)
4889
0
  goto fail;
4890
4891
0
      revkey.fpr[i]=c;
4892
0
    }
4893
0
  if (i != 20 && i != 32)
4894
0
    goto fail;
4895
4896
0
  revkey.fprlen = i;
4897
4898
  /* skip to the tag */
4899
0
  while(*pn && *pn!='s' && *pn!='S')
4900
0
    pn++;
4901
4902
0
  if(ascii_strcasecmp(pn,"sensitive")==0)
4903
0
    revkey.class|=0x40;
4904
4905
0
  memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
4906
4907
0
  return 0;
4908
4909
0
 fail:
4910
0
  log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
4911
0
  return -1; /* error */
4912
0
}
4913
4914
4915
static u32
4916
get_parameter_u32( struct para_data_s *para, enum para_name key )
4917
0
{
4918
0
  struct para_data_s *r = get_parameter( para, key );
4919
4920
0
  if( !r )
4921
0
    return 0;
4922
0
  if (r->key == pKEYCREATIONDATE || r->key == pSUBKEYCREATIONDATE
4923
0
      || r->key == pAUTHKEYCREATIONDATE)
4924
0
    return r->u.creation;
4925
0
  if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
4926
0
    return r->u.expire;
4927
0
  if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
4928
0
    return r->u.usage;
4929
4930
0
  return (unsigned int)strtoul( r->u.value, NULL, 10 );
4931
0
}
4932
4933
static unsigned int
4934
get_parameter_uint( struct para_data_s *para, enum para_name key )
4935
0
{
4936
0
    return get_parameter_u32( para, key );
4937
0
}
4938
4939
static struct revocation_key *
4940
get_parameter_revkey (struct para_data_s *para, unsigned int idx)
4941
0
{
4942
0
  struct para_data_s *r = get_parameter_idx (para, pREVOKER, idx);
4943
0
  return r? &r->u.revkey : NULL;
4944
0
}
4945
4946
static PKT_public_key *
4947
get_parameter_adsk (struct para_data_s *para, unsigned int idx)
4948
0
{
4949
0
  struct para_data_s *r = get_parameter_idx (para, pADSK, idx);
4950
0
  return r? r->u.adsk : NULL;
4951
0
}
4952
4953
static int
4954
get_parameter_bool (struct para_data_s *para, enum para_name key)
4955
0
{
4956
0
  struct para_data_s *r = get_parameter (para, key);
4957
0
  return (r && r->u.abool);
4958
0
}
4959
4960
4961
static int
4962
proc_parameter_file (ctrl_t ctrl, struct para_data_s *para, const char *fname,
4963
                     struct output_control_s *outctrl, int card )
4964
0
{
4965
0
  struct para_data_s *r;
4966
0
  const char *s1, *s2, *s3;
4967
0
  size_t n;
4968
0
  char *p;
4969
0
  strlist_t sl;
4970
0
  int is_default = 0;
4971
0
  int have_user_id = 0;
4972
0
  const char *saved_def_keyserver_url = opt.def_keyserver_url;
4973
0
  int err, algo;
4974
0
  u32 creation_time = (u32)-1;
4975
0
  int res = -1;
4976
4977
  /* Check that we have all required parameters. */
4978
0
  r = get_parameter( para, pKEYTYPE );
4979
0
  if(r)
4980
0
    {
4981
0
      algo = get_parameter_algo (ctrl, para, pKEYTYPE, &is_default);
4982
0
      if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
4983
0
  {
4984
0
    log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
4985
0
          goto leave;
4986
0
  }
4987
0
    }
4988
0
  else
4989
0
    {
4990
0
      log_error ("%s: no Key-Type specified\n",fname);
4991
0
      goto leave;
4992
0
    }
4993
4994
0
  err = parse_parameter_usage (fname, para, pKEYUSAGE);
4995
0
  if (!err)
4996
0
    {
4997
      /* Default to algo capabilities if key-usage is not provided and
4998
         no default algorithm has been requested.  */
4999
0
      r = xmalloc_clear(sizeof(*r));
5000
0
      r->key = pKEYUSAGE;
5001
0
      r->u.usage = (is_default
5002
0
                    ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
5003
0
                    : openpgp_pk_algo_usage(algo));
5004
0
      append_to_parameter (para, r);
5005
0
    }
5006
0
  else if (err == -1)
5007
0
    goto leave;
5008
0
  else
5009
0
    {
5010
0
      r = get_parameter (para, pKEYUSAGE);
5011
0
      if (r && (r->u.usage
5012
0
                & ~(openpgp_pk_algo_usage (algo) | PUBKEY_USAGE_GROUP)))
5013
0
        {
5014
0
          log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
5015
0
                     fname, r->lnr, algo);
5016
0
          goto leave;
5017
0
        }
5018
0
    }
5019
5020
0
  is_default = 0;
5021
0
  r = get_parameter( para, pSUBKEYTYPE );
5022
0
  if(r)
5023
0
    {
5024
0
      algo = get_parameter_algo (ctrl, para, pSUBKEYTYPE, &is_default);
5025
0
      if (openpgp_pk_test_algo (algo))
5026
0
  {
5027
0
    log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
5028
0
          goto leave;
5029
0
  }
5030
5031
0
      err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
5032
0
      if (!err)
5033
0
  {
5034
    /* Default to algo capabilities if subkey-usage is not
5035
       provided.  Take care not to include RENC. */
5036
0
    r = xmalloc_clear (sizeof(*r));
5037
0
    r->key = pSUBKEYUSAGE;
5038
0
    r->u.usage = (is_default
5039
0
                        ? PUBKEY_USAGE_ENC
5040
0
                        : (openpgp_pk_algo_usage (algo)
5041
0
                           & ~PUBKEY_USAGE_RENC)       );
5042
0
          append_to_parameter (para, r);
5043
0
  }
5044
0
      else if (err == -1)
5045
0
        goto leave;
5046
0
      else
5047
0
        {
5048
0
          r = get_parameter (para, pSUBKEYUSAGE);
5049
0
          if (r && (r->u.usage
5050
0
                    & ~(openpgp_pk_algo_usage (algo)|PUBKEY_USAGE_GROUP)))
5051
0
            {
5052
0
              log_error ("%s:%d: specified Subkey-Usage not allowed"
5053
0
                         " for algo %d\n", fname, r->lnr, algo);
5054
0
              goto leave;
5055
0
            }
5056
0
        }
5057
0
    }
5058
5059
5060
0
  if( get_parameter_value( para, pUSERID ) )
5061
0
    have_user_id=1;
5062
0
  else
5063
0
    {
5064
      /* create the formatted user ID */
5065
0
      s1 = get_parameter_value( para, pNAMEREAL );
5066
0
      s2 = get_parameter_value( para, pNAMECOMMENT );
5067
0
      s3 = get_parameter_value( para, pNAMEEMAIL );
5068
0
      if( s1 || s2 || s3 )
5069
0
  {
5070
0
    n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
5071
0
    r = xmalloc_clear( sizeof *r + n + 20 );
5072
0
    r->key = pUSERID;
5073
0
    p = r->u.value;
5074
0
    if( s1 )
5075
0
      p = stpcpy(p, s1 );
5076
0
    if( s2 )
5077
0
      p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
5078
0
    if( s3 )
5079
0
            {
5080
              /* If we have only the email part, do not add the space
5081
               * and the angle brackets.  */
5082
0
              if (*r->u.value)
5083
0
                p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
5084
0
              else
5085
0
                p = stpcpy (p, s3);
5086
0
            }
5087
0
          append_to_parameter (para, r);
5088
0
    have_user_id=1;
5089
0
  }
5090
0
    }
5091
5092
0
  if(!have_user_id)
5093
0
    {
5094
0
      log_error("%s: no User-ID specified\n",fname);
5095
0
      goto leave;
5096
0
    }
5097
5098
  /* Set preferences, if any. */
5099
0
  keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
5100
5101
  /* Set keyserver, if any. */
5102
0
  s1=get_parameter_value( para, pKEYSERVER );
5103
0
  if(s1)
5104
0
    {
5105
0
      struct keyserver_spec *spec;
5106
5107
0
      spec = parse_keyserver_uri (s1, 1);
5108
0
      if(spec)
5109
0
  {
5110
0
    free_keyserver_spec(spec);
5111
0
    opt.def_keyserver_url=s1;
5112
0
  }
5113
0
      else
5114
0
  {
5115
0
          r = get_parameter (para, pKEYSERVER);
5116
0
    log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
5117
0
          goto leave;
5118
0
  }
5119
0
    }
5120
5121
  /* Set revoker from parameter file, if any.  Must be done first so
5122
   * that we don't find a parameter set via prepare_desig_revoker.  */
5123
0
  if (parse_revocation_key (fname, para, pREVOKER))
5124
0
    goto leave;
5125
5126
  /* Check and append revokers from the config file.  */
5127
0
  for (sl = opt.desig_revokers; sl; sl = sl->next)
5128
0
    {
5129
0
      r = prepare_desig_revoker (ctrl, sl->d);
5130
0
      if (!r)
5131
0
        goto leave;
5132
0
      append_to_parameter (para, r);
5133
0
     }
5134
5135
5136
  /* Check and append ADSKs from the config file.  While doing this
5137
   * also check for duplicate specifications.  In addition we remove
5138
   * an optional '!' suffix for easier comparing; the suffix is anyway
5139
   * re-added later.  */
5140
0
  keygen_prepare_new_key_adsks ();
5141
0
  for (sl = opt.def_new_key_adsks; sl; sl = sl->next)
5142
0
    {
5143
0
      if (!*sl->d)
5144
0
        continue;
5145
5146
0
      r = prepare_adsk (ctrl, sl->d);
5147
0
      if (!r)
5148
0
        goto leave;
5149
0
      append_to_parameter (para, r);
5150
0
     }
5151
5152
5153
  /* Make KEYCREATIONDATE from Creation-Date.  We ignore this if the
5154
   * key has been taken from a card and a keycreationtime has already
5155
   * been set.  This is so that we don't generate a key with a
5156
   * fingerprint different from the one stored on the OpenPGP card. */
5157
0
  r = get_parameter (para, pCREATIONDATE);
5158
0
  if (r && *r->u.value && !(get_parameter_bool (para, pCARDKEY)
5159
0
                            && get_parameter_u32 (para, pKEYCREATIONDATE)))
5160
0
    {
5161
0
      creation_time = parse_creation_string (r->u.value);
5162
0
      if (!creation_time)
5163
0
  {
5164
0
    log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
5165
0
          goto leave;
5166
0
  }
5167
0
      r->u.creation = creation_time;
5168
0
      r->key = pKEYCREATIONDATE;  /* Change that entry. */
5169
0
    }
5170
5171
  /* Make KEYEXPIRE from Expire-Date.  */
5172
0
  r = get_parameter( para, pEXPIREDATE );
5173
0
  if( r && *r->u.value )
5174
0
    {
5175
0
      u32 seconds;
5176
5177
0
      seconds = parse_expire_string_with_ct (r->u.value, creation_time);
5178
0
      if( seconds == (u32)-1 )
5179
0
  {
5180
0
    log_error("%s:%d: invalid expire date\n", fname, r->lnr );
5181
0
          goto leave;
5182
0
  }
5183
0
      r->u.expire = seconds;
5184
0
      r->key = pKEYEXPIRE;  /* change that entry */
5185
5186
      /* Make SUBKEYEXPIRE from Subkey-Expire-Date, if any.  */
5187
0
      r = get_parameter( para, pSUBKEYEXPIREDATE );
5188
0
      if( r && *r->u.value )
5189
0
        {
5190
0
          seconds = parse_expire_string_with_ct (r->u.value, creation_time);
5191
0
          if( seconds == (u32)-1 )
5192
0
            {
5193
0
              log_error("%s:%d: invalid subkey expire date\n", fname, r->lnr );
5194
0
              goto leave;
5195
0
            }
5196
0
          r->key = pSUBKEYEXPIRE;  /* change that entry */
5197
0
          r->u.expire = seconds;
5198
0
        }
5199
0
      else
5200
0
        {
5201
          /* Or else, set Expire-Date for the subkey */
5202
0
          r = xmalloc_clear( sizeof *r + 20 );
5203
0
          r->key = pSUBKEYEXPIRE;
5204
0
          r->u.expire = seconds;
5205
0
          append_to_parameter (para, r);
5206
0
        }
5207
0
    }
5208
0
  res = 0;
5209
5210
0
  do_generate_keypair (ctrl, para, outctrl, card );
5211
0
 leave:
5212
0
  opt.def_keyserver_url = saved_def_keyserver_url;
5213
0
  return res;
5214
0
}
5215
5216
5217
/****************
5218
 * Kludge to allow non interactive key generation controlled
5219
 * by a parameter file.
5220
 * Note, that string parameters are expected to be in UTF-8
5221
 */
5222
static void
5223
read_parameter_file (ctrl_t ctrl, const char *fname )
5224
0
{
5225
0
    static struct { const char *name;
5226
0
        enum para_name key;
5227
0
    } keywords[] = {
5228
0
  { "Key-Type",       pKEYTYPE},
5229
0
  { "Key-Length",     pKEYLENGTH },
5230
0
  { "Key-Curve",      pKEYCURVE },
5231
0
  { "Key-Usage",      pKEYUSAGE },
5232
0
  { "Subkey-Type",    pSUBKEYTYPE },
5233
0
  { "Subkey-Length",  pSUBKEYLENGTH },
5234
0
  { "Subkey-Curve",   pSUBKEYCURVE },
5235
0
  { "Subkey-Usage",   pSUBKEYUSAGE },
5236
0
  { "Name-Real",      pNAMEREAL },
5237
0
  { "Name-Email",     pNAMEEMAIL },
5238
0
  { "Name-Comment",   pNAMECOMMENT },
5239
0
        { "User-Id",        pUSERID },
5240
0
  { "Expire-Date",    pEXPIREDATE },
5241
0
  { "Subkey-Expire-Date", pSUBKEYEXPIREDATE },
5242
0
  { "Creation-Date",  pCREATIONDATE },
5243
0
  { "Passphrase",     pPASSPHRASE },
5244
0
  { "Preferences",    pPREFERENCES },
5245
0
  { "Revoker",        pREVOKER },
5246
0
        { "Handle",         pHANDLE },
5247
0
        { "Keyserver",      pKEYSERVER },
5248
0
        { "Keygrip",        pKEYGRIP },
5249
0
        { "Key-Grip",       pKEYGRIP },
5250
0
        { "Subkey-grip",    pSUBKEYGRIP },
5251
0
        { "Key-Version",    pVERSION },
5252
0
        { "Subkey-Version", pSUBVERSION },
5253
0
        { NULL, 0 }
5254
0
    };
5255
0
    IOBUF fp;
5256
0
    byte *line;
5257
0
    unsigned int maxlen, nline;
5258
0
    char *p;
5259
0
    int lnr;
5260
0
    const char *err = NULL;
5261
0
    struct para_data_s *para, *r;
5262
0
    int i;
5263
0
    struct output_control_s outctrl;
5264
5265
0
    memset( &outctrl, 0, sizeof( outctrl ) );
5266
0
    outctrl.pub.afx = new_armor_context ();
5267
5268
0
    if( !fname || !*fname)
5269
0
      fname = "-";
5270
5271
0
    fp = iobuf_open (fname);
5272
0
    if (fp && is_secured_file (iobuf_get_fd (fp)))
5273
0
      {
5274
0
        iobuf_close (fp);
5275
0
        fp = NULL;
5276
0
        gpg_err_set_errno (EPERM);
5277
0
      }
5278
0
    if (!fp) {
5279
0
      log_error (_("can't open '%s': %s\n"), fname, strerror(errno) );
5280
0
      return;
5281
0
    }
5282
0
    iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
5283
5284
0
    lnr = 0;
5285
0
    err = NULL;
5286
0
    para = NULL;
5287
0
    maxlen = 1024;
5288
0
    line = NULL;
5289
0
    nline = 0;
5290
0
    while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
5291
0
  char *keyword, *value;
5292
5293
0
  lnr++;
5294
0
  if( !maxlen ) {
5295
0
      err = "line too long";
5296
0
      break;
5297
0
  }
5298
0
  for( p = line; isspace(*(byte*)p); p++ )
5299
0
      ;
5300
0
  if( !*p || *p == '#' )
5301
0
      continue;
5302
0
  keyword = p;
5303
0
  if( *keyword == '%' ) {
5304
0
      for( ; !isspace(*(byte*)p); p++ )
5305
0
    ;
5306
0
      if( *p )
5307
0
    *p++ = 0;
5308
0
      for( ; isspace(*(byte*)p); p++ )
5309
0
    ;
5310
0
      value = p;
5311
0
      trim_trailing_ws( value, strlen(value) );
5312
0
      if( !ascii_strcasecmp( keyword, "%echo" ) )
5313
0
    log_info("%s\n", value );
5314
0
      else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
5315
0
    outctrl.dryrun = 1;
5316
0
      else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
5317
0
              ; /* Dummy for backward compatibility. */
5318
0
      else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
5319
0
        ; /* Dummy for backward compatibility. */
5320
0
      else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
5321
0
                outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
5322
0
      else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
5323
0
                outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
5324
0
      else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
5325
0
    outctrl.lnr = lnr;
5326
0
    if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
5327
0
                  print_status_key_not_created
5328
0
                    (get_parameter_value (para, pHANDLE));
5329
0
    release_parameter_list( para );
5330
0
    para = NULL;
5331
0
      }
5332
0
      else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
5333
0
    if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
5334
0
        ; /* still the same file - ignore it */
5335
0
    else {
5336
0
        xfree( outctrl.pub.newfname );
5337
0
        outctrl.pub.newfname = xstrdup( value );
5338
0
        outctrl.use_files = 1;
5339
0
    }
5340
0
      }
5341
0
      else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
5342
              /* Ignore this command.  */
5343
0
      }
5344
0
      else
5345
0
    log_info("skipping control '%s' (%s)\n", keyword, value );
5346
5347
5348
0
      continue;
5349
0
  }
5350
5351
5352
0
  if( !(p = strchr( p, ':' )) || p == keyword ) {
5353
0
      err = "missing colon";
5354
0
      break;
5355
0
  }
5356
0
  if( *p )
5357
0
      *p++ = 0;
5358
0
  for( ; isspace(*(byte*)p); p++ )
5359
0
      ;
5360
0
  if( !*p ) {
5361
0
      err = "missing argument";
5362
0
      break;
5363
0
  }
5364
0
  value = p;
5365
0
  trim_trailing_ws( value, strlen(value) );
5366
5367
0
  for(i=0; keywords[i].name; i++ ) {
5368
0
      if( !ascii_strcasecmp( keywords[i].name, keyword ) )
5369
0
    break;
5370
0
  }
5371
0
  if( !keywords[i].name ) {
5372
0
      err = "unknown keyword";
5373
0
      break;
5374
0
  }
5375
0
  if( keywords[i].key != pKEYTYPE && !para ) {
5376
0
      err = "parameter block does not start with \"Key-Type\"";
5377
0
      break;
5378
0
  }
5379
5380
0
  if( keywords[i].key == pKEYTYPE && para ) {
5381
0
      outctrl.lnr = lnr;
5382
0
      if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
5383
0
              print_status_key_not_created
5384
0
                (get_parameter_value (para, pHANDLE));
5385
0
      release_parameter_list( para );
5386
0
      para = NULL;
5387
0
  }
5388
0
  else {
5389
0
      for( r = para; r; r = r->next ) {
5390
0
    if( r->key == keywords[i].key )
5391
0
        break;
5392
0
      }
5393
0
      if( r ) {
5394
0
    err = "duplicate keyword";
5395
0
    break;
5396
0
      }
5397
0
  }
5398
5399
0
        if ((keywords[i].key == pVERSION
5400
0
             || keywords[i].key == pSUBVERSION))
5401
0
          ; /* Ignore version.  */
5402
0
        else
5403
0
          {
5404
0
            r = xmalloc_clear( sizeof *r + strlen( value ) );
5405
0
            r->lnr = lnr;
5406
0
            r->key = keywords[i].key;
5407
0
            strcpy( r->u.value, value );
5408
0
            r->next = para;
5409
0
            para = r;
5410
0
          }
5411
0
    }
5412
0
    if( err )
5413
0
  log_error("%s:%d: %s\n", fname, lnr, err );
5414
0
    else if( iobuf_error (fp) ) {
5415
0
  log_error("%s:%d: read error\n", fname, lnr);
5416
0
    }
5417
0
    else if( para ) {
5418
0
  outctrl.lnr = lnr;
5419
0
  if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
5420
0
          print_status_key_not_created (get_parameter_value (para, pHANDLE));
5421
0
    }
5422
5423
0
    if( outctrl.use_files ) { /* close open streams */
5424
0
  iobuf_close( outctrl.pub.stream );
5425
5426
        /* Must invalidate that ugly cache to actually close it.  */
5427
0
        if (outctrl.pub.fname)
5428
0
          iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
5429
0
                       0, (char*)outctrl.pub.fname);
5430
5431
0
  xfree( outctrl.pub.fname );
5432
0
  xfree( outctrl.pub.newfname );
5433
0
    }
5434
5435
0
    xfree (line);
5436
0
    release_parameter_list( para );
5437
0
    iobuf_close (fp);
5438
0
    release_armor_context (outctrl.pub.afx);
5439
0
}
5440
5441
5442
/* Helper for quick_generate_keypair.  */
5443
static struct para_data_s *
5444
quickgen_set_para (struct para_data_s *para, int for_subkey,
5445
                   int algo, int nbits, const char *curve, unsigned int use,
5446
                   int version, const char *keygrip, u32 keytime)
5447
0
{
5448
0
  struct para_data_s *r;
5449
5450
0
  r = xmalloc_clear (sizeof *r + 50);
5451
0
  r->key = for_subkey? pSUBKEYUSAGE :  pKEYUSAGE;
5452
0
  if (use)
5453
0
    snprintf (r->u.value, 30, "%s%s%s%s%s%s%s",
5454
0
              (use & PUBKEY_USAGE_ENC)?  "encr " : "",
5455
0
              (use & PUBKEY_USAGE_SIG)?  "sign " : "",
5456
0
              (use & PUBKEY_USAGE_AUTH)? "auth " : "",
5457
0
              (use & PUBKEY_USAGE_CERT)? "cert " : "",
5458
0
              (use & PUBKEY_USAGE_RENC)? "renc " : "",
5459
0
              (use & PUBKEY_USAGE_TIME)? "time " : "",
5460
0
              (use & PUBKEY_USAGE_GROUP)?"group ": "");
5461
0
  else
5462
0
    strcpy (r->u.value, for_subkey ? "encr" : "sign");
5463
0
  r->next = para;
5464
0
  para = r;
5465
0
  r = xmalloc_clear (sizeof *r + 20);
5466
0
  r->key = for_subkey? pSUBKEYTYPE : pKEYTYPE;
5467
0
  snprintf (r->u.value, 20, "%d", algo);
5468
0
  r->next = para;
5469
0
  para = r;
5470
5471
0
  if (keygrip)
5472
0
    {
5473
0
      r = xmalloc_clear (sizeof *r + strlen (keygrip));
5474
0
      r->key = for_subkey? pSUBKEYGRIP : pKEYGRIP;
5475
0
      strcpy (r->u.value, keygrip);
5476
0
      r->next = para;
5477
0
      para = r;
5478
0
    }
5479
0
  else if (curve)
5480
0
    {
5481
0
      r = xmalloc_clear (sizeof *r + strlen (curve));
5482
0
      r->key = for_subkey? pSUBKEYCURVE : pKEYCURVE;
5483
0
      strcpy (r->u.value, curve);
5484
0
      r->next = para;
5485
0
      para = r;
5486
0
    }
5487
5488
  /* Always store the size - although not required for ECC it is
5489
   * required for composite algos.  Should not harm anyway.  */
5490
0
  r = xmalloc_clear (sizeof *r + 20);
5491
0
  r->key = for_subkey? pSUBKEYLENGTH : pKEYLENGTH;
5492
0
  sprintf (r->u.value, "%u", nbits);
5493
0
  r->next = para;
5494
0
  para = r;
5495
5496
0
  r = xmalloc_clear (sizeof *r + 20);
5497
0
  r->key = for_subkey? pSUBVERSION : pVERSION;
5498
0
  snprintf (r->u.value, 20, "%d", version);
5499
0
  r->next = para;
5500
0
  para = r;
5501
5502
0
  if (keytime)
5503
0
    {
5504
0
      r = xmalloc_clear (sizeof *r);
5505
0
      r->key = for_subkey? pSUBKEYCREATIONDATE : pKEYCREATIONDATE;
5506
0
      r->u.creation = keytime;
5507
0
      r->next = para;
5508
0
      para = r;
5509
5510
0
    }
5511
5512
0
  return para;
5513
0
}
5514
5515
5516
/*
5517
 * Unattended generation of a standard key.
5518
 */
5519
void
5520
quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr,
5521
                        const char *usagestr, const char *expirestr)
5522
0
{
5523
0
  gpg_error_t err;
5524
0
  struct para_data_s *para = NULL;
5525
0
  struct para_data_s *r;
5526
0
  struct output_control_s outctrl;
5527
0
  int use_tty;
5528
5529
0
  memset (&outctrl, 0, sizeof outctrl);
5530
5531
0
  use_tty = (!opt.batch && !opt.answer_yes
5532
0
             && !*algostr && !*usagestr && !*expirestr
5533
0
             && !cpr_enabled ()
5534
0
             && gnupg_isatty (fileno (stdin))
5535
0
             && gnupg_isatty (fileno (stdout))
5536
0
             && gnupg_isatty (fileno (stderr)));
5537
5538
0
  r = xmalloc_clear (sizeof *r + strlen (uid));
5539
0
  r->key = pUSERID;
5540
0
  strcpy (r->u.value, uid);
5541
0
  r->next = para;
5542
0
  para = r;
5543
5544
0
  uid = trim_spaces (r->u.value);
5545
0
  if (!*uid || (!opt.allow_freeform_uid && !is_valid_user_id (uid)))
5546
0
    {
5547
0
      log_error (_("Key generation failed: %s\n"),
5548
0
                 gpg_strerror (GPG_ERR_INV_USER_ID));
5549
0
      goto leave;
5550
0
    }
5551
5552
  /* If gpg is directly used on the console ask whether a key with the
5553
     given user id shall really be created.  */
5554
0
  if (use_tty)
5555
0
    {
5556
0
      tty_printf (_("About to create a key for:\n    \"%s\"\n\n"), uid);
5557
0
      if (!cpr_get_answer_is_yes_def ("quick_keygen.okay",
5558
0
                                      _("Continue? (Y/n) "), 1))
5559
0
        goto leave;
5560
0
    }
5561
5562
  /* Check whether such a user ID already exists.  */
5563
0
  {
5564
0
    KEYDB_HANDLE kdbhd;
5565
0
    KEYDB_SEARCH_DESC desc;
5566
5567
0
    memset (&desc, 0, sizeof desc);
5568
0
    desc.mode = KEYDB_SEARCH_MODE_EXACT;
5569
0
    desc.u.name = uid;
5570
5571
0
    kdbhd = keydb_new (ctrl);
5572
0
    if (!kdbhd)
5573
0
      goto leave;
5574
5575
0
    err = keydb_search (kdbhd, &desc, 1, NULL);
5576
0
    keydb_release (kdbhd);
5577
0
    if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
5578
0
      {
5579
0
        log_info (_("A key for \"%s\" already exists\n"), uid);
5580
0
        if (opt.answer_yes)
5581
0
          ;
5582
0
        else if (!use_tty
5583
0
                 || !cpr_get_answer_is_yes_def ("quick_keygen.force",
5584
0
                                                _("Create anyway? (y/N) "), 0))
5585
0
          {
5586
0
            write_status_error ("genkey", gpg_error (304));
5587
0
            log_inc_errorcount ();  /* we used log_info */
5588
0
            goto leave;
5589
0
          }
5590
0
        log_info (_("creating anyway\n"));
5591
0
      }
5592
0
  }
5593
5594
0
  if (!*expirestr || strcmp (expirestr, "-") == 0)
5595
0
    expirestr = default_expiration_interval;
5596
5597
0
  if ((!*algostr || !ascii_strcasecmp (algostr, "default")
5598
0
       || !ascii_strcasecmp (algostr, "future-default")
5599
0
       || !ascii_strcasecmp (algostr, "futuredefault")
5600
0
       || !ascii_strcasecmp (algostr, "pqc")
5601
0
       || !ascii_strcasecmp (algostr, "card"))
5602
0
      && (!*usagestr || !ascii_strcasecmp (usagestr, "default")
5603
0
          || !strcmp (usagestr, "-")))
5604
0
    {
5605
      /* Use default key parameters.  */
5606
0
      int algo, subalgo, version, subversion;
5607
0
      unsigned int size, subsize;
5608
0
      unsigned int keyuse, subkeyuse;
5609
0
      const char *curve, *subcurve;
5610
0
      char *keygrip, *subkeygrip;
5611
0
      u32 keytime, subkeytime;
5612
5613
0
      err = parse_key_parameter_string (ctrl, algostr, -1, 0,
5614
0
                                        &algo, &size, &keyuse, &curve, &version,
5615
0
                                        &keygrip, &keytime,
5616
0
                                        &subalgo, &subsize, &subkeyuse,
5617
0
                                        &subcurve, &subversion,
5618
0
                                        &subkeygrip, &subkeytime);
5619
0
      if (err)
5620
0
        {
5621
0
          log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
5622
0
          goto leave;
5623
0
        }
5624
5625
0
      para = quickgen_set_para (para, 0, algo, size, curve, keyuse, version,
5626
0
                                keygrip, keytime);
5627
0
      if (subalgo)
5628
0
        para = quickgen_set_para (para, 1,
5629
0
                                  subalgo, subsize, subcurve, subkeyuse,
5630
0
                                  subversion, subkeygrip, subkeytime);
5631
0
      if (*expirestr)
5632
0
        {
5633
0
          u32 expire;
5634
5635
0
          expire = parse_expire_string (expirestr);
5636
0
          if (expire == (u32)-1 )
5637
0
            {
5638
0
              err = gpg_error (GPG_ERR_INV_VALUE);
5639
0
              log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
5640
0
              goto leave;
5641
0
            }
5642
0
          r = xmalloc_clear (sizeof *r + 20);
5643
0
          r->key = pKEYEXPIRE;
5644
0
          r->u.expire = expire;
5645
0
          r->next = para;
5646
0
          para = r;
5647
0
        }
5648
5649
0
      xfree (keygrip);
5650
0
      xfree (subkeygrip);
5651
0
    }
5652
0
  else
5653
0
    {
5654
      /* Extended unattended mode.  Creates only the primary key. */
5655
0
      int algo, version;
5656
0
      unsigned int use;
5657
0
      u32 expire;
5658
0
      unsigned int nbits;
5659
0
      const char *curve;
5660
0
      char *keygrip;
5661
0
      u32 keytime;
5662
5663
0
      err = parse_algo_usage_expire (ctrl, 0, algostr, usagestr, expirestr,
5664
0
                                     &algo, &use, &expire, &nbits, &curve,
5665
0
                                     &version, &keygrip, &keytime);
5666
0
      if (err)
5667
0
        {
5668
0
          log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
5669
0
          goto leave;
5670
0
        }
5671
5672
0
      para = quickgen_set_para (para, 0, algo, nbits, curve, use, version,
5673
0
                                keygrip, keytime);
5674
0
      r = xmalloc_clear (sizeof *r + 20);
5675
0
      r->key = pKEYEXPIRE;
5676
0
      r->u.expire = expire;
5677
0
      r->next = para;
5678
0
      para = r;
5679
5680
0
      xfree (keygrip);
5681
0
    }
5682
5683
  /* If the pinentry loopback mode is not and we have a static
5684
     passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
5685
     mode), we use that passphrase for the new key.  */
5686
0
  if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
5687
0
      && have_static_passphrase ())
5688
0
    {
5689
0
      const char *s = get_static_passphrase ();
5690
5691
0
      r = xmalloc_clear (sizeof *r + strlen (s));
5692
0
      r->key = pPASSPHRASE;
5693
0
      strcpy (r->u.value, s);
5694
0
      r->next = para;
5695
0
      para = r;
5696
0
    }
5697
5698
0
  if (!ascii_strcasecmp (algostr, "card")
5699
0
      || !ascii_strncasecmp (algostr, "card/", 5))
5700
0
    {
5701
0
      r = xmalloc_clear (sizeof *r);
5702
0
      r->key = pCARDKEY;
5703
0
      r->u.abool = 1;
5704
0
      r->next = para;
5705
0
      para = r;
5706
0
    }
5707
5708
0
  proc_parameter_file (ctrl, para, "[internal]", &outctrl, 0);
5709
5710
0
 leave:
5711
0
  release_parameter_list (para);
5712
0
}
5713
5714
5715
/*
5716
 * Generate a keypair (fname is only used in batch mode) If
5717
 * CARD_SERIALNO is not NULL the function will create the keys on an
5718
 * OpenPGP Card.  If GENFLAGS has the GENERATE_KEYPAIR_CARDBACKUP bit
5719
 * set and CARD_SERIALNO is NOT NULL, the encryption key for the card
5720
 * is generated on the host, imported to the card and a backup file
5721
 * created by gpg-agent.  If GENFLAGS has the GENERATE_KEYPAIR_FULL
5722
 * bit cleared only the basic prompts are used (except for batch
5723
 * mode).
5724
 */
5725
void
5726
generate_keypair (ctrl_t ctrl, const char *fname,
5727
                  const char *card_serialno, unsigned int genflags)
5728
0
{
5729
0
  gpg_error_t err;
5730
0
  unsigned int nbits;
5731
0
  char *uid = NULL;
5732
0
  int algo;
5733
0
  unsigned int use;
5734
0
  int both = 0;
5735
0
  u32 expire;
5736
0
  struct para_data_s *para = NULL;
5737
0
  struct para_data_s *r;
5738
0
  struct output_control_s outctrl;
5739
5740
0
  memset( &outctrl, 0, sizeof( outctrl ) );
5741
5742
0
  if (opt.batch && card_serialno)
5743
0
    {
5744
      /* We don't yet support unattended key generation with a card
5745
       * serial number. */
5746
0
      log_error (_("can't do this in batch mode\n"));
5747
0
      print_further_info ("key generation with card serial number");
5748
0
      return;
5749
0
    }
5750
5751
0
  if (opt.batch)
5752
0
    {
5753
0
      read_parameter_file (ctrl, fname);
5754
0
      return;
5755
0
    }
5756
5757
0
  if (card_serialno)
5758
0
    {
5759
#ifdef ENABLE_CARD_SUPPORT
5760
      struct agent_card_info_s info;
5761
5762
      memset (&info, 0, sizeof (info));
5763
      err = agent_scd_getattr ("KEY-ATTR", &info);
5764
      if (err)
5765
        {
5766
          log_error (_("error getting current key info: %s\n"),
5767
                     gpg_strerror (err));
5768
          return;
5769
        }
5770
5771
      r = xcalloc (1, sizeof *r + strlen (card_serialno) );
5772
      r->key = pSERIALNO;
5773
      strcpy( r->u.value, card_serialno);
5774
      r->next = para;
5775
      para = r;
5776
5777
      r = xcalloc (1, sizeof *r + 20 );
5778
      r->key = pKEYTYPE;
5779
      sprintf( r->u.value, "%d", info.key_attr[0].algo );
5780
      r->next = para;
5781
      para = r;
5782
      r = xcalloc (1, sizeof *r + 20 );
5783
      r->key = pKEYUSAGE;
5784
      strcpy (r->u.value, "sign");
5785
      r->next = para;
5786
      para = r;
5787
5788
      if (!(genflags & GENERATE_KEYPAIR_CARDPRIMARY))
5789
        {
5790
          r = xcalloc (1, sizeof *r + 20 );
5791
          r->key = pSUBKEYTYPE;
5792
          sprintf( r->u.value, "%d", info.key_attr[1].algo );
5793
          r->next = para;
5794
          para = r;
5795
          r = xcalloc (1, sizeof *r + 20 );
5796
          r->key = pSUBKEYUSAGE;
5797
          strcpy (r->u.value, "encrypt");
5798
          r->next = para;
5799
          para = r;
5800
          if (info.key_attr[1].algo == PUBKEY_ALGO_RSA)
5801
            {
5802
              r = xcalloc (1, sizeof *r + 20 );
5803
              r->key = pSUBKEYLENGTH;
5804
              sprintf( r->u.value, "%u", info.key_attr[1].nbits);
5805
              r->next = para;
5806
              para = r;
5807
            }
5808
          else if (info.key_attr[1].algo == PUBKEY_ALGO_ECDSA
5809
                   || info.key_attr[1].algo == PUBKEY_ALGO_EDDSA
5810
                   || info.key_attr[1].algo == PUBKEY_ALGO_ECDH)
5811
            {
5812
              r = xcalloc (1, sizeof *r + strlen (info.key_attr[1].curve));
5813
              r->key = pSUBKEYCURVE;
5814
              strcpy (r->u.value, info.key_attr[1].curve);
5815
              r->next = para;
5816
              para = r;
5817
            }
5818
5819
          r = xcalloc (1, sizeof *r + 20 );
5820
          r->key = pAUTHKEYTYPE;
5821
          sprintf( r->u.value, "%d", info.key_attr[2].algo );
5822
          r->next = para;
5823
          para = r;
5824
5825
          if ((genflags & GENERATE_KEYPAIR_CARDBACKUP))
5826
            {
5827
              r = xcalloc (1, sizeof *r + 1);
5828
              r->key = pCARDBACKUPKEY;
5829
              strcpy (r->u.value, "1");
5830
              r->next = para;
5831
              para = r;
5832
            }
5833
        }
5834
#endif /*ENABLE_CARD_SUPPORT*/
5835
0
    }
5836
0
  else if ((genflags & GENERATE_KEYPAIR_FULL))
5837
0
    {
5838
      /* This is the full featured key generation.  */
5839
0
      int subkey_algo;
5840
0
      char *key_from_hexgrip = NULL;
5841
0
      int cardkey;
5842
0
      u32 keytime;
5843
5844
0
      algo = ask_algo (ctrl, 0, &subkey_algo, &use,
5845
0
                       &key_from_hexgrip, &cardkey, &keytime);
5846
0
      if (key_from_hexgrip)
5847
0
        {
5848
0
          r = xmalloc_clear( sizeof *r + 20 );
5849
0
          r->key = pKEYTYPE;
5850
0
          sprintf( r->u.value, "%d", algo);
5851
0
          r->next = para;
5852
0
          para = r;
5853
5854
0
          if (use)
5855
0
            {
5856
0
              r = xmalloc_clear( sizeof *r + 25 );
5857
0
              r->key = pKEYUSAGE;
5858
0
              sprintf( r->u.value, "%s%s%s",
5859
0
                       (use & PUBKEY_USAGE_SIG)? "sign ":"",
5860
0
                       (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
5861
0
                       (use & PUBKEY_USAGE_AUTH)? "auth":"" );
5862
0
              r->next = para;
5863
0
              para = r;
5864
0
            }
5865
5866
0
          r = xmalloc_clear( sizeof *r + 40 );
5867
0
          r->key = pKEYGRIP;
5868
0
          strcpy (r->u.value, key_from_hexgrip);
5869
0
          r->next = para;
5870
0
          para = r;
5871
5872
0
          r = xmalloc_clear (sizeof *r);
5873
0
          r->key = pCARDKEY;
5874
0
          r->u.abool = cardkey;
5875
0
          r->next = para;
5876
0
          para = r;
5877
5878
0
          if (cardkey)
5879
0
            {
5880
0
              r = xmalloc_clear (sizeof *r);
5881
0
              r->key = pKEYCREATIONDATE;
5882
0
              r->u.creation = keytime;
5883
0
              r->next = para;
5884
0
              para = r;
5885
0
            }
5886
5887
0
          xfree (key_from_hexgrip);
5888
0
        }
5889
0
      else
5890
0
        {
5891
0
          const char *curve = NULL;
5892
5893
0
          if (algo == PUBKEY_ALGO_ECDSA && subkey_algo == PUBKEY_ALGO_KYBER)
5894
0
            {
5895
              /* Create primary and subkey at once.  */
5896
0
              const char *subalgostr;
5897
0
              const char *s;
5898
0
              const char *pricurve;
5899
0
              int prialgo = PUBKEY_ALGO_ECDSA;
5900
5901
0
              both = 1;
5902
0
              subalgostr = ask_kyber_variant ();
5903
0
              if (!subalgostr)  /* Should not happen.  */
5904
0
                subalgostr = PQC_STD_KEY_PARAM_SUB;
5905
5906
              /* Determine the primary key algo from the subkey algo.  */
5907
0
              if (strstr (subalgostr, "bp384"))
5908
0
                pricurve = "brainpoolP384r1";
5909
0
              else if (strstr (subalgostr, "bp256"))
5910
0
                pricurve = "brainpoolP256r1";
5911
0
              else if (strstr (subalgostr, "cv448"))
5912
0
                {
5913
0
                  pricurve = "Ed448";
5914
0
                  prialgo = PUBKEY_ALGO_EDDSA;
5915
0
                }
5916
0
              else
5917
0
                {
5918
0
                  pricurve = "Ed25519";
5919
0
                  prialgo = PUBKEY_ALGO_EDDSA;
5920
0
                }
5921
5922
0
              r = xmalloc_clear (sizeof *r + 20);
5923
0
              r->key = pKEYTYPE;
5924
0
              sprintf (r->u.value, "%d", prialgo);
5925
0
              r->next = para;
5926
0
              para = r;
5927
5928
0
              r = xmalloc_clear (sizeof *r + strlen (pricurve));
5929
0
              r->key = pKEYCURVE;
5930
0
              strcpy (r->u.value, pricurve);
5931
0
              r->next = para;
5932
0
              para = r;
5933
5934
0
              r = xmalloc_clear (sizeof *r + 20);
5935
0
              r->key = pKEYUSAGE;
5936
0
              strcpy (r->u.value, "sign");
5937
0
              r->next = para;
5938
0
              para = r;
5939
5940
0
              r = xmalloc_clear (sizeof *r + 20);
5941
0
              r->key = pSUBKEYTYPE;
5942
0
              sprintf (r->u.value, "%d", PUBKEY_ALGO_KYBER);
5943
0
              r->next = para;
5944
0
              para = r;
5945
5946
0
              r = xmalloc_clear (sizeof *r + 20);
5947
0
              r->key = pSUBKEYLENGTH;
5948
0
              sprintf (r->u.value, "%u",
5949
0
                       strstr (subalgostr, "768_")? 768 : 1024);
5950
0
              r->next = para;
5951
0
              para = r;
5952
5953
0
              s = strchr (subalgostr, '_');
5954
0
              log_assert (s && s[1]);
5955
0
              s++;
5956
0
              r = xmalloc_clear (sizeof *r + strlen (s));
5957
0
              r->key = pSUBKEYCURVE;
5958
0
              strcpy (r->u.value, s);
5959
0
              r->next = para;
5960
0
              para = r;
5961
5962
0
              r = xmalloc_clear (sizeof *r + 20);
5963
0
              r->key = pSUBKEYUSAGE;
5964
0
              strcpy( r->u.value, "encrypt" );
5965
0
              r->next = para;
5966
0
              para = r;
5967
0
            }
5968
0
          else if (subkey_algo)
5969
0
            {
5970
              /* Create primary and subkey at once.  */
5971
0
              both = 1;
5972
0
              if (algo == PUBKEY_ALGO_ECDSA
5973
0
                  || algo == PUBKEY_ALGO_EDDSA
5974
0
                  || algo == PUBKEY_ALGO_ECDH)
5975
0
                {
5976
0
                  curve = ask_curve (&algo, &subkey_algo, NULL);
5977
0
                  r = xmalloc_clear( sizeof *r + 20 );
5978
0
                  r->key = pKEYTYPE;
5979
0
                  sprintf( r->u.value, "%d", algo);
5980
0
                  r->next = para;
5981
0
                  para = r;
5982
0
                  nbits = 0;
5983
0
                  r = xmalloc_clear (sizeof *r + strlen (curve));
5984
0
                  r->key = pKEYCURVE;
5985
0
                  strcpy (r->u.value, curve);
5986
0
                  r->next = para;
5987
0
                  para = r;
5988
0
                  if (!strcmp (curve, "X448") || !strcmp (curve, "Ed448"))
5989
0
                    {
5990
0
                      r = xmalloc_clear (sizeof *r + 20);
5991
0
                      r->key = pVERSION;
5992
0
                      snprintf (r->u.value, 20, "%d", 5);
5993
0
                      r->next = para;
5994
0
                      para = r;
5995
0
                    }
5996
0
                }
5997
0
              else
5998
0
                {
5999
0
                  r = xmalloc_clear( sizeof *r + 20 );
6000
0
                  r->key = pKEYTYPE;
6001
0
                  sprintf( r->u.value, "%d", algo);
6002
0
                  r->next = para;
6003
0
                  para = r;
6004
0
                  nbits = ask_keysize (algo, 0);
6005
0
                  r = xmalloc_clear( sizeof *r + 20 );
6006
0
                  r->key = pKEYLENGTH;
6007
0
                  sprintf( r->u.value, "%u", nbits);
6008
0
                  r->next = para;
6009
0
                  para = r;
6010
0
                }
6011
0
              r = xmalloc_clear( sizeof *r + 20 );
6012
0
              r->key = pKEYUSAGE;
6013
0
              strcpy( r->u.value, "sign" );
6014
0
              r->next = para;
6015
0
              para = r;
6016
6017
0
              r = xmalloc_clear( sizeof *r + 20 );
6018
0
              r->key = pSUBKEYTYPE;
6019
0
              sprintf( r->u.value, "%d", subkey_algo);
6020
0
              r->next = para;
6021
0
              para = r;
6022
0
              r = xmalloc_clear( sizeof *r + 20 );
6023
0
              r->key = pSUBKEYUSAGE;
6024
0
              strcpy( r->u.value, "encrypt" );
6025
0
              r->next = para;
6026
0
              para = r;
6027
6028
0
              if (algo == PUBKEY_ALGO_ECDSA
6029
0
                  || algo == PUBKEY_ALGO_EDDSA
6030
0
                  || algo == PUBKEY_ALGO_ECDH)
6031
0
                {
6032
0
                  if (algo == PUBKEY_ALGO_EDDSA
6033
0
                      && subkey_algo == PUBKEY_ALGO_ECDH)
6034
0
                    {
6035
                      /* Need to switch to a different curve for the
6036
                         encryption key.  */
6037
0
                      if (!strcmp (curve, "Ed25519"))
6038
0
                        curve = "Curve25519";
6039
0
                      else
6040
0
                        {
6041
0
                          curve = "X448";
6042
0
                          r = xmalloc_clear (sizeof *r + 20);
6043
0
                          r->key = pSUBVERSION;
6044
0
                          snprintf (r->u.value, 20, "%d", 5);
6045
0
                          r->next = para;
6046
0
                          para = r;
6047
0
                        }
6048
0
                    }
6049
0
                  r = xmalloc_clear (sizeof *r + strlen (curve));
6050
0
                  r->key = pSUBKEYCURVE;
6051
0
                  strcpy (r->u.value, curve);
6052
0
                  r->next = para;
6053
0
                  para = r;
6054
0
                }
6055
0
            }
6056
0
          else /* Create only a single key.  */
6057
0
            {
6058
              /* For ECC we need to ask for the curve before storing the
6059
                 algo because ask_curve may change the algo.  */
6060
0
              if (algo == PUBKEY_ALGO_ECDSA
6061
0
                  || algo == PUBKEY_ALGO_EDDSA
6062
0
                  || algo == PUBKEY_ALGO_ECDH)
6063
0
                {
6064
0
                  curve = ask_curve (&algo, NULL, NULL);
6065
0
                  r = xmalloc_clear (sizeof *r + strlen (curve));
6066
0
                  r->key = pKEYCURVE;
6067
0
                  strcpy (r->u.value, curve);
6068
0
                  r->next = para;
6069
0
                  para = r;
6070
0
                   if (!strcmp (curve, "X448") || !strcmp (curve, "Ed448"))
6071
0
                    {
6072
0
                      r = xmalloc_clear (sizeof *r + 20);
6073
0
                      r->key = pVERSION;
6074
0
                      snprintf (r->u.value, 20, "%d", 5);
6075
0
                      r->next = para;
6076
0
                      para = r;
6077
0
                    }
6078
0
                }
6079
6080
0
              r = xmalloc_clear( sizeof *r + 20 );
6081
0
              r->key = pKEYTYPE;
6082
0
              sprintf( r->u.value, "%d", algo );
6083
0
              r->next = para;
6084
0
              para = r;
6085
6086
0
              if (use)
6087
0
                {
6088
0
                  r = xmalloc_clear( sizeof *r + 25 );
6089
0
                  r->key = pKEYUSAGE;
6090
0
                  sprintf( r->u.value, "%s%s%s",
6091
0
                           (use & PUBKEY_USAGE_SIG)? "sign ":"",
6092
0
                           (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
6093
0
                           (use & PUBKEY_USAGE_AUTH)? "auth":"" );
6094
0
                  r->next = para;
6095
0
                  para = r;
6096
0
                }
6097
0
              nbits = 0;
6098
0
            }
6099
6100
0
          if (algo == PUBKEY_ALGO_ECDSA
6101
0
              || algo == PUBKEY_ALGO_EDDSA
6102
0
              || algo == PUBKEY_ALGO_ECDH)
6103
0
            {
6104
              /* The curve has already been set.  */
6105
0
            }
6106
0
          else
6107
0
            {
6108
0
              nbits = ask_keysize (both? subkey_algo : algo, nbits);
6109
0
              r = xmalloc_clear( sizeof *r + 20 );
6110
0
              r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
6111
0
              sprintf( r->u.value, "%u", nbits);
6112
0
              r->next = para;
6113
0
              para = r;
6114
0
            }
6115
0
        }
6116
0
    }
6117
0
  else /* Default key generation.  */
6118
0
    {
6119
0
      int subalgo, version, subversion;
6120
0
      unsigned int size, subsize;
6121
0
      unsigned int keyuse, subkeyuse;
6122
0
      const char *curve, *subcurve;
6123
0
      char *keygrip, *subkeygrip;
6124
0
      u32 keytime, subkeytime;
6125
6126
0
      tty_printf ( _("Note: Use \"%s %s\""
6127
0
                     " for a full featured key generation dialog.\n"),
6128
0
                   GPG_NAME
6129
0
                   , "--full-generate-key" );
6130
6131
0
      err = parse_key_parameter_string (ctrl, NULL, -1, 0,
6132
0
                                        &algo, &size, &keyuse, &curve, &version,
6133
0
                                        &keygrip, &keytime,
6134
0
                                        &subalgo, &subsize,
6135
0
                                        &subkeyuse, &subcurve, &subversion,
6136
0
                                        &subkeygrip, &subkeytime);
6137
0
      if (err)
6138
0
        {
6139
0
          log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
6140
0
          return;
6141
0
        }
6142
0
      para = quickgen_set_para (para, 0,
6143
0
                                algo, size, curve, keyuse,
6144
0
                                version, keygrip, keytime);
6145
0
      if (subalgo)
6146
0
        para = quickgen_set_para (para, 1,
6147
0
                                  subalgo, subsize, subcurve, subkeyuse,
6148
0
                                  subversion, subkeygrip, subkeytime);
6149
6150
0
      xfree (keygrip);
6151
0
      xfree (subkeygrip);
6152
0
    }
6153
6154
6155
0
  expire = (genflags & GENERATE_KEYPAIR_FULL)? ask_expire_interval (0, NULL)
6156
0
               : parse_expire_string (default_expiration_interval);
6157
0
  r = xcalloc (1, sizeof *r + 20);
6158
0
  r->key = pKEYEXPIRE;
6159
0
  r->u.expire = expire;
6160
0
  r->next = para;
6161
0
  para = r;
6162
0
  r = xcalloc (1, sizeof *r + 20);
6163
0
  r->key = pSUBKEYEXPIRE;
6164
0
  r->u.expire = expire;
6165
0
  r->next = para;
6166
0
  para = r;
6167
6168
0
  uid = ask_user_id (0, !!(genflags & GENERATE_KEYPAIR_FULL), NULL);
6169
0
  if (!uid)
6170
0
    {
6171
0
      log_error(_("Key generation canceled.\n"));
6172
0
      release_parameter_list( para );
6173
0
      return;
6174
0
    }
6175
0
  r = xcalloc (1, sizeof *r + strlen (uid));
6176
0
  r->key = pUSERID;
6177
0
  strcpy (r->u.value, uid);
6178
0
  r->next = para;
6179
0
  para = r;
6180
6181
0
  proc_parameter_file (ctrl, para, "[internal]", &outctrl, !!card_serialno);
6182
0
  release_parameter_list (para);
6183
0
}
6184
6185
6186
/* Create and delete a dummy packet to start off a list of kbnodes. */
6187
static void
6188
start_tree(KBNODE *tree)
6189
0
{
6190
0
  PACKET *pkt;
6191
6192
0
  pkt=xmalloc_clear(sizeof(*pkt));
6193
0
  pkt->pkttype=PKT_NONE;
6194
0
  *tree=new_kbnode(pkt);
6195
0
  delete_kbnode(*tree);
6196
0
}
6197
6198
6199
/* Write the *protected* secret key to the file.  */
6200
static gpg_error_t
6201
card_write_key_to_backup_file (PKT_public_key *sk, const char *backup_dir)
6202
0
{
6203
0
  gpg_error_t err = 0;
6204
0
  char keyid_buffer[2 * 8 + 1];
6205
0
  char name_buffer[50];
6206
0
  char *fname;
6207
0
  IOBUF fp;
6208
0
  mode_t oldmask;
6209
0
  PACKET *pkt = NULL;
6210
6211
0
  format_keyid (pk_keyid (sk), KF_LONG, keyid_buffer, sizeof (keyid_buffer));
6212
0
  snprintf (name_buffer, sizeof name_buffer, "sk_%s.gpg", keyid_buffer);
6213
6214
0
  fname = make_filename (backup_dir, name_buffer, NULL);
6215
  /* Note that the umask call is not anymore needed because
6216
     iobuf_create now takes care of it.  However, it does not harm
6217
     and thus we keep it.  */
6218
0
  oldmask = umask (077);
6219
0
  if (is_secured_filename (fname))
6220
0
    {
6221
0
      fp = NULL;
6222
0
      gpg_err_set_errno (EPERM);
6223
0
    }
6224
0
  else
6225
0
    fp = iobuf_create (fname, 1);
6226
0
  umask (oldmask);
6227
0
  if (!fp)
6228
0
    {
6229
0
      err = gpg_error_from_syserror ();
6230
0
      log_error (_("can't create backup file '%s': %s\n"), fname, strerror (errno) );
6231
0
      goto leave;
6232
0
    }
6233
6234
0
  pkt = xcalloc (1, sizeof *pkt);
6235
0
  pkt->pkttype = PKT_SECRET_KEY;
6236
0
  pkt->pkt.secret_key = sk;
6237
6238
0
  err = build_packet (fp, pkt);
6239
0
  if (err)
6240
0
    {
6241
0
      log_error ("build packet failed: %s\n", gpg_strerror (err));
6242
0
      iobuf_cancel (fp);
6243
0
    }
6244
0
  else
6245
0
    {
6246
0
      char *fprbuf;
6247
6248
0
      iobuf_close (fp);
6249
0
      iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
6250
0
      log_info (_("Note: backup of card key saved to '%s'\n"), fname);
6251
6252
0
      fprbuf = hexfingerprint (sk, NULL, 0);
6253
0
      if (!fprbuf)
6254
0
        {
6255
0
          err = gpg_error_from_syserror ();
6256
0
          goto leave;
6257
0
        }
6258
0
      write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED, fprbuf,
6259
0
                                    fname, strlen (fname), 0);
6260
0
      xfree (fprbuf);
6261
0
    }
6262
6263
0
 leave:
6264
0
  xfree (pkt);
6265
0
  xfree (fname);
6266
0
  return err;
6267
0
}
6268
6269
6270
/* Store key to card and make a backup file in OpenPGP format.  */
6271
static gpg_error_t
6272
card_store_key_with_backup (ctrl_t ctrl, PKT_public_key *sub_psk,
6273
                            const char *backup_dir)
6274
0
{
6275
0
  gpg_error_t err;
6276
0
  PKT_public_key *sk;
6277
0
  gnupg_isotime_t timestamp;
6278
0
  char *hexgrip = NULL;
6279
0
  struct agent_card_info_s info;
6280
0
  gcry_cipher_hd_t cipherhd = NULL;
6281
0
  char *cache_nonce = NULL;
6282
0
  void *kek = NULL;
6283
0
  size_t keklen;
6284
0
  char *ecdh_param_str = NULL;
6285
0
  int key_is_on_card = 0;
6286
6287
0
  memset (&info, 0, sizeof (info));
6288
6289
0
  sk = copy_public_key (NULL, sub_psk);
6290
0
  if (!sk)
6291
0
    {
6292
0
      err = gpg_error_from_syserror ();
6293
0
      goto leave;
6294
0
    }
6295
6296
0
  epoch2isotime (timestamp, (time_t)sk->timestamp);
6297
0
  if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
6298
0
    {
6299
0
      ecdh_param_str = ecdh_param_str_from_pk (sk);
6300
0
      if (!ecdh_param_str)
6301
0
        {
6302
0
          err = gpg_error_from_syserror ();
6303
0
          goto leave;
6304
0
        }
6305
0
    }
6306
6307
0
  err = hexkeygrip_from_pk (sk, &hexgrip);
6308
0
  if (err)
6309
0
    goto leave;
6310
6311
0
  err = agent_scd_getattr ("SERIALNO", &info);
6312
0
  if (err)
6313
0
    goto leave;
6314
6315
0
  err = agent_keytocard (hexgrip, 2, 1, info.serialno,
6316
0
                         timestamp, ecdh_param_str);
6317
0
  if (err)
6318
0
    goto leave;
6319
6320
0
  key_is_on_card = 1;
6321
0
  err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
6322
0
  if (err)
6323
0
    {
6324
0
      log_error ("error getting the KEK: %s\n", gpg_strerror (err));
6325
0
      goto leave;
6326
0
    }
6327
6328
0
  err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
6329
0
                          GCRY_CIPHER_MODE_AESWRAP, 0);
6330
0
  if (!err)
6331
0
    err = gcry_cipher_setkey (cipherhd, kek, keklen);
6332
0
  if (err)
6333
0
    {
6334
0
      log_error ("error setting up an encryption context: %s\n",
6335
0
                 gpg_strerror (err));
6336
0
      goto leave;
6337
0
    }
6338
6339
0
  err = receive_seckey_from_agent (ctrl, cipherhd, 0, 0, 0,
6340
0
                                   &cache_nonce, hexgrip, sk, NULL);
6341
0
  if (err)
6342
0
    {
6343
0
      log_error ("error getting secret key from agent: %s\n",
6344
0
                 gpg_strerror (err));
6345
0
      goto leave;
6346
0
    }
6347
6348
0
  err = card_write_key_to_backup_file (sk, backup_dir);
6349
0
  if (err)
6350
0
    log_error ("writing card key to backup file: %s\n", gpg_strerror (err));
6351
0
  else
6352
0
    {
6353
      /* Remove secret key data in agent side.  */
6354
0
      agent_scd_learn (NULL, 1);
6355
0
    }
6356
6357
0
 leave:
6358
0
  if (err && key_is_on_card)
6359
0
    {
6360
0
      tty_printf (_(
6361
0
 "Warning: Although the key has been written to the card, a backup file was\n"
6362
0
 "         not properly written to the disk.  You may want to repeat the\n"
6363
0
 "         entire operation or just create a new encryption key on the card.\n"
6364
0
                    ));
6365
0
    }
6366
6367
0
  xfree (info.serialno);
6368
0
  xfree (ecdh_param_str);
6369
0
  xfree (cache_nonce);
6370
0
  gcry_cipher_close (cipherhd);
6371
0
  xfree (kek);
6372
0
  xfree (hexgrip);
6373
0
  free_public_key (sk);
6374
0
  return err;
6375
0
}
6376
6377
6378
static void
6379
do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
6380
         struct output_control_s *outctrl, int card)
6381
0
{
6382
0
  gpg_error_t err;
6383
0
  KBNODE pub_root = NULL;
6384
0
  const char *s;
6385
0
  PKT_public_key *pri_psk = NULL;
6386
0
  PKT_public_key *sub_psk = NULL;
6387
0
  struct revocation_key *revkey;
6388
0
  int did_sub = 0;
6389
0
  u32 keytimestamp, subkeytimestamp, authkeytimestamp, signtimestamp;
6390
0
  char *cache_nonce = NULL;
6391
0
  int algo;
6392
0
  u32 expire;
6393
0
  const char *key_from_hexgrip = NULL;
6394
0
  int cardkey;
6395
0
  unsigned int keygen_flags;
6396
0
  unsigned int idx;
6397
0
  int any_adsk = 0;
6398
6399
0
  if (outctrl->dryrun)
6400
0
    {
6401
0
      log_info("dry-run mode - key generation skipped\n");
6402
0
      return;
6403
0
    }
6404
6405
0
  if ( outctrl->use_files )
6406
0
    {
6407
0
      if ( outctrl->pub.newfname )
6408
0
        {
6409
0
          iobuf_close(outctrl->pub.stream);
6410
0
          outctrl->pub.stream = NULL;
6411
0
          if (outctrl->pub.fname)
6412
0
            iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
6413
0
                         0, (char*)outctrl->pub.fname);
6414
0
          xfree( outctrl->pub.fname );
6415
0
          outctrl->pub.fname =  outctrl->pub.newfname;
6416
0
          outctrl->pub.newfname = NULL;
6417
6418
0
          if (is_secured_filename (outctrl->pub.fname) )
6419
0
            {
6420
0
              outctrl->pub.stream = NULL;
6421
0
              gpg_err_set_errno (EPERM);
6422
0
            }
6423
0
          else
6424
0
            outctrl->pub.stream = iobuf_create (outctrl->pub.fname, 0);
6425
0
          if (!outctrl->pub.stream)
6426
0
            {
6427
0
              log_error(_("can't create '%s': %s\n"), outctrl->pub.newfname,
6428
0
                        strerror(errno) );
6429
0
              return;
6430
0
            }
6431
0
          if (opt.armor)
6432
0
            {
6433
0
              outctrl->pub.afx->what = 1;
6434
0
              push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
6435
0
            }
6436
0
        }
6437
0
      log_assert( outctrl->pub.stream );
6438
0
      if (opt.verbose)
6439
0
        log_info (_("writing public key to '%s'\n"), outctrl->pub.fname );
6440
0
    }
6441
6442
6443
  /* We create the packets as a tree of kbnodes.  Because the
6444
     structure we create is known in advance we simply generate a
6445
     linked list.  The first packet is a dummy packet which we flag as
6446
     deleted.  The very first packet must always be a KEY packet.  */
6447
6448
0
  start_tree (&pub_root);
6449
6450
0
  cardkey = get_parameter_bool (para, pCARDKEY);
6451
6452
  /* In the case that the keys are created from the card we need to
6453
   * take the timestamps from the card.  Only in this case a
6454
   * pSUBKEYCREATIONDATE or pAUTHKEYCREATIONDATE might be defined and
6455
   * then we need to use that so that the fingerprint of the subkey
6456
   * also matches the pre-computed and stored one on the card.  In
6457
   * this case we also use the current time to create the
6458
   * self-signatures.  */
6459
0
  keytimestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
6460
0
  if (!keytimestamp)
6461
0
    keytimestamp = make_timestamp ();
6462
0
  subkeytimestamp = cardkey? get_parameter_u32 (para, pSUBKEYCREATIONDATE) : 0;
6463
0
  if (!subkeytimestamp)
6464
0
    subkeytimestamp = keytimestamp;
6465
0
  authkeytimestamp = cardkey? get_parameter_u32 (para, pAUTHKEYCREATIONDATE): 0;
6466
0
  if (!authkeytimestamp)
6467
0
    authkeytimestamp = keytimestamp;
6468
6469
0
  signtimestamp = cardkey? make_timestamp () : keytimestamp;
6470
6471
  /* log_debug ("XXX: cardkey ..: %d\n", cardkey); */
6472
  /* log_debug ("XXX: keytime ..: %s\n", isotimestamp (keytimestamp)); */
6473
  /* log_debug ("XXX: subkeytime: %s\n", isotimestamp (subkeytimestamp)); */
6474
  /* log_debug ("XXX: authkeytim: %s\n", isotimestamp (authkeytimestamp)); */
6475
  /* log_debug ("XXX: signtime .: %s\n", isotimestamp (signtimestamp)); */
6476
6477
  /* Fixme: Check that this comment is still valid:
6478
     Note that, depending on the backend (i.e. the used scdaemon
6479
     version), the card key generation may update TIMESTAMP for each
6480
     key.  Thus we need to pass TIMESTAMP to all signing function to
6481
     make sure that the binding signature is done using the timestamp
6482
     of the corresponding (sub)key and not that of the primary key.
6483
     An alternative implementation could tell the signing function the
6484
     node of the subkey but that is more work than just to pass the
6485
     current timestamp.  */
6486
6487
0
  algo = get_parameter_algo (ctrl, para, pKEYTYPE, NULL );
6488
0
  expire = get_parameter_u32( para, pKEYEXPIRE );
6489
0
  key_from_hexgrip = get_parameter_value (para, pKEYGRIP);
6490
0
  if (cardkey && !key_from_hexgrip)
6491
0
    BUG ();
6492
6493
0
  keygen_flags = outctrl->keygen_flags;
6494
0
  if (get_parameter_uint (para, pVERSION) == 5)
6495
0
    keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
6496
6497
0
  if (key_from_hexgrip)
6498
0
    err = do_create_from_keygrip (ctrl, algo, key_from_hexgrip, cardkey,
6499
0
                                  pub_root,
6500
0
                                  keytimestamp,
6501
0
                                  expire, 0, &keygen_flags);
6502
0
  else if (!card)
6503
0
    err = do_create (algo,
6504
0
                     get_parameter_uint( para, pKEYLENGTH ),
6505
0
                     get_parameter_value (para, pKEYCURVE),
6506
0
                     pub_root,
6507
0
                     keytimestamp,
6508
0
                     expire, 0,
6509
0
                     &keygen_flags,
6510
0
                     get_parameter_passphrase (para),
6511
0
                     &cache_nonce, NULL,
6512
0
                     NULL, NULL);
6513
0
  else
6514
0
    err = gen_card_key (1, algo,
6515
0
                        1, pub_root, &keytimestamp,
6516
0
                        expire, &keygen_flags);
6517
6518
  /* Get the pointer to the generated public key packet.  */
6519
0
  if (!err)
6520
0
    {
6521
0
      pri_psk = pub_root->next->pkt->pkt.public_key;
6522
0
      log_assert (pri_psk);
6523
6524
      /* Make sure a few fields are correctly set up before going
6525
         further.  */
6526
0
      pri_psk->flags.primary = 1;
6527
0
      keyid_from_pk (pri_psk, NULL);
6528
      /* We don't use pk_keyid to get keyid, because it also asserts
6529
         that main_keyid is set!  */
6530
0
      keyid_copy (pri_psk->main_keyid, pri_psk->keyid);
6531
0
    }
6532
6533
  /* Write all signatures specifying designated revokers.  */
6534
0
  for (idx=0; !err && (revkey = get_parameter_revkey (para, idx)); idx++)
6535
0
    {
6536
0
      err = write_direct_sig (ctrl, pub_root, pri_psk,
6537
0
                              revkey, signtimestamp, cache_nonce);
6538
0
    }
6539
6540
0
  if (!err && (s = get_parameter_value (para, pUSERID)))
6541
0
    {
6542
0
      err = write_uid (pub_root, s );
6543
0
      if (!err)
6544
0
        err = write_selfsigs (ctrl, pub_root, pri_psk,
6545
0
                              get_parameter_uint (para, pKEYUSAGE),
6546
0
                              signtimestamp, cache_nonce);
6547
0
    }
6548
6549
  /* Write the auth key to the card before the encryption key.  This
6550
     is a partial workaround for a PGP bug (as of this writing, all
6551
     versions including 8.1), that causes it to try and encrypt to
6552
     the most recent subkey regardless of whether that subkey is
6553
     actually an encryption type.  In this case, the auth key is an
6554
     RSA key so it succeeds. */
6555
6556
0
  if (!err && card && get_parameter (para, pAUTHKEYTYPE))
6557
0
    {
6558
0
      err = gen_card_key (3, get_parameter_algo (ctrl, para,
6559
0
                                                 pAUTHKEYTYPE, NULL ),
6560
0
                          0, pub_root, &authkeytimestamp, expire,
6561
0
                          &keygen_flags);
6562
0
      if (!err)
6563
0
        err = write_keybinding (ctrl, pub_root, pri_psk, NULL,
6564
0
                                PUBKEY_USAGE_AUTH, signtimestamp, cache_nonce);
6565
0
    }
6566
6567
0
  if (!err && get_parameter (para, pSUBKEYTYPE))
6568
0
    {
6569
0
      int subkey_algo = get_parameter_algo (ctrl, para, pSUBKEYTYPE, NULL);
6570
6571
0
      key_from_hexgrip = get_parameter_value (para, pSUBKEYGRIP);
6572
6573
0
      keygen_flags = outctrl->keygen_flags;
6574
0
      if (get_parameter_uint (para, pSUBVERSION) == 5)
6575
0
        keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
6576
6577
0
      if (key_from_hexgrip)
6578
0
        err = do_create_from_keygrip (ctrl, subkey_algo,
6579
0
                                      key_from_hexgrip, cardkey,
6580
0
                                      pub_root, subkeytimestamp,
6581
0
                                      get_parameter_u32 (para, pSUBKEYEXPIRE),
6582
0
                                      1, &keygen_flags);
6583
0
      else if (get_parameter_value (para, pCARDBACKUPKEY))
6584
0
        {
6585
0
          int lastmode;
6586
0
          unsigned int mykeygenflags = KEYGEN_FLAG_NO_PROTECTION;
6587
6588
0
          err = agent_set_ephemeral_mode (ctrl, 1, &lastmode);
6589
0
          if (err)
6590
0
            log_error ("error switching to ephemeral mode: %s\n",
6591
0
                       gpg_strerror (err));
6592
0
          else
6593
0
            {
6594
0
              err = do_create (subkey_algo,
6595
0
                               get_parameter_uint (para, pSUBKEYLENGTH),
6596
0
                               get_parameter_value (para, pSUBKEYCURVE),
6597
0
                               pub_root,
6598
0
                               subkeytimestamp,
6599
0
                               get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
6600
0
                               &mykeygenflags,
6601
0
                               get_parameter_passphrase (para),
6602
0
                               &cache_nonce, NULL,
6603
0
                               NULL, NULL);
6604
              /* Get the pointer to the generated public subkey packet.  */
6605
0
              if (!err)
6606
0
                {
6607
0
                  kbnode_t node;
6608
6609
0
                  for (node = pub_root; node; node = node->next)
6610
0
                    if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
6611
0
                      sub_psk = node->pkt->pkt.public_key;
6612
0
                  log_assert (sub_psk);
6613
0
                  err = card_store_key_with_backup (ctrl,
6614
0
                                                    sub_psk, gnupg_homedir ());
6615
0
                }
6616
6617
              /* Reset the ephemeral mode as needed.  */
6618
0
              if (!lastmode && agent_set_ephemeral_mode (ctrl, 0, NULL))
6619
0
                log_error ("error clearing the ephemeral mode\n");
6620
0
            }
6621
0
        }
6622
0
      else if (!card)
6623
0
        {
6624
0
          err = do_create (subkey_algo,
6625
0
                           get_parameter_uint (para, pSUBKEYLENGTH),
6626
0
                           get_parameter_value (para, pSUBKEYCURVE),
6627
0
                           pub_root,
6628
0
                           subkeytimestamp,
6629
0
                           get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
6630
0
                           &keygen_flags,
6631
0
                           get_parameter_passphrase (para),
6632
0
                           &cache_nonce, NULL,
6633
0
                           NULL, NULL);
6634
0
          if (!err)
6635
0
            {
6636
0
              kbnode_t node;
6637
6638
0
              for (node = pub_root; node; node = node->next)
6639
0
                if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
6640
0
                  sub_psk = node->pkt->pkt.public_key;
6641
0
              log_assert (sub_psk);
6642
0
            }
6643
0
        }
6644
0
      else
6645
0
        {
6646
0
          err = gen_card_key (2, subkey_algo, 0, pub_root,
6647
0
                              &subkeytimestamp, expire, &keygen_flags);
6648
0
        }
6649
6650
0
      if (!err)
6651
0
        err = write_keybinding (ctrl, pub_root, pri_psk, sub_psk,
6652
0
                                get_parameter_uint (para, pSUBKEYUSAGE),
6653
0
                                signtimestamp, cache_nonce);
6654
0
      did_sub = 1;
6655
0
    }
6656
6657
6658
  /* Get rid of the first empty packet.  */
6659
0
  if (!err)
6660
0
    commit_kbnode (&pub_root);
6661
6662
  /* Add ADSKs if any are specified.  */
6663
0
  if (!err)
6664
0
    {
6665
0
      PKT_public_key *adsk;
6666
6667
0
      for (idx=0; (adsk = get_parameter_adsk (para, idx)); idx++)
6668
0
        {
6669
0
          err = append_adsk_to_key (ctrl, pub_root, adsk,
6670
0
                                    signtimestamp, cache_nonce);
6671
0
          if (err)
6672
0
            break;
6673
0
          any_adsk++;
6674
0
        }
6675
0
    }
6676
6677
0
  if (!err && outctrl->use_files)  /* Direct write to specified files.  */
6678
0
    {
6679
0
      err = write_keyblock (outctrl->pub.stream, pub_root);
6680
0
      if (err)
6681
0
        log_error ("can't write public key: %s\n", gpg_strerror (err));
6682
0
    }
6683
0
  else if (!err) /* Write to the standard keyrings.  */
6684
0
    {
6685
0
      KEYDB_HANDLE pub_hd;
6686
6687
0
      pub_hd = keydb_new (ctrl);
6688
0
      if (!pub_hd)
6689
0
        err = gpg_error_from_syserror ();
6690
0
      else
6691
0
        {
6692
0
          err = keydb_locate_writable (pub_hd);
6693
0
          if (err)
6694
0
            log_error (_("no writable public keyring found: %s\n"),
6695
0
                       gpg_strerror (err));
6696
0
          else
6697
0
            err = keydb_lock (pub_hd);
6698
0
        }
6699
6700
0
      if (!err && opt.verbose)
6701
0
        {
6702
0
          log_info (_("writing public key to '%s'\n"),
6703
0
                    keydb_get_resource_name (pub_hd));
6704
0
        }
6705
6706
0
      if (!err)
6707
0
        {
6708
0
          err = keydb_insert_keyblock (pub_hd, pub_root);
6709
0
          if (err)
6710
0
            log_error (_("error writing public keyring '%s': %s\n"),
6711
0
                       keydb_get_resource_name (pub_hd), gpg_strerror (err));
6712
0
        }
6713
6714
0
      keydb_release (pub_hd);
6715
6716
0
      if (!err)
6717
0
        {
6718
0
          int no_enc_rsa;
6719
0
          PKT_public_key *pk;
6720
6721
0
          no_enc_rsa = ((get_parameter_algo (ctrl, para, pKEYTYPE, NULL)
6722
0
                         == PUBKEY_ALGO_RSA)
6723
0
                        && get_parameter_uint (para, pKEYUSAGE)
6724
0
                        && !((get_parameter_uint (para, pKEYUSAGE)
6725
0
                              & PUBKEY_USAGE_ENC)) );
6726
6727
0
          pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
6728
6729
0
          if (!opt.flags.no_auto_trust_new_key)
6730
0
            update_ownertrust (ctrl, pk,
6731
0
                               ((get_ownertrust (ctrl, pk) & ~TRUST_MASK)
6732
0
                                | TRUST_ULTIMATE ));
6733
6734
0
          gen_standard_revoke (ctrl, pk, cache_nonce);
6735
6736
0
          if (!opt.batch)
6737
0
            {
6738
0
              tty_printf (_("public and secret key created and signed.\n") );
6739
0
              tty_printf ("\n");
6740
0
              merge_keys_and_selfsig (ctrl, pub_root);
6741
6742
0
              list_keyblock_direct (ctrl, pub_root, 0, 1,
6743
0
                                    opt.fingerprint || opt.with_fingerprint,
6744
0
                                    1);
6745
              /* Note that we ignore errors from the list function
6746
               * because that would only be an additional info.  It
6747
               * has already been remarked that the key has been
6748
               * created.  */
6749
0
            }
6750
6751
0
          if (!opt.batch
6752
0
              && (get_parameter_algo (ctrl, para,
6753
0
                                      pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
6754
0
                  || no_enc_rsa )
6755
0
              && !get_parameter (para, pSUBKEYTYPE) )
6756
0
            {
6757
0
              tty_printf(_("Note that this key cannot be used for "
6758
0
                           "encryption.  You may want to use\n"
6759
0
                           "the command \"--edit-key\" to generate a "
6760
0
                           "subkey for this purpose.\n") );
6761
0
            }
6762
0
        }
6763
0
    }
6764
6765
0
  if (err)
6766
0
    {
6767
0
      if (opt.batch)
6768
0
        log_error ("key generation failed: %s\n", gpg_strerror (err) );
6769
0
      else
6770
0
        tty_printf (_("Key generation failed: %s\n"), gpg_strerror (err) );
6771
0
      write_status_error (card? "card_key_generate":"key_generate", err);
6772
0
      print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
6773
0
    }
6774
0
  else
6775
0
    {
6776
0
      PKT_public_key *pk = find_kbnode (pub_root,
6777
0
                                        PKT_PUBLIC_KEY)->pkt->pkt.public_key;
6778
0
      print_status_key_created (did_sub? 'B':'P', pk,
6779
0
                                get_parameter_value (para, pHANDLE));
6780
0
      es_fflush (es_stdout);
6781
0
      if (any_adsk)
6782
0
        log_info (_("Note: The key has been created with one or more ADSK!\n"));
6783
6784
0
      if (opt.flags.auto_key_upload)
6785
0
        {
6786
0
          unsigned int saved_options = opt.keyserver_options.options;
6787
6788
0
          opt.keyserver_options.options |= KEYSERVER_LDAP_ONLY;
6789
0
          opt.keyserver_options.options |= KEYSERVER_WARN_ONLY;
6790
0
          keyserver_export_pubkey (ctrl, pk, 1/*Assume new key*/);
6791
0
          opt.keyserver_options.options = saved_options;
6792
0
         }
6793
0
    }
6794
6795
0
  release_kbnode (pub_root);
6796
0
  xfree (cache_nonce);
6797
0
}
6798
6799
6800
static gpg_error_t
6801
parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
6802
                         const char *algostr, const char *usagestr,
6803
                         const char *expirestr,
6804
                         int *r_algo, unsigned int *r_usage, u32 *r_expire,
6805
                         unsigned int *r_nbits, const char **r_curve,
6806
                         int *r_version, char **r_keygrip, u32 *r_keytime)
6807
0
{
6808
0
  gpg_error_t err;
6809
0
  int algo;
6810
0
  unsigned int use, nbits;
6811
0
  u32 expire;
6812
0
  int wantuse;
6813
0
  int version = 4;
6814
0
  const char *curve = NULL;
6815
6816
0
  *r_curve = NULL;
6817
0
  if (r_keygrip)
6818
0
    *r_keygrip = NULL;
6819
0
  if (r_keytime)
6820
0
    *r_keytime = 0;
6821
6822
0
  nbits = 0;
6823
6824
  /* Parse the algo string.  */
6825
0
  if (algostr && *algostr == '&' && strlen (algostr) == 41)
6826
0
    {
6827
      /* Take algo from existing key.  */
6828
0
      algo = check_keygrip (ctrl, algostr+1);
6829
      /* FIXME: We need the curve name as well.  */
6830
0
      return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
6831
0
    }
6832
6833
0
  err = parse_key_parameter_string (ctrl, algostr, for_subkey? 1 : 0,
6834
0
                                    usagestr? parse_usagestr (usagestr):0,
6835
0
                                    &algo, &nbits, &use, &curve, &version,
6836
0
                                    r_keygrip, r_keytime,
6837
0
                                    NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6838
0
  if (err)
6839
0
    {
6840
0
      if (r_keygrip)
6841
0
        {
6842
0
          xfree (*r_keygrip);
6843
0
          *r_keygrip = NULL;
6844
0
        }
6845
0
      return err;
6846
0
    }
6847
6848
  /* Parse the usage string.  */
6849
0
  if (!usagestr || !*usagestr
6850
0
      || !ascii_strcasecmp (usagestr, "default") || !strcmp (usagestr, "-"))
6851
0
    ; /* Keep usage from parse_key_parameter_string.  */
6852
0
  else if ((wantuse = parse_usagestr (usagestr)) != -1)
6853
0
    use = wantuse;
6854
0
  else
6855
0
    {
6856
0
      if (r_keygrip)
6857
0
        {
6858
0
          xfree (*r_keygrip);
6859
0
          *r_keygrip = NULL;
6860
0
        }
6861
0
      return gpg_error (GPG_ERR_INV_VALUE);
6862
0
    }
6863
6864
  /* Now do the tricky ECDSA/ECDH adjustment.  */
6865
0
  algo = adjust_algo_for_ecdh_ecdsa (algo, use, curve);
6866
6867
  /* Make sure a primary key has the CERT usage.  */
6868
0
  if (!for_subkey)
6869
0
    use |= PUBKEY_USAGE_CERT;
6870
6871
  /* Check that usage is possible.  NB: We have the same check in
6872
   * parse_key_parameter_string but need it here again in case the
6873
   * separate usage value has been given. */
6874
0
  if (/**/((use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
6875
0
           && !pubkey_get_nsig (algo))
6876
0
       || ((use & PUBKEY_USAGE_ENC)
6877
0
           && !pubkey_get_nenc (algo))
6878
0
       || (for_subkey && (use & PUBKEY_USAGE_CERT)))
6879
0
    {
6880
0
      if (r_keygrip)
6881
0
        {
6882
0
          xfree (*r_keygrip);
6883
0
          *r_keygrip = NULL;
6884
0
        }
6885
0
      return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
6886
0
    }
6887
6888
  /* Parse the expire string.  */
6889
0
  expire = parse_expire_string (expirestr);
6890
0
  if (expire == (u32)-1 )
6891
0
    {
6892
0
      if (r_keygrip)
6893
0
        {
6894
0
          xfree (*r_keygrip);
6895
0
          *r_keygrip = NULL;
6896
0
        }
6897
0
      return gpg_error (GPG_ERR_INV_VALUE);
6898
0
    }
6899
6900
0
  if (curve)
6901
0
    *r_curve = curve;
6902
0
  *r_algo = algo;
6903
0
  *r_usage = use;
6904
0
  *r_expire = expire;
6905
0
  *r_nbits = nbits;
6906
0
  *r_version = version;
6907
0
  return 0;
6908
0
}
6909
6910
6911
/* Add a new subkey to an existing key.  Returns 0 if a new key has
6912
   been generated and put into the keyblocks.  If any of ALGOSTR,
6913
   USAGESTR, or EXPIRESTR is NULL interactive mode is used. */
6914
gpg_error_t
6915
generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr,
6916
                     const char *usagestr, const char *expirestr)
6917
0
{
6918
0
  gpg_error_t err = 0;
6919
0
  int interactive;
6920
0
  kbnode_t node;
6921
0
  PKT_public_key *pri_psk = NULL;
6922
0
  PKT_public_key *sub_psk = NULL;
6923
0
  int algo;
6924
0
  unsigned int use;
6925
0
  u32 expire;
6926
0
  unsigned int nbits = 0;
6927
0
  const char *curve = NULL;
6928
0
  u32 cur_time;
6929
0
  char *key_from_hexgrip = NULL;
6930
0
  u32 keytime = 0;
6931
0
  int cardkey = 0;
6932
0
  char *hexgrip = NULL;
6933
0
  char *serialno = NULL;
6934
0
  char *cache_nonce = NULL;
6935
0
  char *passwd_nonce = NULL;
6936
0
  int keygen_flags = 0;
6937
6938
0
  interactive = (!algostr || !usagestr || !expirestr);
6939
6940
  /* Break out the primary key.  */
6941
0
  node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
6942
0
  if (!node)
6943
0
    {
6944
0
      log_error ("Oops; primary key missing in keyblock!\n");
6945
0
      err = gpg_error (GPG_ERR_BUG);
6946
0
      goto leave;
6947
0
    }
6948
0
  pri_psk = node->pkt->pkt.public_key;
6949
6950
0
  cur_time = make_timestamp ();
6951
6952
0
  if (pri_psk->timestamp > cur_time)
6953
0
    {
6954
0
      ulong d = pri_psk->timestamp - cur_time;
6955
0
      log_info ( d==1 ? _("key has been created %lu second "
6956
0
                          "in future (time warp or clock problem)\n")
6957
0
                 : _("key has been created %lu seconds "
6958
0
                     "in future (time warp or clock problem)\n"), d );
6959
0
      if (!opt.ignore_time_conflict)
6960
0
        {
6961
0
          err = gpg_error (GPG_ERR_TIME_CONFLICT);
6962
0
          goto leave;
6963
0
        }
6964
0
    }
6965
6966
0
  if (pri_psk->version < 4)
6967
0
    {
6968
0
      log_info (_("Note: creating subkeys for v3 keys "
6969
0
                  "is not OpenPGP compliant\n"));
6970
0
      err = gpg_error (GPG_ERR_CONFLICT);
6971
0
      goto leave;
6972
0
    }
6973
6974
0
  err = hexkeygrip_from_pk (pri_psk, &hexgrip);
6975
0
  if (err)
6976
0
    goto leave;
6977
  /* FIXME: Right now the primary key won't be a composite key.  But this
6978
   *        will change */
6979
0
  if (agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
6980
0
    {
6981
0
      if (interactive)
6982
0
        tty_printf (_("Secret parts of primary key are not available.\n"));
6983
0
      else
6984
0
        log_info (  _("Secret parts of primary key are not available.\n"));
6985
0
      err = gpg_error (GPG_ERR_NO_SECKEY);
6986
0
      goto leave;
6987
0
    }
6988
0
  if (serialno)
6989
0
    {
6990
0
      if (interactive)
6991
0
        tty_printf (_("Secret parts of primary key are stored on-card.\n"));
6992
0
      else
6993
0
        log_info (  _("Secret parts of primary key are stored on-card.\n"));
6994
0
    }
6995
6996
0
  if (interactive)
6997
0
    {
6998
0
      algo = ask_algo (ctrl, 1, NULL, &use, &key_from_hexgrip, &cardkey,
6999
0
                       &keytime);
7000
0
      log_assert (algo);
7001
7002
0
      if (key_from_hexgrip)
7003
0
        nbits = 0;
7004
0
      else if (algo == PUBKEY_ALGO_ECDSA
7005
0
               || algo == PUBKEY_ALGO_EDDSA
7006
0
               || algo == PUBKEY_ALGO_ECDH)
7007
0
        {
7008
0
          curve = ask_curve (&algo, NULL, NULL);
7009
7010
0
          if (curve && (!strcmp (curve, "X448") || !strcmp (curve, "Ed448")))
7011
0
            keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
7012
0
        }
7013
0
      else if (algo == PUBKEY_ALGO_KYBER)
7014
0
        {
7015
0
          const char *kyberalgostr;
7016
7017
0
          kyberalgostr = ask_kyber_variant ();
7018
0
          if (!kyberalgostr)  /* Should not happen.  */
7019
0
            kyberalgostr = PQC_STD_KEY_PARAM_SUB;
7020
7021
0
          nbits = strstr (kyberalgostr, "768_")? 768 : 1024;
7022
0
          curve = strchr (kyberalgostr, '_');
7023
0
          log_assert (curve && curve[1]);
7024
0
          curve++;
7025
0
        }
7026
0
      else
7027
0
        nbits = ask_keysize (algo, 0);
7028
7029
0
      expire = ask_expire_interval (0, NULL);
7030
0
      if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
7031
0
                                                   _("Really create? (y/N) ")))
7032
0
        {
7033
0
          err = gpg_error (GPG_ERR_CANCELED);
7034
0
          goto leave;
7035
0
        }
7036
0
    }
7037
0
  else /* Unattended mode.  */
7038
0
    {
7039
0
      int version;
7040
7041
0
      err = parse_algo_usage_expire (ctrl, 1, algostr, usagestr, expirestr,
7042
0
                                     &algo, &use, &expire, &nbits, &curve,
7043
0
                                     &version, &key_from_hexgrip, &keytime);
7044
0
      if (err)
7045
0
        goto leave;
7046
7047
0
      if (version == 5)
7048
0
        keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
7049
0
    }
7050
7051
  /* Verify the passphrase now so that we get a cache item for the
7052
   * primary key passphrase.  The agent also returns a passphrase
7053
   * nonce, which we can use to set the passphrase for the subkey to
7054
   * that of the primary key.  */
7055
0
  {
7056
0
    char *desc = gpg_format_keydesc (ctrl, pri_psk, FORMAT_KEYDESC_NORMAL, 1);
7057
0
    err = agent_passwd (ctrl, hexgrip, desc, 1 /*=verify*/,
7058
0
                        &cache_nonce, &passwd_nonce);
7059
0
    xfree (desc);
7060
0
    if (gpg_err_code (err) == GPG_ERR_NOT_IMPLEMENTED
7061
0
        && gpg_err_source (err) == GPG_ERR_SOURCE_GPGAGENT)
7062
0
      err = 0;  /* Very likely that the key is on a card.  */
7063
0
    if (err)
7064
0
      goto leave;
7065
0
  }
7066
7067
  /* Start creation.  */
7068
0
  if (key_from_hexgrip)
7069
0
    {
7070
0
      err = do_create_from_keygrip (ctrl, algo, key_from_hexgrip, cardkey,
7071
0
                                    keyblock,
7072
0
                                    keytime? keytime : cur_time,
7073
0
                                    expire, 1,
7074
0
                                    &keygen_flags);
7075
0
    }
7076
0
  else
7077
0
    {
7078
0
      const char *passwd;
7079
7080
      /* If the pinentry loopback mode is not and we have a static
7081
         passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
7082
         mode), we use that passphrase for the new subkey.  */
7083
0
      if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
7084
0
          && have_static_passphrase ())
7085
0
        passwd = get_static_passphrase ();
7086
0
      else
7087
0
        passwd = NULL;
7088
7089
0
      err = do_create (algo, nbits, curve,
7090
0
                       keyblock, cur_time, expire, 1, &keygen_flags,
7091
0
                       passwd, &cache_nonce, &passwd_nonce, NULL, NULL);
7092
0
    }
7093
0
  if (err)
7094
0
    goto leave;
7095
7096
  /* Get the pointer to the generated public subkey packet.  */
7097
0
  for (node = keyblock; node; node = node->next)
7098
0
    if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
7099
0
      sub_psk = node->pkt->pkt.public_key;
7100
7101
  /* Write the binding signature.  */
7102
0
  err = write_keybinding (ctrl, keyblock, pri_psk, sub_psk, use, cur_time,
7103
0
                          cache_nonce);
7104
0
  if (err)
7105
0
    goto leave;
7106
7107
0
  print_status_key_created ('S', sub_psk, NULL);
7108
7109
7110
0
 leave:
7111
0
  xfree (key_from_hexgrip);
7112
0
  xfree (hexgrip);
7113
0
  xfree (serialno);
7114
0
  xfree (cache_nonce);
7115
0
  xfree (passwd_nonce);
7116
0
  if (err)
7117
0
    {
7118
0
      log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
7119
0
      write_status_error (cardkey? "card_key_generate":"key_generate", err);
7120
0
      print_status_key_not_created ( NULL );
7121
0
    }
7122
0
  return err;
7123
0
}
7124
7125
7126
/* Append the subkey SUB_PK to the KEYBLOCK but first verify that this
7127
 * key is not yet part of that keyblock; return GPG_ERR_EEXIST in that
7128
 * case.  USE gives the usage to set for the new key (take care: no
7129
 * check for compatibiliy with the algorithm is done).  Return 0 if
7130
 * the key was sucessfully added to keyblock.  On error KEYBLOCK might
7131
 * be modified but missing the key binding; the caller should take
7132
 * care of this.  */
7133
gpg_error_t
7134
append_subkey_to_keyblock (ctrl_t ctrl, kbnode_t keyblock,
7135
                           PKT_public_key *sub_pk, int use)
7136
0
{
7137
0
  gpg_error_t err = 0;
7138
0
  kbnode_t node;
7139
0
  PKT_public_key *pri_pk = NULL;
7140
0
  u32 cur_time;
7141
0
  PACKET *pkt;
7142
7143
  /* First make a copy of SUB_PK so that we do not interfere with the
7144
   * callers copy.  */
7145
0
  sub_pk = copy_public_key (NULL, sub_pk);
7146
7147
  /* Break out the primary key.  */
7148
0
  node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
7149
0
  if (!node)
7150
0
    {
7151
0
      log_error ("Oops; primary key missing in keyblock!\n");
7152
0
      err = gpg_error (GPG_ERR_BUG);
7153
0
      goto leave;
7154
0
    }
7155
0
  pri_pk = node->pkt->pkt.public_key;
7156
7157
0
  cur_time = make_timestamp();
7158
  /* FIXME: Factor out the next two checks.  */
7159
0
  if (pri_pk->timestamp > cur_time)
7160
0
    {
7161
0
      ulong d = pri_pk->timestamp - cur_time;
7162
0
      log_info (d==1 ? _("key has been created %lu second "
7163
0
                         "in future (time warp or clock problem)\n")
7164
0
                     : _("key has been created %lu seconds "
7165
0
                         "in future (time warp or clock problem)\n"), d );
7166
0
  if (!opt.ignore_time_conflict)
7167
0
          {
7168
0
      err = gpg_error (GPG_ERR_TIME_CONFLICT);
7169
0
      goto leave;
7170
0
          }
7171
0
    }
7172
7173
0
  if (pri_pk->version < 4)
7174
0
    {
7175
0
      log_info (_("Note: creating subkeys for v3 keys "
7176
0
                  "is not OpenPGP compliant\n"));
7177
0
      err = gpg_error (GPG_ERR_NOT_SUPPORTED);
7178
0
      goto leave;
7179
0
    }
7180
7181
  /* Check that the key is not yet on the keyblock  */
7182
0
  for (node = keyblock; node; node = node->next)
7183
0
    if ((node->pkt->pkttype == PKT_PUBLIC_KEY
7184
0
         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
7185
0
        && !cmp_public_keys (node->pkt->pkt.public_key, sub_pk))
7186
0
      {
7187
0
        log_info (_("key \"%s\" is already on this keyblock\n"),
7188
0
                  keystr_from_pk (sub_pk));
7189
0
        err = gpg_error (GPG_ERR_EEXIST);
7190
0
        goto leave;
7191
0
      }
7192
7193
  /* Append a copy of the subkey to the keyblock.  */
7194
0
  pkt = xmalloc_clear (sizeof *pkt);
7195
0
  pkt->pkttype = PKT_PUBLIC_SUBKEY;
7196
0
  pkt->pkt.public_key = sub_pk;
7197
0
  sub_pk = NULL;
7198
0
  add_kbnode (keyblock, new_kbnode (pkt));
7199
  /* Write a new keybinding.  */
7200
0
  err = write_keybinding (ctrl, keyblock, pri_pk, sub_pk,
7201
0
                          use, cur_time, NULL);
7202
7203
0
 leave:
7204
0
  free_public_key (sub_pk);
7205
0
  return err;
7206
0
}
7207
7208
7209
#ifdef ENABLE_CARD_SUPPORT
7210
/* Generate a subkey on a card. */
7211
gpg_error_t
7212
generate_card_subkeypair (ctrl_t ctrl, kbnode_t pub_keyblock,
7213
                          int keyno, const char *serialno)
7214
{
7215
  gpg_error_t err = 0;
7216
  kbnode_t node;
7217
  PKT_public_key *pri_pk = NULL;
7218
  unsigned int use;
7219
  u32 expire;
7220
  u32 cur_time;
7221
  struct para_data_s *para = NULL;
7222
  PKT_public_key *sub_pk = NULL;
7223
  int algo;
7224
  struct agent_card_info_s info;
7225
  int keygen_flags = 0;  /* FIXME!!! */
7226
7227
  log_assert (keyno >= 1 && keyno <= 3);
7228
7229
  memset (&info, 0, sizeof (info));
7230
  err = agent_scd_getattr ("KEY-ATTR", &info);
7231
  if (err)
7232
    {
7233
      log_error (_("error getting current key info: %s\n"), gpg_strerror (err));
7234
      return err;
7235
    }
7236
  algo = info.key_attr[keyno-1].algo;
7237
7238
  para = xtrycalloc (1, sizeof *para + strlen (serialno) );
7239
  if (!para)
7240
    {
7241
      err = gpg_error_from_syserror ();
7242
      goto leave;
7243
    }
7244
  para->key = pSERIALNO;
7245
  strcpy (para->u.value, serialno);
7246
7247
  /* Break out the primary secret key */
7248
  node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
7249
  if (!node)
7250
    {
7251
      log_error ("Oops; public key lost!\n");
7252
      err = gpg_error (GPG_ERR_INTERNAL);
7253
      goto leave;
7254
    }
7255
  pri_pk = node->pkt->pkt.public_key;
7256
7257
  cur_time = make_timestamp();
7258
  if (pri_pk->timestamp > cur_time)
7259
    {
7260
      ulong d = pri_pk->timestamp - cur_time;
7261
      log_info (d==1 ? _("key has been created %lu second "
7262
                         "in future (time warp or clock problem)\n")
7263
                     : _("key has been created %lu seconds "
7264
                         "in future (time warp or clock problem)\n"), d );
7265
  if (!opt.ignore_time_conflict)
7266
          {
7267
      err = gpg_error (GPG_ERR_TIME_CONFLICT);
7268
      goto leave;
7269
          }
7270
    }
7271
7272
  if (pri_pk->version < 4)
7273
    {
7274
      log_info (_("Note: creating subkeys for v3 keys "
7275
                  "is not OpenPGP compliant\n"));
7276
      err = gpg_error (GPG_ERR_NOT_SUPPORTED);
7277
      goto leave;
7278
    }
7279
7280
  expire = ask_expire_interval (0, NULL);
7281
  if (keyno == 1)
7282
    use = PUBKEY_USAGE_SIG;
7283
  else if (keyno == 2)
7284
    use = PUBKEY_USAGE_ENC;
7285
  else
7286
    use = PUBKEY_USAGE_AUTH;
7287
  if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
7288
                                               _("Really create? (y/N) ")))
7289
    {
7290
      err = gpg_error (GPG_ERR_CANCELED);
7291
      goto leave;
7292
    }
7293
7294
  /* Note, that depending on the backend, the card key generation may
7295
     update CUR_TIME.  */
7296
  err = gen_card_key (keyno, algo, 0, pub_keyblock, &cur_time, expire,
7297
                      &keygen_flags);
7298
  /* Get the pointer to the generated public subkey packet.  */
7299
  if (!err)
7300
    {
7301
      for (node = pub_keyblock; node; node = node->next)
7302
        if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
7303
          sub_pk = node->pkt->pkt.public_key;
7304
      log_assert (sub_pk);
7305
      err = write_keybinding (ctrl, pub_keyblock, pri_pk, sub_pk,
7306
                              use, cur_time, NULL);
7307
    }
7308
7309
 leave:
7310
  if (err)
7311
    log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
7312
  else
7313
    print_status_key_created ('S', sub_pk, NULL);
7314
  release_parameter_list (para);
7315
  return err;
7316
}
7317
#endif /* !ENABLE_CARD_SUPPORT */
7318
7319
/*
7320
 * Write a keyblock to an output stream
7321
 */
7322
static int
7323
write_keyblock( IOBUF out, KBNODE node )
7324
0
{
7325
0
  for( ; node ; node = node->next )
7326
0
    {
7327
0
      if(!is_deleted_kbnode(node))
7328
0
  {
7329
0
    int rc = build_packet( out, node->pkt );
7330
0
    if( rc )
7331
0
      {
7332
0
        log_error("build_packet(%d) failed: %s\n",
7333
0
      node->pkt->pkttype, gpg_strerror (rc) );
7334
0
        return rc;
7335
0
      }
7336
0
  }
7337
0
    }
7338
7339
0
  return 0;
7340
0
}
7341
7342
7343
/* Note that timestamp is an in/out arg. */
7344
static gpg_error_t
7345
gen_card_key (int keyno, int algo, int is_primary, kbnode_t pub_root,
7346
              u32 *timestamp, u32 expireval, int *keygen_flags)
7347
0
{
7348
#ifdef ENABLE_CARD_SUPPORT
7349
  gpg_error_t err;
7350
  PACKET *pkt;
7351
  PKT_public_key *pk;
7352
  char keyid[10];
7353
  unsigned char *public;
7354
  gcry_sexp_t s_key;
7355
7356
  snprintf (keyid, DIM(keyid), "OPENPGP.%d", keyno);
7357
7358
  pk = xtrycalloc (1, sizeof *pk );
7359
  if (!pk)
7360
    return gpg_error_from_syserror ();
7361
  pkt = xtrycalloc (1, sizeof *pkt);
7362
  if (!pkt)
7363
    {
7364
      xfree (pk);
7365
      return gpg_error_from_syserror ();
7366
    }
7367
7368
  /* Note: SCD knows the serialnumber, thus there is no point in passing it.  */
7369
  err = agent_scd_genkey (keyno, 1, timestamp);
7370
  /*  The code below is not used because we force creation of
7371
   *  the a card key (3rd arg).
7372
   * if (gpg_err_code (rc) == GPG_ERR_EEXIST)
7373
   *   {
7374
   *     tty_printf ("\n");
7375
   *     log_error ("WARNING: key does already exists!\n");
7376
   *     tty_printf ("\n");
7377
   *     if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
7378
   *                                 _("Replace existing key? ")))
7379
   *       rc = agent_scd_genkey (keyno, 1, timestamp);
7380
   *   }
7381
  */
7382
  if (err)
7383
    {
7384
      log_error ("key generation failed: %s\n", gpg_strerror (err));
7385
      xfree (pkt);
7386
      xfree (pk);
7387
      return err;
7388
    }
7389
7390
  /* Send the READKEY command so that the agent creates a shadow key for
7391
     card key.  We need to do that now so that we are able to create
7392
     the self-signatures. */
7393
  err = agent_readkey (NULL, 1, keyid, &public);
7394
  if (err)
7395
    {
7396
      xfree (pkt);
7397
      xfree (pk);
7398
      return err;
7399
    }
7400
  err = gcry_sexp_sscan (&s_key, NULL, public,
7401
                         gcry_sexp_canon_len (public, 0, NULL, NULL));
7402
  xfree (public);
7403
  if (err)
7404
    {
7405
      xfree (pkt);
7406
      xfree (pk);
7407
      return err;
7408
    }
7409
7410
  /* Force creation of v5 keys for X448.  */
7411
  if (curve_is_448 (s_key))
7412
    *keygen_flags |= KEYGEN_FLAG_CREATE_V5_KEY;
7413
7414
  pk->version = (*keygen_flags & KEYGEN_FLAG_CREATE_V5_KEY)? 5 : 4;
7415
7416
  if (algo == PUBKEY_ALGO_RSA)
7417
    err = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
7418
  else if (algo == PUBKEY_ALGO_ECDSA
7419
           || algo == PUBKEY_ALGO_EDDSA
7420
           || algo == PUBKEY_ALGO_ECDH )
7421
    err = ecckey_from_sexp (pk->pkey, s_key, NULL, algo, pk->version);
7422
  else
7423
    err = gpg_error (GPG_ERR_PUBKEY_ALGO);
7424
  gcry_sexp_release (s_key);
7425
7426
  if (err)
7427
    {
7428
      log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
7429
      free_public_key (pk);
7430
      return err;
7431
    }
7432
7433
  pk->timestamp = *timestamp;
7434
  if (expireval)
7435
    pk->expiredate = pk->timestamp + expireval;
7436
  pk->pubkey_algo = algo;
7437
7438
  pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
7439
  pkt->pkt.public_key = pk;
7440
  add_kbnode (pub_root, new_kbnode (pkt));
7441
7442
  return 0;
7443
#else
7444
0
  (void)keyno;
7445
0
  (void)is_primary;
7446
0
  (void)pub_root;
7447
0
  (void)timestamp;
7448
0
  (void)expireval;
7449
0
  return gpg_error (GPG_ERR_NOT_SUPPORTED);
7450
0
#endif /*!ENABLE_CARD_SUPPORT*/
7451
0
}