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