Line data Source code
1 : /* keygen.c - Generate a key pair
2 : * Copyright (C) 1998-2007, 2009-2011 Free Software Foundation, Inc.
3 : * Copyright (C) 2014, 2015, 2016 Werner Koch
4 : *
5 : * This file is part of GnuPG.
6 : *
7 : * GnuPG is free software; you can redistribute it and/or modify
8 : * it under the terms of the GNU General Public License as published by
9 : * the Free Software Foundation; either version 3 of the License, or
10 : * (at your option) any later version.
11 : *
12 : * GnuPG is distributed in the hope that it will be useful,
13 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 : * GNU General Public License for more details.
16 : *
17 : * You should have received a copy of the GNU General Public License
18 : * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 : */
20 :
21 : #include <config.h>
22 : #include <stdio.h>
23 : #include <stdlib.h>
24 : #include <string.h>
25 : #include <ctype.h>
26 : #include <errno.h>
27 : #include <sys/types.h>
28 : #include <sys/stat.h>
29 : #include <unistd.h>
30 :
31 : #include "gpg.h"
32 : #include "util.h"
33 : #include "main.h"
34 : #include "packet.h"
35 : #include "ttyio.h"
36 : #include "options.h"
37 : #include "keydb.h"
38 : #include "trustdb.h"
39 : #include "status.h"
40 : #include "i18n.h"
41 : #include "keyserver-internal.h"
42 : #include "call-agent.h"
43 : #include "pkglue.h"
44 : #include "../common/shareddefs.h"
45 : #include "host2net.h"
46 : #include "mbox-util.h"
47 :
48 :
49 : /* The default algorithms. If you change them remember to change them
50 : also in gpg.c:gpgconf_list. You should also check that the value
51 : is inside the bounds enforced by ask_keysize and gen_xxx. */
52 : #define DEFAULT_STD_ALGO PUBKEY_ALGO_RSA
53 : #define DEFAULT_STD_KEYSIZE 2048
54 : #define DEFAULT_STD_KEYUSE (PUBKEY_USAGE_CERT|PUBKEY_USAGE_SIG)
55 : #define DEFAULT_STD_CURVE NULL
56 : #define DEFAULT_STD_SUBALGO PUBKEY_ALGO_RSA
57 : #define DEFAULT_STD_SUBKEYSIZE 2048
58 : #define DEFAULT_STD_SUBKEYUSE PUBKEY_USAGE_ENC
59 : #define DEFAULT_STD_SUBCURVE NULL
60 :
61 : /* Flag bits used during key generation. */
62 : #define KEYGEN_FLAG_NO_PROTECTION 1
63 : #define KEYGEN_FLAG_TRANSIENT_KEY 2
64 :
65 : /* Maximum number of supported algorithm preferences. */
66 : #define MAX_PREFS 30
67 :
68 : enum para_name {
69 : pKEYTYPE,
70 : pKEYLENGTH,
71 : pKEYCURVE,
72 : pKEYUSAGE,
73 : pSUBKEYTYPE,
74 : pSUBKEYLENGTH,
75 : pSUBKEYCURVE,
76 : pSUBKEYUSAGE,
77 : pAUTHKEYTYPE,
78 : pNAMEREAL,
79 : pNAMEEMAIL,
80 : pNAMECOMMENT,
81 : pPREFERENCES,
82 : pREVOKER,
83 : pUSERID,
84 : pCREATIONDATE,
85 : pKEYCREATIONDATE, /* Same in seconds since epoch. */
86 : pEXPIREDATE,
87 : pKEYEXPIRE, /* in n seconds */
88 : pSUBKEYEXPIRE, /* in n seconds */
89 : pPASSPHRASE,
90 : pSERIALNO,
91 : pCARDBACKUPKEY,
92 : pHANDLE,
93 : pKEYSERVER
94 : };
95 :
96 : struct para_data_s {
97 : struct para_data_s *next;
98 : int lnr;
99 : enum para_name key;
100 : union {
101 : u32 expire;
102 : u32 creation;
103 : unsigned int usage;
104 : struct revocation_key revkey;
105 : char value[1];
106 : } u;
107 : };
108 :
109 : struct output_control_s
110 : {
111 : int lnr;
112 : int dryrun;
113 : unsigned int keygen_flags;
114 : int use_files;
115 : struct {
116 : char *fname;
117 : char *newfname;
118 : IOBUF stream;
119 : armor_filter_context_t *afx;
120 : } pub;
121 : };
122 :
123 :
124 : struct opaque_data_usage_and_pk {
125 : unsigned int usage;
126 : PKT_public_key *pk;
127 : };
128 :
129 :
130 : static int prefs_initialized = 0;
131 : static byte sym_prefs[MAX_PREFS];
132 : static int nsym_prefs;
133 : static byte hash_prefs[MAX_PREFS];
134 : static int nhash_prefs;
135 : static byte zip_prefs[MAX_PREFS];
136 : static int nzip_prefs;
137 : static int mdc_available,ks_modify;
138 :
139 : static gpg_error_t parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
140 : const char *algostr, const char *usagestr,
141 : const char *expirestr,
142 : int *r_algo, unsigned int *r_usage,
143 : u32 *r_expire,
144 : unsigned int *r_nbits, char **r_curve);
145 : static void do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
146 : struct output_control_s *outctrl, int card );
147 : static int write_keyblock (iobuf_t out, kbnode_t node);
148 : static gpg_error_t gen_card_key (int algo, int keyno, int is_primary,
149 : kbnode_t pub_root,
150 : u32 *timestamp, u32 expireval);
151 :
152 :
153 : static void
154 2 : print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
155 : {
156 : byte array[MAX_FINGERPRINT_LEN], *s;
157 : char *buf, *p;
158 : size_t i, n;
159 :
160 2 : if (!handle)
161 2 : handle = "";
162 :
163 2 : buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
164 :
165 2 : p = buf;
166 2 : if (letter || pk)
167 : {
168 2 : *p++ = letter;
169 2 : if (pk)
170 : {
171 2 : *p++ = ' ';
172 2 : fingerprint_from_pk (pk, array, &n);
173 2 : s = array;
174 42 : for (i=0; i < n ; i++, s++, p += 2)
175 40 : sprintf (p, "%02X", *s);
176 : }
177 : }
178 2 : if (*handle)
179 : {
180 0 : *p++ = ' ';
181 0 : for (i=0; handle[i] && i < 100; i++)
182 0 : *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
183 : }
184 2 : *p = 0;
185 2 : write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
186 : buf);
187 2 : xfree (buf);
188 2 : }
189 :
190 : static void
191 0 : print_status_key_not_created (const char *handle)
192 : {
193 0 : print_status_key_created (0, NULL, handle);
194 0 : }
195 :
196 :
197 :
198 : static void
199 2 : write_uid( KBNODE root, const char *s )
200 : {
201 2 : PACKET *pkt = xmalloc_clear(sizeof *pkt );
202 2 : size_t n = strlen(s);
203 :
204 2 : pkt->pkttype = PKT_USER_ID;
205 2 : pkt->pkt.user_id = xmalloc_clear (sizeof *pkt->pkt.user_id + n);
206 2 : pkt->pkt.user_id->len = n;
207 2 : pkt->pkt.user_id->ref = 1;
208 2 : strcpy(pkt->pkt.user_id->name, s);
209 2 : add_kbnode( root, new_kbnode( pkt ) );
210 2 : }
211 :
212 : static void
213 3 : do_add_key_flags (PKT_signature *sig, unsigned int use)
214 : {
215 : byte buf[1];
216 :
217 3 : buf[0] = 0;
218 :
219 : /* The spec says that all primary keys MUST be able to certify. */
220 3 : if(sig->sig_class!=0x18)
221 2 : buf[0] |= 0x01;
222 :
223 3 : if (use & PUBKEY_USAGE_SIG)
224 2 : buf[0] |= 0x02;
225 3 : if (use & PUBKEY_USAGE_ENC)
226 2 : buf[0] |= 0x04 | 0x08;
227 3 : if (use & PUBKEY_USAGE_AUTH)
228 1 : buf[0] |= 0x20;
229 :
230 3 : build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
231 3 : }
232 :
233 :
234 : int
235 3 : keygen_add_key_expire (PKT_signature *sig, void *opaque)
236 : {
237 3 : PKT_public_key *pk = opaque;
238 : byte buf[8];
239 : u32 u;
240 :
241 3 : if (pk->expiredate)
242 : {
243 3 : if (pk->expiredate > pk->timestamp)
244 3 : u = pk->expiredate - pk->timestamp;
245 : else
246 0 : u = 1;
247 :
248 3 : buf[0] = (u >> 24) & 0xff;
249 3 : buf[1] = (u >> 16) & 0xff;
250 3 : buf[2] = (u >> 8) & 0xff;
251 3 : buf[3] = u & 0xff;
252 3 : build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
253 : }
254 : else
255 : {
256 : /* Make sure we don't leave a key expiration subpacket lying
257 : around */
258 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
259 : }
260 :
261 3 : return 0;
262 : }
263 :
264 :
265 : /* Add the key usage (i.e. key flags) in SIG from the public keys
266 : * pubkey_usage field. OPAQUE has the public key. */
267 : int
268 0 : keygen_add_key_flags (PKT_signature *sig, void *opaque)
269 : {
270 0 : PKT_public_key *pk = opaque;
271 :
272 0 : do_add_key_flags (sig, pk->pubkey_usage);
273 0 : return 0;
274 : }
275 :
276 :
277 : static int
278 1 : keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
279 : {
280 1 : struct opaque_data_usage_and_pk *oduap = opaque;
281 :
282 1 : do_add_key_flags (sig, oduap->usage);
283 1 : return keygen_add_key_expire (sig, oduap->pk);
284 : }
285 :
286 :
287 : static int
288 24 : set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
289 : {
290 : int i;
291 :
292 62 : for (i=0; i < *nbuf; i++ )
293 38 : if (buf[i] == val)
294 : {
295 0 : log_info (_("preference '%s' duplicated\n"), item);
296 0 : return -1;
297 : }
298 :
299 24 : if (*nbuf >= MAX_PREFS)
300 : {
301 0 : if(type==1)
302 0 : log_info(_("too many cipher preferences\n"));
303 0 : else if(type==2)
304 0 : log_info(_("too many digest preferences\n"));
305 0 : else if(type==3)
306 0 : log_info(_("too many compression preferences\n"));
307 : else
308 0 : BUG();
309 :
310 0 : return -1;
311 : }
312 :
313 24 : buf[(*nbuf)++] = val;
314 24 : return 0;
315 : }
316 :
317 : /*
318 : * Parse the supplied string and use it to set the standard
319 : * preferences. The string may be in a form like the one printed by
320 : * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
321 : * cipher/hash/compress names. Use NULL to set the default
322 : * preferences. Returns: 0 = okay
323 : */
324 : int
325 2 : keygen_set_std_prefs (const char *string,int personal)
326 : {
327 : byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
328 2 : int nsym=0, nhash=0, nzip=0, val, rc=0;
329 2 : int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
330 : char dummy_string[20*4+1]; /* Enough for 20 items. */
331 :
332 2 : if (!string || !ascii_strcasecmp (string, "default"))
333 : {
334 4 : if (opt.def_preference_list)
335 0 : string=opt.def_preference_list;
336 : else
337 : {
338 2 : int any_compress = 0;
339 2 : dummy_string[0]='\0';
340 :
341 : /* The rationale why we use the order AES256,192,128 is
342 : for compatibility reasons with PGP. If gpg would
343 : define AES128 first, we would get the somewhat
344 : confusing situation:
345 :
346 : gpg -r pgpkey -r gpgkey ---gives--> AES256
347 : gpg -r gpgkey -r pgpkey ---gives--> AES
348 :
349 : Note that by using --personal-cipher-preferences it is
350 : possible to prefer AES128.
351 : */
352 :
353 : /* Make sure we do not add more than 15 items here, as we
354 : could overflow the size of dummy_string. We currently
355 : have at most 12. */
356 2 : if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
357 2 : strcat(dummy_string,"S9 ");
358 2 : if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
359 2 : strcat(dummy_string,"S8 ");
360 2 : if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
361 2 : strcat(dummy_string,"S7 ");
362 2 : strcat(dummy_string,"S2 "); /* 3DES */
363 :
364 : /* The default hash algo order is:
365 : SHA-256, SHA-384, SHA-512, SHA-224, SHA-1.
366 : */
367 2 : if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
368 2 : strcat (dummy_string, "H8 ");
369 :
370 2 : if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
371 2 : strcat (dummy_string, "H9 ");
372 :
373 2 : if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
374 2 : strcat (dummy_string, "H10 ");
375 :
376 2 : if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
377 2 : strcat (dummy_string, "H11 ");
378 :
379 2 : strcat (dummy_string, "H2 "); /* SHA-1 */
380 :
381 2 : if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
382 : {
383 2 : strcat(dummy_string,"Z2 ");
384 2 : any_compress = 1;
385 : }
386 :
387 2 : if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
388 : {
389 2 : strcat(dummy_string,"Z3 ");
390 2 : any_compress = 1;
391 : }
392 :
393 2 : if(!check_compress_algo(COMPRESS_ALGO_ZIP))
394 : {
395 2 : strcat(dummy_string,"Z1 ");
396 2 : any_compress = 1;
397 : }
398 :
399 : /* In case we have no compress algo at all, declare that
400 : we prefer no compresssion. */
401 2 : if (!any_compress)
402 0 : strcat(dummy_string,"Z0 ");
403 :
404 : /* Remove the trailing space. */
405 2 : if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
406 2 : dummy_string[strlen (dummy_string)-1] = 0;
407 :
408 2 : string=dummy_string;
409 : }
410 : }
411 0 : else if (!ascii_strcasecmp (string, "none"))
412 0 : string = "";
413 :
414 2 : if(strlen(string))
415 : {
416 : char *dup, *tok, *prefstring;
417 :
418 2 : dup = prefstring = xstrdup (string); /* need a writable string! */
419 :
420 28 : while((tok=strsep(&prefstring," ,")))
421 : {
422 24 : if((val=string_to_cipher_algo (tok)))
423 : {
424 8 : if(set_one_pref(val,1,tok,sym,&nsym))
425 0 : rc=-1;
426 : }
427 16 : else if((val=string_to_digest_algo (tok)))
428 : {
429 10 : if(set_one_pref(val,2,tok,hash,&nhash))
430 0 : rc=-1;
431 : }
432 6 : else if((val=string_to_compress_algo(tok))>-1)
433 : {
434 6 : if(set_one_pref(val,3,tok,zip,&nzip))
435 0 : rc=-1;
436 : }
437 0 : else if (ascii_strcasecmp(tok,"mdc")==0)
438 0 : mdc=1;
439 0 : else if (ascii_strcasecmp(tok,"no-mdc")==0)
440 0 : mdc=0;
441 0 : else if (ascii_strcasecmp(tok,"ks-modify")==0)
442 0 : modify=1;
443 0 : else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
444 0 : modify=0;
445 : else
446 : {
447 0 : log_info (_("invalid item '%s' in preference string\n"),tok);
448 0 : rc=-1;
449 : }
450 : }
451 :
452 2 : xfree (dup);
453 : }
454 :
455 2 : if(!rc)
456 : {
457 2 : if(personal)
458 : {
459 0 : if(personal==PREFTYPE_SYM)
460 : {
461 0 : xfree(opt.personal_cipher_prefs);
462 :
463 0 : if(nsym==0)
464 0 : opt.personal_cipher_prefs=NULL;
465 : else
466 : {
467 : int i;
468 :
469 0 : opt.personal_cipher_prefs=
470 0 : xmalloc(sizeof(prefitem_t *)*(nsym+1));
471 :
472 0 : for (i=0; i<nsym; i++)
473 : {
474 0 : opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
475 0 : opt.personal_cipher_prefs[i].value = sym[i];
476 : }
477 :
478 0 : opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
479 0 : opt.personal_cipher_prefs[i].value = 0;
480 : }
481 : }
482 0 : else if(personal==PREFTYPE_HASH)
483 : {
484 0 : xfree(opt.personal_digest_prefs);
485 :
486 0 : if(nhash==0)
487 0 : opt.personal_digest_prefs=NULL;
488 : else
489 : {
490 : int i;
491 :
492 0 : opt.personal_digest_prefs=
493 0 : xmalloc(sizeof(prefitem_t *)*(nhash+1));
494 :
495 0 : for (i=0; i<nhash; i++)
496 : {
497 0 : opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
498 0 : opt.personal_digest_prefs[i].value = hash[i];
499 : }
500 :
501 0 : opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
502 0 : opt.personal_digest_prefs[i].value = 0;
503 : }
504 : }
505 0 : else if(personal==PREFTYPE_ZIP)
506 : {
507 0 : xfree(opt.personal_compress_prefs);
508 :
509 0 : if(nzip==0)
510 0 : opt.personal_compress_prefs=NULL;
511 : else
512 : {
513 : int i;
514 :
515 0 : opt.personal_compress_prefs=
516 0 : xmalloc(sizeof(prefitem_t *)*(nzip+1));
517 :
518 0 : for (i=0; i<nzip; i++)
519 : {
520 0 : opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
521 0 : opt.personal_compress_prefs[i].value = zip[i];
522 : }
523 :
524 0 : opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
525 0 : opt.personal_compress_prefs[i].value = 0;
526 : }
527 : }
528 : }
529 : else
530 : {
531 2 : memcpy (sym_prefs, sym, (nsym_prefs=nsym));
532 2 : memcpy (hash_prefs, hash, (nhash_prefs=nhash));
533 2 : memcpy (zip_prefs, zip, (nzip_prefs=nzip));
534 2 : mdc_available = mdc;
535 2 : ks_modify = modify;
536 2 : prefs_initialized = 1;
537 : }
538 : }
539 :
540 2 : return rc;
541 : }
542 :
543 : /* Return a fake user ID containing the preferences. Caller must
544 : free. */
545 : PKT_user_id *
546 0 : keygen_get_std_prefs(void)
547 : {
548 0 : int i,j=0;
549 0 : PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
550 :
551 0 : if(!prefs_initialized)
552 0 : keygen_set_std_prefs(NULL,0);
553 :
554 0 : uid->ref=1;
555 :
556 0 : uid->prefs=xmalloc((sizeof(prefitem_t *)*
557 : (nsym_prefs+nhash_prefs+nzip_prefs+1)));
558 :
559 0 : for(i=0;i<nsym_prefs;i++,j++)
560 : {
561 0 : uid->prefs[j].type=PREFTYPE_SYM;
562 0 : uid->prefs[j].value=sym_prefs[i];
563 : }
564 :
565 0 : for(i=0;i<nhash_prefs;i++,j++)
566 : {
567 0 : uid->prefs[j].type=PREFTYPE_HASH;
568 0 : uid->prefs[j].value=hash_prefs[i];
569 : }
570 :
571 0 : for(i=0;i<nzip_prefs;i++,j++)
572 : {
573 0 : uid->prefs[j].type=PREFTYPE_ZIP;
574 0 : uid->prefs[j].value=zip_prefs[i];
575 : }
576 :
577 0 : uid->prefs[j].type=PREFTYPE_NONE;
578 0 : uid->prefs[j].value=0;
579 :
580 0 : uid->flags.mdc=mdc_available;
581 0 : uid->flags.ks_modify=ks_modify;
582 :
583 0 : return uid;
584 : }
585 :
586 : static void
587 2 : add_feature_mdc (PKT_signature *sig,int enabled)
588 : {
589 : const byte *s;
590 : size_t n;
591 : int i;
592 : char *buf;
593 :
594 2 : s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
595 : /* Already set or cleared */
596 2 : if (s && n &&
597 0 : ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
598 2 : return;
599 :
600 2 : if (!s || !n) { /* create a new one */
601 2 : n = 1;
602 2 : buf = xmalloc_clear (n);
603 : }
604 : else {
605 0 : buf = xmalloc (n);
606 0 : memcpy (buf, s, n);
607 : }
608 :
609 2 : if(enabled)
610 2 : buf[0] |= 0x01; /* MDC feature */
611 : else
612 0 : buf[0] &= ~0x01;
613 :
614 : /* Are there any bits set? */
615 2 : for(i=0;i<n;i++)
616 2 : if(buf[i]!=0)
617 2 : break;
618 :
619 2 : if(i==n)
620 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
621 : else
622 2 : build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
623 :
624 2 : xfree (buf);
625 : }
626 :
627 : static void
628 2 : add_keyserver_modify (PKT_signature *sig,int enabled)
629 : {
630 : const byte *s;
631 : size_t n;
632 : int i;
633 : char *buf;
634 :
635 : /* The keyserver modify flag is a negative flag (i.e. no-modify) */
636 2 : enabled=!enabled;
637 :
638 2 : s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
639 : /* Already set or cleared */
640 2 : if (s && n &&
641 0 : ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
642 2 : return;
643 :
644 2 : if (!s || !n) { /* create a new one */
645 2 : n = 1;
646 2 : buf = xmalloc_clear (n);
647 : }
648 : else {
649 0 : buf = xmalloc (n);
650 0 : memcpy (buf, s, n);
651 : }
652 :
653 2 : if(enabled)
654 2 : buf[0] |= 0x80; /* no-modify flag */
655 : else
656 0 : buf[0] &= ~0x80;
657 :
658 : /* Are there any bits set? */
659 2 : for(i=0;i<n;i++)
660 2 : if(buf[i]!=0)
661 2 : break;
662 :
663 2 : if(i==n)
664 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
665 : else
666 2 : build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
667 :
668 2 : xfree (buf);
669 : }
670 :
671 :
672 : int
673 2 : keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
674 : {
675 : (void)opaque;
676 :
677 2 : if (!prefs_initialized)
678 0 : keygen_set_std_prefs (NULL, 0);
679 :
680 2 : if (nsym_prefs)
681 2 : build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
682 : else
683 : {
684 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
685 0 : delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
686 : }
687 :
688 2 : if (nhash_prefs)
689 2 : build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
690 : else
691 : {
692 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
693 0 : delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
694 : }
695 :
696 2 : if (nzip_prefs)
697 2 : build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
698 : else
699 : {
700 0 : delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
701 0 : delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
702 : }
703 :
704 : /* Make sure that the MDC feature flag is set if needed. */
705 2 : add_feature_mdc (sig,mdc_available);
706 2 : add_keyserver_modify (sig,ks_modify);
707 2 : keygen_add_keyserver_url(sig,NULL);
708 :
709 2 : return 0;
710 : }
711 :
712 :
713 : /****************
714 : * Add preference to the self signature packet.
715 : * This is only called for packets with version > 3.
716 : */
717 : int
718 2 : keygen_add_std_prefs (PKT_signature *sig, void *opaque)
719 : {
720 2 : PKT_public_key *pk = opaque;
721 :
722 2 : do_add_key_flags (sig, pk->pubkey_usage);
723 2 : keygen_add_key_expire (sig, opaque );
724 2 : keygen_upd_std_prefs (sig, opaque);
725 2 : keygen_add_keyserver_url (sig,NULL);
726 :
727 2 : return 0;
728 : }
729 :
730 : int
731 4 : keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
732 : {
733 4 : const char *url=opaque;
734 :
735 4 : if(!url)
736 4 : url=opt.def_keyserver_url;
737 :
738 4 : if(url)
739 0 : build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
740 : else
741 4 : delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
742 :
743 4 : return 0;
744 : }
745 :
746 : int
747 0 : keygen_add_notations(PKT_signature *sig,void *opaque)
748 : {
749 : struct notation *notation;
750 :
751 : /* We always start clean */
752 0 : delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
753 0 : delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
754 0 : sig->flags.notation=0;
755 :
756 0 : for(notation=opaque;notation;notation=notation->next)
757 0 : if(!notation->flags.ignore)
758 : {
759 : unsigned char *buf;
760 : unsigned int n1,n2;
761 :
762 0 : n1=strlen(notation->name);
763 0 : if(notation->altvalue)
764 0 : n2=strlen(notation->altvalue);
765 0 : else if(notation->bdat)
766 0 : n2=notation->blen;
767 : else
768 0 : n2=strlen(notation->value);
769 :
770 0 : buf = xmalloc( 8 + n1 + n2 );
771 :
772 : /* human readable or not */
773 0 : buf[0] = notation->bdat?0:0x80;
774 0 : buf[1] = buf[2] = buf[3] = 0;
775 0 : buf[4] = n1 >> 8;
776 0 : buf[5] = n1;
777 0 : buf[6] = n2 >> 8;
778 0 : buf[7] = n2;
779 0 : memcpy(buf+8, notation->name, n1 );
780 0 : if(notation->altvalue)
781 0 : memcpy(buf+8+n1, notation->altvalue, n2 );
782 0 : else if(notation->bdat)
783 0 : memcpy(buf+8+n1, notation->bdat, n2 );
784 : else
785 0 : memcpy(buf+8+n1, notation->value, n2 );
786 0 : build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
787 0 : (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
788 0 : buf, 8+n1+n2 );
789 0 : xfree(buf);
790 : }
791 :
792 0 : return 0;
793 : }
794 :
795 : int
796 0 : keygen_add_revkey (PKT_signature *sig, void *opaque)
797 : {
798 0 : struct revocation_key *revkey = opaque;
799 : byte buf[2+MAX_FINGERPRINT_LEN];
800 :
801 0 : buf[0] = revkey->class;
802 0 : buf[1] = revkey->algid;
803 0 : memcpy (&buf[2], revkey->fpr, MAX_FINGERPRINT_LEN);
804 :
805 0 : build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+MAX_FINGERPRINT_LEN);
806 :
807 : /* All sigs with revocation keys set are nonrevocable. */
808 0 : sig->flags.revocable = 0;
809 0 : buf[0] = 0;
810 0 : build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
811 :
812 0 : parse_revkeys (sig);
813 :
814 0 : return 0;
815 : }
816 :
817 :
818 :
819 : /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
820 : signature creation time. */
821 : gpg_error_t
822 0 : make_backsig (PKT_signature *sig, PKT_public_key *pk,
823 : PKT_public_key *sub_pk, PKT_public_key *sub_psk,
824 : u32 timestamp, const char *cache_nonce)
825 : {
826 : gpg_error_t err;
827 : PKT_signature *backsig;
828 :
829 0 : cache_public_key (sub_pk);
830 :
831 0 : err = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_psk, 0x19,
832 : 0, timestamp, 0, NULL, NULL, cache_nonce);
833 0 : if (err)
834 0 : log_error ("make_keysig_packet failed for backsig: %s\n",
835 : gpg_strerror (err));
836 : else
837 : {
838 : /* Get it into a binary packed form. */
839 0 : IOBUF backsig_out = iobuf_temp();
840 : PACKET backsig_pkt;
841 :
842 0 : init_packet (&backsig_pkt);
843 0 : backsig_pkt.pkttype = PKT_SIGNATURE;
844 0 : backsig_pkt.pkt.signature = backsig;
845 0 : err = build_packet (backsig_out, &backsig_pkt);
846 0 : free_packet (&backsig_pkt);
847 0 : if (err)
848 0 : log_error ("build_packet failed for backsig: %s\n", gpg_strerror (err));
849 : else
850 : {
851 0 : size_t pktlen = 0;
852 0 : byte *buf = iobuf_get_temp_buffer (backsig_out);
853 :
854 : /* Remove the packet header. */
855 0 : if(buf[0]&0x40)
856 : {
857 0 : if (buf[1] < 192)
858 : {
859 0 : pktlen = buf[1];
860 0 : buf += 2;
861 : }
862 0 : else if(buf[1] < 224)
863 : {
864 0 : pktlen = (buf[1]-192)*256;
865 0 : pktlen += buf[2]+192;
866 0 : buf += 3;
867 : }
868 0 : else if (buf[1] == 255)
869 : {
870 0 : pktlen = buf32_to_size_t (buf+2);
871 0 : buf += 6;
872 : }
873 : else
874 0 : BUG ();
875 : }
876 : else
877 : {
878 0 : int mark = 1;
879 :
880 0 : switch (buf[0]&3)
881 : {
882 : case 3:
883 0 : BUG ();
884 : break;
885 :
886 : case 2:
887 0 : pktlen = (size_t)buf[mark++] << 24;
888 0 : pktlen |= buf[mark++] << 16;
889 :
890 : case 1:
891 0 : pktlen |= buf[mark++] << 8;
892 :
893 : case 0:
894 0 : pktlen |= buf[mark++];
895 : }
896 :
897 0 : buf += mark;
898 : }
899 :
900 : /* Now make the binary blob into a subpacket. */
901 0 : build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
902 :
903 0 : iobuf_close (backsig_out);
904 : }
905 : }
906 :
907 0 : return err;
908 : }
909 :
910 :
911 : /* Write a direct key signature to the first key in ROOT using the key
912 : PSK. REVKEY is describes the direct key signature and TIMESTAMP is
913 : the timestamp to set on the signature. */
914 : static gpg_error_t
915 0 : write_direct_sig (KBNODE root, PKT_public_key *psk,
916 : struct revocation_key *revkey, u32 timestamp,
917 : const char *cache_nonce)
918 : {
919 : gpg_error_t err;
920 : PACKET *pkt;
921 : PKT_signature *sig;
922 : KBNODE node;
923 : PKT_public_key *pk;
924 :
925 0 : if (opt.verbose)
926 0 : log_info (_("writing direct signature\n"));
927 :
928 : /* Get the pk packet from the pub_tree. */
929 0 : node = find_kbnode (root, PKT_PUBLIC_KEY);
930 0 : if (!node)
931 0 : BUG ();
932 0 : pk = node->pkt->pkt.public_key;
933 :
934 : /* We have to cache the key, so that the verification of the
935 : signature creation is able to retrieve the public key. */
936 0 : cache_public_key (pk);
937 :
938 : /* Make the signature. */
939 0 : err = make_keysig_packet (&sig, pk, NULL,NULL, psk, 0x1F,
940 : 0, timestamp, 0,
941 : keygen_add_revkey, revkey, cache_nonce);
942 0 : if (err)
943 : {
944 0 : log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err) );
945 0 : return err;
946 : }
947 :
948 0 : pkt = xmalloc_clear (sizeof *pkt);
949 0 : pkt->pkttype = PKT_SIGNATURE;
950 0 : pkt->pkt.signature = sig;
951 0 : add_kbnode (root, new_kbnode (pkt));
952 0 : return err;
953 : }
954 :
955 :
956 :
957 : /* Write a self-signature to the first user id in ROOT using the key
958 : PSK. USE and TIMESTAMP give the extra data we need for the
959 : signature. */
960 : static gpg_error_t
961 2 : write_selfsigs (KBNODE root, PKT_public_key *psk,
962 : unsigned int use, u32 timestamp, const char *cache_nonce)
963 : {
964 : gpg_error_t err;
965 : PACKET *pkt;
966 : PKT_signature *sig;
967 : PKT_user_id *uid;
968 : KBNODE node;
969 : PKT_public_key *pk;
970 :
971 2 : if (opt.verbose)
972 0 : log_info (_("writing self signature\n"));
973 :
974 : /* Get the uid packet from the list. */
975 2 : node = find_kbnode (root, PKT_USER_ID);
976 2 : if (!node)
977 0 : BUG(); /* No user id packet in tree. */
978 2 : uid = node->pkt->pkt.user_id;
979 :
980 : /* Get the pk packet from the pub_tree. */
981 2 : node = find_kbnode (root, PKT_PUBLIC_KEY);
982 2 : if (!node)
983 0 : BUG();
984 2 : pk = node->pkt->pkt.public_key;
985 :
986 : /* The usage has not yet been set - do it now. */
987 2 : pk->pubkey_usage = use;
988 :
989 : /* We have to cache the key, so that the verification of the
990 : signature creation is able to retrieve the public key. */
991 2 : cache_public_key (pk);
992 :
993 : /* Make the signature. */
994 2 : err = make_keysig_packet (&sig, pk, uid, NULL, psk, 0x13,
995 : 0, timestamp, 0,
996 : keygen_add_std_prefs, pk, cache_nonce);
997 2 : if (err)
998 : {
999 0 : log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
1000 0 : return err;
1001 : }
1002 :
1003 2 : pkt = xmalloc_clear (sizeof *pkt);
1004 2 : pkt->pkttype = PKT_SIGNATURE;
1005 2 : pkt->pkt.signature = sig;
1006 2 : add_kbnode (root, new_kbnode (pkt));
1007 :
1008 2 : return err;
1009 : }
1010 :
1011 :
1012 : /* Write the key binding signature. If TIMESTAMP is not NULL use the
1013 : signature creation time. PRI_PSK is the key use for signing.
1014 : SUB_PSK is a key used to create a back-signature; that one is only
1015 : used if USE has the PUBKEY_USAGE_SIG capability. */
1016 : static int
1017 1 : write_keybinding (KBNODE root, PKT_public_key *pri_psk, PKT_public_key *sub_psk,
1018 : unsigned int use, u32 timestamp, const char *cache_nonce)
1019 : {
1020 : gpg_error_t err;
1021 : PACKET *pkt;
1022 : PKT_signature *sig;
1023 : KBNODE node;
1024 : PKT_public_key *pri_pk, *sub_pk;
1025 : struct opaque_data_usage_and_pk oduap;
1026 :
1027 1 : if (opt.verbose)
1028 0 : log_info(_("writing key binding signature\n"));
1029 :
1030 : /* Get the primary pk packet from the tree. */
1031 1 : node = find_kbnode (root, PKT_PUBLIC_KEY);
1032 1 : if (!node)
1033 0 : BUG();
1034 1 : pri_pk = node->pkt->pkt.public_key;
1035 :
1036 : /* We have to cache the key, so that the verification of the
1037 : * signature creation is able to retrieve the public key. */
1038 1 : cache_public_key (pri_pk);
1039 :
1040 : /* Find the last subkey. */
1041 1 : sub_pk = NULL;
1042 6 : for (node = root; node; node = node->next )
1043 : {
1044 5 : if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1045 1 : sub_pk = node->pkt->pkt.public_key;
1046 : }
1047 1 : if (!sub_pk)
1048 0 : BUG();
1049 :
1050 : /* Make the signature. */
1051 1 : oduap.usage = use;
1052 1 : oduap.pk = sub_pk;
1053 1 : err = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
1054 : 0, timestamp, 0,
1055 : keygen_add_key_flags_and_expire, &oduap,
1056 : cache_nonce);
1057 1 : if (err)
1058 : {
1059 0 : log_error ("make_keysig_packeto failed: %s\n", gpg_strerror (err));
1060 0 : return err;
1061 : }
1062 :
1063 : /* Make a backsig. */
1064 1 : if (use & PUBKEY_USAGE_SIG)
1065 : {
1066 0 : err = make_backsig (sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
1067 0 : if (err)
1068 0 : return err;
1069 : }
1070 :
1071 1 : pkt = xmalloc_clear ( sizeof *pkt );
1072 1 : pkt->pkttype = PKT_SIGNATURE;
1073 1 : pkt->pkt.signature = sig;
1074 1 : add_kbnode (root, new_kbnode (pkt) );
1075 1 : return err;
1076 : }
1077 :
1078 :
1079 : static gpg_error_t
1080 0 : ecckey_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp, int algo)
1081 : {
1082 : gpg_error_t err;
1083 : gcry_sexp_t list, l2;
1084 : char *curve;
1085 : int i;
1086 : const char *oidstr;
1087 : unsigned int nbits;
1088 :
1089 0 : array[0] = NULL;
1090 0 : array[1] = NULL;
1091 0 : array[2] = NULL;
1092 :
1093 0 : list = gcry_sexp_find_token (sexp, "public-key", 0);
1094 0 : if (!list)
1095 0 : return gpg_error (GPG_ERR_INV_OBJ);
1096 0 : l2 = gcry_sexp_cadr (list);
1097 0 : gcry_sexp_release (list);
1098 0 : list = l2;
1099 0 : if (!list)
1100 0 : return gpg_error (GPG_ERR_NO_OBJ);
1101 :
1102 0 : l2 = gcry_sexp_find_token (list, "curve", 0);
1103 0 : if (!l2)
1104 : {
1105 0 : err = gpg_error (GPG_ERR_NO_OBJ);
1106 0 : goto leave;
1107 : }
1108 0 : curve = gcry_sexp_nth_string (l2, 1);
1109 0 : if (!curve)
1110 : {
1111 0 : err = gpg_error (GPG_ERR_NO_OBJ);
1112 0 : goto leave;
1113 : }
1114 0 : gcry_sexp_release (l2);
1115 0 : oidstr = openpgp_curve_to_oid (curve, &nbits);
1116 0 : if (!oidstr)
1117 : {
1118 : /* That can't happen because we used one of the curves
1119 : gpg_curve_to_oid knows about. */
1120 0 : err = gpg_error (GPG_ERR_INV_OBJ);
1121 0 : goto leave;
1122 : }
1123 0 : err = openpgp_oid_from_str (oidstr, &array[0]);
1124 0 : if (err)
1125 0 : goto leave;
1126 :
1127 0 : l2 = gcry_sexp_find_token (list, "q", 0);
1128 0 : if (!l2)
1129 : {
1130 0 : err = gpg_error (GPG_ERR_NO_OBJ);
1131 0 : goto leave;
1132 : }
1133 0 : array[1] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1134 0 : gcry_sexp_release (l2);
1135 0 : if (!array[1])
1136 : {
1137 0 : err = gpg_error (GPG_ERR_INV_OBJ);
1138 0 : goto leave;
1139 : }
1140 0 : gcry_sexp_release (list);
1141 :
1142 0 : if (algo == PUBKEY_ALGO_ECDH)
1143 : {
1144 0 : array[2] = pk_ecdh_default_params (nbits);
1145 0 : if (!array[2])
1146 : {
1147 0 : err = gpg_error_from_syserror ();
1148 0 : goto leave;
1149 : }
1150 : }
1151 :
1152 : leave:
1153 0 : if (err)
1154 : {
1155 0 : for (i=0; i < 3; i++)
1156 : {
1157 0 : gcry_mpi_release (array[i]);
1158 0 : array[i] = NULL;
1159 : }
1160 : }
1161 0 : return err;
1162 : }
1163 :
1164 :
1165 : /* Extract key parameters from SEXP and store them in ARRAY. ELEMS is
1166 : a string where each character denotes a parameter name. TOPNAME is
1167 : the name of the top element above the elements. */
1168 : static int
1169 3 : key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1170 : const char *topname, const char *elems)
1171 : {
1172 : gcry_sexp_t list, l2;
1173 : const char *s;
1174 : int i, idx;
1175 3 : int rc = 0;
1176 :
1177 3 : list = gcry_sexp_find_token (sexp, topname, 0);
1178 3 : if (!list)
1179 0 : return gpg_error (GPG_ERR_INV_OBJ);
1180 3 : l2 = gcry_sexp_cadr (list);
1181 3 : gcry_sexp_release (list);
1182 3 : list = l2;
1183 3 : if (!list)
1184 0 : return gpg_error (GPG_ERR_NO_OBJ);
1185 :
1186 12 : for (idx=0,s=elems; *s; s++, idx++)
1187 : {
1188 9 : l2 = gcry_sexp_find_token (list, s, 1);
1189 9 : if (!l2)
1190 : {
1191 0 : rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1192 0 : goto leave;
1193 : }
1194 9 : array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1195 9 : gcry_sexp_release (l2);
1196 9 : if (!array[idx])
1197 : {
1198 0 : rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1199 0 : goto leave;
1200 : }
1201 : }
1202 3 : gcry_sexp_release (list);
1203 :
1204 : leave:
1205 3 : if (rc)
1206 : {
1207 0 : for (i=0; i<idx; i++)
1208 : {
1209 0 : gcry_mpi_release (array[i]);
1210 0 : array[i] = NULL;
1211 : }
1212 0 : gcry_sexp_release (list);
1213 : }
1214 3 : return rc;
1215 : }
1216 :
1217 :
1218 : /* Create a keyblock using the given KEYGRIP. ALGO is the OpenPGP
1219 : algorithm of that keygrip. */
1220 : static int
1221 0 : do_create_from_keygrip (ctrl_t ctrl, int algo, const char *hexkeygrip,
1222 : kbnode_t pub_root, u32 timestamp, u32 expireval,
1223 : int is_subkey)
1224 : {
1225 : int err;
1226 : PACKET *pkt;
1227 : PKT_public_key *pk;
1228 : gcry_sexp_t s_key;
1229 : const char *algoelem;
1230 :
1231 0 : if (hexkeygrip[0] == '&')
1232 0 : hexkeygrip++;
1233 :
1234 0 : switch (algo)
1235 : {
1236 0 : case PUBKEY_ALGO_RSA: algoelem = "ne"; break;
1237 0 : case PUBKEY_ALGO_DSA: algoelem = "pqgy"; break;
1238 0 : case PUBKEY_ALGO_ELGAMAL_E: algoelem = "pgy"; break;
1239 : case PUBKEY_ALGO_ECDH:
1240 0 : case PUBKEY_ALGO_ECDSA: algoelem = ""; break;
1241 0 : case PUBKEY_ALGO_EDDSA: algoelem = ""; break;
1242 0 : default: return gpg_error (GPG_ERR_INTERNAL);
1243 : }
1244 :
1245 :
1246 : /* Ask the agent for the public key matching HEXKEYGRIP. */
1247 : {
1248 : unsigned char *public;
1249 :
1250 0 : err = agent_readkey (ctrl, 0, hexkeygrip, &public);
1251 0 : if (err)
1252 0 : return err;
1253 0 : err = gcry_sexp_sscan (&s_key, NULL,
1254 : public, gcry_sexp_canon_len (public, 0, NULL, NULL));
1255 0 : xfree (public);
1256 0 : if (err)
1257 0 : return err;
1258 : }
1259 :
1260 : /* Build a public key packet. */
1261 0 : pk = xtrycalloc (1, sizeof *pk);
1262 0 : if (!pk)
1263 : {
1264 0 : err = gpg_error_from_syserror ();
1265 0 : gcry_sexp_release (s_key);
1266 0 : return err;
1267 : }
1268 :
1269 0 : pk->timestamp = timestamp;
1270 0 : pk->version = 4;
1271 0 : if (expireval)
1272 0 : pk->expiredate = pk->timestamp + expireval;
1273 0 : pk->pubkey_algo = algo;
1274 :
1275 0 : if (algo == PUBKEY_ALGO_ECDSA
1276 0 : || algo == PUBKEY_ALGO_EDDSA
1277 0 : || algo == PUBKEY_ALGO_ECDH )
1278 0 : err = ecckey_from_sexp (pk->pkey, s_key, algo);
1279 : else
1280 0 : err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1281 0 : if (err)
1282 : {
1283 0 : log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1284 0 : gcry_sexp_release (s_key);
1285 0 : free_public_key (pk);
1286 0 : return err;
1287 : }
1288 0 : gcry_sexp_release (s_key);
1289 :
1290 0 : pkt = xtrycalloc (1, sizeof *pkt);
1291 0 : if (!pkt)
1292 : {
1293 0 : err = gpg_error_from_syserror ();
1294 0 : free_public_key (pk);
1295 0 : return err;
1296 : }
1297 :
1298 0 : pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1299 0 : pkt->pkt.public_key = pk;
1300 0 : add_kbnode (pub_root, new_kbnode (pkt));
1301 :
1302 0 : return 0;
1303 : }
1304 :
1305 :
1306 : /* Common code for the key generation function gen_xxx. */
1307 : static int
1308 3 : common_gen (const char *keyparms, int algo, const char *algoelem,
1309 : kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
1310 : int keygen_flags, const char *passphrase,
1311 : char **cache_nonce_addr, char **passwd_nonce_addr)
1312 : {
1313 : int err;
1314 : PACKET *pkt;
1315 : PKT_public_key *pk;
1316 : gcry_sexp_t s_key;
1317 :
1318 3 : err = agent_genkey (NULL, cache_nonce_addr, passwd_nonce_addr, keyparms,
1319 3 : !!(keygen_flags & KEYGEN_FLAG_NO_PROTECTION),
1320 : passphrase,
1321 : &s_key);
1322 3 : if (err)
1323 : {
1324 0 : log_error ("agent_genkey failed: %s\n", gpg_strerror (err) );
1325 0 : return err;
1326 : }
1327 :
1328 3 : pk = xtrycalloc (1, sizeof *pk);
1329 3 : if (!pk)
1330 : {
1331 0 : err = gpg_error_from_syserror ();
1332 0 : gcry_sexp_release (s_key);
1333 0 : return err;
1334 : }
1335 :
1336 3 : pk->timestamp = timestamp;
1337 3 : pk->version = 4;
1338 3 : if (expireval)
1339 3 : pk->expiredate = pk->timestamp + expireval;
1340 3 : pk->pubkey_algo = algo;
1341 :
1342 3 : if (algo == PUBKEY_ALGO_ECDSA
1343 3 : || algo == PUBKEY_ALGO_EDDSA
1344 3 : || algo == PUBKEY_ALGO_ECDH )
1345 0 : err = ecckey_from_sexp (pk->pkey, s_key, algo);
1346 : else
1347 3 : err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1348 3 : if (err)
1349 : {
1350 0 : log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1351 0 : gcry_sexp_release (s_key);
1352 0 : free_public_key (pk);
1353 0 : return err;
1354 : }
1355 3 : gcry_sexp_release (s_key);
1356 :
1357 3 : pkt = xtrycalloc (1, sizeof *pkt);
1358 3 : if (!pkt)
1359 : {
1360 0 : err = gpg_error_from_syserror ();
1361 0 : free_public_key (pk);
1362 0 : return err;
1363 : }
1364 :
1365 3 : pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1366 3 : pkt->pkt.public_key = pk;
1367 3 : add_kbnode (pub_root, new_kbnode (pkt));
1368 :
1369 3 : return 0;
1370 : }
1371 :
1372 :
1373 : /*
1374 : * Generate an Elgamal key.
1375 : */
1376 : static int
1377 1 : gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
1378 : u32 timestamp, u32 expireval, int is_subkey,
1379 : int keygen_flags, const char *passphrase,
1380 : char **cache_nonce_addr, char **passwd_nonce_addr)
1381 : {
1382 : int err;
1383 : char *keyparms;
1384 : char nbitsstr[35];
1385 :
1386 1 : log_assert (is_ELGAMAL (algo));
1387 :
1388 1 : if (nbits < 1024)
1389 : {
1390 0 : nbits = 2048;
1391 0 : log_info (_("keysize invalid; using %u bits\n"), nbits );
1392 : }
1393 1 : else if (nbits > 4096)
1394 : {
1395 0 : nbits = 4096;
1396 0 : log_info (_("keysize invalid; using %u bits\n"), nbits );
1397 : }
1398 :
1399 1 : if ((nbits % 32))
1400 : {
1401 0 : nbits = ((nbits + 31) / 32) * 32;
1402 0 : log_info (_("keysize rounded up to %u bits\n"), nbits );
1403 : }
1404 :
1405 : /* Note that we use transient-key only if no-protection has also
1406 : been enabled. */
1407 1 : snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1408 2 : keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
1409 : algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1410 0 : algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1411 : strlen (nbitsstr), nbitsstr,
1412 1 : ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1413 1 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1414 : "(transient-key)" : "" );
1415 1 : if (!keyparms)
1416 0 : err = gpg_error_from_syserror ();
1417 : else
1418 : {
1419 1 : err = common_gen (keyparms, algo, "pgy",
1420 : pub_root, timestamp, expireval, is_subkey,
1421 : keygen_flags, passphrase,
1422 : cache_nonce_addr, passwd_nonce_addr);
1423 1 : xfree (keyparms);
1424 : }
1425 :
1426 1 : return err;
1427 : }
1428 :
1429 :
1430 : /*
1431 : * Generate an DSA key
1432 : */
1433 : static gpg_error_t
1434 1 : gen_dsa (unsigned int nbits, KBNODE pub_root,
1435 : u32 timestamp, u32 expireval, int is_subkey,
1436 : int keygen_flags, const char *passphrase,
1437 : char **cache_nonce_addr, char **passwd_nonce_addr)
1438 : {
1439 : int err;
1440 : unsigned int qbits;
1441 : char *keyparms;
1442 : char nbitsstr[35];
1443 : char qbitsstr[35];
1444 :
1445 1 : if (nbits < 768)
1446 : {
1447 0 : nbits = 2048;
1448 0 : log_info(_("keysize invalid; using %u bits\n"), nbits );
1449 : }
1450 1 : else if ( nbits > 3072 )
1451 : {
1452 0 : nbits = 3072;
1453 0 : log_info(_("keysize invalid; using %u bits\n"), nbits );
1454 : }
1455 :
1456 1 : if( (nbits % 64) )
1457 : {
1458 0 : nbits = ((nbits + 63) / 64) * 64;
1459 0 : log_info(_("keysize rounded up to %u bits\n"), nbits );
1460 : }
1461 :
1462 : /* To comply with FIPS rules we round up to the next value unless in
1463 : expert mode. */
1464 1 : if (!opt.expert && nbits > 1024 && (nbits % 1024))
1465 : {
1466 0 : nbits = ((nbits + 1023) / 1024) * 1024;
1467 0 : log_info(_("keysize rounded up to %u bits\n"), nbits );
1468 : }
1469 :
1470 : /*
1471 : Figure out a q size based on the key size. FIPS 180-3 says:
1472 :
1473 : L = 1024, N = 160
1474 : L = 2048, N = 224
1475 : L = 2048, N = 256
1476 : L = 3072, N = 256
1477 :
1478 : 2048/256 is an odd pair since there is also a 2048/224 and
1479 : 3072/256. Matching sizes is not a very exact science.
1480 :
1481 : We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1482 : but less than 2048, and 160 for 1024 (DSA1).
1483 : */
1484 :
1485 1 : if (nbits > 2047)
1486 0 : qbits = 256;
1487 1 : else if ( nbits > 1024)
1488 0 : qbits = 224;
1489 : else
1490 1 : qbits = 160;
1491 :
1492 1 : if (qbits != 160 )
1493 0 : log_info (_("WARNING: some OpenPGP programs can't"
1494 : " handle a DSA key with this digest size\n"));
1495 :
1496 1 : snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1497 1 : snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
1498 2 : keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
1499 : strlen (nbitsstr), nbitsstr,
1500 : strlen (qbitsstr), qbitsstr,
1501 1 : ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1502 1 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1503 : "(transient-key)" : "" );
1504 1 : if (!keyparms)
1505 0 : err = gpg_error_from_syserror ();
1506 : else
1507 : {
1508 1 : err = common_gen (keyparms, PUBKEY_ALGO_DSA, "pqgy",
1509 : pub_root, timestamp, expireval, is_subkey,
1510 : keygen_flags, passphrase,
1511 : cache_nonce_addr, passwd_nonce_addr);
1512 1 : xfree (keyparms);
1513 : }
1514 :
1515 1 : return err;
1516 : }
1517 :
1518 :
1519 :
1520 : /*
1521 : * Generate an ECC key
1522 : */
1523 : static gpg_error_t
1524 0 : gen_ecc (int algo, const char *curve, kbnode_t pub_root,
1525 : u32 timestamp, u32 expireval, int is_subkey,
1526 : int keygen_flags, const char *passphrase,
1527 : char **cache_nonce_addr, char **passwd_nonce_addr)
1528 : {
1529 : gpg_error_t err;
1530 : char *keyparms;
1531 :
1532 0 : log_assert (algo == PUBKEY_ALGO_ECDSA
1533 : || algo == PUBKEY_ALGO_EDDSA
1534 : || algo == PUBKEY_ALGO_ECDH);
1535 :
1536 0 : if (!curve || !*curve)
1537 0 : return gpg_error (GPG_ERR_UNKNOWN_CURVE);
1538 :
1539 : /* Note that we use the "comp" flag with EdDSA to request the use of
1540 : a 0x40 compression prefix octet. */
1541 0 : if (algo == PUBKEY_ALGO_EDDSA)
1542 0 : keyparms = xtryasprintf
1543 : ("(genkey(ecc(curve %zu:%s)(flags eddsa comp%s)))",
1544 : strlen (curve), curve,
1545 0 : (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1546 0 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1547 : " transient-key" : ""));
1548 0 : else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "Curve25519"))
1549 0 : keyparms = xtryasprintf
1550 : ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
1551 : strlen (curve), curve,
1552 0 : (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1553 0 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1554 : " transient-key" : ""));
1555 : else
1556 0 : keyparms = xtryasprintf
1557 : ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
1558 : strlen (curve), curve,
1559 0 : (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1560 0 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1561 : " transient-key" : ""));
1562 :
1563 0 : if (!keyparms)
1564 0 : err = gpg_error_from_syserror ();
1565 : else
1566 : {
1567 0 : err = common_gen (keyparms, algo, "",
1568 : pub_root, timestamp, expireval, is_subkey,
1569 : keygen_flags, passphrase,
1570 : cache_nonce_addr, passwd_nonce_addr);
1571 0 : xfree (keyparms);
1572 : }
1573 :
1574 0 : return err;
1575 : }
1576 :
1577 :
1578 : /*
1579 : * Generate an RSA key.
1580 : */
1581 : static int
1582 1 : gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
1583 : u32 timestamp, u32 expireval, int is_subkey,
1584 : int keygen_flags, const char *passphrase,
1585 : char **cache_nonce_addr, char **passwd_nonce_addr)
1586 : {
1587 : int err;
1588 : char *keyparms;
1589 : char nbitsstr[35];
1590 1 : const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
1591 :
1592 1 : log_assert (is_RSA(algo));
1593 :
1594 1 : if (!nbits)
1595 0 : nbits = DEFAULT_STD_KEYSIZE;
1596 :
1597 1 : if (nbits < 1024)
1598 : {
1599 0 : nbits = 2048;
1600 0 : log_info (_("keysize invalid; using %u bits\n"), nbits );
1601 : }
1602 1 : else if (nbits > maxsize)
1603 : {
1604 0 : nbits = maxsize;
1605 0 : log_info (_("keysize invalid; using %u bits\n"), nbits );
1606 : }
1607 :
1608 1 : if ((nbits % 32))
1609 : {
1610 0 : nbits = ((nbits + 31) / 32) * 32;
1611 0 : log_info (_("keysize rounded up to %u bits\n"), nbits );
1612 : }
1613 :
1614 1 : snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1615 2 : keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
1616 : strlen (nbitsstr), nbitsstr,
1617 1 : ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1618 1 : && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1619 : "(transient-key)" : "" );
1620 1 : if (!keyparms)
1621 0 : err = gpg_error_from_syserror ();
1622 : else
1623 : {
1624 1 : err = common_gen (keyparms, algo, "ne",
1625 : pub_root, timestamp, expireval, is_subkey,
1626 : keygen_flags, passphrase,
1627 : cache_nonce_addr, passwd_nonce_addr);
1628 1 : xfree (keyparms);
1629 : }
1630 :
1631 1 : return err;
1632 : }
1633 :
1634 :
1635 : /****************
1636 : * check valid days:
1637 : * return 0 on error or the multiplier
1638 : */
1639 : static int
1640 133 : check_valid_days( const char *s )
1641 : {
1642 133 : if( !digitp(s) )
1643 0 : return 0;
1644 133 : for( s++; *s; s++)
1645 0 : if( !digitp(s) )
1646 : break;
1647 133 : if( !*s )
1648 133 : return 1;
1649 0 : if( s[1] )
1650 0 : return 0; /* e.g. "2323wc" */
1651 0 : if( *s == 'd' || *s == 'D' )
1652 0 : return 1;
1653 0 : if( *s == 'w' || *s == 'W' )
1654 0 : return 7;
1655 0 : if( *s == 'm' || *s == 'M' )
1656 0 : return 30;
1657 0 : if( *s == 'y' || *s == 'Y' )
1658 0 : return 365;
1659 0 : return 0;
1660 : }
1661 :
1662 :
1663 : static void
1664 0 : print_key_flags(int flags)
1665 : {
1666 0 : if(flags&PUBKEY_USAGE_SIG)
1667 0 : tty_printf("%s ",_("Sign"));
1668 :
1669 0 : if(flags&PUBKEY_USAGE_CERT)
1670 0 : tty_printf("%s ",_("Certify"));
1671 :
1672 0 : if(flags&PUBKEY_USAGE_ENC)
1673 0 : tty_printf("%s ",_("Encrypt"));
1674 :
1675 0 : if(flags&PUBKEY_USAGE_AUTH)
1676 0 : tty_printf("%s ",_("Authenticate"));
1677 0 : }
1678 :
1679 :
1680 : /* Ask for the key flags and return them. CURRENT gives the current
1681 : * usage which should normally be given as 0. */
1682 : unsigned int
1683 0 : ask_key_flags (int algo, int subkey, unsigned int current)
1684 : {
1685 : /* TRANSLATORS: Please use only plain ASCII characters for the
1686 : translation. If this is not possible use single digits. The
1687 : string needs to 8 bytes long. Here is a description of the
1688 : functions:
1689 :
1690 : s = Toggle signing capability
1691 : e = Toggle encryption capability
1692 : a = Toggle authentication capability
1693 : q = Finish
1694 : */
1695 0 : const char *togglers = _("SsEeAaQq");
1696 0 : char *answer = NULL;
1697 : const char *s;
1698 0 : unsigned int possible = openpgp_pk_algo_usage(algo);
1699 :
1700 0 : if ( strlen(togglers) != 8 )
1701 : {
1702 0 : tty_printf ("NOTE: Bad translation at %s:%d. "
1703 : "Please report.\n", __FILE__, __LINE__);
1704 0 : togglers = "11223300";
1705 : }
1706 :
1707 : /* Only primary keys may certify. */
1708 0 : if(subkey)
1709 0 : possible&=~PUBKEY_USAGE_CERT;
1710 :
1711 : /* Preload the current set with the possible set, minus
1712 : authentication if CURRENT has been given as 0. If CURRENT has
1713 : been has non-zero we mask with all possible usages. */
1714 0 : if (current)
1715 0 : current &= possible;
1716 : else
1717 0 : current = (possible&~PUBKEY_USAGE_AUTH);
1718 :
1719 : for(;;)
1720 : {
1721 0 : tty_printf("\n");
1722 0 : tty_printf(_("Possible actions for a %s key: "),
1723 : (algo == PUBKEY_ALGO_ECDSA
1724 0 : || algo == PUBKEY_ALGO_EDDSA)
1725 0 : ? "ECDSA/EdDSA" : openpgp_pk_algo_name (algo));
1726 0 : print_key_flags(possible);
1727 0 : tty_printf("\n");
1728 0 : tty_printf(_("Current allowed actions: "));
1729 0 : print_key_flags(current);
1730 0 : tty_printf("\n\n");
1731 :
1732 0 : if(possible&PUBKEY_USAGE_SIG)
1733 0 : tty_printf(_(" (%c) Toggle the sign capability\n"),
1734 0 : togglers[0]);
1735 0 : if(possible&PUBKEY_USAGE_ENC)
1736 0 : tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1737 0 : togglers[2]);
1738 0 : if(possible&PUBKEY_USAGE_AUTH)
1739 0 : tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1740 0 : togglers[4]);
1741 :
1742 0 : tty_printf(_(" (%c) Finished\n"),togglers[6]);
1743 0 : tty_printf("\n");
1744 :
1745 0 : xfree(answer);
1746 0 : answer = cpr_get("keygen.flags",_("Your selection? "));
1747 0 : cpr_kill_prompt();
1748 :
1749 0 : if (*answer == '=')
1750 : {
1751 : /* Hack to allow direct entry of the capabilities. */
1752 0 : current = 0;
1753 0 : for (s=answer+1; *s; s++)
1754 : {
1755 0 : if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
1756 0 : current |= PUBKEY_USAGE_SIG;
1757 0 : else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
1758 0 : current |= PUBKEY_USAGE_ENC;
1759 0 : else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
1760 0 : current |= PUBKEY_USAGE_AUTH;
1761 0 : else if (!subkey && *s == 'c')
1762 : {
1763 : /* Accept 'c' for the primary key because USAGE_CERT
1764 : will will be set anyway. This is for folks who
1765 : want to experiment with a cert-only primary key. */
1766 0 : current |= PUBKEY_USAGE_CERT;
1767 : }
1768 : }
1769 0 : break;
1770 : }
1771 0 : else if (strlen(answer)>1)
1772 0 : tty_printf(_("Invalid selection.\n"));
1773 0 : else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1774 : break;
1775 0 : else if((*answer==togglers[0] || *answer==togglers[1])
1776 0 : && possible&PUBKEY_USAGE_SIG)
1777 : {
1778 0 : if(current&PUBKEY_USAGE_SIG)
1779 0 : current&=~PUBKEY_USAGE_SIG;
1780 : else
1781 0 : current|=PUBKEY_USAGE_SIG;
1782 : }
1783 0 : else if((*answer==togglers[2] || *answer==togglers[3])
1784 0 : && possible&PUBKEY_USAGE_ENC)
1785 : {
1786 0 : if(current&PUBKEY_USAGE_ENC)
1787 0 : current&=~PUBKEY_USAGE_ENC;
1788 : else
1789 0 : current|=PUBKEY_USAGE_ENC;
1790 : }
1791 0 : else if((*answer==togglers[4] || *answer==togglers[5])
1792 0 : && possible&PUBKEY_USAGE_AUTH)
1793 : {
1794 0 : if(current&PUBKEY_USAGE_AUTH)
1795 0 : current&=~PUBKEY_USAGE_AUTH;
1796 : else
1797 0 : current|=PUBKEY_USAGE_AUTH;
1798 : }
1799 : else
1800 0 : tty_printf(_("Invalid selection.\n"));
1801 0 : }
1802 :
1803 0 : xfree(answer);
1804 :
1805 0 : return current;
1806 : }
1807 :
1808 :
1809 : /* Check whether we have a key for the key with HEXGRIP. Returns 0 if
1810 : there is no such key or the OpenPGP algo number for the key. */
1811 : static int
1812 0 : check_keygrip (ctrl_t ctrl, const char *hexgrip)
1813 : {
1814 : gpg_error_t err;
1815 : unsigned char *public;
1816 : size_t publiclen;
1817 : const char *algostr;
1818 :
1819 0 : if (hexgrip[0] == '&')
1820 0 : hexgrip++;
1821 :
1822 0 : err = agent_readkey (ctrl, 0, hexgrip, &public);
1823 0 : if (err)
1824 0 : return 0;
1825 0 : publiclen = gcry_sexp_canon_len (public, 0, NULL, NULL);
1826 :
1827 0 : get_pk_algo_from_canon_sexp (public, publiclen, &algostr);
1828 0 : xfree (public);
1829 :
1830 : /* FIXME: Mapping of ECC algorithms is probably not correct. */
1831 0 : if (!algostr)
1832 0 : return 0;
1833 0 : else if (!strcmp (algostr, "rsa"))
1834 0 : return PUBKEY_ALGO_RSA;
1835 0 : else if (!strcmp (algostr, "dsa"))
1836 0 : return PUBKEY_ALGO_DSA;
1837 0 : else if (!strcmp (algostr, "elg"))
1838 0 : return PUBKEY_ALGO_ELGAMAL_E;
1839 0 : else if (!strcmp (algostr, "ecc"))
1840 0 : return PUBKEY_ALGO_ECDH;
1841 0 : else if (!strcmp (algostr, "ecdsa"))
1842 0 : return PUBKEY_ALGO_ECDSA;
1843 0 : else if (!strcmp (algostr, "eddsa"))
1844 0 : return PUBKEY_ALGO_EDDSA;
1845 : else
1846 0 : return 0;
1847 : }
1848 :
1849 :
1850 :
1851 : /* Ask for an algorithm. The function returns the algorithm id to
1852 : * create. If ADDMODE is false the function won't show an option to
1853 : * create the primary and subkey combined and won't set R_USAGE
1854 : * either. If a combined algorithm has been selected, the subkey
1855 : * algorithm is stored at R_SUBKEY_ALGO. If R_KEYGRIP is given, the
1856 : * user has the choice to enter the keygrip of an existing key. That
1857 : * keygrip is then stored at this address. The caller needs to free
1858 : * it. */
1859 : static int
1860 0 : ask_algo (ctrl_t ctrl, int addmode, int *r_subkey_algo, unsigned int *r_usage,
1861 : char **r_keygrip)
1862 : {
1863 0 : char *keygrip = NULL;
1864 0 : char *answer = NULL;
1865 : int algo;
1866 : int dummy_algo;
1867 :
1868 0 : if (!r_subkey_algo)
1869 0 : r_subkey_algo = &dummy_algo;
1870 :
1871 0 : tty_printf (_("Please select what kind of key you want:\n"));
1872 :
1873 : #if GPG_USE_RSA
1874 0 : if (!addmode)
1875 0 : tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1876 : #endif
1877 :
1878 0 : if (!addmode)
1879 0 : tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1880 :
1881 0 : tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1882 : #if GPG_USE_RSA
1883 0 : tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1884 : #endif
1885 :
1886 0 : if (addmode)
1887 : {
1888 0 : tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1889 : #if GPG_USE_RSA
1890 0 : tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1891 : #endif
1892 : }
1893 0 : if (opt.expert)
1894 : {
1895 0 : tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1896 : #if GPG_USE_RSA
1897 0 : tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1898 : #endif
1899 : }
1900 :
1901 : #if GPG_USE_ECDSA || GPG_USE_ECDH || GPG_USE_EDDSA
1902 0 : if (opt.expert && !addmode)
1903 0 : tty_printf (_(" (%d) ECC and ECC\n"), 9 );
1904 0 : if (opt.expert)
1905 0 : tty_printf (_(" (%d) ECC (sign only)\n"), 10 );
1906 0 : if (opt.expert)
1907 0 : tty_printf (_(" (%d) ECC (set your own capabilities)\n"), 11 );
1908 0 : if (opt.expert && addmode)
1909 0 : tty_printf (_(" (%d) ECC (encrypt only)\n"), 12 );
1910 : #endif
1911 :
1912 0 : if (opt.expert && r_keygrip)
1913 0 : tty_printf (_(" (%d) Existing key\n"), 13 );
1914 :
1915 : for (;;)
1916 : {
1917 0 : *r_usage = 0;
1918 0 : *r_subkey_algo = 0;
1919 0 : xfree (answer);
1920 0 : answer = cpr_get ("keygen.algo", _("Your selection? "));
1921 0 : cpr_kill_prompt ();
1922 0 : algo = *answer? atoi (answer) : 1;
1923 0 : if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
1924 : {
1925 0 : algo = PUBKEY_ALGO_RSA;
1926 0 : *r_subkey_algo = PUBKEY_ALGO_RSA;
1927 0 : break;
1928 : }
1929 0 : else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
1930 : {
1931 0 : algo = PUBKEY_ALGO_DSA;
1932 0 : *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1933 0 : break;
1934 : }
1935 0 : else if (algo == 3 || !strcmp (answer, "dsa"))
1936 : {
1937 0 : algo = PUBKEY_ALGO_DSA;
1938 0 : *r_usage = PUBKEY_USAGE_SIG;
1939 0 : break;
1940 : }
1941 0 : else if (algo == 4 || !strcmp (answer, "rsa/s"))
1942 : {
1943 0 : algo = PUBKEY_ALGO_RSA;
1944 0 : *r_usage = PUBKEY_USAGE_SIG;
1945 0 : break;
1946 : }
1947 0 : else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
1948 : {
1949 0 : algo = PUBKEY_ALGO_ELGAMAL_E;
1950 0 : *r_usage = PUBKEY_USAGE_ENC;
1951 0 : break;
1952 : }
1953 0 : else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
1954 : {
1955 0 : algo = PUBKEY_ALGO_RSA;
1956 0 : *r_usage = PUBKEY_USAGE_ENC;
1957 0 : break;
1958 : }
1959 0 : else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
1960 : {
1961 0 : algo = PUBKEY_ALGO_DSA;
1962 0 : *r_usage = ask_key_flags (algo, addmode, 0);
1963 0 : break;
1964 : }
1965 0 : else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
1966 : {
1967 0 : algo = PUBKEY_ALGO_RSA;
1968 0 : *r_usage = ask_key_flags (algo, addmode, 0);
1969 0 : break;
1970 : }
1971 0 : else if ((algo == 9 || !strcmp (answer, "ecc+ecc"))
1972 0 : && opt.expert && !addmode)
1973 : {
1974 0 : algo = PUBKEY_ALGO_ECDSA;
1975 0 : *r_subkey_algo = PUBKEY_ALGO_ECDH;
1976 0 : break;
1977 : }
1978 0 : else if ((algo == 10 || !strcmp (answer, "ecc/s")) && opt.expert)
1979 : {
1980 0 : algo = PUBKEY_ALGO_ECDSA;
1981 0 : *r_usage = PUBKEY_USAGE_SIG;
1982 0 : break;
1983 : }
1984 0 : else if ((algo == 11 || !strcmp (answer, "ecc/*")) && opt.expert)
1985 : {
1986 0 : algo = PUBKEY_ALGO_ECDSA;
1987 0 : *r_usage = ask_key_flags (algo, addmode, 0);
1988 0 : break;
1989 : }
1990 0 : else if ((algo == 12 || !strcmp (answer, "ecc/e"))
1991 0 : && opt.expert && addmode)
1992 : {
1993 0 : algo = PUBKEY_ALGO_ECDH;
1994 0 : *r_usage = PUBKEY_USAGE_ENC;
1995 0 : break;
1996 : }
1997 0 : else if ((algo == 13 || !strcmp (answer, "keygrip"))
1998 0 : && opt.expert && r_keygrip)
1999 : {
2000 : for (;;)
2001 : {
2002 0 : xfree (answer);
2003 0 : answer = tty_get (_("Enter the keygrip: "));
2004 0 : tty_kill_prompt ();
2005 0 : trim_spaces (answer);
2006 0 : if (!*answer)
2007 : {
2008 0 : xfree (answer);
2009 0 : answer = NULL;
2010 0 : continue;
2011 : }
2012 :
2013 0 : if (strlen (answer) != 40 &&
2014 0 : !(answer[0] == '&' && strlen (answer+1) == 40))
2015 0 : tty_printf
2016 0 : (_("Not a valid keygrip (expecting 40 hex digits)\n"));
2017 0 : else if (!(algo = check_keygrip (ctrl, answer)) )
2018 0 : tty_printf (_("No key with this keygrip\n"));
2019 : else
2020 0 : break; /* Okay. */
2021 0 : }
2022 0 : xfree (keygrip);
2023 0 : keygrip = answer;
2024 0 : answer = NULL;
2025 0 : *r_usage = ask_key_flags (algo, addmode, 0);
2026 0 : break;
2027 : }
2028 : else
2029 0 : tty_printf (_("Invalid selection.\n"));
2030 :
2031 0 : }
2032 :
2033 0 : xfree(answer);
2034 0 : if (r_keygrip)
2035 0 : *r_keygrip = keygrip;
2036 0 : return algo;
2037 : }
2038 :
2039 :
2040 : static void
2041 0 : get_keysize_range (int algo,
2042 : unsigned int *min, unsigned int *def, unsigned int *max)
2043 : {
2044 0 : *min = 1024;
2045 0 : *def = DEFAULT_STD_KEYSIZE;
2046 0 : *max = 4096;
2047 :
2048 : /* Deviations from the standard values. */
2049 0 : switch(algo)
2050 : {
2051 : case PUBKEY_ALGO_DSA:
2052 0 : *min = opt.expert? 768 : 1024;
2053 0 : *def=2048;
2054 0 : *max=3072;
2055 0 : break;
2056 :
2057 : case PUBKEY_ALGO_ECDSA:
2058 : case PUBKEY_ALGO_ECDH:
2059 0 : *min=256;
2060 0 : *def=256;
2061 0 : *max=521;
2062 0 : break;
2063 :
2064 : case PUBKEY_ALGO_EDDSA:
2065 0 : *min=255;
2066 0 : *def=255;
2067 0 : *max=441;
2068 0 : break;
2069 : }
2070 0 : }
2071 :
2072 :
2073 : /* Return a fixed up keysize depending on ALGO. */
2074 : static unsigned int
2075 0 : fixup_keysize (unsigned int nbits, int algo, int silent)
2076 : {
2077 0 : if (algo == PUBKEY_ALGO_DSA && (nbits % 64))
2078 : {
2079 0 : nbits = ((nbits + 63) / 64) * 64;
2080 0 : if (!silent)
2081 0 : tty_printf (_("rounded up to %u bits\n"), nbits);
2082 : }
2083 0 : else if (algo == PUBKEY_ALGO_EDDSA)
2084 : {
2085 0 : if (nbits != 255 && nbits != 441)
2086 : {
2087 0 : if (nbits < 256)
2088 0 : nbits = 255;
2089 : else
2090 0 : nbits = 441;
2091 0 : if (!silent)
2092 0 : tty_printf (_("rounded to %u bits\n"), nbits);
2093 : }
2094 : }
2095 0 : else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2096 : {
2097 0 : if (nbits != 256 && nbits != 384 && nbits != 521)
2098 : {
2099 0 : if (nbits < 256)
2100 0 : nbits = 256;
2101 0 : else if (nbits < 384)
2102 0 : nbits = 384;
2103 : else
2104 0 : nbits = 521;
2105 0 : if (!silent)
2106 0 : tty_printf (_("rounded to %u bits\n"), nbits);
2107 : }
2108 : }
2109 0 : else if ((nbits % 32))
2110 : {
2111 0 : nbits = ((nbits + 31) / 32) * 32;
2112 0 : if (!silent)
2113 0 : tty_printf (_("rounded up to %u bits\n"), nbits );
2114 : }
2115 :
2116 0 : return nbits;
2117 : }
2118 :
2119 :
2120 : /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
2121 : is not 0, the function asks for the size of the encryption
2122 : subkey. */
2123 : static unsigned
2124 0 : ask_keysize (int algo, unsigned int primary_keysize)
2125 : {
2126 : unsigned int nbits;
2127 : unsigned int min, def, max;
2128 0 : int for_subkey = !!primary_keysize;
2129 0 : int autocomp = 0;
2130 :
2131 0 : get_keysize_range (algo, &min, &def, &max);
2132 :
2133 0 : if (primary_keysize && !opt.expert)
2134 : {
2135 : /* Deduce the subkey size from the primary key size. */
2136 0 : if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
2137 0 : nbits = 3072; /* For performance reasons we don't support more
2138 : than 3072 bit DSA. However we won't see this
2139 : case anyway because DSA can't be used as an
2140 : encryption subkey ;-). */
2141 : else
2142 0 : nbits = primary_keysize;
2143 0 : autocomp = 1;
2144 0 : goto leave;
2145 : }
2146 :
2147 0 : tty_printf(_("%s keys may be between %u and %u bits long.\n"),
2148 : openpgp_pk_algo_name (algo), min, max);
2149 :
2150 : for (;;)
2151 : {
2152 : char *prompt, *answer;
2153 :
2154 0 : if (for_subkey)
2155 0 : prompt = xasprintf (_("What keysize do you want "
2156 : "for the subkey? (%u) "), def);
2157 : else
2158 0 : prompt = xasprintf (_("What keysize do you want? (%u) "), def);
2159 0 : answer = cpr_get ("keygen.size", prompt);
2160 0 : cpr_kill_prompt ();
2161 0 : nbits = *answer? atoi (answer): def;
2162 0 : xfree(prompt);
2163 0 : xfree(answer);
2164 :
2165 0 : if(nbits<min || nbits>max)
2166 0 : tty_printf(_("%s keysizes must be in the range %u-%u\n"),
2167 : openpgp_pk_algo_name (algo), min, max);
2168 : else
2169 : break;
2170 0 : }
2171 :
2172 0 : tty_printf (_("Requested keysize is %u bits\n"), nbits);
2173 :
2174 : leave:
2175 0 : nbits = fixup_keysize (nbits, algo, autocomp);
2176 0 : return nbits;
2177 : }
2178 :
2179 :
2180 : /* Ask for the curve. ALGO is the selected algorithm which this
2181 : function may adjust. Returns a malloced string with the name of
2182 : the curve. BOTH tells that gpg creates a primary and subkey. */
2183 : static char *
2184 0 : ask_curve (int *algo, int *subkey_algo)
2185 : {
2186 : /* NB: We always use a complete algo list so that we have stable
2187 : numbers in the menu regardless on how Gpg was configured. */
2188 : struct {
2189 : const char *name;
2190 : int available; /* Available in Libycrypt (runtime checked) */
2191 : int expert_only;
2192 : const char* eddsa_curve; /* Corresponding EdDSA curve. */
2193 : const char *pretty_name;
2194 : int supported; /* Supported by gpg. */
2195 0 : } curves[] = {
2196 : #if GPG_USE_ECDSA || GPG_USE_ECDH
2197 : # define MY_USE_ECDSADH 1
2198 : #else
2199 : # define MY_USE_ECDSADH 0
2200 : #endif
2201 : { "Curve25519", 0, 0, "Ed25519", "Curve 25519", GPG_USE_EDDSA },
2202 : { "Curve448", 0, 1, "Ed448", "Curve 448", 0/*reserved*/ },
2203 : { "NIST P-256", 0, 1, NULL, NULL, MY_USE_ECDSADH },
2204 : { "NIST P-384", 0, 0, NULL, NULL, MY_USE_ECDSADH },
2205 : { "NIST P-521", 0, 1, NULL, NULL, MY_USE_ECDSADH },
2206 : { "brainpoolP256r1", 0, 1, NULL, "Brainpool P-256", MY_USE_ECDSADH },
2207 : { "brainpoolP384r1", 0, 1, NULL, "Brainpool P-384", MY_USE_ECDSADH },
2208 : { "brainpoolP512r1", 0, 1, NULL, "Brainpool P-512", MY_USE_ECDSADH },
2209 : { "secp256k1", 0, 1, NULL, NULL, MY_USE_ECDSADH },
2210 : };
2211 : #undef MY_USE_ECDSADH
2212 : int idx;
2213 : char *answer;
2214 0 : char *result = NULL;
2215 : gcry_sexp_t keyparms;
2216 :
2217 0 : tty_printf (_("Please select which elliptic curve you want:\n"));
2218 :
2219 0 : keyparms = NULL;
2220 0 : for (idx=0; idx < DIM(curves); idx++)
2221 : {
2222 : int rc;
2223 :
2224 0 : curves[idx].available = 0;
2225 0 : if (!curves[idx].supported)
2226 0 : continue;
2227 0 : if (!opt.expert && curves[idx].expert_only)
2228 0 : continue;
2229 :
2230 : /* We need to switch from the ECDH name of the curve to the
2231 : EDDSA name of the curve if we want a signing key. */
2232 0 : gcry_sexp_release (keyparms);
2233 0 : rc = gcry_sexp_build (&keyparms, NULL,
2234 : "(public-key(ecc(curve %s)))",
2235 0 : curves[idx].eddsa_curve? curves[idx].eddsa_curve
2236 : /**/ : curves[idx].name);
2237 0 : if (rc)
2238 0 : continue;
2239 0 : if (!gcry_pk_get_curve (keyparms, 0, NULL))
2240 0 : continue;
2241 0 : if (subkey_algo && curves[idx].eddsa_curve)
2242 : {
2243 : /* Both Curve 25519 (or 448) keys are to be created. Check that
2244 : Libgcrypt also supports the real Curve25519 (or 448). */
2245 0 : gcry_sexp_release (keyparms);
2246 0 : rc = gcry_sexp_build (&keyparms, NULL,
2247 : "(public-key(ecc(curve %s)))",
2248 : curves[idx].name);
2249 0 : if (rc)
2250 0 : continue;
2251 0 : if (!gcry_pk_get_curve (keyparms, 0, NULL))
2252 0 : continue;
2253 : }
2254 :
2255 0 : curves[idx].available = 1;
2256 0 : tty_printf (" (%d) %s\n", idx + 1,
2257 0 : curves[idx].pretty_name?
2258 : curves[idx].pretty_name:curves[idx].name);
2259 : }
2260 0 : gcry_sexp_release (keyparms);
2261 :
2262 :
2263 : for (;;)
2264 : {
2265 0 : answer = cpr_get ("keygen.curve", _("Your selection? "));
2266 0 : cpr_kill_prompt ();
2267 0 : idx = *answer? atoi (answer) : 1;
2268 0 : if (*answer && !idx)
2269 : {
2270 : /* See whether the user entered the name of the curve. */
2271 0 : for (idx=0; idx < DIM(curves); idx++)
2272 : {
2273 0 : if (!opt.expert && curves[idx].expert_only)
2274 0 : continue;
2275 0 : if (!stricmp (curves[idx].name, answer)
2276 0 : || (curves[idx].pretty_name
2277 0 : && !stricmp (curves[idx].pretty_name, answer)))
2278 : break;
2279 : }
2280 0 : if (idx == DIM(curves))
2281 0 : idx = -1;
2282 : }
2283 : else
2284 0 : idx--;
2285 0 : xfree(answer);
2286 0 : answer = NULL;
2287 0 : if (idx < 0 || idx >= DIM (curves) || !curves[idx].available)
2288 0 : tty_printf (_("Invalid selection.\n"));
2289 : else
2290 : {
2291 : /* If the user selected a signing algorithm and Curve25519
2292 : we need to set the algo to EdDSA and update the curve name. */
2293 0 : if ((*algo == PUBKEY_ALGO_ECDSA || *algo == PUBKEY_ALGO_EDDSA)
2294 0 : && curves[idx].eddsa_curve)
2295 : {
2296 0 : if (subkey_algo && *subkey_algo == PUBKEY_ALGO_ECDSA)
2297 0 : *subkey_algo = PUBKEY_ALGO_EDDSA;
2298 0 : *algo = PUBKEY_ALGO_EDDSA;
2299 0 : result = xstrdup (curves[idx].eddsa_curve);
2300 : }
2301 : else
2302 0 : result = xstrdup (curves[idx].name);
2303 0 : break;
2304 : }
2305 0 : }
2306 :
2307 0 : if (!result)
2308 0 : result = xstrdup (curves[0].name);
2309 :
2310 0 : return result;
2311 : }
2312 :
2313 :
2314 : /****************
2315 : * Parse an expire string and return its value in seconds.
2316 : * Returns (u32)-1 on error.
2317 : * This isn't perfect since scan_isodatestr returns unix time, and
2318 : * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
2319 : * Because of this, we only permit setting expirations up to 2106, but
2320 : * OpenPGP could theoretically allow up to 2242. I think we'll all
2321 : * just cope for the next few years until we get a 64-bit time_t or
2322 : * similar.
2323 : */
2324 : u32
2325 133 : parse_expire_string( const char *string )
2326 : {
2327 : int mult;
2328 : u32 seconds;
2329 133 : u32 abs_date = 0;
2330 133 : u32 curtime = make_timestamp ();
2331 : time_t tt;
2332 :
2333 133 : if (!*string)
2334 0 : seconds = 0;
2335 133 : else if (!strncmp (string, "seconds=", 8))
2336 0 : seconds = atoi (string+8);
2337 133 : else if ((abs_date = scan_isodatestr(string))
2338 0 : && (abs_date+86400/2) > curtime)
2339 0 : seconds = (abs_date+86400/2) - curtime;
2340 133 : else if ((tt = isotime2epoch (string)) != (time_t)(-1))
2341 0 : seconds = (u32)tt - curtime;
2342 133 : else if ((mult = check_valid_days (string)))
2343 133 : seconds = atoi (string) * 86400L * mult;
2344 : else
2345 0 : seconds = (u32)(-1);
2346 :
2347 133 : return seconds;
2348 : }
2349 :
2350 : /* Parsean Creation-Date string which is either "1986-04-26" or
2351 : "19860426T042640". Returns 0 on error. */
2352 : static u32
2353 0 : parse_creation_string (const char *string)
2354 : {
2355 : u32 seconds;
2356 :
2357 0 : if (!*string)
2358 0 : seconds = 0;
2359 0 : else if ( !strncmp (string, "seconds=", 8) )
2360 0 : seconds = atoi (string+8);
2361 0 : else if ( !(seconds = scan_isodatestr (string)))
2362 : {
2363 0 : time_t tmp = isotime2epoch (string);
2364 0 : seconds = (tmp == (time_t)(-1))? 0 : tmp;
2365 : }
2366 0 : return seconds;
2367 : }
2368 :
2369 :
2370 : /* object == 0 for a key, and 1 for a sig */
2371 : u32
2372 0 : ask_expire_interval(int object,const char *def_expire)
2373 : {
2374 : u32 interval;
2375 : char *answer;
2376 :
2377 0 : switch(object)
2378 : {
2379 : case 0:
2380 0 : if(def_expire)
2381 0 : BUG();
2382 0 : tty_printf(_("Please specify how long the key should be valid.\n"
2383 : " 0 = key does not expire\n"
2384 : " <n> = key expires in n days\n"
2385 : " <n>w = key expires in n weeks\n"
2386 : " <n>m = key expires in n months\n"
2387 : " <n>y = key expires in n years\n"));
2388 0 : break;
2389 :
2390 : case 1:
2391 0 : if(!def_expire)
2392 0 : BUG();
2393 0 : tty_printf(_("Please specify how long the signature should be valid.\n"
2394 : " 0 = signature does not expire\n"
2395 : " <n> = signature expires in n days\n"
2396 : " <n>w = signature expires in n weeks\n"
2397 : " <n>m = signature expires in n months\n"
2398 : " <n>y = signature expires in n years\n"));
2399 0 : break;
2400 :
2401 : default:
2402 0 : BUG();
2403 : }
2404 :
2405 : /* Note: The elgamal subkey for DSA has no expiration date because
2406 : * it must be signed with the DSA key and this one has the expiration
2407 : * date */
2408 :
2409 0 : answer = NULL;
2410 : for(;;)
2411 : {
2412 : u32 curtime;
2413 :
2414 0 : xfree(answer);
2415 0 : if(object==0)
2416 0 : answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
2417 : else
2418 : {
2419 : char *prompt;
2420 :
2421 : #define PROMPTSTRING _("Signature is valid for? (%s) ")
2422 : /* This will actually end up larger than necessary because
2423 : of the 2 bytes for '%s' */
2424 0 : prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
2425 0 : sprintf(prompt,PROMPTSTRING,def_expire);
2426 : #undef PROMPTSTRING
2427 :
2428 0 : answer = cpr_get("siggen.valid",prompt);
2429 0 : xfree(prompt);
2430 :
2431 0 : if(*answer=='\0')
2432 0 : answer=xstrdup(def_expire);
2433 : }
2434 0 : cpr_kill_prompt();
2435 0 : trim_spaces(answer);
2436 0 : curtime = make_timestamp ();
2437 0 : interval = parse_expire_string( answer );
2438 0 : if( interval == (u32)-1 )
2439 : {
2440 0 : tty_printf(_("invalid value\n"));
2441 0 : continue;
2442 : }
2443 :
2444 0 : if( !interval )
2445 : {
2446 0 : tty_printf((object==0)
2447 : ? _("Key does not expire at all\n")
2448 : : _("Signature does not expire at all\n"));
2449 : }
2450 : else
2451 : {
2452 0 : tty_printf(object==0
2453 : ? _("Key expires at %s\n")
2454 : : _("Signature expires at %s\n"),
2455 : asctimestamp((ulong)(curtime + interval) ) );
2456 : #if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
2457 : if ( (time_t)((ulong)(curtime+interval)) < 0 )
2458 : tty_printf (_("Your system can't display dates beyond 2038.\n"
2459 : "However, it will be correctly handled up to"
2460 : " 2106.\n"));
2461 : else
2462 : #endif /*SIZEOF_TIME_T*/
2463 0 : if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
2464 : {
2465 0 : tty_printf (_("invalid value\n"));
2466 0 : continue;
2467 : }
2468 : }
2469 :
2470 0 : if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2471 0 : _("Is this correct? (y/N) ")) )
2472 : break;
2473 0 : }
2474 :
2475 0 : xfree(answer);
2476 0 : return interval;
2477 : }
2478 :
2479 : u32
2480 0 : ask_expiredate()
2481 : {
2482 0 : u32 x = ask_expire_interval(0,NULL);
2483 0 : return x? make_timestamp() + x : 0;
2484 : }
2485 :
2486 :
2487 :
2488 : static PKT_user_id *
2489 0 : uid_from_string (const char *string)
2490 : {
2491 : size_t n;
2492 : PKT_user_id *uid;
2493 :
2494 0 : n = strlen (string);
2495 0 : uid = xmalloc_clear (sizeof *uid + n);
2496 0 : uid->len = n;
2497 0 : strcpy (uid->name, string);
2498 0 : uid->ref = 1;
2499 0 : return uid;
2500 : }
2501 :
2502 :
2503 : /* Return true if the user id UID already exists in the keyblock. */
2504 : static int
2505 0 : uid_already_in_keyblock (kbnode_t keyblock, const char *uid)
2506 : {
2507 0 : PKT_user_id *uidpkt = uid_from_string (uid);
2508 : kbnode_t node;
2509 0 : int result = 0;
2510 :
2511 0 : for (node=keyblock; node && !result; node=node->next)
2512 0 : if (!is_deleted_kbnode (node)
2513 0 : && node->pkt->pkttype == PKT_USER_ID
2514 0 : && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2515 0 : result = 1;
2516 0 : free_user_id (uidpkt);
2517 0 : return result;
2518 : }
2519 :
2520 :
2521 : /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2522 : printed for use during a new key creation. If KEYBLOCK is not NULL
2523 : the function prevents the creation of an already existing user
2524 : ID. IF FULL is not set some prompts are not shown. */
2525 : static char *
2526 0 : ask_user_id (int mode, int full, KBNODE keyblock)
2527 : {
2528 : char *answer;
2529 : char *aname, *acomment, *amail, *uid;
2530 :
2531 0 : if ( !mode )
2532 : {
2533 : /* TRANSLATORS: This is the new string telling the user what
2534 : gpg is now going to do (i.e. ask for the parts of the user
2535 : ID). Note that if you do not translate this string, a
2536 : different string will be used, which might still have
2537 : a correct translation. */
2538 0 : const char *s1 =
2539 : N_("\n"
2540 : "GnuPG needs to construct a user ID to identify your key.\n"
2541 : "\n");
2542 0 : const char *s2 = _(s1);
2543 :
2544 0 : if (!strcmp (s1, s2))
2545 : {
2546 : /* There is no translation for the string thus we to use
2547 : the old info text. gettext has no way to tell whether
2548 : a translation is actually available, thus we need to
2549 : to compare again. */
2550 : /* TRANSLATORS: This string is in general not anymore used
2551 : but you should keep your existing translation. In case
2552 : the new string is not translated this old string will
2553 : be used. */
2554 0 : const char *s3 = N_("\n"
2555 : "You need a user ID to identify your key; "
2556 : "the software constructs the user ID\n"
2557 : "from the Real Name, Comment and Email Address in this form:\n"
2558 : " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2559 0 : const char *s4 = _(s3);
2560 0 : if (strcmp (s3, s4))
2561 0 : s2 = s3; /* A translation exists - use it. */
2562 : }
2563 0 : tty_printf ("%s", s2) ;
2564 : }
2565 0 : uid = aname = acomment = amail = NULL;
2566 : for(;;) {
2567 : char *p;
2568 0 : int fail=0;
2569 :
2570 0 : if( !aname ) {
2571 : for(;;) {
2572 0 : xfree(aname);
2573 0 : aname = cpr_get("keygen.name",_("Real name: "));
2574 0 : trim_spaces(aname);
2575 0 : cpr_kill_prompt();
2576 :
2577 0 : if( opt.allow_freeform_uid )
2578 0 : break;
2579 :
2580 0 : if( strpbrk( aname, "<>" ) )
2581 : {
2582 0 : tty_printf(_("Invalid character in name\n"));
2583 0 : tty_printf(_("The characters '%s' and '%s' may not "
2584 : "appear in name\n"), "<", ">");
2585 : }
2586 0 : else if( digitp(aname) )
2587 0 : tty_printf(_("Name may not start with a digit\n"));
2588 0 : else if (*aname && strlen (aname) < 5)
2589 : {
2590 0 : tty_printf(_("Name must be at least 5 characters long\n"));
2591 : /* However, we allow an empty name. */
2592 : }
2593 : else
2594 : break;
2595 0 : }
2596 : }
2597 0 : if( !amail ) {
2598 : for(;;) {
2599 0 : xfree(amail);
2600 0 : amail = cpr_get("keygen.email",_("Email address: "));
2601 0 : trim_spaces(amail);
2602 0 : cpr_kill_prompt();
2603 0 : if( !*amail || opt.allow_freeform_uid )
2604 : break; /* no email address is okay */
2605 0 : else if ( !is_valid_mailbox (amail) )
2606 0 : tty_printf(_("Not a valid email address\n"));
2607 : else
2608 0 : break;
2609 0 : }
2610 : }
2611 0 : if (!acomment) {
2612 0 : if (full) {
2613 : for(;;) {
2614 0 : xfree(acomment);
2615 0 : acomment = cpr_get("keygen.comment",_("Comment: "));
2616 0 : trim_spaces(acomment);
2617 0 : cpr_kill_prompt();
2618 0 : if( !*acomment )
2619 0 : break; /* no comment is okay */
2620 0 : else if( strpbrk( acomment, "()" ) )
2621 0 : tty_printf(_("Invalid character in comment\n"));
2622 : else
2623 0 : break;
2624 0 : }
2625 : }
2626 : else {
2627 0 : xfree (acomment);
2628 0 : acomment = xstrdup ("");
2629 : }
2630 : }
2631 :
2632 :
2633 0 : xfree(uid);
2634 0 : uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2635 0 : if (!*aname && *amail && !*acomment && !random_is_faked ())
2636 : { /* Empty name and comment but with mail address. Use
2637 : simplified form with only the non-angle-bracketed mail
2638 : address. */
2639 0 : p = stpcpy (p, amail);
2640 : }
2641 : else
2642 : {
2643 0 : p = stpcpy (p, aname );
2644 0 : if (*acomment)
2645 0 : p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2646 0 : if (*amail)
2647 0 : p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2648 : }
2649 :
2650 : /* Append a warning if the RNG is switched into fake mode. */
2651 0 : if ( random_is_faked () )
2652 0 : strcpy(p, " (insecure!)" );
2653 :
2654 : /* print a note in case that UTF8 mapping has to be done */
2655 0 : for(p=uid; *p; p++ ) {
2656 0 : if( *p & 0x80 ) {
2657 0 : tty_printf(_("You are using the '%s' character set.\n"),
2658 : get_native_charset() );
2659 0 : break;
2660 : }
2661 : }
2662 :
2663 0 : tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2664 :
2665 0 : if( !*amail && !opt.allow_freeform_uid
2666 0 : && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2667 0 : fail = 1;
2668 0 : tty_printf(_("Please don't put the email address "
2669 : "into the real name or the comment\n") );
2670 : }
2671 :
2672 0 : if (!fail && keyblock)
2673 : {
2674 0 : if (uid_already_in_keyblock (keyblock, uid))
2675 : {
2676 0 : tty_printf (_("Such a user ID already exists on this key!\n"));
2677 0 : fail = 1;
2678 : }
2679 : }
2680 :
2681 : for(;;) {
2682 : /* TRANSLATORS: These are the allowed answers in
2683 : lower and uppercase. Below you will find the matching
2684 : string which should be translated accordingly and the
2685 : letter changed to match the one in the answer string.
2686 :
2687 : n = Change name
2688 : c = Change comment
2689 : e = Change email
2690 : o = Okay (ready, continue)
2691 : q = Quit
2692 : */
2693 0 : const char *ansstr = _("NnCcEeOoQq");
2694 :
2695 0 : if( strlen(ansstr) != 10 )
2696 0 : BUG();
2697 0 : if( cpr_enabled() ) {
2698 0 : answer = xstrdup (ansstr + (fail?8:6));
2699 0 : answer[1] = 0;
2700 : }
2701 0 : else if (full) {
2702 0 : answer = cpr_get("keygen.userid.cmd", fail?
2703 : _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2704 : _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2705 0 : cpr_kill_prompt();
2706 : }
2707 : else {
2708 0 : answer = cpr_get("keygen.userid.cmd", fail?
2709 : _("Change (N)ame, (E)mail, or (Q)uit? ") :
2710 : _("Change (N)ame, (E)mail, or (O)kay/(Q)uit? "));
2711 0 : cpr_kill_prompt();
2712 : }
2713 0 : if( strlen(answer) > 1 )
2714 : ;
2715 0 : else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2716 0 : xfree(aname); aname = NULL;
2717 0 : break;
2718 : }
2719 0 : else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2720 0 : xfree(acomment); acomment = NULL;
2721 0 : break;
2722 : }
2723 0 : else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2724 0 : xfree(amail); amail = NULL;
2725 0 : break;
2726 : }
2727 0 : else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2728 0 : if( fail ) {
2729 0 : tty_printf(_("Please correct the error first\n"));
2730 : }
2731 : else {
2732 0 : xfree(aname); aname = NULL;
2733 0 : xfree(acomment); acomment = NULL;
2734 0 : xfree(amail); amail = NULL;
2735 0 : break;
2736 : }
2737 : }
2738 0 : else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2739 0 : xfree(aname); aname = NULL;
2740 0 : xfree(acomment); acomment = NULL;
2741 0 : xfree(amail); amail = NULL;
2742 0 : xfree(uid); uid = NULL;
2743 0 : break;
2744 : }
2745 0 : xfree(answer);
2746 0 : }
2747 0 : xfree(answer);
2748 0 : if (!amail && !acomment)
2749 0 : break;
2750 0 : xfree(uid); uid = NULL;
2751 0 : }
2752 0 : if( uid ) {
2753 0 : char *p = native_to_utf8( uid );
2754 0 : xfree( uid );
2755 0 : uid = p;
2756 : }
2757 0 : return uid;
2758 : }
2759 :
2760 :
2761 : /* Basic key generation. Here we divert to the actual generation
2762 : routines based on the requested algorithm. */
2763 : static int
2764 3 : do_create (int algo, unsigned int nbits, const char *curve, KBNODE pub_root,
2765 : u32 timestamp, u32 expiredate, int is_subkey,
2766 : int keygen_flags, const char *passphrase,
2767 : char **cache_nonce_addr, char **passwd_nonce_addr)
2768 : {
2769 : gpg_error_t err;
2770 :
2771 : /* Fixme: The entropy collecting message should be moved to a
2772 : libgcrypt progress handler. */
2773 3 : if (!opt.batch)
2774 0 : tty_printf (_(
2775 : "We need to generate a lot of random bytes. It is a good idea to perform\n"
2776 : "some other action (type on the keyboard, move the mouse, utilize the\n"
2777 : "disks) during the prime generation; this gives the random number\n"
2778 : "generator a better chance to gain enough entropy.\n") );
2779 :
2780 3 : if (algo == PUBKEY_ALGO_ELGAMAL_E)
2781 1 : err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2782 : keygen_flags, passphrase,
2783 : cache_nonce_addr, passwd_nonce_addr);
2784 2 : else if (algo == PUBKEY_ALGO_DSA)
2785 1 : err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
2786 : keygen_flags, passphrase,
2787 : cache_nonce_addr, passwd_nonce_addr);
2788 1 : else if (algo == PUBKEY_ALGO_ECDSA
2789 1 : || algo == PUBKEY_ALGO_EDDSA
2790 1 : || algo == PUBKEY_ALGO_ECDH)
2791 0 : err = gen_ecc (algo, curve, pub_root, timestamp, expiredate, is_subkey,
2792 : keygen_flags, passphrase,
2793 : cache_nonce_addr, passwd_nonce_addr);
2794 1 : else if (algo == PUBKEY_ALGO_RSA)
2795 1 : err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2796 : keygen_flags, passphrase,
2797 : cache_nonce_addr, passwd_nonce_addr);
2798 : else
2799 0 : BUG();
2800 :
2801 3 : return err;
2802 : }
2803 :
2804 :
2805 : /* Generate a new user id packet or return NULL if canceled. If
2806 : KEYBLOCK is not NULL the function prevents the creation of an
2807 : already existing user ID. If UIDSTR is not NULL the user is not
2808 : asked but UIDSTR is used to create the user id packet; if the user
2809 : id already exists NULL is returned. UIDSTR is expected to be utf-8
2810 : encoded and should have already been checked for a valid length
2811 : etc. */
2812 : PKT_user_id *
2813 0 : generate_user_id (KBNODE keyblock, const char *uidstr)
2814 : {
2815 : PKT_user_id *uid;
2816 : char *p;
2817 :
2818 0 : if (uidstr)
2819 : {
2820 0 : if (uid_already_in_keyblock (keyblock, uidstr))
2821 0 : return NULL; /* Already exists. */
2822 0 : uid = uid_from_string (uidstr);
2823 : }
2824 : else
2825 : {
2826 0 : p = ask_user_id (1, 1, keyblock);
2827 0 : if (!p)
2828 0 : return NULL; /* Canceled. */
2829 0 : uid = uid_from_string (p);
2830 0 : xfree (p);
2831 : }
2832 0 : return uid;
2833 : }
2834 :
2835 :
2836 : /* Append R to the linked list PARA. */
2837 : static void
2838 6 : append_to_parameter (struct para_data_s *para, struct para_data_s *r)
2839 : {
2840 6 : log_assert (para);
2841 59 : while (para->next)
2842 47 : para = para->next;
2843 6 : para->next = r;
2844 6 : }
2845 :
2846 : /* Release the parameter list R. */
2847 : static void
2848 4 : release_parameter_list (struct para_data_s *r)
2849 : {
2850 : struct para_data_s *r2;
2851 :
2852 25 : for (; r ; r = r2)
2853 : {
2854 21 : r2 = r->next;
2855 21 : if (r->key == pPASSPHRASE && *r->u.value)
2856 0 : wipememory (r->u.value, strlen (r->u.value));
2857 21 : xfree (r);
2858 : }
2859 4 : }
2860 :
2861 : static struct para_data_s *
2862 61 : get_parameter( struct para_data_s *para, enum para_name key )
2863 : {
2864 : struct para_data_s *r;
2865 :
2866 61 : for( r = para; r && r->key != key; r = r->next )
2867 : ;
2868 61 : return r;
2869 : }
2870 :
2871 : static const char *
2872 19 : get_parameter_value( struct para_data_s *para, enum para_name key )
2873 : {
2874 19 : struct para_data_s *r = get_parameter( para, key );
2875 19 : return (r && *r->u.value)? r->u.value : NULL;
2876 : }
2877 :
2878 :
2879 : /* This is similar to get_parameter_value but also returns the empty
2880 : string. This is required so that quick_generate_keypair can use an
2881 : empty Passphrase to specify no-protection. */
2882 : static const char *
2883 3 : get_parameter_passphrase (struct para_data_s *para)
2884 : {
2885 3 : struct para_data_s *r = get_parameter (para, pPASSPHRASE);
2886 3 : return r ? r->u.value : NULL;
2887 : }
2888 :
2889 :
2890 : static int
2891 8 : get_parameter_algo( struct para_data_s *para, enum para_name key,
2892 : int *r_default)
2893 : {
2894 : int i;
2895 8 : struct para_data_s *r = get_parameter( para, key );
2896 :
2897 8 : if (r_default)
2898 3 : *r_default = 0;
2899 :
2900 8 : if (!r)
2901 0 : return -1;
2902 :
2903 : /* Note that we need to handle the ECC algorithms specified as
2904 : strings directly because Libgcrypt folds them all to ECC. */
2905 8 : if (!ascii_strcasecmp (r->u.value, "default"))
2906 : {
2907 : /* Note: If you change this default algo, remember to change it
2908 : also in gpg.c:gpgconf_list. */
2909 0 : i = DEFAULT_STD_ALGO;
2910 0 : if (r_default)
2911 0 : *r_default = 1;
2912 : }
2913 8 : else if (digitp (r->u.value))
2914 0 : i = atoi( r->u.value );
2915 8 : else if (!strcmp (r->u.value, "ELG-E")
2916 8 : || !strcmp (r->u.value, "ELG"))
2917 2 : i = PUBKEY_ALGO_ELGAMAL_E;
2918 6 : else if (!ascii_strcasecmp (r->u.value, "EdDSA"))
2919 0 : i = PUBKEY_ALGO_EDDSA;
2920 6 : else if (!ascii_strcasecmp (r->u.value, "ECDSA"))
2921 0 : i = PUBKEY_ALGO_ECDSA;
2922 6 : else if (!ascii_strcasecmp (r->u.value, "ECDH"))
2923 0 : i = PUBKEY_ALGO_ECDH;
2924 : else
2925 6 : i = map_pk_gcry_to_openpgp (gcry_pk_map_name (r->u.value));
2926 :
2927 8 : if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2928 0 : i = 0; /* we don't want to allow generation of these algorithms */
2929 8 : return i;
2930 : }
2931 :
2932 :
2933 : /* Parse a usage string. The usage keywords "auth", "sign", "encr"
2934 : * may be elimited by space, tab, or comma. On error -1 is returned
2935 : * instead of the usage flags/ */
2936 : static int
2937 1 : parse_usagestr (const char *usagestr)
2938 : {
2939 : gpg_error_t err;
2940 1 : char **tokens = NULL;
2941 : const char *s;
2942 : int i;
2943 1 : unsigned int use = 0;
2944 :
2945 1 : tokens = strtokenize (usagestr, " \t,");
2946 1 : if (!tokens)
2947 : {
2948 0 : err = gpg_error_from_syserror ();
2949 0 : log_error ("strtokenize failed: %s\n", gpg_strerror (err));
2950 0 : return -1;
2951 : }
2952 :
2953 3 : for (i=0; (s = tokens[i]); i++)
2954 : {
2955 2 : if (!*s)
2956 : ;
2957 2 : else if (!ascii_strcasecmp (s, "sign"))
2958 1 : use |= PUBKEY_USAGE_SIG;
2959 1 : else if (!ascii_strcasecmp (s, "encrypt")
2960 0 : || !ascii_strcasecmp (s, "encr"))
2961 1 : use |= PUBKEY_USAGE_ENC;
2962 0 : else if (!ascii_strcasecmp (s, "auth"))
2963 0 : use |= PUBKEY_USAGE_AUTH;
2964 0 : else if (!ascii_strcasecmp (s, "cert"))
2965 0 : use |= PUBKEY_USAGE_CERT;
2966 : else
2967 : {
2968 0 : xfree (tokens);
2969 0 : return -1; /* error */
2970 : }
2971 : }
2972 :
2973 1 : xfree (tokens);
2974 1 : return use;
2975 : }
2976 :
2977 :
2978 : /*
2979 : * Parse the usage parameter and set the keyflags. Returns -1 on
2980 : * error, 0 for no usage given or 1 for usage available.
2981 : */
2982 : static int
2983 3 : parse_parameter_usage (const char *fname,
2984 : struct para_data_s *para, enum para_name key)
2985 : {
2986 3 : struct para_data_s *r = get_parameter( para, key );
2987 : int i;
2988 :
2989 3 : if (!r)
2990 2 : return 0; /* none (this is an optional parameter)*/
2991 :
2992 1 : i = parse_usagestr (r->u.value);
2993 1 : if (i == -1)
2994 : {
2995 0 : log_error ("%s:%d: invalid usage list\n", fname, r->lnr );
2996 0 : return -1; /* error */
2997 : }
2998 :
2999 1 : r->u.usage = i;
3000 1 : return 1;
3001 : }
3002 :
3003 :
3004 : static int
3005 2 : parse_revocation_key (const char *fname,
3006 : struct para_data_s *para, enum para_name key)
3007 : {
3008 2 : struct para_data_s *r = get_parameter( para, key );
3009 : struct revocation_key revkey;
3010 : char *pn;
3011 : int i;
3012 :
3013 2 : if( !r )
3014 2 : return 0; /* none (this is an optional parameter) */
3015 :
3016 0 : pn = r->u.value;
3017 :
3018 0 : revkey.class=0x80;
3019 0 : revkey.algid=atoi(pn);
3020 0 : if(!revkey.algid)
3021 0 : goto fail;
3022 :
3023 : /* Skip to the fpr */
3024 0 : while(*pn && *pn!=':')
3025 0 : pn++;
3026 :
3027 0 : if(*pn!=':')
3028 0 : goto fail;
3029 :
3030 0 : pn++;
3031 :
3032 0 : for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
3033 : {
3034 0 : int c=hextobyte(pn);
3035 0 : if(c==-1)
3036 0 : goto fail;
3037 :
3038 0 : revkey.fpr[i]=c;
3039 : }
3040 :
3041 : /* skip to the tag */
3042 0 : while(*pn && *pn!='s' && *pn!='S')
3043 0 : pn++;
3044 :
3045 0 : if(ascii_strcasecmp(pn,"sensitive")==0)
3046 0 : revkey.class|=0x40;
3047 :
3048 0 : memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
3049 :
3050 0 : return 0;
3051 :
3052 : fail:
3053 0 : log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
3054 0 : return -1; /* error */
3055 : }
3056 :
3057 :
3058 : static u32
3059 13 : get_parameter_u32( struct para_data_s *para, enum para_name key )
3060 : {
3061 13 : struct para_data_s *r = get_parameter( para, key );
3062 :
3063 13 : if( !r )
3064 2 : return 0;
3065 11 : if( r->key == pKEYCREATIONDATE )
3066 0 : return r->u.creation;
3067 11 : if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
3068 3 : return r->u.expire;
3069 8 : if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
3070 5 : return r->u.usage;
3071 :
3072 3 : return (unsigned int)strtoul( r->u.value, NULL, 10 );
3073 : }
3074 :
3075 : static unsigned int
3076 8 : get_parameter_uint( struct para_data_s *para, enum para_name key )
3077 : {
3078 8 : return get_parameter_u32( para, key );
3079 : }
3080 :
3081 : static struct revocation_key *
3082 2 : get_parameter_revkey( struct para_data_s *para, enum para_name key )
3083 : {
3084 2 : struct para_data_s *r = get_parameter( para, key );
3085 2 : return r? &r->u.revkey : NULL;
3086 : }
3087 :
3088 : static int
3089 2 : proc_parameter_file (ctrl_t ctrl, struct para_data_s *para, const char *fname,
3090 : struct output_control_s *outctrl, int card )
3091 : {
3092 : struct para_data_s *r;
3093 : const char *s1, *s2, *s3;
3094 : size_t n;
3095 : char *p;
3096 2 : int is_default = 0;
3097 2 : int have_user_id = 0;
3098 : int err, algo;
3099 :
3100 : /* Check that we have all required parameters. */
3101 2 : r = get_parameter( para, pKEYTYPE );
3102 2 : if(r)
3103 : {
3104 2 : algo = get_parameter_algo (para, pKEYTYPE, &is_default);
3105 2 : if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
3106 : {
3107 0 : log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3108 0 : return -1;
3109 : }
3110 : }
3111 : else
3112 : {
3113 0 : log_error ("%s: no Key-Type specified\n",fname);
3114 0 : return -1;
3115 : }
3116 :
3117 2 : err = parse_parameter_usage (fname, para, pKEYUSAGE);
3118 2 : if (!err)
3119 : {
3120 : /* Default to algo capabilities if key-usage is not provided and
3121 : no default algorithm has been requested. */
3122 1 : r = xmalloc_clear(sizeof(*r));
3123 1 : r->key = pKEYUSAGE;
3124 2 : r->u.usage = (is_default
3125 1 : ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
3126 1 : : openpgp_pk_algo_usage(algo));
3127 1 : append_to_parameter (para, r);
3128 : }
3129 1 : else if (err == -1)
3130 0 : return -1;
3131 : else
3132 : {
3133 1 : r = get_parameter (para, pKEYUSAGE);
3134 1 : if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3135 : {
3136 0 : log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
3137 : fname, r->lnr, algo);
3138 0 : return -1;
3139 : }
3140 : }
3141 :
3142 2 : is_default = 0;
3143 2 : r = get_parameter( para, pSUBKEYTYPE );
3144 2 : if(r)
3145 : {
3146 1 : algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
3147 1 : if (openpgp_pk_test_algo (algo))
3148 : {
3149 0 : log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3150 0 : return -1;
3151 : }
3152 :
3153 1 : err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
3154 1 : if (!err)
3155 : {
3156 : /* Default to algo capabilities if subkey-usage is not
3157 : provided */
3158 1 : r = xmalloc_clear (sizeof(*r));
3159 1 : r->key = pSUBKEYUSAGE;
3160 2 : r->u.usage = (is_default
3161 1 : ? PUBKEY_USAGE_ENC
3162 1 : : openpgp_pk_algo_usage (algo));
3163 1 : append_to_parameter (para, r);
3164 : }
3165 0 : else if (err == -1)
3166 0 : return -1;
3167 : else
3168 : {
3169 0 : r = get_parameter (para, pSUBKEYUSAGE);
3170 0 : if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3171 : {
3172 0 : log_error ("%s:%d: specified Subkey-Usage not allowed"
3173 : " for algo %d\n", fname, r->lnr, algo);
3174 0 : return -1;
3175 : }
3176 : }
3177 : }
3178 :
3179 :
3180 2 : if( get_parameter_value( para, pUSERID ) )
3181 0 : have_user_id=1;
3182 : else
3183 : {
3184 : /* create the formatted user ID */
3185 2 : s1 = get_parameter_value( para, pNAMEREAL );
3186 2 : s2 = get_parameter_value( para, pNAMECOMMENT );
3187 2 : s3 = get_parameter_value( para, pNAMEEMAIL );
3188 2 : if( s1 || s2 || s3 )
3189 : {
3190 2 : n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
3191 2 : r = xmalloc_clear( sizeof *r + n + 20 );
3192 2 : r->key = pUSERID;
3193 2 : p = r->u.value;
3194 2 : if( s1 )
3195 2 : p = stpcpy(p, s1 );
3196 2 : if( s2 )
3197 2 : p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
3198 2 : if( s3 )
3199 2 : p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
3200 2 : append_to_parameter (para, r);
3201 2 : have_user_id=1;
3202 : }
3203 : }
3204 :
3205 2 : if(!have_user_id)
3206 : {
3207 0 : log_error("%s: no User-ID specified\n",fname);
3208 0 : return -1;
3209 : }
3210 :
3211 : /* Set preferences, if any. */
3212 2 : keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
3213 :
3214 : /* Set keyserver, if any. */
3215 2 : s1=get_parameter_value( para, pKEYSERVER );
3216 2 : if(s1)
3217 : {
3218 : struct keyserver_spec *spec;
3219 :
3220 0 : spec = parse_keyserver_uri (s1, 1);
3221 0 : if(spec)
3222 : {
3223 0 : free_keyserver_spec(spec);
3224 0 : opt.def_keyserver_url=s1;
3225 : }
3226 : else
3227 : {
3228 0 : r = get_parameter (para, pKEYSERVER);
3229 0 : log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
3230 0 : return -1;
3231 : }
3232 : }
3233 :
3234 : /* Set revoker, if any. */
3235 2 : if (parse_revocation_key (fname, para, pREVOKER))
3236 0 : return -1;
3237 :
3238 :
3239 : /* Make KEYCREATIONDATE from Creation-Date. */
3240 2 : r = get_parameter (para, pCREATIONDATE);
3241 2 : if (r && *r->u.value)
3242 : {
3243 : u32 seconds;
3244 :
3245 0 : seconds = parse_creation_string (r->u.value);
3246 0 : if (!seconds)
3247 : {
3248 0 : log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
3249 0 : return -1;
3250 : }
3251 0 : r->u.creation = seconds;
3252 0 : r->key = pKEYCREATIONDATE; /* Change that entry. */
3253 : }
3254 :
3255 : /* Make KEYEXPIRE from Expire-Date. */
3256 2 : r = get_parameter( para, pEXPIREDATE );
3257 2 : if( r && *r->u.value )
3258 : {
3259 : u32 seconds;
3260 :
3261 2 : seconds = parse_expire_string( r->u.value );
3262 2 : if( seconds == (u32)-1 )
3263 : {
3264 0 : log_error("%s:%d: invalid expire date\n", fname, r->lnr );
3265 0 : return -1;
3266 : }
3267 2 : r->u.expire = seconds;
3268 2 : r->key = pKEYEXPIRE; /* change hat entry */
3269 : /* also set it for the subkey */
3270 2 : r = xmalloc_clear( sizeof *r + 20 );
3271 2 : r->key = pSUBKEYEXPIRE;
3272 2 : r->u.expire = seconds;
3273 2 : append_to_parameter (para, r);
3274 : }
3275 :
3276 2 : do_generate_keypair (ctrl, para, outctrl, card );
3277 2 : return 0;
3278 : }
3279 :
3280 :
3281 : /****************
3282 : * Kludge to allow non interactive key generation controlled
3283 : * by a parameter file.
3284 : * Note, that string parameters are expected to be in UTF-8
3285 : */
3286 : static void
3287 2 : read_parameter_file (ctrl_t ctrl, const char *fname )
3288 : {
3289 : static struct { const char *name;
3290 : enum para_name key;
3291 : } keywords[] = {
3292 : { "Key-Type", pKEYTYPE},
3293 : { "Key-Length", pKEYLENGTH },
3294 : { "Key-Curve", pKEYCURVE },
3295 : { "Key-Usage", pKEYUSAGE },
3296 : { "Subkey-Type", pSUBKEYTYPE },
3297 : { "Subkey-Length", pSUBKEYLENGTH },
3298 : { "Subkey-Curve", pSUBKEYCURVE },
3299 : { "Subkey-Usage", pSUBKEYUSAGE },
3300 : { "Name-Real", pNAMEREAL },
3301 : { "Name-Email", pNAMEEMAIL },
3302 : { "Name-Comment", pNAMECOMMENT },
3303 : { "Expire-Date", pEXPIREDATE },
3304 : { "Creation-Date", pCREATIONDATE },
3305 : { "Passphrase", pPASSPHRASE },
3306 : { "Preferences", pPREFERENCES },
3307 : { "Revoker", pREVOKER },
3308 : { "Handle", pHANDLE },
3309 : { "Keyserver", pKEYSERVER },
3310 : { NULL, 0 }
3311 : };
3312 : IOBUF fp;
3313 : byte *line;
3314 : unsigned int maxlen, nline;
3315 : char *p;
3316 : int lnr;
3317 2 : const char *err = NULL;
3318 : struct para_data_s *para, *r;
3319 : int i;
3320 : struct output_control_s outctrl;
3321 :
3322 2 : memset( &outctrl, 0, sizeof( outctrl ) );
3323 2 : outctrl.pub.afx = new_armor_context ();
3324 :
3325 2 : if( !fname || !*fname)
3326 2 : fname = "-";
3327 :
3328 2 : fp = iobuf_open (fname);
3329 2 : if (fp && is_secured_file (iobuf_get_fd (fp)))
3330 : {
3331 0 : iobuf_close (fp);
3332 0 : fp = NULL;
3333 0 : gpg_err_set_errno (EPERM);
3334 : }
3335 2 : if (!fp) {
3336 0 : log_error (_("can't open '%s': %s\n"), fname, strerror(errno) );
3337 2 : return;
3338 : }
3339 2 : iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
3340 :
3341 2 : lnr = 0;
3342 2 : err = NULL;
3343 2 : para = NULL;
3344 2 : maxlen = 1024;
3345 2 : line = NULL;
3346 25 : while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
3347 : char *keyword, *value;
3348 :
3349 21 : lnr++;
3350 21 : if( !maxlen ) {
3351 0 : err = "line too long";
3352 0 : break;
3353 : }
3354 21 : for( p = line; isspace(*(byte*)p); p++ )
3355 : ;
3356 21 : if( !*p || *p == '#' )
3357 0 : continue;
3358 21 : keyword = p;
3359 21 : if( *keyword == '%' ) {
3360 6 : for( ; !isspace(*(byte*)p); p++ )
3361 : ;
3362 6 : if( *p )
3363 6 : *p++ = 0;
3364 6 : for( ; isspace(*(byte*)p); p++ )
3365 : ;
3366 6 : value = p;
3367 6 : trim_trailing_ws( value, strlen(value) );
3368 6 : if( !ascii_strcasecmp( keyword, "%echo" ) )
3369 0 : log_info("%s\n", value );
3370 6 : else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
3371 0 : outctrl.dryrun = 1;
3372 6 : else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
3373 : ; /* Dummy for backward compatibility. */
3374 6 : else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
3375 : ; /* Dummy for backward compatibility. */
3376 6 : else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
3377 2 : outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
3378 4 : else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
3379 2 : outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
3380 2 : else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
3381 2 : outctrl.lnr = lnr;
3382 2 : if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3383 0 : print_status_key_not_created
3384 : (get_parameter_value (para, pHANDLE));
3385 2 : release_parameter_list( para );
3386 2 : para = NULL;
3387 : }
3388 0 : else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
3389 0 : if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
3390 : ; /* still the same file - ignore it */
3391 : else {
3392 0 : xfree( outctrl.pub.newfname );
3393 0 : outctrl.pub.newfname = xstrdup( value );
3394 0 : outctrl.use_files = 1;
3395 : }
3396 : }
3397 0 : else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
3398 : /* Ignore this command. */
3399 : }
3400 : else
3401 0 : log_info("skipping control '%s' (%s)\n", keyword, value );
3402 :
3403 :
3404 6 : continue;
3405 : }
3406 :
3407 :
3408 15 : if( !(p = strchr( p, ':' )) || p == keyword ) {
3409 0 : err = "missing colon";
3410 0 : break;
3411 : }
3412 15 : if( *p )
3413 15 : *p++ = 0;
3414 15 : for( ; isspace(*(byte*)p); p++ )
3415 : ;
3416 15 : if( !*p ) {
3417 0 : err = "missing argument";
3418 0 : break;
3419 : }
3420 15 : value = p;
3421 15 : trim_trailing_ws( value, strlen(value) );
3422 :
3423 105 : for(i=0; keywords[i].name; i++ ) {
3424 105 : if( !ascii_strcasecmp( keywords[i].name, keyword ) )
3425 15 : break;
3426 : }
3427 15 : if( !keywords[i].name ) {
3428 0 : err = "unknown keyword";
3429 0 : break;
3430 : }
3431 15 : if( keywords[i].key != pKEYTYPE && !para ) {
3432 0 : err = "parameter block does not start with \"Key-Type\"";
3433 0 : break;
3434 : }
3435 :
3436 15 : if( keywords[i].key == pKEYTYPE && para ) {
3437 0 : outctrl.lnr = lnr;
3438 0 : if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3439 0 : print_status_key_not_created
3440 : (get_parameter_value (para, pHANDLE));
3441 0 : release_parameter_list( para );
3442 0 : para = NULL;
3443 : }
3444 : else {
3445 64 : for( r = para; r; r = r->next ) {
3446 49 : if( r->key == keywords[i].key )
3447 0 : break;
3448 : }
3449 15 : if( r ) {
3450 0 : err = "duplicate keyword";
3451 0 : break;
3452 : }
3453 : }
3454 15 : r = xmalloc_clear( sizeof *r + strlen( value ) );
3455 15 : r->lnr = lnr;
3456 15 : r->key = keywords[i].key;
3457 15 : strcpy( r->u.value, value );
3458 15 : r->next = para;
3459 15 : para = r;
3460 : }
3461 2 : if( err )
3462 0 : log_error("%s:%d: %s\n", fname, lnr, err );
3463 2 : else if( iobuf_error (fp) ) {
3464 0 : log_error("%s:%d: read error\n", fname, lnr);
3465 : }
3466 2 : else if( para ) {
3467 0 : outctrl.lnr = lnr;
3468 0 : if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3469 0 : print_status_key_not_created (get_parameter_value (para, pHANDLE));
3470 : }
3471 :
3472 2 : if( outctrl.use_files ) { /* close open streams */
3473 0 : iobuf_close( outctrl.pub.stream );
3474 :
3475 : /* Must invalidate that ugly cache to actually close it. */
3476 0 : if (outctrl.pub.fname)
3477 0 : iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
3478 0 : 0, (char*)outctrl.pub.fname);
3479 :
3480 0 : xfree( outctrl.pub.fname );
3481 0 : xfree( outctrl.pub.newfname );
3482 : }
3483 :
3484 2 : xfree (line);
3485 2 : release_parameter_list( para );
3486 2 : iobuf_close (fp);
3487 2 : release_armor_context (outctrl.pub.afx);
3488 : }
3489 :
3490 :
3491 : /* Helper for quick_generate_keypair. */
3492 : static struct para_data_s *
3493 0 : quickgen_set_para (struct para_data_s *para, int for_subkey,
3494 : int algo, int nbits, const char *curve, unsigned int use)
3495 : {
3496 : struct para_data_s *r;
3497 :
3498 0 : r = xmalloc_clear (sizeof *r + 30);
3499 0 : r->key = for_subkey? pSUBKEYUSAGE : pKEYUSAGE;
3500 0 : if (use)
3501 0 : snprintf (r->u.value, 30, "%s%s%s%s",
3502 0 : (use & PUBKEY_USAGE_ENC)? "encr " : "",
3503 0 : (use & PUBKEY_USAGE_SIG)? "sign " : "",
3504 0 : (use & PUBKEY_USAGE_AUTH)? "auth " : "",
3505 0 : (use & PUBKEY_USAGE_CERT)? "cert " : "");
3506 : else
3507 0 : strcpy (r->u.value, for_subkey ? "encr" : "sign");
3508 0 : r->next = para;
3509 0 : para = r;
3510 0 : r = xmalloc_clear (sizeof *r + 20);
3511 0 : r->key = for_subkey? pSUBKEYTYPE : pKEYTYPE;
3512 0 : snprintf (r->u.value, 20, "%d", algo);
3513 0 : r->next = para;
3514 0 : para = r;
3515 :
3516 0 : if (curve)
3517 : {
3518 0 : r = xmalloc_clear (sizeof *r + strlen (curve));
3519 0 : r->key = for_subkey? pSUBKEYCURVE : pKEYCURVE;
3520 0 : strcpy (r->u.value, curve);
3521 0 : r->next = para;
3522 0 : para = r;
3523 : }
3524 : else
3525 : {
3526 0 : r = xmalloc_clear (sizeof *r + 20);
3527 0 : r->key = for_subkey? pSUBKEYLENGTH : pKEYLENGTH;
3528 0 : sprintf (r->u.value, "%u", nbits);
3529 0 : r->next = para;
3530 0 : para = r;
3531 : }
3532 :
3533 0 : return para;
3534 : }
3535 :
3536 :
3537 : /*
3538 : * Unattended generation of a standard key.
3539 : */
3540 : void
3541 0 : quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr,
3542 : const char *usagestr, const char *expirestr)
3543 : {
3544 : gpg_error_t err;
3545 0 : struct para_data_s *para = NULL;
3546 : struct para_data_s *r;
3547 : struct output_control_s outctrl;
3548 : int use_tty;
3549 :
3550 0 : memset (&outctrl, 0, sizeof outctrl);
3551 :
3552 0 : use_tty = (!opt.batch && !opt.answer_yes
3553 0 : && !*algostr && !*usagestr && !*expirestr
3554 0 : && !cpr_enabled ()
3555 0 : && gnupg_isatty (fileno (stdin))
3556 0 : && gnupg_isatty (fileno (stdout))
3557 0 : && gnupg_isatty (fileno (stderr)));
3558 :
3559 0 : r = xmalloc_clear (sizeof *r + strlen (uid));
3560 0 : r->key = pUSERID;
3561 0 : strcpy (r->u.value, uid);
3562 0 : r->next = para;
3563 0 : para = r;
3564 :
3565 0 : uid = trim_spaces (r->u.value);
3566 0 : if (!*uid || (!opt.allow_freeform_uid && !is_valid_user_id (uid)))
3567 : {
3568 0 : log_error (_("Key generation failed: %s\n"),
3569 : gpg_strerror (GPG_ERR_INV_USER_ID));
3570 0 : goto leave;
3571 : }
3572 :
3573 : /* If gpg is directly used on the console ask whether a key with the
3574 : given user id shall really be created. */
3575 0 : if (use_tty)
3576 : {
3577 0 : tty_printf (_("About to create a key for:\n \"%s\"\n\n"), uid);
3578 0 : if (!cpr_get_answer_is_yes_def ("quick_keygen.okay",
3579 0 : _("Continue? (Y/n) "), 1))
3580 0 : goto leave;
3581 : }
3582 :
3583 : /* Check whether such a user ID already exists. */
3584 : {
3585 : KEYDB_HANDLE kdbhd;
3586 : KEYDB_SEARCH_DESC desc;
3587 :
3588 0 : memset (&desc, 0, sizeof desc);
3589 0 : desc.mode = KEYDB_SEARCH_MODE_EXACT;
3590 0 : desc.u.name = uid;
3591 :
3592 0 : kdbhd = keydb_new ();
3593 0 : if (!kdbhd)
3594 0 : goto leave;
3595 :
3596 0 : err = keydb_search (kdbhd, &desc, 1, NULL);
3597 0 : keydb_release (kdbhd);
3598 0 : if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
3599 : {
3600 0 : log_info (_("A key for \"%s\" already exists\n"), uid);
3601 0 : if (opt.answer_yes)
3602 : ;
3603 0 : else if (!use_tty
3604 0 : || !cpr_get_answer_is_yes_def ("quick_keygen.force",
3605 0 : _("Create anyway? (y/N) "), 0))
3606 : {
3607 0 : log_inc_errorcount (); /* we used log_info */
3608 0 : goto leave;
3609 : }
3610 0 : log_info (_("creating anyway\n"));
3611 : }
3612 : }
3613 :
3614 :
3615 0 : if (!strcmp (algostr, "test-default"))
3616 : {
3617 0 : para = quickgen_set_para (para, 0, PUBKEY_ALGO_EDDSA, 0, "Ed25519", 0);
3618 0 : para = quickgen_set_para (para, 1, PUBKEY_ALGO_ECDH, 0, "Curve25519", 0);
3619 : }
3620 0 : else if (*algostr || *usagestr || *expirestr)
3621 0 : {
3622 : /* Extended unattended mode. Creates only the primary key. */
3623 : int algo;
3624 : unsigned int use;
3625 : u32 expire;
3626 : unsigned int nbits;
3627 : char *curve;
3628 :
3629 0 : err = parse_algo_usage_expire (ctrl, 0, algostr, usagestr, expirestr,
3630 : &algo, &use, &expire, &nbits, &curve);
3631 0 : if (err)
3632 : {
3633 0 : log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
3634 0 : goto leave;
3635 : }
3636 :
3637 0 : para = quickgen_set_para (para, 0, algo, nbits, curve, use);
3638 0 : r = xmalloc_clear (sizeof *r + 20);
3639 0 : r->key = pKEYEXPIRE;
3640 0 : r->u.expire = expire;
3641 0 : r->next = para;
3642 0 : para = r;
3643 : }
3644 : else
3645 : {
3646 0 : para = quickgen_set_para (para, 0,
3647 : DEFAULT_STD_ALGO, DEFAULT_STD_KEYSIZE,
3648 : DEFAULT_STD_CURVE, 0);
3649 0 : para = quickgen_set_para (para, 1,
3650 : DEFAULT_STD_SUBALGO, DEFAULT_STD_SUBKEYSIZE,
3651 : DEFAULT_STD_SUBCURVE, 0);
3652 : }
3653 :
3654 : /* If the pinentry loopback mode is not and we have a static
3655 : passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
3656 : mode), we use that passphrase for the new key. */
3657 0 : if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
3658 0 : && have_static_passphrase ())
3659 : {
3660 0 : const char *s = get_static_passphrase ();
3661 :
3662 0 : r = xmalloc_clear (sizeof *r + strlen (s));
3663 0 : r->key = pPASSPHRASE;
3664 0 : strcpy (r->u.value, s);
3665 0 : r->next = para;
3666 0 : para = r;
3667 : }
3668 :
3669 0 : proc_parameter_file (ctrl, para, "[internal]", &outctrl, 0);
3670 :
3671 : leave:
3672 0 : release_parameter_list (para);
3673 0 : }
3674 :
3675 :
3676 : /*
3677 : * Generate a keypair (fname is only used in batch mode) If
3678 : * CARD_SERIALNO is not NULL the function will create the keys on an
3679 : * OpenPGP Card. If CARD_BACKUP_KEY has been set and CARD_SERIALNO is
3680 : * NOT NULL, the encryption key for the card is generated on the host,
3681 : * imported to the card and a backup file created by gpg-agent. If
3682 : * FULL is not set only the basic prompts are used (except for batch
3683 : * mode).
3684 : */
3685 : void
3686 2 : generate_keypair (ctrl_t ctrl, int full, const char *fname,
3687 : const char *card_serialno, int card_backup_key)
3688 : {
3689 : unsigned int nbits;
3690 2 : char *uid = NULL;
3691 : int algo;
3692 : unsigned int use;
3693 2 : int both = 0;
3694 : u32 expire;
3695 2 : struct para_data_s *para = NULL;
3696 : struct para_data_s *r;
3697 : struct output_control_s outctrl;
3698 :
3699 : #ifndef ENABLE_CARD_SUPPORT
3700 : (void)card_backup_key;
3701 : #endif
3702 :
3703 2 : memset( &outctrl, 0, sizeof( outctrl ) );
3704 :
3705 2 : if (opt.batch && card_serialno)
3706 : {
3707 : /* We don't yet support unattended key generation. */
3708 0 : log_error (_("can't do this in batch mode\n"));
3709 0 : return;
3710 : }
3711 :
3712 2 : if (opt.batch)
3713 : {
3714 2 : read_parameter_file (ctrl, fname);
3715 2 : return;
3716 : }
3717 :
3718 0 : if (card_serialno)
3719 : {
3720 : #ifdef ENABLE_CARD_SUPPORT
3721 0 : r = xcalloc (1, sizeof *r + strlen (card_serialno) );
3722 0 : r->key = pSERIALNO;
3723 0 : strcpy( r->u.value, card_serialno);
3724 0 : r->next = para;
3725 0 : para = r;
3726 :
3727 0 : algo = PUBKEY_ALGO_RSA;
3728 :
3729 0 : r = xcalloc (1, sizeof *r + 20 );
3730 0 : r->key = pKEYTYPE;
3731 0 : sprintf( r->u.value, "%d", algo );
3732 0 : r->next = para;
3733 0 : para = r;
3734 0 : r = xcalloc (1, sizeof *r + 20 );
3735 0 : r->key = pKEYUSAGE;
3736 0 : strcpy (r->u.value, "sign");
3737 0 : r->next = para;
3738 0 : para = r;
3739 :
3740 0 : r = xcalloc (1, sizeof *r + 20 );
3741 0 : r->key = pSUBKEYTYPE;
3742 0 : sprintf( r->u.value, "%d", algo );
3743 0 : r->next = para;
3744 0 : para = r;
3745 0 : r = xcalloc (1, sizeof *r + 20 );
3746 0 : r->key = pSUBKEYUSAGE;
3747 0 : strcpy (r->u.value, "encrypt");
3748 0 : r->next = para;
3749 0 : para = r;
3750 :
3751 0 : r = xcalloc (1, sizeof *r + 20 );
3752 0 : r->key = pAUTHKEYTYPE;
3753 0 : sprintf( r->u.value, "%d", algo );
3754 0 : r->next = para;
3755 0 : para = r;
3756 :
3757 0 : if (card_backup_key)
3758 : {
3759 0 : r = xcalloc (1, sizeof *r + 1);
3760 0 : r->key = pCARDBACKUPKEY;
3761 0 : strcpy (r->u.value, "1");
3762 0 : r->next = para;
3763 0 : para = r;
3764 : }
3765 : #endif /*ENABLE_CARD_SUPPORT*/
3766 : }
3767 0 : else if (full) /* Full featured key generation. */
3768 : {
3769 : int subkey_algo;
3770 0 : char *curve = NULL;
3771 :
3772 : /* Fixme: To support creating a primary key by keygrip we better
3773 : also define the keyword for the parameter file. Note that
3774 : the subkey case will never be asserted if a keygrip has been
3775 : given. */
3776 0 : algo = ask_algo (ctrl, 0, &subkey_algo, &use, NULL);
3777 0 : if (subkey_algo)
3778 : {
3779 : /* Create primary and subkey at once. */
3780 0 : both = 1;
3781 0 : if (algo == PUBKEY_ALGO_ECDSA
3782 0 : || algo == PUBKEY_ALGO_EDDSA
3783 0 : || algo == PUBKEY_ALGO_ECDH)
3784 : {
3785 0 : curve = ask_curve (&algo, &subkey_algo);
3786 0 : r = xmalloc_clear( sizeof *r + 20 );
3787 0 : r->key = pKEYTYPE;
3788 0 : sprintf( r->u.value, "%d", algo);
3789 0 : r->next = para;
3790 0 : para = r;
3791 0 : nbits = 0;
3792 0 : r = xmalloc_clear (sizeof *r + strlen (curve));
3793 0 : r->key = pKEYCURVE;
3794 0 : strcpy (r->u.value, curve);
3795 0 : r->next = para;
3796 0 : para = r;
3797 : }
3798 : else
3799 : {
3800 0 : r = xmalloc_clear( sizeof *r + 20 );
3801 0 : r->key = pKEYTYPE;
3802 0 : sprintf( r->u.value, "%d", algo);
3803 0 : r->next = para;
3804 0 : para = r;
3805 0 : nbits = ask_keysize (algo, 0);
3806 0 : r = xmalloc_clear( sizeof *r + 20 );
3807 0 : r->key = pKEYLENGTH;
3808 0 : sprintf( r->u.value, "%u", nbits);
3809 0 : r->next = para;
3810 0 : para = r;
3811 : }
3812 0 : r = xmalloc_clear( sizeof *r + 20 );
3813 0 : r->key = pKEYUSAGE;
3814 0 : strcpy( r->u.value, "sign" );
3815 0 : r->next = para;
3816 0 : para = r;
3817 :
3818 0 : r = xmalloc_clear( sizeof *r + 20 );
3819 0 : r->key = pSUBKEYTYPE;
3820 0 : sprintf( r->u.value, "%d", subkey_algo);
3821 0 : r->next = para;
3822 0 : para = r;
3823 0 : r = xmalloc_clear( sizeof *r + 20 );
3824 0 : r->key = pSUBKEYUSAGE;
3825 0 : strcpy( r->u.value, "encrypt" );
3826 0 : r->next = para;
3827 0 : para = r;
3828 :
3829 0 : if (algo == PUBKEY_ALGO_ECDSA
3830 0 : || algo == PUBKEY_ALGO_EDDSA
3831 0 : || algo == PUBKEY_ALGO_ECDH)
3832 : {
3833 0 : if (algo == PUBKEY_ALGO_EDDSA
3834 0 : && subkey_algo == PUBKEY_ALGO_ECDH)
3835 : {
3836 : /* Need to switch to a different curve for the
3837 : encryption key. */
3838 0 : xfree (curve);
3839 0 : curve = xstrdup ("Curve25519");
3840 : }
3841 0 : r = xmalloc_clear (sizeof *r + strlen (curve));
3842 0 : r->key = pSUBKEYCURVE;
3843 0 : strcpy (r->u.value, curve);
3844 0 : r->next = para;
3845 0 : para = r;
3846 : }
3847 : }
3848 : else /* Create only a single key. */
3849 : {
3850 : /* For ECC we need to ask for the curve before storing the
3851 : algo because ask_curve may change the algo. */
3852 0 : if (algo == PUBKEY_ALGO_ECDSA
3853 0 : || algo == PUBKEY_ALGO_EDDSA
3854 0 : || algo == PUBKEY_ALGO_ECDH)
3855 : {
3856 0 : curve = ask_curve (&algo, NULL);
3857 0 : r = xmalloc_clear (sizeof *r + strlen (curve));
3858 0 : r->key = pKEYCURVE;
3859 0 : strcpy (r->u.value, curve);
3860 0 : r->next = para;
3861 0 : para = r;
3862 : }
3863 :
3864 0 : r = xmalloc_clear( sizeof *r + 20 );
3865 0 : r->key = pKEYTYPE;
3866 0 : sprintf( r->u.value, "%d", algo );
3867 0 : r->next = para;
3868 0 : para = r;
3869 :
3870 0 : if (use)
3871 : {
3872 0 : r = xmalloc_clear( sizeof *r + 25 );
3873 0 : r->key = pKEYUSAGE;
3874 0 : sprintf( r->u.value, "%s%s%s",
3875 0 : (use & PUBKEY_USAGE_SIG)? "sign ":"",
3876 0 : (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3877 0 : (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3878 0 : r->next = para;
3879 0 : para = r;
3880 : }
3881 0 : nbits = 0;
3882 : }
3883 :
3884 0 : if (algo == PUBKEY_ALGO_ECDSA
3885 0 : || algo == PUBKEY_ALGO_EDDSA
3886 0 : || algo == PUBKEY_ALGO_ECDH)
3887 : {
3888 : /* The curve has already been set. */
3889 : }
3890 : else
3891 : {
3892 0 : nbits = ask_keysize (both? subkey_algo : algo, nbits);
3893 0 : r = xmalloc_clear( sizeof *r + 20 );
3894 0 : r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3895 0 : sprintf( r->u.value, "%u", nbits);
3896 0 : r->next = para;
3897 0 : para = r;
3898 : }
3899 :
3900 0 : xfree (curve);
3901 : }
3902 : else /* Default key generation. */
3903 : {
3904 0 : tty_printf ( _("Note: Use \"%s %s\""
3905 : " for a full featured key generation dialog.\n"),
3906 : #if USE_GPG2_HACK
3907 : GPG_NAME "2"
3908 : #else
3909 : GPG_NAME
3910 : #endif
3911 : , "--full-gen-key" );
3912 0 : para = quickgen_set_para (para, 0,
3913 : DEFAULT_STD_ALGO, DEFAULT_STD_KEYSIZE,
3914 : DEFAULT_STD_CURVE, 0);
3915 0 : para = quickgen_set_para (para, 1,
3916 : DEFAULT_STD_SUBALGO, DEFAULT_STD_SUBKEYSIZE,
3917 : DEFAULT_STD_SUBCURVE, 0);
3918 : }
3919 :
3920 :
3921 0 : expire = full? ask_expire_interval (0, NULL) : 0;
3922 0 : r = xcalloc (1, sizeof *r + 20);
3923 0 : r->key = pKEYEXPIRE;
3924 0 : r->u.expire = expire;
3925 0 : r->next = para;
3926 0 : para = r;
3927 0 : r = xcalloc (1, sizeof *r + 20);
3928 0 : r->key = pSUBKEYEXPIRE;
3929 0 : r->u.expire = expire;
3930 0 : r->next = para;
3931 0 : para = r;
3932 :
3933 0 : uid = ask_user_id (0, full, NULL);
3934 0 : if (!uid)
3935 : {
3936 0 : log_error(_("Key generation canceled.\n"));
3937 0 : release_parameter_list( para );
3938 0 : return;
3939 : }
3940 0 : r = xcalloc (1, sizeof *r + strlen (uid));
3941 0 : r->key = pUSERID;
3942 0 : strcpy (r->u.value, uid);
3943 0 : r->next = para;
3944 0 : para = r;
3945 :
3946 0 : proc_parameter_file (ctrl, para, "[internal]", &outctrl, !!card_serialno);
3947 0 : release_parameter_list (para);
3948 : }
3949 :
3950 :
3951 : /* Create and delete a dummy packet to start off a list of kbnodes. */
3952 : static void
3953 2 : start_tree(KBNODE *tree)
3954 : {
3955 : PACKET *pkt;
3956 :
3957 2 : pkt=xmalloc_clear(sizeof(*pkt));
3958 2 : pkt->pkttype=PKT_NONE;
3959 2 : *tree=new_kbnode(pkt);
3960 2 : delete_kbnode(*tree);
3961 2 : }
3962 :
3963 :
3964 : /* Write the *protected* secret key to the file. */
3965 : static gpg_error_t
3966 0 : card_write_key_to_backup_file (PKT_public_key *sk, const char *backup_dir)
3967 : {
3968 0 : gpg_error_t err = 0;
3969 : int rc;
3970 : char keyid_buffer[2 * 8 + 1];
3971 : char name_buffer[50];
3972 : char *fname;
3973 : IOBUF fp;
3974 : mode_t oldmask;
3975 0 : PACKET *pkt = NULL;
3976 :
3977 0 : format_keyid (pk_keyid (sk), KF_LONG, keyid_buffer, sizeof (keyid_buffer));
3978 0 : snprintf (name_buffer, sizeof name_buffer, "sk_%s.gpg", keyid_buffer);
3979 :
3980 0 : fname = make_filename (backup_dir, name_buffer, NULL);
3981 : /* Note that the umask call is not anymore needed because
3982 : iobuf_create now takes care of it. However, it does not harm
3983 : and thus we keep it. */
3984 0 : oldmask = umask (077);
3985 0 : if (is_secured_filename (fname))
3986 : {
3987 0 : fp = NULL;
3988 0 : gpg_err_set_errno (EPERM);
3989 : }
3990 : else
3991 0 : fp = iobuf_create (fname, 1);
3992 0 : umask (oldmask);
3993 0 : if (!fp)
3994 : {
3995 0 : err = gpg_error_from_syserror ();
3996 0 : log_error (_("can't create backup file '%s': %s\n"), fname, strerror (errno) );
3997 0 : goto leave;
3998 : }
3999 :
4000 0 : pkt = xcalloc (1, sizeof *pkt);
4001 0 : pkt->pkttype = PKT_SECRET_KEY;
4002 0 : pkt->pkt.secret_key = sk;
4003 :
4004 0 : rc = build_packet (fp, pkt);
4005 0 : if (rc)
4006 : {
4007 0 : log_error ("build packet failed: %s\n", gpg_strerror (rc));
4008 0 : iobuf_cancel (fp);
4009 : }
4010 : else
4011 : {
4012 : char *fprbuf;
4013 :
4014 0 : iobuf_close (fp);
4015 0 : iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
4016 0 : log_info (_("Note: backup of card key saved to '%s'\n"), fname);
4017 :
4018 0 : fprbuf = hexfingerprint (sk, NULL, 0);
4019 0 : write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED, fprbuf,
4020 : fname, strlen (fname), 0);
4021 0 : xfree (fprbuf);
4022 : }
4023 :
4024 : leave:
4025 0 : xfree (pkt);
4026 0 : xfree (fname);
4027 0 : return err;
4028 : }
4029 :
4030 :
4031 : /* Store key to card and make a backup file in OpenPGP format. */
4032 : static gpg_error_t
4033 0 : card_store_key_with_backup (ctrl_t ctrl, PKT_public_key *sub_psk,
4034 : const char *backup_dir)
4035 : {
4036 : PKT_public_key *sk;
4037 : gnupg_isotime_t timestamp;
4038 : gpg_error_t err;
4039 : char *hexgrip;
4040 : int rc;
4041 : struct agent_card_info_s info;
4042 0 : gcry_cipher_hd_t cipherhd = NULL;
4043 0 : char *cache_nonce = NULL;
4044 0 : void *kek = NULL;
4045 : size_t keklen;
4046 :
4047 0 : sk = copy_public_key (NULL, sub_psk);
4048 0 : if (!sk)
4049 0 : return gpg_error_from_syserror ();
4050 :
4051 0 : epoch2isotime (timestamp, (time_t)sk->timestamp);
4052 0 : err = hexkeygrip_from_pk (sk, &hexgrip);
4053 0 : if (err)
4054 0 : return err;
4055 :
4056 0 : memset(&info, 0, sizeof (info));
4057 0 : rc = agent_scd_getattr ("SERIALNO", &info);
4058 0 : if (rc)
4059 0 : return (gpg_error_t)rc;
4060 :
4061 0 : rc = agent_keytocard (hexgrip, 2, 1, info.serialno, timestamp);
4062 0 : xfree (info.serialno);
4063 0 : if (rc)
4064 : {
4065 0 : err = (gpg_error_t)rc;
4066 0 : goto leave;
4067 : }
4068 :
4069 0 : err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
4070 0 : if (err)
4071 : {
4072 0 : log_error ("error getting the KEK: %s\n", gpg_strerror (err));
4073 0 : goto leave;
4074 : }
4075 :
4076 0 : err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
4077 : GCRY_CIPHER_MODE_AESWRAP, 0);
4078 0 : if (!err)
4079 0 : err = gcry_cipher_setkey (cipherhd, kek, keklen);
4080 0 : if (err)
4081 : {
4082 0 : log_error ("error setting up an encryption context: %s\n",
4083 : gpg_strerror (err));
4084 0 : goto leave;
4085 : }
4086 :
4087 0 : err = receive_seckey_from_agent (ctrl, cipherhd, 0,
4088 : &cache_nonce, hexgrip, sk);
4089 0 : if (err)
4090 : {
4091 0 : log_error ("error getting secret key from agent: %s\n",
4092 : gpg_strerror (err));
4093 0 : goto leave;
4094 : }
4095 :
4096 0 : err = card_write_key_to_backup_file (sk, backup_dir);
4097 0 : if (err)
4098 0 : log_error ("writing card key to backup file: %s\n", gpg_strerror (err));
4099 : else
4100 : /* Remove secret key data in agent side. */
4101 0 : agent_scd_learn (NULL, 1);
4102 :
4103 : leave:
4104 0 : xfree (cache_nonce);
4105 0 : gcry_cipher_close (cipherhd);
4106 0 : xfree (kek);
4107 0 : xfree (hexgrip);
4108 0 : free_public_key (sk);
4109 0 : return err;
4110 : }
4111 :
4112 :
4113 : static void
4114 2 : do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
4115 : struct output_control_s *outctrl, int card)
4116 : {
4117 : gpg_error_t err;
4118 2 : KBNODE pub_root = NULL;
4119 : const char *s;
4120 2 : PKT_public_key *pri_psk = NULL;
4121 2 : PKT_public_key *sub_psk = NULL;
4122 : struct revocation_key *revkey;
4123 2 : int did_sub = 0;
4124 : u32 timestamp;
4125 2 : char *cache_nonce = NULL;
4126 :
4127 2 : if (outctrl->dryrun)
4128 : {
4129 0 : log_info("dry-run mode - key generation skipped\n");
4130 0 : return;
4131 : }
4132 :
4133 2 : if ( outctrl->use_files )
4134 : {
4135 0 : if ( outctrl->pub.newfname )
4136 : {
4137 0 : iobuf_close(outctrl->pub.stream);
4138 0 : outctrl->pub.stream = NULL;
4139 0 : if (outctrl->pub.fname)
4140 0 : iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
4141 0 : 0, (char*)outctrl->pub.fname);
4142 0 : xfree( outctrl->pub.fname );
4143 0 : outctrl->pub.fname = outctrl->pub.newfname;
4144 0 : outctrl->pub.newfname = NULL;
4145 :
4146 0 : if (is_secured_filename (outctrl->pub.fname) )
4147 : {
4148 0 : outctrl->pub.stream = NULL;
4149 0 : gpg_err_set_errno (EPERM);
4150 : }
4151 : else
4152 0 : outctrl->pub.stream = iobuf_create (outctrl->pub.fname, 0);
4153 0 : if (!outctrl->pub.stream)
4154 : {
4155 0 : log_error(_("can't create '%s': %s\n"), outctrl->pub.newfname,
4156 0 : strerror(errno) );
4157 0 : return;
4158 : }
4159 0 : if (opt.armor)
4160 : {
4161 0 : outctrl->pub.afx->what = 1;
4162 0 : push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
4163 : }
4164 : }
4165 0 : log_assert( outctrl->pub.stream );
4166 0 : if (opt.verbose)
4167 0 : log_info (_("writing public key to '%s'\n"), outctrl->pub.fname );
4168 : }
4169 :
4170 :
4171 : /* We create the packets as a tree of kbnodes. Because the
4172 : structure we create is known in advance we simply generate a
4173 : linked list. The first packet is a dummy packet which we flag as
4174 : deleted. The very first packet must always be a KEY packet. */
4175 :
4176 2 : start_tree (&pub_root);
4177 :
4178 2 : timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
4179 2 : if (!timestamp)
4180 2 : timestamp = make_timestamp ();
4181 :
4182 : /* Note that, depending on the backend (i.e. the used scdaemon
4183 : version), the card key generation may update TIMESTAMP for each
4184 : key. Thus we need to pass TIMESTAMP to all signing function to
4185 : make sure that the binding signature is done using the timestamp
4186 : of the corresponding (sub)key and not that of the primary key.
4187 : An alternative implementation could tell the signing function the
4188 : node of the subkey but that is more work than just to pass the
4189 : current timestamp. */
4190 :
4191 2 : if (!card)
4192 4 : err = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
4193 : get_parameter_uint( para, pKEYLENGTH ),
4194 : get_parameter_value (para, pKEYCURVE),
4195 : pub_root,
4196 : timestamp,
4197 : get_parameter_u32( para, pKEYEXPIRE ), 0,
4198 2 : outctrl->keygen_flags,
4199 : get_parameter_passphrase (para),
4200 : &cache_nonce, NULL);
4201 : else
4202 0 : err = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root,
4203 : ×tamp,
4204 : get_parameter_u32 (para, pKEYEXPIRE));
4205 :
4206 : /* Get the pointer to the generated public key packet. */
4207 2 : if (!err)
4208 : {
4209 2 : pri_psk = pub_root->next->pkt->pkt.public_key;
4210 2 : log_assert (pri_psk);
4211 :
4212 : /* Make sure a few fields are correctly set up before going
4213 : further. */
4214 2 : pri_psk->flags.primary = 1;
4215 2 : keyid_from_pk (pri_psk, NULL);
4216 : /* We don't use pk_keyid to get keyid, because it also asserts
4217 : that main_keyid is set! */
4218 2 : keyid_copy (pri_psk->main_keyid, pri_psk->keyid);
4219 : }
4220 :
4221 2 : if (!err && (revkey = get_parameter_revkey (para, pREVOKER)))
4222 0 : err = write_direct_sig (pub_root, pri_psk, revkey, timestamp, cache_nonce);
4223 :
4224 2 : if (!err && (s = get_parameter_value (para, pUSERID)))
4225 : {
4226 2 : write_uid (pub_root, s );
4227 2 : err = write_selfsigs (pub_root, pri_psk,
4228 : get_parameter_uint (para, pKEYUSAGE), timestamp,
4229 : cache_nonce);
4230 : }
4231 :
4232 : /* Write the auth key to the card before the encryption key. This
4233 : is a partial workaround for a PGP bug (as of this writing, all
4234 : versions including 8.1), that causes it to try and encrypt to
4235 : the most recent subkey regardless of whether that subkey is
4236 : actually an encryption type. In this case, the auth key is an
4237 : RSA key so it succeeds. */
4238 :
4239 2 : if (!err && card && get_parameter (para, pAUTHKEYTYPE))
4240 : {
4241 0 : err = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root,
4242 : ×tamp,
4243 : get_parameter_u32 (para, pKEYEXPIRE));
4244 0 : if (!err)
4245 0 : err = write_keybinding (pub_root, pri_psk, NULL,
4246 : PUBKEY_USAGE_AUTH, timestamp, cache_nonce);
4247 : }
4248 :
4249 2 : if (!err && get_parameter (para, pSUBKEYTYPE))
4250 : {
4251 1 : sub_psk = NULL;
4252 1 : s = NULL;
4253 1 : if (!card || (s = get_parameter_value (para, pCARDBACKUPKEY)))
4254 : {
4255 2 : err = do_create (get_parameter_algo (para, pSUBKEYTYPE, NULL),
4256 : get_parameter_uint (para, pSUBKEYLENGTH),
4257 : get_parameter_value (para, pSUBKEYCURVE),
4258 : pub_root,
4259 : timestamp,
4260 : get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
4261 1 : s ? KEYGEN_FLAG_NO_PROTECTION : outctrl->keygen_flags,
4262 : get_parameter_passphrase (para),
4263 : &cache_nonce, NULL);
4264 : /* Get the pointer to the generated public subkey packet. */
4265 2 : if (!err)
4266 : {
4267 : kbnode_t node;
4268 :
4269 6 : for (node = pub_root; node; node = node->next)
4270 5 : if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4271 1 : sub_psk = node->pkt->pkt.public_key;
4272 1 : log_assert (sub_psk);
4273 :
4274 1 : if (s)
4275 0 : err = card_store_key_with_backup (ctrl,
4276 : sub_psk, gnupg_homedir ());
4277 : }
4278 : }
4279 : else
4280 : {
4281 0 : err = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, ×tamp,
4282 : get_parameter_u32 (para, pKEYEXPIRE));
4283 : }
4284 :
4285 1 : if (!err)
4286 1 : err = write_keybinding (pub_root, pri_psk, sub_psk,
4287 : get_parameter_uint (para, pSUBKEYUSAGE),
4288 : timestamp, cache_nonce);
4289 1 : did_sub = 1;
4290 : }
4291 :
4292 2 : if (!err && outctrl->use_files) /* Direct write to specified files. */
4293 : {
4294 0 : err = write_keyblock (outctrl->pub.stream, pub_root);
4295 0 : if (err)
4296 0 : log_error ("can't write public key: %s\n", gpg_strerror (err));
4297 : }
4298 2 : else if (!err) /* Write to the standard keyrings. */
4299 : {
4300 : KEYDB_HANDLE pub_hd;
4301 :
4302 2 : pub_hd = keydb_new ();
4303 2 : if (!pub_hd)
4304 0 : err = gpg_error_from_syserror ();
4305 : else
4306 : {
4307 2 : err = keydb_locate_writable (pub_hd);
4308 2 : if (err)
4309 0 : log_error (_("no writable public keyring found: %s\n"),
4310 : gpg_strerror (err));
4311 : }
4312 :
4313 2 : if (!err && opt.verbose)
4314 : {
4315 0 : log_info (_("writing public key to '%s'\n"),
4316 : keydb_get_resource_name (pub_hd));
4317 : }
4318 :
4319 2 : if (!err)
4320 : {
4321 2 : err = keydb_insert_keyblock (pub_hd, pub_root);
4322 2 : if (err)
4323 0 : log_error (_("error writing public keyring '%s': %s\n"),
4324 : keydb_get_resource_name (pub_hd), gpg_strerror (err));
4325 : }
4326 :
4327 2 : keydb_release (pub_hd);
4328 :
4329 2 : if (!err)
4330 : {
4331 : int no_enc_rsa;
4332 : PKT_public_key *pk;
4333 :
4334 4 : no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
4335 : == PUBKEY_ALGO_RSA)
4336 1 : && get_parameter_uint (para, pKEYUSAGE)
4337 4 : && !((get_parameter_uint (para, pKEYUSAGE)
4338 1 : & PUBKEY_USAGE_ENC)) );
4339 :
4340 2 : pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4341 :
4342 2 : keyid_from_pk (pk, pk->main_keyid);
4343 2 : register_trusted_keyid (pk->main_keyid);
4344 :
4345 2 : update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
4346 : | TRUST_ULTIMATE ));
4347 :
4348 2 : gen_standard_revoke (pk, cache_nonce);
4349 :
4350 : /* Get rid of the first empty packet. */
4351 2 : commit_kbnode (&pub_root);
4352 :
4353 2 : if (!opt.batch)
4354 : {
4355 0 : tty_printf (_("public and secret key created and signed.\n") );
4356 0 : tty_printf ("\n");
4357 0 : merge_keys_and_selfsig (pub_root);
4358 0 : list_keyblock_direct (ctrl, pub_root, 0, 1, 1, 1);
4359 : }
4360 :
4361 :
4362 2 : if (!opt.batch
4363 0 : && (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
4364 0 : || no_enc_rsa )
4365 0 : && !get_parameter (para, pSUBKEYTYPE) )
4366 : {
4367 0 : tty_printf(_("Note that this key cannot be used for "
4368 : "encryption. You may want to use\n"
4369 : "the command \"--edit-key\" to generate a "
4370 : "subkey for this purpose.\n") );
4371 : }
4372 : }
4373 : }
4374 :
4375 2 : if (err)
4376 : {
4377 0 : if (opt.batch)
4378 0 : log_error ("key generation failed: %s\n", gpg_strerror (err) );
4379 : else
4380 0 : tty_printf (_("Key generation failed: %s\n"), gpg_strerror (err) );
4381 0 : write_status_error (card? "card_key_generate":"key_generate", err);
4382 0 : print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
4383 : }
4384 : else
4385 : {
4386 4 : PKT_public_key *pk = find_kbnode (pub_root,
4387 2 : PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4388 2 : print_status_key_created (did_sub? 'B':'P', pk,
4389 : get_parameter_value (para, pHANDLE));
4390 : }
4391 :
4392 2 : release_kbnode (pub_root);
4393 2 : xfree (cache_nonce);
4394 : }
4395 :
4396 :
4397 : static gpg_error_t
4398 0 : parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
4399 : const char *algostr, const char *usagestr,
4400 : const char *expirestr,
4401 : int *r_algo, unsigned int *r_usage, u32 *r_expire,
4402 : unsigned int *r_nbits, char **r_curve)
4403 : {
4404 : int algo;
4405 : unsigned int use, nbits;
4406 : u32 expire;
4407 : int wantuse;
4408 : unsigned int min, def, max;
4409 0 : const char *curve = NULL;
4410 0 : int eccalgo = 0;
4411 :
4412 0 : *r_curve = NULL;
4413 :
4414 0 : nbits = 0;
4415 : /* Parse the algo string. */
4416 0 : if (!algostr || !*algostr
4417 0 : || !strcmp (algostr, "default") || !strcmp (algostr, "-"))
4418 : {
4419 0 : algo = for_subkey? DEFAULT_STD_SUBALGO : DEFAULT_STD_ALGO;
4420 0 : use = for_subkey? DEFAULT_STD_SUBKEYUSE : DEFAULT_STD_KEYUSE;
4421 0 : nbits = for_subkey?DEFAULT_STD_SUBKEYSIZE : DEFAULT_STD_KEYSIZE;
4422 : }
4423 0 : else if (*algostr == '&' && strlen (algostr) == 41)
4424 : {
4425 : /* Take algo from existing key. */
4426 0 : algo = check_keygrip (ctrl, algostr+1);
4427 : /* FIXME: We need the curve name as well. */
4428 0 : return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
4429 : }
4430 0 : else if (!strncmp (algostr, "rsa", 3))
4431 : {
4432 0 : algo = PUBKEY_ALGO_RSA;
4433 0 : use = for_subkey? DEFAULT_STD_SUBKEYUSE : DEFAULT_STD_KEYUSE;
4434 0 : if (algostr[3])
4435 0 : nbits = atoi (algostr + 3);
4436 : }
4437 0 : else if (!strncmp (algostr, "elg", 3))
4438 : {
4439 0 : algo = PUBKEY_ALGO_ELGAMAL_E;
4440 0 : use = PUBKEY_USAGE_ENC;
4441 0 : if (algostr[3])
4442 0 : nbits = atoi (algostr + 3);
4443 : }
4444 0 : else if (!strncmp (algostr, "dsa", 3))
4445 : {
4446 0 : algo = PUBKEY_ALGO_DSA;
4447 0 : use = PUBKEY_USAGE_SIG;
4448 0 : if (algostr[3])
4449 0 : nbits = atoi (algostr + 3);
4450 : }
4451 0 : else if ((curve = openpgp_is_curve_supported (algostr, &algo)))
4452 : {
4453 0 : if (!algo)
4454 : {
4455 0 : algo = PUBKEY_ALGO_ECDH; /* Default ECC algorithm. */
4456 0 : eccalgo = 1; /* Remember - we may need to fix it up. */
4457 : }
4458 :
4459 0 : if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA)
4460 0 : use = PUBKEY_USAGE_SIG;
4461 : else
4462 0 : use = PUBKEY_USAGE_ENC;
4463 : }
4464 : else
4465 0 : return gpg_error (GPG_ERR_INV_CURVE);
4466 :
4467 : /* Parse the usage string. */
4468 0 : if (!usagestr || !*usagestr
4469 0 : || !strcmp (usagestr, "default") || !strcmp (usagestr, "-"))
4470 : ; /* Keep default usage */
4471 0 : else if ((wantuse = parse_usagestr (usagestr)) != -1)
4472 : {
4473 0 : use = wantuse;
4474 0 : if (eccalgo && !(use & PUBKEY_USAGE_ENC))
4475 0 : algo = PUBKEY_ALGO_ECDSA; /* Switch from ECDH to ECDSA. */
4476 : }
4477 : else
4478 0 : return gpg_error (GPG_ERR_INV_VALUE);
4479 :
4480 : /* Make sure a primary key has the CERT usage. */
4481 0 : if (!for_subkey)
4482 0 : use |= PUBKEY_USAGE_CERT;
4483 :
4484 : /* Check that usage is possible. */
4485 0 : if (/**/((use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
4486 0 : && !pubkey_get_nsig (algo))
4487 0 : || ((use & PUBKEY_USAGE_ENC)
4488 0 : && !pubkey_get_nenc (algo))
4489 0 : || (for_subkey && (use & PUBKEY_USAGE_CERT)))
4490 0 : return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
4491 :
4492 : /* Parse the expire string. */
4493 0 : if (!expirestr || !*expirestr || !strcmp (expirestr, "none")
4494 0 : || !strcmp (expirestr, "never") || !strcmp (expirestr, "-"))
4495 0 : expire = 0;
4496 : else
4497 0 : expire = parse_expire_string (expirestr);
4498 0 : if (expire == (u32)-1 )
4499 0 : return gpg_error (GPG_ERR_INV_VALUE);
4500 :
4501 : /* Make sure the keysize is in the allowed range. */
4502 0 : get_keysize_range (algo, &min, &def, &max);
4503 0 : if (!nbits)
4504 0 : nbits = def;
4505 0 : else if (nbits < min)
4506 0 : nbits = min;
4507 0 : else if (nbits > max)
4508 0 : nbits = max;
4509 :
4510 0 : nbits = fixup_keysize (nbits, algo, 1);
4511 :
4512 0 : if (curve)
4513 : {
4514 0 : *r_curve = xtrystrdup (curve);
4515 0 : if (!*r_curve)
4516 0 : return gpg_error_from_syserror ();
4517 : }
4518 0 : *r_algo = algo;
4519 0 : *r_usage = use;
4520 0 : *r_expire = expire;
4521 0 : *r_nbits = nbits;
4522 0 : return 0;
4523 : }
4524 :
4525 :
4526 : /* Add a new subkey to an existing key. Returns 0 if a new key has
4527 : been generated and put into the keyblocks. If any of ALGOSTR,
4528 : USAGESTR, or EXPIRESTR is NULL interactive mode is used. */
4529 : gpg_error_t
4530 0 : generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr,
4531 : const char *usagestr, const char *expirestr)
4532 : {
4533 0 : gpg_error_t err = 0;
4534 : int interactive;
4535 : kbnode_t node;
4536 0 : PKT_public_key *pri_psk = NULL;
4537 0 : PKT_public_key *sub_psk = NULL;
4538 : int algo;
4539 : unsigned int use;
4540 : u32 expire;
4541 0 : unsigned int nbits = 0;
4542 0 : char *curve = NULL;
4543 : u32 cur_time;
4544 0 : char *key_from_hexgrip = NULL;
4545 0 : char *hexgrip = NULL;
4546 0 : char *serialno = NULL;
4547 0 : char *cache_nonce = NULL;
4548 0 : char *passwd_nonce = NULL;
4549 :
4550 0 : interactive = (!algostr || !usagestr || !expirestr);
4551 :
4552 : /* Break out the primary key. */
4553 0 : node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
4554 0 : if (!node)
4555 : {
4556 0 : log_error ("Oops; primary key missing in keyblock!\n");
4557 0 : err = gpg_error (GPG_ERR_BUG);
4558 0 : goto leave;
4559 : }
4560 0 : pri_psk = node->pkt->pkt.public_key;
4561 :
4562 0 : cur_time = make_timestamp ();
4563 :
4564 0 : if (pri_psk->timestamp > cur_time)
4565 : {
4566 0 : ulong d = pri_psk->timestamp - cur_time;
4567 0 : log_info ( d==1 ? _("key has been created %lu second "
4568 : "in future (time warp or clock problem)\n")
4569 : : _("key has been created %lu seconds "
4570 : "in future (time warp or clock problem)\n"), d );
4571 0 : if (!opt.ignore_time_conflict)
4572 : {
4573 0 : err = gpg_error (GPG_ERR_TIME_CONFLICT);
4574 0 : goto leave;
4575 : }
4576 : }
4577 :
4578 0 : if (pri_psk->version < 4)
4579 : {
4580 0 : log_info (_("Note: creating subkeys for v3 keys "
4581 : "is not OpenPGP compliant\n"));
4582 0 : err = gpg_error (GPG_ERR_CONFLICT);
4583 0 : goto leave;
4584 : }
4585 :
4586 0 : err = hexkeygrip_from_pk (pri_psk, &hexgrip);
4587 0 : if (err)
4588 0 : goto leave;
4589 0 : if (agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
4590 : {
4591 0 : if (interactive)
4592 0 : tty_printf (_("Secret parts of primary key are not available.\n"));
4593 : else
4594 0 : log_info ( _("Secret parts of primary key are not available.\n"));
4595 0 : err = gpg_error (GPG_ERR_NO_SECKEY);
4596 0 : goto leave;
4597 : }
4598 0 : if (serialno)
4599 : {
4600 0 : if (interactive)
4601 0 : tty_printf (_("Secret parts of primary key are stored on-card.\n"));
4602 : else
4603 0 : log_info ( _("Secret parts of primary key are stored on-card.\n"));
4604 : }
4605 :
4606 0 : if (interactive)
4607 : {
4608 0 : algo = ask_algo (ctrl, 1, NULL, &use, &key_from_hexgrip);
4609 0 : log_assert (algo);
4610 :
4611 0 : if (key_from_hexgrip)
4612 0 : nbits = 0;
4613 0 : else if (algo == PUBKEY_ALGO_ECDSA
4614 0 : || algo == PUBKEY_ALGO_EDDSA
4615 0 : || algo == PUBKEY_ALGO_ECDH)
4616 0 : curve = ask_curve (&algo, NULL);
4617 : else
4618 0 : nbits = ask_keysize (algo, 0);
4619 :
4620 0 : expire = ask_expire_interval (0, NULL);
4621 0 : if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
4622 0 : _("Really create? (y/N) ")))
4623 : {
4624 0 : err = gpg_error (GPG_ERR_CANCELED);
4625 0 : goto leave;
4626 : }
4627 : }
4628 : else /* Unattended mode. */
4629 : {
4630 0 : err = parse_algo_usage_expire (ctrl, 1, algostr, usagestr, expirestr,
4631 : &algo, &use, &expire, &nbits, &curve);
4632 0 : if (err)
4633 0 : goto leave;
4634 : }
4635 :
4636 : /* Verify the passphrase now so that we get a cache item for the
4637 : * primary key passphrase. The agent also returns a passphrase
4638 : * nonce, which we can use to set the passphrase for the subkey to
4639 : * that of the primary key. */
4640 : {
4641 0 : char *desc = gpg_format_keydesc (pri_psk, FORMAT_KEYDESC_NORMAL, 1);
4642 0 : err = agent_passwd (ctrl, hexgrip, desc, 1 /*=verify*/,
4643 : &cache_nonce, &passwd_nonce);
4644 0 : xfree (desc);
4645 : }
4646 :
4647 : /* Start creation. */
4648 0 : if (key_from_hexgrip)
4649 : {
4650 0 : err = do_create_from_keygrip (ctrl, algo, key_from_hexgrip,
4651 : keyblock, cur_time, expire, 1);
4652 : }
4653 : else
4654 : {
4655 : const char *passwd;
4656 :
4657 : /* If the pinentry loopback mode is not and we have a static
4658 : passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
4659 : mode), we use that passphrase for the new subkey. */
4660 0 : if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
4661 0 : && have_static_passphrase ())
4662 0 : passwd = get_static_passphrase ();
4663 : else
4664 0 : passwd = NULL;
4665 :
4666 0 : err = do_create (algo, nbits, curve,
4667 : keyblock, cur_time, expire, 1, 0,
4668 : passwd, &cache_nonce, &passwd_nonce);
4669 : }
4670 0 : if (err)
4671 0 : goto leave;
4672 :
4673 : /* Get the pointer to the generated public subkey packet. */
4674 0 : for (node = keyblock; node; node = node->next)
4675 0 : if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4676 0 : sub_psk = node->pkt->pkt.public_key;
4677 :
4678 : /* Write the binding signature. */
4679 0 : err = write_keybinding (keyblock, pri_psk, sub_psk, use, cur_time,
4680 : cache_nonce);
4681 0 : if (err)
4682 0 : goto leave;
4683 :
4684 0 : print_status_key_created ('S', sub_psk, NULL);
4685 :
4686 :
4687 : leave:
4688 0 : xfree (key_from_hexgrip);
4689 0 : xfree (curve);
4690 0 : xfree (hexgrip);
4691 0 : xfree (serialno);
4692 0 : xfree (cache_nonce);
4693 0 : xfree (passwd_nonce);
4694 0 : if (err)
4695 0 : log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4696 0 : return err;
4697 : }
4698 :
4699 :
4700 : #ifdef ENABLE_CARD_SUPPORT
4701 : /* Generate a subkey on a card. */
4702 : gpg_error_t
4703 0 : generate_card_subkeypair (kbnode_t pub_keyblock,
4704 : int keyno, const char *serialno)
4705 : {
4706 0 : gpg_error_t err = 0;
4707 : kbnode_t node;
4708 0 : PKT_public_key *pri_pk = NULL;
4709 : int algo;
4710 : unsigned int use;
4711 : u32 expire;
4712 : u32 cur_time;
4713 0 : struct para_data_s *para = NULL;
4714 0 : PKT_public_key *sub_pk = NULL;
4715 :
4716 0 : log_assert (keyno >= 1 && keyno <= 3);
4717 :
4718 0 : para = xtrycalloc (1, sizeof *para + strlen (serialno) );
4719 0 : if (!para)
4720 : {
4721 0 : err = gpg_error_from_syserror ();
4722 0 : goto leave;
4723 : }
4724 0 : para->key = pSERIALNO;
4725 0 : strcpy (para->u.value, serialno);
4726 :
4727 : /* Break out the primary secret key */
4728 0 : node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
4729 0 : if (!node)
4730 : {
4731 0 : log_error ("Oops; publkic key lost!\n");
4732 0 : err = gpg_error (GPG_ERR_INTERNAL);
4733 0 : goto leave;
4734 : }
4735 0 : pri_pk = node->pkt->pkt.public_key;
4736 :
4737 0 : cur_time = make_timestamp();
4738 0 : if (pri_pk->timestamp > cur_time)
4739 : {
4740 0 : ulong d = pri_pk->timestamp - cur_time;
4741 0 : log_info (d==1 ? _("key has been created %lu second "
4742 : "in future (time warp or clock problem)\n")
4743 : : _("key has been created %lu seconds "
4744 : "in future (time warp or clock problem)\n"), d );
4745 0 : if (!opt.ignore_time_conflict)
4746 : {
4747 0 : err = gpg_error (GPG_ERR_TIME_CONFLICT);
4748 0 : goto leave;
4749 : }
4750 : }
4751 :
4752 0 : if (pri_pk->version < 4)
4753 : {
4754 0 : log_info (_("Note: creating subkeys for v3 keys "
4755 : "is not OpenPGP compliant\n"));
4756 0 : err = gpg_error (GPG_ERR_NOT_SUPPORTED);
4757 0 : goto leave;
4758 : }
4759 :
4760 0 : algo = PUBKEY_ALGO_RSA;
4761 0 : expire = ask_expire_interval (0, NULL);
4762 0 : if (keyno == 1)
4763 0 : use = PUBKEY_USAGE_SIG;
4764 0 : else if (keyno == 2)
4765 0 : use = PUBKEY_USAGE_ENC;
4766 : else
4767 0 : use = PUBKEY_USAGE_AUTH;
4768 0 : if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
4769 0 : _("Really create? (y/N) ")))
4770 : {
4771 0 : err = gpg_error (GPG_ERR_CANCELED);
4772 0 : goto leave;
4773 : }
4774 :
4775 : /* Note, that depending on the backend, the card key generation may
4776 : update CUR_TIME. */
4777 0 : err = gen_card_key (algo, keyno, 0, pub_keyblock, &cur_time, expire);
4778 : /* Get the pointer to the generated public subkey packet. */
4779 0 : if (!err)
4780 : {
4781 0 : for (node = pub_keyblock; node; node = node->next)
4782 0 : if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4783 0 : sub_pk = node->pkt->pkt.public_key;
4784 0 : log_assert (sub_pk);
4785 0 : err = write_keybinding (pub_keyblock, pri_pk, sub_pk,
4786 : use, cur_time, NULL);
4787 : }
4788 :
4789 : leave:
4790 0 : if (err)
4791 0 : log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4792 : else
4793 0 : print_status_key_created ('S', sub_pk, NULL);
4794 0 : release_parameter_list (para);
4795 0 : return err;
4796 : }
4797 : #endif /* !ENABLE_CARD_SUPPORT */
4798 :
4799 : /*
4800 : * Write a keyblock to an output stream
4801 : */
4802 : static int
4803 0 : write_keyblock( IOBUF out, KBNODE node )
4804 : {
4805 0 : for( ; node ; node = node->next )
4806 : {
4807 0 : if(!is_deleted_kbnode(node))
4808 : {
4809 0 : int rc = build_packet( out, node->pkt );
4810 0 : if( rc )
4811 : {
4812 0 : log_error("build_packet(%d) failed: %s\n",
4813 0 : node->pkt->pkttype, gpg_strerror (rc) );
4814 0 : return rc;
4815 : }
4816 : }
4817 : }
4818 :
4819 0 : return 0;
4820 : }
4821 :
4822 :
4823 : /* Note that timestamp is an in/out arg. */
4824 : static gpg_error_t
4825 0 : gen_card_key (int algo, int keyno, int is_primary, kbnode_t pub_root,
4826 : u32 *timestamp, u32 expireval)
4827 : {
4828 : #ifdef ENABLE_CARD_SUPPORT
4829 : gpg_error_t err;
4830 : struct agent_card_genkey_s info;
4831 : PACKET *pkt;
4832 : PKT_public_key *pk;
4833 :
4834 0 : if (algo != PUBKEY_ALGO_RSA)
4835 0 : return gpg_error (GPG_ERR_PUBKEY_ALGO);
4836 :
4837 0 : pk = xtrycalloc (1, sizeof *pk );
4838 0 : if (!pk)
4839 0 : return gpg_error_from_syserror ();
4840 0 : pkt = xtrycalloc (1, sizeof *pkt);
4841 0 : if (!pkt)
4842 : {
4843 0 : xfree (pk);
4844 0 : return gpg_error_from_syserror ();
4845 : }
4846 :
4847 : /* Note: SCD knows the serialnumber, thus there is no point in passing it. */
4848 0 : err = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
4849 : /* The code below is not used because we force creation of
4850 : * the a card key (3rd arg).
4851 : * if (gpg_err_code (rc) == GPG_ERR_EEXIST)
4852 : * {
4853 : * tty_printf ("\n");
4854 : * log_error ("WARNING: key does already exists!\n");
4855 : * tty_printf ("\n");
4856 : * if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
4857 : * _("Replace existing key? ")))
4858 : * rc = agent_scd_genkey (&info, keyno, 1);
4859 : * }
4860 : */
4861 0 : if (!err && (!info.n || !info.e))
4862 : {
4863 0 : log_error ("communication error with SCD\n");
4864 0 : gcry_mpi_release (info.n);
4865 0 : gcry_mpi_release (info.e);
4866 0 : err = gpg_error (GPG_ERR_GENERAL);
4867 : }
4868 0 : if (err)
4869 : {
4870 0 : log_error ("key generation failed: %s\n", gpg_strerror (err));
4871 0 : xfree (pkt);
4872 0 : xfree (pk);
4873 0 : return err;
4874 : }
4875 :
4876 : /* Send the learn command so that the agent creates a shadow key for
4877 : card key. We need to do that now so that we are able to create
4878 : the self-signatures. */
4879 0 : err = agent_scd_learn (NULL, 0);
4880 0 : if (err)
4881 : {
4882 : /* Oops: Card removed during generation. */
4883 0 : log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err));
4884 0 : xfree (pkt);
4885 0 : xfree (pk);
4886 0 : return err;
4887 : }
4888 :
4889 0 : if (*timestamp != info.created_at)
4890 0 : log_info ("NOTE: the key does not use the suggested creation date\n");
4891 0 : *timestamp = info.created_at;
4892 :
4893 0 : pk->timestamp = info.created_at;
4894 0 : pk->version = 4;
4895 0 : if (expireval)
4896 0 : pk->expiredate = pk->timestamp + expireval;
4897 0 : pk->pubkey_algo = algo;
4898 0 : pk->pkey[0] = info.n;
4899 0 : pk->pkey[1] = info.e;
4900 :
4901 0 : pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4902 0 : pkt->pkt.public_key = pk;
4903 0 : add_kbnode (pub_root, new_kbnode (pkt));
4904 :
4905 0 : return 0;
4906 : #else
4907 : (void)algo;
4908 : (void)keyno;
4909 : (void)is_primary;
4910 : (void)pub_root;
4911 : (void)timestamp;
4912 : (void)expireval;
4913 : return gpg_error (GPG_ERR_NOT_SUPPORTED);
4914 : #endif /*!ENABLE_CARD_SUPPORT*/
4915 : }
|