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
5 * This file is part of GnuPG.
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.
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.
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/>.
27 #include <sys/types.h>
41 #include "keyserver-internal.h"
42 #include "call-agent.h"
44 #include "../common/shareddefs.h"
46 #include "mbox-util.h"
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. See also
52 get_keysize_range which encodes the allowed ranges. */
53 #define DEFAULT_STD_KEY_PARAM "rsa2048/cert,sign+rsa2048/encr"
54 #define FUTURE_STD_KEY_PARAM "ed25519/cert,sign+cv25519/encr"
56 /* When generating keys using the streamlined key generation dialog,
57 use this as a default expiration interval. */
58 const char *default_expiration_interval = "2y";
60 /* Flag bits used during key generation. */
61 #define KEYGEN_FLAG_NO_PROTECTION 1
62 #define KEYGEN_FLAG_TRANSIENT_KEY 2
64 /* Maximum number of supported algorithm preferences. */
84 pKEYCREATIONDATE, /* Same in seconds since epoch. */
86 pKEYEXPIRE, /* in n seconds */
87 pSUBKEYEXPIRE, /* in n seconds */
96 struct para_data_s *next;
103 struct revocation_key revkey;
108 struct output_control_s
112 unsigned int keygen_flags;
118 armor_filter_context_t *afx;
123 struct opaque_data_usage_and_pk {
129 static int prefs_initialized = 0;
130 static byte sym_prefs[MAX_PREFS];
131 static int nsym_prefs;
132 static byte hash_prefs[MAX_PREFS];
133 static int nhash_prefs;
134 static byte zip_prefs[MAX_PREFS];
135 static int nzip_prefs;
136 static int mdc_available,ks_modify;
138 static gpg_error_t parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
139 const char *algostr, const char *usagestr,
140 const char *expirestr,
141 int *r_algo, unsigned int *r_usage,
143 unsigned int *r_nbits, char **r_curve);
144 static void do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
145 struct output_control_s *outctrl, int card );
146 static int write_keyblock (iobuf_t out, kbnode_t node);
147 static gpg_error_t gen_card_key (int keyno, int algo, int is_primary,
148 kbnode_t pub_root, u32 *timestamp,
150 static unsigned int get_keysize_range (int algo,
151 unsigned int *min, unsigned int *max);
155 /* Return the algo string for a default new key. */
157 get_default_pubkey_algo (void)
159 if (opt.def_new_key_algo)
161 if (*opt.def_new_key_algo && !strchr (opt.def_new_key_algo, ':'))
162 return opt.def_new_key_algo;
163 /* To avoid checking that option every time we delay that until
164 * here. The only thing we really need to make sure is that
165 * there is no colon in the string so that the --gpgconf-list
166 * command won't mess up its output. */
167 log_info (_("invalid value for option '%s'\n"), "--default-new-key-algo");
169 return DEFAULT_STD_KEY_PARAM;
174 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
176 byte array[MAX_FINGERPRINT_LEN], *s;
183 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
192 fingerprint_from_pk (pk, array, &n);
194 /* Fixme: Use bin2hex */
195 for (i=0; i < n ; i++, s++, p += 2)
196 snprintf (p, 3, "%02X", *s);
202 for (i=0; handle[i] && i < 100; i++)
203 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
206 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
212 print_status_key_not_created (const char *handle)
214 print_status_key_created (0, NULL, handle);
220 write_uid( KBNODE root, const char *s )
222 PACKET *pkt = xmalloc_clear(sizeof *pkt );
223 size_t n = strlen(s);
225 pkt->pkttype = PKT_USER_ID;
226 pkt->pkt.user_id = xmalloc_clear (sizeof *pkt->pkt.user_id + n);
227 pkt->pkt.user_id->len = n;
228 pkt->pkt.user_id->ref = 1;
229 strcpy(pkt->pkt.user_id->name, s);
230 add_kbnode( root, new_kbnode( pkt ) );
234 do_add_key_flags (PKT_signature *sig, unsigned int use)
240 /* The spec says that all primary keys MUST be able to certify. */
241 if(sig->sig_class!=0x18)
244 if (use & PUBKEY_USAGE_SIG)
246 if (use & PUBKEY_USAGE_ENC)
247 buf[0] |= 0x04 | 0x08;
248 if (use & PUBKEY_USAGE_AUTH)
251 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
256 keygen_add_key_expire (PKT_signature *sig, void *opaque)
258 PKT_public_key *pk = opaque;
264 if (pk->expiredate > pk->timestamp)
265 u = pk->expiredate - pk->timestamp;
269 buf[0] = (u >> 24) & 0xff;
270 buf[1] = (u >> 16) & 0xff;
271 buf[2] = (u >> 8) & 0xff;
273 build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
277 /* Make sure we don't leave a key expiration subpacket lying
279 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
286 /* Add the key usage (i.e. key flags) in SIG from the public keys
287 * pubkey_usage field. OPAQUE has the public key. */
289 keygen_add_key_flags (PKT_signature *sig, void *opaque)
291 PKT_public_key *pk = opaque;
293 do_add_key_flags (sig, pk->pubkey_usage);
299 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
301 struct opaque_data_usage_and_pk *oduap = opaque;
303 do_add_key_flags (sig, oduap->usage);
304 return keygen_add_key_expire (sig, oduap->pk);
309 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
313 for (i=0; i < *nbuf; i++ )
316 log_info (_("preference '%s' duplicated\n"), item);
320 if (*nbuf >= MAX_PREFS)
323 log_info(_("too many cipher preferences\n"));
325 log_info(_("too many digest preferences\n"));
327 log_info(_("too many compression preferences\n"));
334 buf[(*nbuf)++] = val;
339 * Parse the supplied string and use it to set the standard
340 * preferences. The string may be in a form like the one printed by
341 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
342 * cipher/hash/compress names. Use NULL to set the default
343 * preferences. Returns: 0 = okay
346 keygen_set_std_prefs (const char *string,int personal)
348 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
349 int nsym=0, nhash=0, nzip=0, val, rc=0;
350 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
351 char dummy_string[20*4+1]; /* Enough for 20 items. */
353 if (!string || !ascii_strcasecmp (string, "default"))
355 if (opt.def_preference_list)
356 string=opt.def_preference_list;
359 int any_compress = 0;
360 dummy_string[0]='\0';
362 /* The rationale why we use the order AES256,192,128 is
363 for compatibility reasons with PGP. If gpg would
364 define AES128 first, we would get the somewhat
367 gpg -r pgpkey -r gpgkey ---gives--> AES256
368 gpg -r gpgkey -r pgpkey ---gives--> AES
370 Note that by using --personal-cipher-preferences it is
371 possible to prefer AES128.
374 /* Make sure we do not add more than 15 items here, as we
375 could overflow the size of dummy_string. We currently
377 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
378 strcat(dummy_string,"S9 ");
379 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
380 strcat(dummy_string,"S8 ");
381 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
382 strcat(dummy_string,"S7 ");
383 strcat(dummy_string,"S2 "); /* 3DES */
385 /* The default hash algo order is:
386 SHA-256, SHA-384, SHA-512, SHA-224, SHA-1.
388 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
389 strcat (dummy_string, "H8 ");
391 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
392 strcat (dummy_string, "H9 ");
394 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
395 strcat (dummy_string, "H10 ");
397 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
398 strcat (dummy_string, "H11 ");
400 strcat (dummy_string, "H2 "); /* SHA-1 */
402 if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
404 strcat(dummy_string,"Z2 ");
408 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
410 strcat(dummy_string,"Z3 ");
414 if(!check_compress_algo(COMPRESS_ALGO_ZIP))
416 strcat(dummy_string,"Z1 ");
420 /* In case we have no compress algo at all, declare that
421 we prefer no compresssion. */
423 strcat(dummy_string,"Z0 ");
425 /* Remove the trailing space. */
426 if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
427 dummy_string[strlen (dummy_string)-1] = 0;
432 else if (!ascii_strcasecmp (string, "none"))
438 char *tok, *prefstring;
440 /* We need a writable string. */
441 prefstring = prefstringbuf = xstrdup (string);
443 while((tok=strsep(&prefstring," ,")))
445 if((val=string_to_cipher_algo (tok)))
447 if(set_one_pref(val,1,tok,sym,&nsym))
450 else if((val=string_to_digest_algo (tok)))
452 if(set_one_pref(val,2,tok,hash,&nhash))
455 else if((val=string_to_compress_algo(tok))>-1)
457 if(set_one_pref(val,3,tok,zip,&nzip))
460 else if (ascii_strcasecmp(tok,"mdc")==0)
462 else if (ascii_strcasecmp(tok,"no-mdc")==0)
464 else if (ascii_strcasecmp(tok,"ks-modify")==0)
466 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
470 log_info (_("invalid item '%s' in preference string\n"),tok);
475 xfree (prefstringbuf);
482 if(personal==PREFTYPE_SYM)
484 xfree(opt.personal_cipher_prefs);
487 opt.personal_cipher_prefs=NULL;
492 opt.personal_cipher_prefs=
493 xmalloc(sizeof(prefitem_t *)*(nsym+1));
495 for (i=0; i<nsym; i++)
497 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
498 opt.personal_cipher_prefs[i].value = sym[i];
501 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
502 opt.personal_cipher_prefs[i].value = 0;
505 else if(personal==PREFTYPE_HASH)
507 xfree(opt.personal_digest_prefs);
510 opt.personal_digest_prefs=NULL;
515 opt.personal_digest_prefs=
516 xmalloc(sizeof(prefitem_t *)*(nhash+1));
518 for (i=0; i<nhash; i++)
520 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
521 opt.personal_digest_prefs[i].value = hash[i];
524 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
525 opt.personal_digest_prefs[i].value = 0;
528 else if(personal==PREFTYPE_ZIP)
530 xfree(opt.personal_compress_prefs);
533 opt.personal_compress_prefs=NULL;
538 opt.personal_compress_prefs=
539 xmalloc(sizeof(prefitem_t *)*(nzip+1));
541 for (i=0; i<nzip; i++)
543 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
544 opt.personal_compress_prefs[i].value = zip[i];
547 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
548 opt.personal_compress_prefs[i].value = 0;
554 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
555 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
556 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
559 prefs_initialized = 1;
566 /* Return a fake user ID containing the preferences. Caller must
569 keygen_get_std_prefs(void)
572 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
574 if(!prefs_initialized)
575 keygen_set_std_prefs(NULL,0);
579 uid->prefs=xmalloc((sizeof(prefitem_t *)*
580 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
582 for(i=0;i<nsym_prefs;i++,j++)
584 uid->prefs[j].type=PREFTYPE_SYM;
585 uid->prefs[j].value=sym_prefs[i];
588 for(i=0;i<nhash_prefs;i++,j++)
590 uid->prefs[j].type=PREFTYPE_HASH;
591 uid->prefs[j].value=hash_prefs[i];
594 for(i=0;i<nzip_prefs;i++,j++)
596 uid->prefs[j].type=PREFTYPE_ZIP;
597 uid->prefs[j].value=zip_prefs[i];
600 uid->prefs[j].type=PREFTYPE_NONE;
601 uid->prefs[j].value=0;
603 uid->flags.mdc=mdc_available;
604 uid->flags.ks_modify=ks_modify;
610 add_feature_mdc (PKT_signature *sig,int enabled)
617 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
618 /* Already set or cleared */
620 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
623 if (!s || !n) { /* create a new one */
625 buf = xmalloc_clear (n);
633 buf[0] |= 0x01; /* MDC feature */
637 /* Are there any bits set? */
643 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
645 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
651 add_keyserver_modify (PKT_signature *sig,int enabled)
658 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
661 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
662 /* Already set or cleared */
664 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
667 if (!s || !n) { /* create a new one */
669 buf = xmalloc_clear (n);
677 buf[0] |= 0x80; /* no-modify flag */
681 /* Are there any bits set? */
687 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
689 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
696 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
700 if (!prefs_initialized)
701 keygen_set_std_prefs (NULL, 0);
704 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
707 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
708 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
712 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
715 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
716 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
720 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
723 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
724 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
727 /* Make sure that the MDC feature flag is set if needed. */
728 add_feature_mdc (sig,mdc_available);
729 add_keyserver_modify (sig,ks_modify);
730 keygen_add_keyserver_url(sig,NULL);
737 * Add preference to the self signature packet.
738 * This is only called for packets with version > 3.
741 keygen_add_std_prefs (PKT_signature *sig, void *opaque)
743 PKT_public_key *pk = opaque;
745 do_add_key_flags (sig, pk->pubkey_usage);
746 keygen_add_key_expire (sig, opaque );
747 keygen_upd_std_prefs (sig, opaque);
748 keygen_add_keyserver_url (sig,NULL);
754 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
756 const char *url=opaque;
759 url=opt.def_keyserver_url;
762 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
764 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
770 keygen_add_notations(PKT_signature *sig,void *opaque)
772 struct notation *notation;
774 /* We always start clean */
775 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
776 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
777 sig->flags.notation=0;
779 for(notation=opaque;notation;notation=notation->next)
780 if(!notation->flags.ignore)
785 n1=strlen(notation->name);
786 if(notation->altvalue)
787 n2=strlen(notation->altvalue);
788 else if(notation->bdat)
791 n2=strlen(notation->value);
793 buf = xmalloc( 8 + n1 + n2 );
795 /* human readable or not */
796 buf[0] = notation->bdat?0:0x80;
797 buf[1] = buf[2] = buf[3] = 0;
802 memcpy(buf+8, notation->name, n1 );
803 if(notation->altvalue)
804 memcpy(buf+8+n1, notation->altvalue, n2 );
805 else if(notation->bdat)
806 memcpy(buf+8+n1, notation->bdat, n2 );
808 memcpy(buf+8+n1, notation->value, n2 );
809 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
810 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
819 keygen_add_revkey (PKT_signature *sig, void *opaque)
821 struct revocation_key *revkey = opaque;
822 byte buf[2+MAX_FINGERPRINT_LEN];
824 buf[0] = revkey->class;
825 buf[1] = revkey->algid;
826 memcpy (&buf[2], revkey->fpr, MAX_FINGERPRINT_LEN);
828 build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+MAX_FINGERPRINT_LEN);
830 /* All sigs with revocation keys set are nonrevocable. */
831 sig->flags.revocable = 0;
833 build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
842 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
843 signature creation time. */
845 make_backsig (PKT_signature *sig, PKT_public_key *pk,
846 PKT_public_key *sub_pk, PKT_public_key *sub_psk,
847 u32 timestamp, const char *cache_nonce)
850 PKT_signature *backsig;
852 cache_public_key (sub_pk);
854 err = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_psk, 0x19,
855 0, timestamp, 0, NULL, NULL, cache_nonce);
857 log_error ("make_keysig_packet failed for backsig: %s\n",
861 /* Get it into a binary packed form. */
862 IOBUF backsig_out = iobuf_temp();
865 init_packet (&backsig_pkt);
866 backsig_pkt.pkttype = PKT_SIGNATURE;
867 backsig_pkt.pkt.signature = backsig;
868 err = build_packet (backsig_out, &backsig_pkt);
869 free_packet (&backsig_pkt);
871 log_error ("build_packet failed for backsig: %s\n", gpg_strerror (err));
875 byte *buf = iobuf_get_temp_buffer (backsig_out);
877 /* Remove the packet header. */
885 else if(buf[1] < 224)
887 pktlen = (buf[1]-192)*256;
888 pktlen += buf[2]+192;
891 else if (buf[1] == 255)
893 pktlen = buf32_to_size_t (buf+2);
910 pktlen = (size_t)buf[mark++] << 24;
911 pktlen |= buf[mark++] << 16;
914 pktlen |= buf[mark++] << 8;
917 pktlen |= buf[mark++];
923 /* Now make the binary blob into a subpacket. */
924 build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
926 iobuf_close (backsig_out);
934 /* Write a direct key signature to the first key in ROOT using the key
935 PSK. REVKEY is describes the direct key signature and TIMESTAMP is
936 the timestamp to set on the signature. */
938 write_direct_sig (KBNODE root, PKT_public_key *psk,
939 struct revocation_key *revkey, u32 timestamp,
940 const char *cache_nonce)
949 log_info (_("writing direct signature\n"));
951 /* Get the pk packet from the pub_tree. */
952 node = find_kbnode (root, PKT_PUBLIC_KEY);
955 pk = node->pkt->pkt.public_key;
957 /* We have to cache the key, so that the verification of the
958 signature creation is able to retrieve the public key. */
959 cache_public_key (pk);
961 /* Make the signature. */
962 err = make_keysig_packet (&sig, pk, NULL,NULL, psk, 0x1F,
964 keygen_add_revkey, revkey, cache_nonce);
967 log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err) );
971 pkt = xmalloc_clear (sizeof *pkt);
972 pkt->pkttype = PKT_SIGNATURE;
973 pkt->pkt.signature = sig;
974 add_kbnode (root, new_kbnode (pkt));
980 /* Write a self-signature to the first user id in ROOT using the key
981 PSK. USE and TIMESTAMP give the extra data we need for the
984 write_selfsigs (KBNODE root, PKT_public_key *psk,
985 unsigned int use, u32 timestamp, const char *cache_nonce)
995 log_info (_("writing self signature\n"));
997 /* Get the uid packet from the list. */
998 node = find_kbnode (root, PKT_USER_ID);
1000 BUG(); /* No user id packet in tree. */
1001 uid = node->pkt->pkt.user_id;
1003 /* Get the pk packet from the pub_tree. */
1004 node = find_kbnode (root, PKT_PUBLIC_KEY);
1007 pk = node->pkt->pkt.public_key;
1009 /* The usage has not yet been set - do it now. */
1010 pk->pubkey_usage = use;
1012 /* We have to cache the key, so that the verification of the
1013 signature creation is able to retrieve the public key. */
1014 cache_public_key (pk);
1016 /* Make the signature. */
1017 err = make_keysig_packet (&sig, pk, uid, NULL, psk, 0x13,
1019 keygen_add_std_prefs, pk, cache_nonce);
1022 log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
1026 pkt = xmalloc_clear (sizeof *pkt);
1027 pkt->pkttype = PKT_SIGNATURE;
1028 pkt->pkt.signature = sig;
1029 add_kbnode (root, new_kbnode (pkt));
1035 /* Write the key binding signature. If TIMESTAMP is not NULL use the
1036 signature creation time. PRI_PSK is the key use for signing.
1037 SUB_PSK is a key used to create a back-signature; that one is only
1038 used if USE has the PUBKEY_USAGE_SIG capability. */
1040 write_keybinding (KBNODE root, PKT_public_key *pri_psk, PKT_public_key *sub_psk,
1041 unsigned int use, u32 timestamp, const char *cache_nonce)
1047 PKT_public_key *pri_pk, *sub_pk;
1048 struct opaque_data_usage_and_pk oduap;
1051 log_info(_("writing key binding signature\n"));
1053 /* Get the primary pk packet from the tree. */
1054 node = find_kbnode (root, PKT_PUBLIC_KEY);
1057 pri_pk = node->pkt->pkt.public_key;
1059 /* We have to cache the key, so that the verification of the
1060 * signature creation is able to retrieve the public key. */
1061 cache_public_key (pri_pk);
1063 /* Find the last subkey. */
1065 for (node = root; node; node = node->next )
1067 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1068 sub_pk = node->pkt->pkt.public_key;
1073 /* Make the signature. */
1076 err = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
1078 keygen_add_key_flags_and_expire, &oduap,
1082 log_error ("make_keysig_packeto failed: %s\n", gpg_strerror (err));
1086 /* Make a backsig. */
1087 if (use & PUBKEY_USAGE_SIG)
1089 err = make_backsig (sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
1094 pkt = xmalloc_clear ( sizeof *pkt );
1095 pkt->pkttype = PKT_SIGNATURE;
1096 pkt->pkt.signature = sig;
1097 add_kbnode (root, new_kbnode (pkt) );
1103 ecckey_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp, int algo)
1106 gcry_sexp_t list, l2;
1116 list = gcry_sexp_find_token (sexp, "public-key", 0);
1118 return gpg_error (GPG_ERR_INV_OBJ);
1119 l2 = gcry_sexp_cadr (list);
1120 gcry_sexp_release (list);
1123 return gpg_error (GPG_ERR_NO_OBJ);
1125 l2 = gcry_sexp_find_token (list, "curve", 0);
1128 err = gpg_error (GPG_ERR_NO_OBJ);
1131 curve = gcry_sexp_nth_string (l2, 1);
1134 err = gpg_error (GPG_ERR_NO_OBJ);
1137 gcry_sexp_release (l2);
1138 oidstr = openpgp_curve_to_oid (curve, &nbits);
1141 /* That can't happen because we used one of the curves
1142 gpg_curve_to_oid knows about. */
1143 err = gpg_error (GPG_ERR_INV_OBJ);
1146 err = openpgp_oid_from_str (oidstr, &array[0]);
1150 l2 = gcry_sexp_find_token (list, "q", 0);
1153 err = gpg_error (GPG_ERR_NO_OBJ);
1156 array[1] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1157 gcry_sexp_release (l2);
1160 err = gpg_error (GPG_ERR_INV_OBJ);
1163 gcry_sexp_release (list);
1165 if (algo == PUBKEY_ALGO_ECDH)
1167 array[2] = pk_ecdh_default_params (nbits);
1170 err = gpg_error_from_syserror ();
1179 for (i=0; i < 3; i++)
1181 gcry_mpi_release (array[i]);
1189 /* Extract key parameters from SEXP and store them in ARRAY. ELEMS is
1190 a string where each character denotes a parameter name. TOPNAME is
1191 the name of the top element above the elements. */
1193 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1194 const char *topname, const char *elems)
1196 gcry_sexp_t list, l2;
1201 list = gcry_sexp_find_token (sexp, topname, 0);
1203 return gpg_error (GPG_ERR_INV_OBJ);
1204 l2 = gcry_sexp_cadr (list);
1205 gcry_sexp_release (list);
1208 return gpg_error (GPG_ERR_NO_OBJ);
1210 for (idx=0,s=elems; *s; s++, idx++)
1212 l2 = gcry_sexp_find_token (list, s, 1);
1215 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1218 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1219 gcry_sexp_release (l2);
1222 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1226 gcry_sexp_release (list);
1231 for (i=0; i<idx; i++)
1233 gcry_mpi_release (array[i]);
1236 gcry_sexp_release (list);
1242 /* Create a keyblock using the given KEYGRIP. ALGO is the OpenPGP
1243 algorithm of that keygrip. */
1245 do_create_from_keygrip (ctrl_t ctrl, int algo, const char *hexkeygrip,
1246 kbnode_t pub_root, u32 timestamp, u32 expireval,
1253 const char *algoelem;
1255 if (hexkeygrip[0] == '&')
1260 case PUBKEY_ALGO_RSA: algoelem = "ne"; break;
1261 case PUBKEY_ALGO_DSA: algoelem = "pqgy"; break;
1262 case PUBKEY_ALGO_ELGAMAL_E: algoelem = "pgy"; break;
1263 case PUBKEY_ALGO_ECDH:
1264 case PUBKEY_ALGO_ECDSA: algoelem = ""; break;
1265 case PUBKEY_ALGO_EDDSA: algoelem = ""; break;
1266 default: return gpg_error (GPG_ERR_INTERNAL);
1270 /* Ask the agent for the public key matching HEXKEYGRIP. */
1272 unsigned char *public;
1274 err = agent_readkey (ctrl, 0, hexkeygrip, &public);
1277 err = gcry_sexp_sscan (&s_key, NULL,
1278 public, gcry_sexp_canon_len (public, 0, NULL, NULL));
1284 /* Build a public key packet. */
1285 pk = xtrycalloc (1, sizeof *pk);
1288 err = gpg_error_from_syserror ();
1289 gcry_sexp_release (s_key);
1293 pk->timestamp = timestamp;
1296 pk->expiredate = pk->timestamp + expireval;
1297 pk->pubkey_algo = algo;
1299 if (algo == PUBKEY_ALGO_ECDSA
1300 || algo == PUBKEY_ALGO_EDDSA
1301 || algo == PUBKEY_ALGO_ECDH )
1302 err = ecckey_from_sexp (pk->pkey, s_key, algo);
1304 err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1307 log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1308 gcry_sexp_release (s_key);
1309 free_public_key (pk);
1312 gcry_sexp_release (s_key);
1314 pkt = xtrycalloc (1, sizeof *pkt);
1317 err = gpg_error_from_syserror ();
1318 free_public_key (pk);
1322 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1323 pkt->pkt.public_key = pk;
1324 add_kbnode (pub_root, new_kbnode (pkt));
1330 /* Common code for the key generation function gen_xxx. */
1332 common_gen (const char *keyparms, int algo, const char *algoelem,
1333 kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
1334 int keygen_flags, const char *passphrase,
1335 char **cache_nonce_addr, char **passwd_nonce_addr)
1342 err = agent_genkey (NULL, cache_nonce_addr, passwd_nonce_addr, keyparms,
1343 !!(keygen_flags & KEYGEN_FLAG_NO_PROTECTION),
1348 log_error ("agent_genkey failed: %s\n", gpg_strerror (err) );
1352 pk = xtrycalloc (1, sizeof *pk);
1355 err = gpg_error_from_syserror ();
1356 gcry_sexp_release (s_key);
1360 pk->timestamp = timestamp;
1363 pk->expiredate = pk->timestamp + expireval;
1364 pk->pubkey_algo = algo;
1366 if (algo == PUBKEY_ALGO_ECDSA
1367 || algo == PUBKEY_ALGO_EDDSA
1368 || algo == PUBKEY_ALGO_ECDH )
1369 err = ecckey_from_sexp (pk->pkey, s_key, algo);
1371 err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1374 log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1375 gcry_sexp_release (s_key);
1376 free_public_key (pk);
1379 gcry_sexp_release (s_key);
1381 pkt = xtrycalloc (1, sizeof *pkt);
1384 err = gpg_error_from_syserror ();
1385 free_public_key (pk);
1389 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1390 pkt->pkt.public_key = pk;
1391 add_kbnode (pub_root, new_kbnode (pkt));
1398 * Generate an Elgamal key.
1401 gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
1402 u32 timestamp, u32 expireval, int is_subkey,
1403 int keygen_flags, const char *passphrase,
1404 char **cache_nonce_addr, char **passwd_nonce_addr)
1410 log_assert (is_ELGAMAL (algo));
1415 log_info (_("keysize invalid; using %u bits\n"), nbits );
1417 else if (nbits > 4096)
1420 log_info (_("keysize invalid; using %u bits\n"), nbits );
1425 nbits = ((nbits + 31) / 32) * 32;
1426 log_info (_("keysize rounded up to %u bits\n"), nbits );
1429 /* Note that we use transient-key only if no-protection has also
1431 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1432 keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
1433 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1434 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1435 strlen (nbitsstr), nbitsstr,
1436 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1437 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1438 "(transient-key)" : "" );
1440 err = gpg_error_from_syserror ();
1443 err = common_gen (keyparms, algo, "pgy",
1444 pub_root, timestamp, expireval, is_subkey,
1445 keygen_flags, passphrase,
1446 cache_nonce_addr, passwd_nonce_addr);
1455 * Generate an DSA key
1458 gen_dsa (unsigned int nbits, KBNODE pub_root,
1459 u32 timestamp, u32 expireval, int is_subkey,
1460 int keygen_flags, const char *passphrase,
1461 char **cache_nonce_addr, char **passwd_nonce_addr)
1472 log_info(_("keysize invalid; using %u bits\n"), nbits );
1474 else if ( nbits > 3072 )
1477 log_info(_("keysize invalid; using %u bits\n"), nbits );
1482 nbits = ((nbits + 63) / 64) * 64;
1483 log_info(_("keysize rounded up to %u bits\n"), nbits );
1486 /* To comply with FIPS rules we round up to the next value unless in
1488 if (!opt.expert && nbits > 1024 && (nbits % 1024))
1490 nbits = ((nbits + 1023) / 1024) * 1024;
1491 log_info(_("keysize rounded up to %u bits\n"), nbits );
1495 Figure out a q size based on the key size. FIPS 180-3 says:
1502 2048/256 is an odd pair since there is also a 2048/224 and
1503 3072/256. Matching sizes is not a very exact science.
1505 We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1506 but less than 2048, and 160 for 1024 (DSA1).
1511 else if ( nbits > 1024)
1517 log_info (_("WARNING: some OpenPGP programs can't"
1518 " handle a DSA key with this digest size\n"));
1520 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1521 snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
1522 keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
1523 strlen (nbitsstr), nbitsstr,
1524 strlen (qbitsstr), qbitsstr,
1525 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1526 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1527 "(transient-key)" : "" );
1529 err = gpg_error_from_syserror ();
1532 err = common_gen (keyparms, PUBKEY_ALGO_DSA, "pqgy",
1533 pub_root, timestamp, expireval, is_subkey,
1534 keygen_flags, passphrase,
1535 cache_nonce_addr, passwd_nonce_addr);
1545 * Generate an ECC key
1548 gen_ecc (int algo, const char *curve, kbnode_t pub_root,
1549 u32 timestamp, u32 expireval, int is_subkey,
1550 int keygen_flags, const char *passphrase,
1551 char **cache_nonce_addr, char **passwd_nonce_addr)
1556 log_assert (algo == PUBKEY_ALGO_ECDSA
1557 || algo == PUBKEY_ALGO_EDDSA
1558 || algo == PUBKEY_ALGO_ECDH);
1560 if (!curve || !*curve)
1561 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
1563 /* Note that we use the "comp" flag with EdDSA to request the use of
1564 a 0x40 compression prefix octet. */
1565 if (algo == PUBKEY_ALGO_EDDSA)
1566 keyparms = xtryasprintf
1567 ("(genkey(ecc(curve %zu:%s)(flags eddsa comp%s)))",
1568 strlen (curve), curve,
1569 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1570 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1571 " transient-key" : ""));
1572 else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "Curve25519"))
1573 keyparms = xtryasprintf
1574 ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
1575 strlen (curve), curve,
1576 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1577 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1578 " transient-key" : ""));
1580 keyparms = xtryasprintf
1581 ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
1582 strlen (curve), curve,
1583 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1584 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1585 " transient-key" : ""));
1588 err = gpg_error_from_syserror ();
1591 err = common_gen (keyparms, algo, "",
1592 pub_root, timestamp, expireval, is_subkey,
1593 keygen_flags, passphrase,
1594 cache_nonce_addr, passwd_nonce_addr);
1603 * Generate an RSA key.
1606 gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
1607 u32 timestamp, u32 expireval, int is_subkey,
1608 int keygen_flags, const char *passphrase,
1609 char **cache_nonce_addr, char **passwd_nonce_addr)
1614 const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
1616 log_assert (is_RSA(algo));
1619 nbits = get_keysize_range (algo, NULL, NULL);
1624 log_info (_("keysize invalid; using %u bits\n"), nbits );
1626 else if (nbits > maxsize)
1629 log_info (_("keysize invalid; using %u bits\n"), nbits );
1634 nbits = ((nbits + 31) / 32) * 32;
1635 log_info (_("keysize rounded up to %u bits\n"), nbits );
1638 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1639 keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
1640 strlen (nbitsstr), nbitsstr,
1641 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1642 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1643 "(transient-key)" : "" );
1645 err = gpg_error_from_syserror ();
1648 err = common_gen (keyparms, algo, "ne",
1649 pub_root, timestamp, expireval, is_subkey,
1650 keygen_flags, passphrase,
1651 cache_nonce_addr, passwd_nonce_addr);
1661 * return 0 on error or the multiplier
1664 check_valid_days( const char *s )
1674 return 0; /* e.g. "2323wc" */
1675 if( *s == 'd' || *s == 'D' )
1677 if( *s == 'w' || *s == 'W' )
1679 if( *s == 'm' || *s == 'M' )
1681 if( *s == 'y' || *s == 'Y' )
1688 print_key_flags(int flags)
1690 if(flags&PUBKEY_USAGE_SIG)
1691 tty_printf("%s ",_("Sign"));
1693 if(flags&PUBKEY_USAGE_CERT)
1694 tty_printf("%s ",_("Certify"));
1696 if(flags&PUBKEY_USAGE_ENC)
1697 tty_printf("%s ",_("Encrypt"));
1699 if(flags&PUBKEY_USAGE_AUTH)
1700 tty_printf("%s ",_("Authenticate"));
1704 /* Ask for the key flags and return them. CURRENT gives the current
1705 * usage which should normally be given as 0. */
1707 ask_key_flags (int algo, int subkey, unsigned int current)
1709 /* TRANSLATORS: Please use only plain ASCII characters for the
1710 translation. If this is not possible use single digits. The
1711 string needs to 8 bytes long. Here is a description of the
1714 s = Toggle signing capability
1715 e = Toggle encryption capability
1716 a = Toggle authentication capability
1719 const char *togglers = _("SsEeAaQq");
1720 char *answer = NULL;
1722 unsigned int possible = openpgp_pk_algo_usage(algo);
1724 if ( strlen(togglers) != 8 )
1726 tty_printf ("NOTE: Bad translation at %s:%d. "
1727 "Please report.\n", __FILE__, __LINE__);
1728 togglers = "11223300";
1731 /* Only primary keys may certify. */
1733 possible&=~PUBKEY_USAGE_CERT;
1735 /* Preload the current set with the possible set, minus
1736 authentication if CURRENT has been given as 0. If CURRENT has
1737 been has non-zero we mask with all possible usages. */
1739 current &= possible;
1741 current = (possible&~PUBKEY_USAGE_AUTH);
1746 tty_printf(_("Possible actions for a %s key: "),
1747 (algo == PUBKEY_ALGO_ECDSA
1748 || algo == PUBKEY_ALGO_EDDSA)
1749 ? "ECDSA/EdDSA" : openpgp_pk_algo_name (algo));
1750 print_key_flags(possible);
1752 tty_printf(_("Current allowed actions: "));
1753 print_key_flags(current);
1756 if(possible&PUBKEY_USAGE_SIG)
1757 tty_printf(_(" (%c) Toggle the sign capability\n"),
1759 if(possible&PUBKEY_USAGE_ENC)
1760 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1762 if(possible&PUBKEY_USAGE_AUTH)
1763 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1766 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1770 answer = cpr_get("keygen.flags",_("Your selection? "));
1775 /* Hack to allow direct entry of the capabilities. */
1777 for (s=answer+1; *s; s++)
1779 if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
1780 current |= PUBKEY_USAGE_SIG;
1781 else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
1782 current |= PUBKEY_USAGE_ENC;
1783 else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
1784 current |= PUBKEY_USAGE_AUTH;
1785 else if (!subkey && *s == 'c')
1787 /* Accept 'c' for the primary key because USAGE_CERT
1788 will will be set anyway. This is for folks who
1789 want to experiment with a cert-only primary key. */
1790 current |= PUBKEY_USAGE_CERT;
1795 else if (strlen(answer)>1)
1796 tty_printf(_("Invalid selection.\n"));
1797 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1799 else if((*answer==togglers[0] || *answer==togglers[1])
1800 && possible&PUBKEY_USAGE_SIG)
1802 if(current&PUBKEY_USAGE_SIG)
1803 current&=~PUBKEY_USAGE_SIG;
1805 current|=PUBKEY_USAGE_SIG;
1807 else if((*answer==togglers[2] || *answer==togglers[3])
1808 && possible&PUBKEY_USAGE_ENC)
1810 if(current&PUBKEY_USAGE_ENC)
1811 current&=~PUBKEY_USAGE_ENC;
1813 current|=PUBKEY_USAGE_ENC;
1815 else if((*answer==togglers[4] || *answer==togglers[5])
1816 && possible&PUBKEY_USAGE_AUTH)
1818 if(current&PUBKEY_USAGE_AUTH)
1819 current&=~PUBKEY_USAGE_AUTH;
1821 current|=PUBKEY_USAGE_AUTH;
1824 tty_printf(_("Invalid selection.\n"));
1833 /* Check whether we have a key for the key with HEXGRIP. Returns 0 if
1834 there is no such key or the OpenPGP algo number for the key. */
1836 check_keygrip (ctrl_t ctrl, const char *hexgrip)
1839 unsigned char *public;
1843 if (hexgrip[0] == '&')
1846 err = agent_readkey (ctrl, 0, hexgrip, &public);
1849 publiclen = gcry_sexp_canon_len (public, 0, NULL, NULL);
1851 algo = get_pk_algo_from_canon_sexp (public, publiclen);
1854 return map_pk_gcry_to_openpgp (algo);
1859 /* Ask for an algorithm. The function returns the algorithm id to
1860 * create. If ADDMODE is false the function won't show an option to
1861 * create the primary and subkey combined and won't set R_USAGE
1862 * either. If a combined algorithm has been selected, the subkey
1863 * algorithm is stored at R_SUBKEY_ALGO. If R_KEYGRIP is given, the
1864 * user has the choice to enter the keygrip of an existing key. That
1865 * keygrip is then stored at this address. The caller needs to free
1868 ask_algo (ctrl_t ctrl, int addmode, int *r_subkey_algo, unsigned int *r_usage,
1871 char *keygrip = NULL;
1872 char *answer = NULL;
1877 r_subkey_algo = &dummy_algo;
1879 tty_printf (_("Please select what kind of key you want:\n"));
1883 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1886 if (!addmode && opt.compliance != CO_DE_VS)
1887 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1889 if (opt.compliance != CO_DE_VS)
1890 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1892 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1897 if (opt.compliance != CO_DE_VS)
1898 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1900 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1905 if (opt.compliance != CO_DE_VS)
1906 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1908 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1912 #if GPG_USE_ECDSA || GPG_USE_ECDH || GPG_USE_EDDSA
1913 if (opt.expert && !addmode)
1914 tty_printf (_(" (%d) ECC and ECC\n"), 9 );
1916 tty_printf (_(" (%d) ECC (sign only)\n"), 10 );
1918 tty_printf (_(" (%d) ECC (set your own capabilities)\n"), 11 );
1919 if (opt.expert && addmode)
1920 tty_printf (_(" (%d) ECC (encrypt only)\n"), 12 );
1923 if (opt.expert && r_keygrip)
1924 tty_printf (_(" (%d) Existing key\n"), 13 );
1931 answer = cpr_get ("keygen.algo", _("Your selection? "));
1933 algo = *answer? atoi (answer) : 1;
1935 if (opt.compliance == CO_DE_VS
1936 && (algo == 2 || algo == 3 || algo == 5 || algo == 7))
1938 tty_printf (_("Invalid selection.\n"));
1940 else if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
1942 algo = PUBKEY_ALGO_RSA;
1943 *r_subkey_algo = PUBKEY_ALGO_RSA;
1946 else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
1948 algo = PUBKEY_ALGO_DSA;
1949 *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1952 else if (algo == 3 || !strcmp (answer, "dsa"))
1954 algo = PUBKEY_ALGO_DSA;
1955 *r_usage = PUBKEY_USAGE_SIG;
1958 else if (algo == 4 || !strcmp (answer, "rsa/s"))
1960 algo = PUBKEY_ALGO_RSA;
1961 *r_usage = PUBKEY_USAGE_SIG;
1964 else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
1966 algo = PUBKEY_ALGO_ELGAMAL_E;
1967 *r_usage = PUBKEY_USAGE_ENC;
1970 else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
1972 algo = PUBKEY_ALGO_RSA;
1973 *r_usage = PUBKEY_USAGE_ENC;
1976 else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
1978 algo = PUBKEY_ALGO_DSA;
1979 *r_usage = ask_key_flags (algo, addmode, 0);
1982 else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
1984 algo = PUBKEY_ALGO_RSA;
1985 *r_usage = ask_key_flags (algo, addmode, 0);
1988 else if ((algo == 9 || !strcmp (answer, "ecc+ecc"))
1989 && opt.expert && !addmode)
1991 algo = PUBKEY_ALGO_ECDSA;
1992 *r_subkey_algo = PUBKEY_ALGO_ECDH;
1995 else if ((algo == 10 || !strcmp (answer, "ecc/s")) && opt.expert)
1997 algo = PUBKEY_ALGO_ECDSA;
1998 *r_usage = PUBKEY_USAGE_SIG;
2001 else if ((algo == 11 || !strcmp (answer, "ecc/*")) && opt.expert)
2003 algo = PUBKEY_ALGO_ECDSA;
2004 *r_usage = ask_key_flags (algo, addmode, 0);
2007 else if ((algo == 12 || !strcmp (answer, "ecc/e"))
2008 && opt.expert && addmode)
2010 algo = PUBKEY_ALGO_ECDH;
2011 *r_usage = PUBKEY_USAGE_ENC;
2014 else if ((algo == 13 || !strcmp (answer, "keygrip"))
2015 && opt.expert && r_keygrip)
2020 answer = tty_get (_("Enter the keygrip: "));
2022 trim_spaces (answer);
2030 if (strlen (answer) != 40 &&
2031 !(answer[0] == '&' && strlen (answer+1) == 40))
2033 (_("Not a valid keygrip (expecting 40 hex digits)\n"));
2034 else if (!(algo = check_keygrip (ctrl, answer)) )
2035 tty_printf (_("No key with this keygrip\n"));
2042 *r_usage = ask_key_flags (algo, addmode, 0);
2046 tty_printf (_("Invalid selection.\n"));
2052 *r_keygrip = keygrip;
2058 get_keysize_range (int algo, unsigned int *min, unsigned int *max)
2061 unsigned int dummy1, dummy2;
2070 case PUBKEY_ALGO_DSA:
2071 *min = opt.expert? 768 : 1024;
2076 case PUBKEY_ALGO_ECDSA:
2077 case PUBKEY_ALGO_ECDH:
2083 case PUBKEY_ALGO_EDDSA:
2090 *min = opt.compliance == CO_DE_VS ? 2048: 1024;
2100 /* Return a fixed up keysize depending on ALGO. */
2102 fixup_keysize (unsigned int nbits, int algo, int silent)
2104 if (algo == PUBKEY_ALGO_DSA && (nbits % 64))
2106 nbits = ((nbits + 63) / 64) * 64;
2108 tty_printf (_("rounded up to %u bits\n"), nbits);
2110 else if (algo == PUBKEY_ALGO_EDDSA)
2112 if (nbits != 255 && nbits != 441)
2119 tty_printf (_("rounded to %u bits\n"), nbits);
2122 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2124 if (nbits != 256 && nbits != 384 && nbits != 521)
2128 else if (nbits < 384)
2133 tty_printf (_("rounded to %u bits\n"), nbits);
2136 else if ((nbits % 32))
2138 nbits = ((nbits + 31) / 32) * 32;
2140 tty_printf (_("rounded up to %u bits\n"), nbits );
2147 /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
2148 is not 0, the function asks for the size of the encryption
2151 ask_keysize (int algo, unsigned int primary_keysize)
2154 unsigned int min, def, max;
2155 int for_subkey = !!primary_keysize;
2158 def = get_keysize_range (algo, &min, &max);
2160 if (primary_keysize && !opt.expert)
2162 /* Deduce the subkey size from the primary key size. */
2163 if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
2164 nbits = 3072; /* For performance reasons we don't support more
2165 than 3072 bit DSA. However we won't see this
2166 case anyway because DSA can't be used as an
2167 encryption subkey ;-). */
2169 nbits = primary_keysize;
2174 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
2175 openpgp_pk_algo_name (algo), min, max);
2179 char *prompt, *answer;
2182 prompt = xasprintf (_("What keysize do you want "
2183 "for the subkey? (%u) "), def);
2185 prompt = xasprintf (_("What keysize do you want? (%u) "), def);
2186 answer = cpr_get ("keygen.size", prompt);
2188 nbits = *answer? atoi (answer): def;
2192 if(nbits<min || nbits>max)
2193 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
2194 openpgp_pk_algo_name (algo), min, max);
2199 tty_printf (_("Requested keysize is %u bits\n"), nbits);
2202 nbits = fixup_keysize (nbits, algo, autocomp);
2207 /* Ask for the curve. ALGO is the selected algorithm which this
2208 function may adjust. Returns a malloced string with the name of
2209 the curve. BOTH tells that gpg creates a primary and subkey. */
2211 ask_curve (int *algo, int *subkey_algo)
2213 /* NB: We always use a complete algo list so that we have stable
2214 numbers in the menu regardless on how Gpg was configured. */
2217 const char* eddsa_curve; /* Corresponding EdDSA curve. */
2218 const char *pretty_name;
2219 unsigned int supported : 1; /* Supported by gpg. */
2220 unsigned int de_vs : 1; /* Allowed in CO_DE_VS. */
2221 unsigned int expert_only : 1; /* Only with --expert */
2222 unsigned int available : 1; /* Available in Libycrypt (runtime checked) */
2224 #if GPG_USE_ECDSA || GPG_USE_ECDH
2225 # define MY_USE_ECDSADH 1
2227 # define MY_USE_ECDSADH 0
2229 { "Curve25519", "Ed25519", "Curve 25519", !!GPG_USE_EDDSA, 0, 0, 0 },
2230 { "Curve448", "Ed448", "Curve 448", 0/*reserved*/ , 0, 1, 0 },
2231 { "NIST P-256", NULL, NULL, MY_USE_ECDSADH, 0, 1, 0 },
2232 { "NIST P-384", NULL, NULL, MY_USE_ECDSADH, 0, 0, 0 },
2233 { "NIST P-521", NULL, NULL, MY_USE_ECDSADH, 0, 1, 0 },
2234 { "brainpoolP256r1", NULL, "Brainpool P-256", MY_USE_ECDSADH, 1, 1, 0 },
2235 { "brainpoolP384r1", NULL, "Brainpool P-384", MY_USE_ECDSADH, 1, 1, 0 },
2236 { "brainpoolP512r1", NULL, "Brainpool P-512", MY_USE_ECDSADH, 1, 1, 0 },
2237 { "secp256k1", NULL, NULL, MY_USE_ECDSADH, 0, 1, 0 },
2239 #undef MY_USE_ECDSADH
2242 char *result = NULL;
2243 gcry_sexp_t keyparms;
2245 tty_printf (_("Please select which elliptic curve you want:\n"));
2248 for (idx=0; idx < DIM(curves); idx++)
2252 curves[idx].available = 0;
2253 if (!curves[idx].supported)
2256 if (opt.compliance==CO_DE_VS)
2258 if (!curves[idx].de_vs)
2259 continue; /* Not allowed. */
2261 else if (!opt.expert && curves[idx].expert_only)
2264 /* We need to switch from the ECDH name of the curve to the
2265 EDDSA name of the curve if we want a signing key. */
2266 gcry_sexp_release (keyparms);
2267 rc = gcry_sexp_build (&keyparms, NULL,
2268 "(public-key(ecc(curve %s)))",
2269 curves[idx].eddsa_curve? curves[idx].eddsa_curve
2270 /**/ : curves[idx].name);
2273 if (!gcry_pk_get_curve (keyparms, 0, NULL))
2275 if (subkey_algo && curves[idx].eddsa_curve)
2277 /* Both Curve 25519 (or 448) keys are to be created. Check that
2278 Libgcrypt also supports the real Curve25519 (or 448). */
2279 gcry_sexp_release (keyparms);
2280 rc = gcry_sexp_build (&keyparms, NULL,
2281 "(public-key(ecc(curve %s)))",
2285 if (!gcry_pk_get_curve (keyparms, 0, NULL))
2289 curves[idx].available = 1;
2290 tty_printf (" (%d) %s\n", idx + 1,
2291 curves[idx].pretty_name?
2292 curves[idx].pretty_name:curves[idx].name);
2294 gcry_sexp_release (keyparms);
2299 answer = cpr_get ("keygen.curve", _("Your selection? "));
2301 idx = *answer? atoi (answer) : 1;
2302 if (*answer && !idx)
2304 /* See whether the user entered the name of the curve. */
2305 for (idx=0; idx < DIM(curves); idx++)
2307 if (!opt.expert && curves[idx].expert_only)
2309 if (!stricmp (curves[idx].name, answer)
2310 || (curves[idx].pretty_name
2311 && !stricmp (curves[idx].pretty_name, answer)))
2314 if (idx == DIM(curves))
2321 if (idx < 0 || idx >= DIM (curves) || !curves[idx].available)
2322 tty_printf (_("Invalid selection.\n"));
2325 /* If the user selected a signing algorithm and Curve25519
2326 we need to set the algo to EdDSA and update the curve name. */
2327 if ((*algo == PUBKEY_ALGO_ECDSA || *algo == PUBKEY_ALGO_EDDSA)
2328 && curves[idx].eddsa_curve)
2330 if (subkey_algo && *subkey_algo == PUBKEY_ALGO_ECDSA)
2331 *subkey_algo = PUBKEY_ALGO_EDDSA;
2332 *algo = PUBKEY_ALGO_EDDSA;
2333 result = xstrdup (curves[idx].eddsa_curve);
2336 result = xstrdup (curves[idx].name);
2342 result = xstrdup (curves[0].name);
2349 * Parse an expire string and return its value in seconds.
2350 * Returns (u32)-1 on error.
2351 * This isn't perfect since scan_isodatestr returns unix time, and
2352 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
2353 * Because of this, we only permit setting expirations up to 2106, but
2354 * OpenPGP could theoretically allow up to 2242. I think we'll all
2355 * just cope for the next few years until we get a 64-bit time_t or
2359 parse_expire_string( const char *string )
2364 u32 curtime = make_timestamp ();
2367 if (!string || !*string || !strcmp (string, "none")
2368 || !strcmp (string, "never") || !strcmp (string, "-"))
2370 else if (!strncmp (string, "seconds=", 8))
2371 seconds = atoi (string+8);
2372 else if ((abs_date = scan_isodatestr(string))
2373 && (abs_date+86400/2) > curtime)
2374 seconds = (abs_date+86400/2) - curtime;
2375 else if ((tt = isotime2epoch (string)) != (time_t)(-1))
2376 seconds = (u32)tt - curtime;
2377 else if ((mult = check_valid_days (string)))
2378 seconds = atoi (string) * 86400L * mult;
2380 seconds = (u32)(-1);
2385 /* Parse a Creation-Date string which is either "1986-04-26" or
2386 "19860426T042640". Returns 0 on error. */
2388 parse_creation_string (const char *string)
2394 else if ( !strncmp (string, "seconds=", 8) )
2395 seconds = atoi (string+8);
2396 else if ( !(seconds = scan_isodatestr (string)))
2398 time_t tmp = isotime2epoch (string);
2399 seconds = (tmp == (time_t)(-1))? 0 : tmp;
2405 /* object == 0 for a key, and 1 for a sig */
2407 ask_expire_interval(int object,const char *def_expire)
2417 tty_printf(_("Please specify how long the key should be valid.\n"
2418 " 0 = key does not expire\n"
2419 " <n> = key expires in n days\n"
2420 " <n>w = key expires in n weeks\n"
2421 " <n>m = key expires in n months\n"
2422 " <n>y = key expires in n years\n"));
2428 tty_printf(_("Please specify how long the signature should be valid.\n"
2429 " 0 = signature does not expire\n"
2430 " <n> = signature expires in n days\n"
2431 " <n>w = signature expires in n weeks\n"
2432 " <n>m = signature expires in n months\n"
2433 " <n>y = signature expires in n years\n"));
2440 /* Note: The elgamal subkey for DSA has no expiration date because
2441 * it must be signed with the DSA key and this one has the expiration
2451 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
2456 prompt = xasprintf (_("Signature is valid for? (%s) "), def_expire);
2457 answer = cpr_get("siggen.valid",prompt);
2461 answer=xstrdup(def_expire);
2464 trim_spaces(answer);
2465 curtime = make_timestamp ();
2466 interval = parse_expire_string( answer );
2467 if( interval == (u32)-1 )
2469 tty_printf(_("invalid value\n"));
2475 tty_printf((object==0)
2476 ? _("Key does not expire at all\n")
2477 : _("Signature does not expire at all\n"));
2481 tty_printf(object==0
2482 ? _("Key expires at %s\n")
2483 : _("Signature expires at %s\n"),
2484 asctimestamp((ulong)(curtime + interval) ) );
2485 #if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
2486 if ( (time_t)((ulong)(curtime+interval)) < 0 )
2487 tty_printf (_("Your system can't display dates beyond 2038.\n"
2488 "However, it will be correctly handled up to"
2491 #endif /*SIZEOF_TIME_T*/
2492 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
2494 tty_printf (_("invalid value\n"));
2499 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2500 _("Is this correct? (y/N) ")) )
2511 u32 x = ask_expire_interval(0,NULL);
2512 return x? make_timestamp() + x : 0;
2517 static PKT_user_id *
2518 uid_from_string (const char *string)
2523 n = strlen (string);
2524 uid = xmalloc_clear (sizeof *uid + n);
2526 strcpy (uid->name, string);
2532 /* Return true if the user id UID already exists in the keyblock. */
2534 uid_already_in_keyblock (kbnode_t keyblock, const char *uid)
2536 PKT_user_id *uidpkt = uid_from_string (uid);
2540 for (node=keyblock; node && !result; node=node->next)
2541 if (!is_deleted_kbnode (node)
2542 && node->pkt->pkttype == PKT_USER_ID
2543 && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2545 free_user_id (uidpkt);
2550 /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2551 printed for use during a new key creation. If KEYBLOCK is not NULL
2552 the function prevents the creation of an already existing user
2553 ID. IF FULL is not set some prompts are not shown. */
2555 ask_user_id (int mode, int full, KBNODE keyblock)
2558 char *aname, *acomment, *amail, *uid;
2562 /* TRANSLATORS: This is the new string telling the user what
2563 gpg is now going to do (i.e. ask for the parts of the user
2564 ID). Note that if you do not translate this string, a
2565 different string will be used, which might still have
2566 a correct translation. */
2569 "GnuPG needs to construct a user ID to identify your key.\n"
2571 const char *s2 = _(s1);
2573 if (!strcmp (s1, s2))
2575 /* There is no translation for the string thus we to use
2576 the old info text. gettext has no way to tell whether
2577 a translation is actually available, thus we need to
2578 to compare again. */
2579 /* TRANSLATORS: This string is in general not anymore used
2580 but you should keep your existing translation. In case
2581 the new string is not translated this old string will
2583 const char *s3 = N_("\n"
2584 "You need a user ID to identify your key; "
2585 "the software constructs the user ID\n"
2586 "from the Real Name, Comment and Email Address in this form:\n"
2587 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2588 const char *s4 = _(s3);
2589 if (strcmp (s3, s4))
2590 s2 = s3; /* A translation exists - use it. */
2592 tty_printf ("%s", s2) ;
2594 uid = aname = acomment = amail = NULL;
2602 aname = cpr_get("keygen.name",_("Real name: "));
2606 if( opt.allow_freeform_uid )
2609 if( strpbrk( aname, "<>" ) )
2611 tty_printf(_("Invalid character in name\n"));
2612 tty_printf(_("The characters '%s' and '%s' may not "
2613 "appear in name\n"), "<", ">");
2615 else if( digitp(aname) )
2616 tty_printf(_("Name may not start with a digit\n"));
2617 else if (*aname && strlen (aname) < 5)
2619 tty_printf(_("Name must be at least 5 characters long\n"));
2620 /* However, we allow an empty name. */
2629 amail = cpr_get("keygen.email",_("Email address: "));
2632 if( !*amail || opt.allow_freeform_uid )
2633 break; /* no email address is okay */
2634 else if ( !is_valid_mailbox (amail) )
2635 tty_printf(_("Not a valid email address\n"));
2644 acomment = cpr_get("keygen.comment",_("Comment: "));
2645 trim_spaces(acomment);
2648 break; /* no comment is okay */
2649 else if( strpbrk( acomment, "()" ) )
2650 tty_printf(_("Invalid character in comment\n"));
2657 acomment = xstrdup ("");
2663 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2664 if (!*aname && *amail && !*acomment && !random_is_faked ())
2665 { /* Empty name and comment but with mail address. Use
2666 simplified form with only the non-angle-bracketed mail
2668 p = stpcpy (p, amail);
2672 p = stpcpy (p, aname );
2674 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2676 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2679 /* Append a warning if the RNG is switched into fake mode. */
2680 if ( random_is_faked () )
2681 strcpy(p, " (insecure!)" );
2683 /* print a note in case that UTF8 mapping has to be done */
2684 for(p=uid; *p; p++ ) {
2686 tty_printf(_("You are using the '%s' character set.\n"),
2687 get_native_charset() );
2692 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2694 if( !*amail && !opt.allow_freeform_uid
2695 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2697 tty_printf(_("Please don't put the email address "
2698 "into the real name or the comment\n") );
2701 if (!fail && keyblock)
2703 if (uid_already_in_keyblock (keyblock, uid))
2705 tty_printf (_("Such a user ID already exists on this key!\n"));
2711 /* TRANSLATORS: These are the allowed answers in
2712 lower and uppercase. Below you will find the matching
2713 string which should be translated accordingly and the
2714 letter changed to match the one in the answer string.
2719 o = Okay (ready, continue)
2722 const char *ansstr = _("NnCcEeOoQq");
2724 if( strlen(ansstr) != 10 )
2726 if( cpr_enabled() ) {
2727 answer = xstrdup (ansstr + (fail?8:6));
2731 answer = cpr_get("keygen.userid.cmd", fail?
2732 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2733 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2737 answer = cpr_get("keygen.userid.cmd", fail?
2738 _("Change (N)ame, (E)mail, or (Q)uit? ") :
2739 _("Change (N)ame, (E)mail, or (O)kay/(Q)uit? "));
2742 if( strlen(answer) > 1 )
2744 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2745 xfree(aname); aname = NULL;
2748 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2749 xfree(acomment); acomment = NULL;
2752 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2753 xfree(amail); amail = NULL;
2756 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2758 tty_printf(_("Please correct the error first\n"));
2761 xfree(aname); aname = NULL;
2762 xfree(acomment); acomment = NULL;
2763 xfree(amail); amail = NULL;
2767 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2768 xfree(aname); aname = NULL;
2769 xfree(acomment); acomment = NULL;
2770 xfree(amail); amail = NULL;
2771 xfree(uid); uid = NULL;
2777 if (!amail && !acomment)
2779 xfree(uid); uid = NULL;
2782 char *p = native_to_utf8( uid );
2790 /* Basic key generation. Here we divert to the actual generation
2791 routines based on the requested algorithm. */
2793 do_create (int algo, unsigned int nbits, const char *curve, KBNODE pub_root,
2794 u32 timestamp, u32 expiredate, int is_subkey,
2795 int keygen_flags, const char *passphrase,
2796 char **cache_nonce_addr, char **passwd_nonce_addr)
2800 /* Fixme: The entropy collecting message should be moved to a
2801 libgcrypt progress handler. */
2804 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2805 "some other action (type on the keyboard, move the mouse, utilize the\n"
2806 "disks) during the prime generation; this gives the random number\n"
2807 "generator a better chance to gain enough entropy.\n") );
2809 if (algo == PUBKEY_ALGO_ELGAMAL_E)
2810 err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2811 keygen_flags, passphrase,
2812 cache_nonce_addr, passwd_nonce_addr);
2813 else if (algo == PUBKEY_ALGO_DSA)
2814 err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
2815 keygen_flags, passphrase,
2816 cache_nonce_addr, passwd_nonce_addr);
2817 else if (algo == PUBKEY_ALGO_ECDSA
2818 || algo == PUBKEY_ALGO_EDDSA
2819 || algo == PUBKEY_ALGO_ECDH)
2820 err = gen_ecc (algo, curve, pub_root, timestamp, expiredate, is_subkey,
2821 keygen_flags, passphrase,
2822 cache_nonce_addr, passwd_nonce_addr);
2823 else if (algo == PUBKEY_ALGO_RSA)
2824 err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2825 keygen_flags, passphrase,
2826 cache_nonce_addr, passwd_nonce_addr);
2834 /* Generate a new user id packet or return NULL if canceled. If
2835 KEYBLOCK is not NULL the function prevents the creation of an
2836 already existing user ID. If UIDSTR is not NULL the user is not
2837 asked but UIDSTR is used to create the user id packet; if the user
2838 id already exists NULL is returned. UIDSTR is expected to be utf-8
2839 encoded and should have already been checked for a valid length
2842 generate_user_id (KBNODE keyblock, const char *uidstr)
2849 if (uid_already_in_keyblock (keyblock, uidstr))
2850 return NULL; /* Already exists. */
2851 uid = uid_from_string (uidstr);
2855 p = ask_user_id (1, 1, keyblock);
2857 return NULL; /* Canceled. */
2858 uid = uid_from_string (p);
2865 /* Helper for parse_key_parameter_string for one part of the
2866 * specification string; i.e. ALGO/FLAGS. If STRING is NULL or empty
2867 * success is returned. On error an error code is returned. Note
2868 * that STRING may be modified by this function. NULL may be passed
2869 * for any parameter. FOR_SUBKEY shall be true if this is used as a
2872 parse_key_parameter_part (char *string, int for_subkey,
2873 int *r_algo, unsigned int *r_size,
2874 unsigned int *r_keyuse,
2875 char const **r_curve)
2880 const char *curve = NULL;
2881 int ecdh_or_ecdsa = 0;
2887 if (!string || !*string)
2888 return 0; /* Success. */
2890 flags = strchr (string, '/');
2895 if (strlen (string) >= 3 && (digitp (string+3) || !string[3]))
2897 if (!ascii_memcasecmp (string, "rsa", 3))
2898 algo = PUBKEY_ALGO_RSA;
2899 else if (!ascii_memcasecmp (string, "dsa", 3))
2900 algo = PUBKEY_ALGO_DSA;
2901 else if (!ascii_memcasecmp (string, "elg", 3))
2902 algo = PUBKEY_ALGO_ELGAMAL_E;
2907 size = get_keysize_range (algo, NULL, NULL);
2910 size = strtoul (string+3, &endp, 10);
2911 if (size < 512 || size > 16384 || *endp)
2912 return gpg_error (GPG_ERR_INV_VALUE);
2915 else if ((curve = openpgp_is_curve_supported (string, &algo, &size)))
2919 algo = PUBKEY_ALGO_ECDH; /* Default ECC algorithm. */
2920 ecdh_or_ecdsa = 1; /* We may need to switch the algo. */
2924 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
2926 /* Parse the flags. */
2930 char **tokens = NULL;
2932 tokens = strtokenize (flags, ",");
2934 return gpg_error_from_syserror ();
2936 for (i=0; (s = tokens[i]); i++)
2940 else if (!ascii_strcasecmp (s, "sign"))
2941 keyuse |= PUBKEY_USAGE_SIG;
2942 else if (!ascii_strcasecmp (s, "encrypt")
2943 || !ascii_strcasecmp (s, "encr"))
2944 keyuse |= PUBKEY_USAGE_ENC;
2945 else if (!ascii_strcasecmp (s, "auth"))
2946 keyuse |= PUBKEY_USAGE_AUTH;
2947 else if (!ascii_strcasecmp (s, "cert"))
2948 keyuse |= PUBKEY_USAGE_CERT;
2949 else if (!ascii_strcasecmp (s, "ecdsa"))
2951 if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2952 algo = PUBKEY_ALGO_ECDSA;
2956 return gpg_error (GPG_ERR_INV_FLAG);
2960 else if (!ascii_strcasecmp (s, "ecdh"))
2962 if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2963 algo = PUBKEY_ALGO_ECDH;
2967 return gpg_error (GPG_ERR_INV_FLAG);
2971 else if (!ascii_strcasecmp (s, "eddsa"))
2973 /* Not required but we allow it for consistency. */
2974 if (algo == PUBKEY_ALGO_EDDSA)
2979 return gpg_error (GPG_ERR_INV_FLAG);
2985 return gpg_error (GPG_ERR_UNKNOWN_FLAG);
2992 /* If not yet decided switch between ecdh and ecdsa. */
2993 if (ecdh_or_ecdsa && keyuse)
2994 algo = (keyuse & PUBKEY_USAGE_ENC)? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
2995 else if (ecdh_or_ecdsa)
2996 algo = for_subkey? PUBKEY_ALGO_ECDH : PUBKEY_ALGO_ECDSA;
2998 /* Set or fix key usage. */
3001 if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
3002 || algo == PUBKEY_ALGO_DSA)
3003 keyuse = PUBKEY_USAGE_SIG;
3004 else if (algo == PUBKEY_ALGO_RSA)
3005 keyuse = for_subkey? PUBKEY_USAGE_ENC : PUBKEY_USAGE_SIG;
3007 keyuse = PUBKEY_USAGE_ENC;
3009 else if (algo == PUBKEY_ALGO_ECDSA || algo == PUBKEY_ALGO_EDDSA
3010 || algo == PUBKEY_ALGO_DSA)
3012 keyuse &= ~PUBKEY_USAGE_ENC; /* Forbid encryption. */
3014 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ELGAMAL_E)
3016 keyuse = PUBKEY_USAGE_ENC; /* Allow only encryption. */
3019 /* Make sure a primary key can certify. */
3021 keyuse |= PUBKEY_USAGE_CERT;
3023 /* Check that usage is actually possible. */
3024 if (/**/((keyuse & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
3025 && !pubkey_get_nsig (algo))
3026 || ((keyuse & PUBKEY_USAGE_ENC)
3027 && !pubkey_get_nenc (algo))
3028 || (for_subkey && (keyuse & PUBKEY_USAGE_CERT)))
3029 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
3031 /* Return values. */
3036 unsigned int min, def, max;
3038 /* Make sure the keysize is in the allowed range. */
3039 def = get_keysize_range (algo, &min, &max);
3042 else if (size < min)
3044 else if (size > max)
3047 *r_size = fixup_keysize (size, algo, 1);
3057 /* Parse and return the standard key generation parameter.
3058 * The string is expected to be in this format:
3060 * ALGO[/FLAGS][+SUBALGO[/FLAGS]]
3062 * Here ALGO is a string in the same format as printed by the
3063 * keylisting. For example:
3065 * rsa3072 := RSA with 3072 bit.
3066 * dsa2048 := DSA with 2048 bit.
3067 * elg2048 := Elgamal with 2048 bit.
3068 * ed25519 := EDDSA using curve Ed25519.
3069 * cv25519 := ECDH using curve Curve25519.
3070 * nistp256:= ECDSA or ECDH using curve NIST P-256
3072 * All strings with an unknown prefix are considered an elliptic
3073 * curve. Curves which have no implicit algorithm require that FLAGS
3074 * is given to select whether ECDSA or ECDH is used; this can eoither
3075 * be done using an algorithm keyword or usage keywords.
3077 * FLAGS is a comma delimited string of keywords:
3079 * cert := Allow usage Certify
3080 * sign := Allow usage Sign
3081 * encr := Allow usage Encrypt
3082 * auth := Allow usage Authentication
3083 * encrypt := Alias for "encr"
3084 * ecdsa := Use algorithm ECDSA.
3085 * eddsa := Use algorithm EdDSA.
3086 * ecdh := Use algorithm ECDH.
3088 * There are several defaults and fallbacks depending on the
3089 * algorithm. PART can be used to select which part of STRING is
3092 * 0 := Only the part of the primary key
3093 * 1 := If there is one part parse that one, if there are
3094 * two parts parse the second part. Always return
3095 * in the args for the primary key (R_ALGO,....).
3099 parse_key_parameter_string (const char *string, int part,
3100 int *r_algo, unsigned int *r_size,
3102 char const **r_curve,
3103 int *r_subalgo, unsigned int *r_subsize,
3104 unsigned *r_subkeyuse,
3105 char const **r_subcurve)
3107 gpg_error_t err = 0;
3108 char *primary, *secondary;
3127 if (!string || !*string
3128 || !strcmp (string, "default") || !strcmp (string, "-"))
3129 string = get_default_pubkey_algo ();
3130 else if (!strcmp (string, "future-default"))
3131 string = FUTURE_STD_KEY_PARAM;
3133 primary = xstrdup (string);
3134 secondary = strchr (primary, '+');
3137 if (part == -1 || part == 0)
3139 err = parse_key_parameter_part (primary, 0, r_algo, r_size,
3141 if (!err && part == -1)
3142 err = parse_key_parameter_part (secondary, 1, r_subalgo, r_subsize,
3143 r_subkeyuse, r_subcurve);
3147 /* If we have SECONDARY, use that part. If there is only one
3148 * part consider this to be the subkey algo. */
3149 err = parse_key_parameter_part (secondary? secondary : primary, 1,
3150 r_algo, r_size, r_keyuse, r_curve);
3160 /* Append R to the linked list PARA. */
3162 append_to_parameter (struct para_data_s *para, struct para_data_s *r)
3170 /* Release the parameter list R. */
3172 release_parameter_list (struct para_data_s *r)
3174 struct para_data_s *r2;
3179 if (r->key == pPASSPHRASE && *r->u.value)
3180 wipememory (r->u.value, strlen (r->u.value));
3185 static struct para_data_s *
3186 get_parameter( struct para_data_s *para, enum para_name key )
3188 struct para_data_s *r;
3190 for( r = para; r && r->key != key; r = r->next )
3196 get_parameter_value( struct para_data_s *para, enum para_name key )
3198 struct para_data_s *r = get_parameter( para, key );
3199 return (r && *r->u.value)? r->u.value : NULL;
3203 /* This is similar to get_parameter_value but also returns the empty
3204 string. This is required so that quick_generate_keypair can use an
3205 empty Passphrase to specify no-protection. */
3207 get_parameter_passphrase (struct para_data_s *para)
3209 struct para_data_s *r = get_parameter (para, pPASSPHRASE);
3210 return r ? r->u.value : NULL;
3215 get_parameter_algo( struct para_data_s *para, enum para_name key,
3219 struct para_data_s *r = get_parameter( para, key );
3227 /* Note that we need to handle the ECC algorithms specified as
3228 strings directly because Libgcrypt folds them all to ECC. */
3229 if (!ascii_strcasecmp (r->u.value, "default"))
3231 /* Note: If you change this default algo, remember to change it
3232 * also in gpg.c:gpgconf_list. */
3233 /* FIXME: We only allow the algo here and have a separate thing
3234 * for the curve etc. That is a ugly but demanded for backward
3235 * compatibility with the batch key generation. It would be
3236 * better to make full use of parse_key_parameter_string. */
3237 parse_key_parameter_string (NULL, 0,
3238 &i, NULL, NULL, NULL,
3239 NULL, NULL, NULL, NULL);
3244 else if (digitp (r->u.value))
3245 i = atoi( r->u.value );
3246 else if (!strcmp (r->u.value, "ELG-E")
3247 || !strcmp (r->u.value, "ELG"))
3248 i = PUBKEY_ALGO_ELGAMAL_E;
3249 else if (!ascii_strcasecmp (r->u.value, "EdDSA"))
3250 i = PUBKEY_ALGO_EDDSA;
3251 else if (!ascii_strcasecmp (r->u.value, "ECDSA"))
3252 i = PUBKEY_ALGO_ECDSA;
3253 else if (!ascii_strcasecmp (r->u.value, "ECDH"))
3254 i = PUBKEY_ALGO_ECDH;
3256 i = map_pk_gcry_to_openpgp (gcry_pk_map_name (r->u.value));
3258 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
3259 i = 0; /* we don't want to allow generation of these algorithms */
3264 /* Parse a usage string. The usage keywords "auth", "sign", "encr"
3265 * may be delimited by space, tab, or comma. On error -1 is returned
3266 * instead of the usage flags. */
3268 parse_usagestr (const char *usagestr)
3271 char **tokens = NULL;
3274 unsigned int use = 0;
3276 tokens = strtokenize (usagestr, " \t,");
3279 err = gpg_error_from_syserror ();
3280 log_error ("strtokenize failed: %s\n", gpg_strerror (err));
3284 for (i=0; (s = tokens[i]); i++)
3288 else if (!ascii_strcasecmp (s, "sign"))
3289 use |= PUBKEY_USAGE_SIG;
3290 else if (!ascii_strcasecmp (s, "encrypt")
3291 || !ascii_strcasecmp (s, "encr"))
3292 use |= PUBKEY_USAGE_ENC;
3293 else if (!ascii_strcasecmp (s, "auth"))
3294 use |= PUBKEY_USAGE_AUTH;
3295 else if (!ascii_strcasecmp (s, "cert"))
3296 use |= PUBKEY_USAGE_CERT;
3300 return -1; /* error */
3310 * Parse the usage parameter and set the keyflags. Returns -1 on
3311 * error, 0 for no usage given or 1 for usage available.
3314 parse_parameter_usage (const char *fname,
3315 struct para_data_s *para, enum para_name key)
3317 struct para_data_s *r = get_parameter( para, key );
3321 return 0; /* none (this is an optional parameter)*/
3323 i = parse_usagestr (r->u.value);
3326 log_error ("%s:%d: invalid usage list\n", fname, r->lnr );
3327 return -1; /* error */
3336 parse_revocation_key (const char *fname,
3337 struct para_data_s *para, enum para_name key)
3339 struct para_data_s *r = get_parameter( para, key );
3340 struct revocation_key revkey;
3345 return 0; /* none (this is an optional parameter) */
3350 revkey.algid=atoi(pn);
3354 /* Skip to the fpr */
3355 while(*pn && *pn!=':')
3363 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
3365 int c=hextobyte(pn);
3372 /* skip to the tag */
3373 while(*pn && *pn!='s' && *pn!='S')
3376 if(ascii_strcasecmp(pn,"sensitive")==0)
3379 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
3384 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
3385 return -1; /* error */
3390 get_parameter_u32( struct para_data_s *para, enum para_name key )
3392 struct para_data_s *r = get_parameter( para, key );
3396 if( r->key == pKEYCREATIONDATE )
3397 return r->u.creation;
3398 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
3400 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
3403 return (unsigned int)strtoul( r->u.value, NULL, 10 );
3407 get_parameter_uint( struct para_data_s *para, enum para_name key )
3409 return get_parameter_u32( para, key );
3412 static struct revocation_key *
3413 get_parameter_revkey( struct para_data_s *para, enum para_name key )
3415 struct para_data_s *r = get_parameter( para, key );
3416 return r? &r->u.revkey : NULL;
3420 proc_parameter_file (ctrl_t ctrl, struct para_data_s *para, const char *fname,
3421 struct output_control_s *outctrl, int card )
3423 struct para_data_s *r;
3424 const char *s1, *s2, *s3;
3428 int have_user_id = 0;
3431 /* Check that we have all required parameters. */
3432 r = get_parameter( para, pKEYTYPE );
3435 algo = get_parameter_algo (para, pKEYTYPE, &is_default);
3436 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
3438 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3444 log_error ("%s: no Key-Type specified\n",fname);
3448 err = parse_parameter_usage (fname, para, pKEYUSAGE);
3451 /* Default to algo capabilities if key-usage is not provided and
3452 no default algorithm has been requested. */
3453 r = xmalloc_clear(sizeof(*r));
3455 r->u.usage = (is_default
3456 ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
3457 : openpgp_pk_algo_usage(algo));
3458 append_to_parameter (para, r);
3464 r = get_parameter (para, pKEYUSAGE);
3465 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3467 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
3468 fname, r->lnr, algo);
3474 r = get_parameter( para, pSUBKEYTYPE );
3477 algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
3478 if (openpgp_pk_test_algo (algo))
3480 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3484 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
3487 /* Default to algo capabilities if subkey-usage is not
3489 r = xmalloc_clear (sizeof(*r));
3490 r->key = pSUBKEYUSAGE;
3491 r->u.usage = (is_default
3493 : openpgp_pk_algo_usage (algo));
3494 append_to_parameter (para, r);
3500 r = get_parameter (para, pSUBKEYUSAGE);
3501 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3503 log_error ("%s:%d: specified Subkey-Usage not allowed"
3504 " for algo %d\n", fname, r->lnr, algo);
3511 if( get_parameter_value( para, pUSERID ) )
3515 /* create the formatted user ID */
3516 s1 = get_parameter_value( para, pNAMEREAL );
3517 s2 = get_parameter_value( para, pNAMECOMMENT );
3518 s3 = get_parameter_value( para, pNAMEEMAIL );
3519 if( s1 || s2 || s3 )
3521 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
3522 r = xmalloc_clear( sizeof *r + n + 20 );
3528 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
3530 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
3531 append_to_parameter (para, r);
3538 log_error("%s: no User-ID specified\n",fname);
3542 /* Set preferences, if any. */
3543 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
3545 /* Set keyserver, if any. */
3546 s1=get_parameter_value( para, pKEYSERVER );
3549 struct keyserver_spec *spec;
3551 spec = parse_keyserver_uri (s1, 1);
3554 free_keyserver_spec(spec);
3555 opt.def_keyserver_url=s1;
3559 r = get_parameter (para, pKEYSERVER);
3560 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
3565 /* Set revoker, if any. */
3566 if (parse_revocation_key (fname, para, pREVOKER))
3570 /* Make KEYCREATIONDATE from Creation-Date. */
3571 r = get_parameter (para, pCREATIONDATE);
3572 if (r && *r->u.value)
3576 seconds = parse_creation_string (r->u.value);
3579 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
3582 r->u.creation = seconds;
3583 r->key = pKEYCREATIONDATE; /* Change that entry. */
3586 /* Make KEYEXPIRE from Expire-Date. */
3587 r = get_parameter( para, pEXPIREDATE );
3588 if( r && *r->u.value )
3592 seconds = parse_expire_string( r->u.value );
3593 if( seconds == (u32)-1 )
3595 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
3598 r->u.expire = seconds;
3599 r->key = pKEYEXPIRE; /* change hat entry */
3600 /* also set it for the subkey */
3601 r = xmalloc_clear( sizeof *r + 20 );
3602 r->key = pSUBKEYEXPIRE;
3603 r->u.expire = seconds;
3604 append_to_parameter (para, r);
3607 do_generate_keypair (ctrl, para, outctrl, card );
3613 * Kludge to allow non interactive key generation controlled
3614 * by a parameter file.
3615 * Note, that string parameters are expected to be in UTF-8
3618 read_parameter_file (ctrl_t ctrl, const char *fname )
3620 static struct { const char *name;
3623 { "Key-Type", pKEYTYPE},
3624 { "Key-Length", pKEYLENGTH },
3625 { "Key-Curve", pKEYCURVE },
3626 { "Key-Usage", pKEYUSAGE },
3627 { "Subkey-Type", pSUBKEYTYPE },
3628 { "Subkey-Length", pSUBKEYLENGTH },
3629 { "Subkey-Curve", pSUBKEYCURVE },
3630 { "Subkey-Usage", pSUBKEYUSAGE },
3631 { "Name-Real", pNAMEREAL },
3632 { "Name-Email", pNAMEEMAIL },
3633 { "Name-Comment", pNAMECOMMENT },
3634 { "Expire-Date", pEXPIREDATE },
3635 { "Creation-Date", pCREATIONDATE },
3636 { "Passphrase", pPASSPHRASE },
3637 { "Preferences", pPREFERENCES },
3638 { "Revoker", pREVOKER },
3639 { "Handle", pHANDLE },
3640 { "Keyserver", pKEYSERVER },
3645 unsigned int maxlen, nline;
3648 const char *err = NULL;
3649 struct para_data_s *para, *r;
3651 struct output_control_s outctrl;
3653 memset( &outctrl, 0, sizeof( outctrl ) );
3654 outctrl.pub.afx = new_armor_context ();
3656 if( !fname || !*fname)
3659 fp = iobuf_open (fname);
3660 if (fp && is_secured_file (iobuf_get_fd (fp)))
3664 gpg_err_set_errno (EPERM);
3667 log_error (_("can't open '%s': %s\n"), fname, strerror(errno) );
3670 iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
3677 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
3678 char *keyword, *value;
3682 err = "line too long";
3685 for( p = line; isspace(*(byte*)p); p++ )
3687 if( !*p || *p == '#' )
3690 if( *keyword == '%' ) {
3691 for( ; !isspace(*(byte*)p); p++ )
3695 for( ; isspace(*(byte*)p); p++ )
3698 trim_trailing_ws( value, strlen(value) );
3699 if( !ascii_strcasecmp( keyword, "%echo" ) )
3700 log_info("%s\n", value );
3701 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
3703 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
3704 ; /* Dummy for backward compatibility. */
3705 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
3706 ; /* Dummy for backward compatibility. */
3707 else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
3708 outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
3709 else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
3710 outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
3711 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
3713 if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3714 print_status_key_not_created
3715 (get_parameter_value (para, pHANDLE));
3716 release_parameter_list( para );
3719 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
3720 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
3721 ; /* still the same file - ignore it */
3723 xfree( outctrl.pub.newfname );
3724 outctrl.pub.newfname = xstrdup( value );
3725 outctrl.use_files = 1;
3728 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
3729 /* Ignore this command. */
3732 log_info("skipping control '%s' (%s)\n", keyword, value );
3739 if( !(p = strchr( p, ':' )) || p == keyword ) {
3740 err = "missing colon";
3745 for( ; isspace(*(byte*)p); p++ )
3748 err = "missing argument";
3752 trim_trailing_ws( value, strlen(value) );
3754 for(i=0; keywords[i].name; i++ ) {
3755 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
3758 if( !keywords[i].name ) {
3759 err = "unknown keyword";
3762 if( keywords[i].key != pKEYTYPE && !para ) {
3763 err = "parameter block does not start with \"Key-Type\"";
3767 if( keywords[i].key == pKEYTYPE && para ) {
3769 if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3770 print_status_key_not_created
3771 (get_parameter_value (para, pHANDLE));
3772 release_parameter_list( para );
3776 for( r = para; r; r = r->next ) {
3777 if( r->key == keywords[i].key )
3781 err = "duplicate keyword";
3785 r = xmalloc_clear( sizeof *r + strlen( value ) );
3787 r->key = keywords[i].key;
3788 strcpy( r->u.value, value );
3793 log_error("%s:%d: %s\n", fname, lnr, err );
3794 else if( iobuf_error (fp) ) {
3795 log_error("%s:%d: read error\n", fname, lnr);
3799 if (proc_parameter_file (ctrl, para, fname, &outctrl, 0 ))
3800 print_status_key_not_created (get_parameter_value (para, pHANDLE));
3803 if( outctrl.use_files ) { /* close open streams */
3804 iobuf_close( outctrl.pub.stream );
3806 /* Must invalidate that ugly cache to actually close it. */
3807 if (outctrl.pub.fname)
3808 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
3809 0, (char*)outctrl.pub.fname);
3811 xfree( outctrl.pub.fname );
3812 xfree( outctrl.pub.newfname );
3816 release_parameter_list( para );
3818 release_armor_context (outctrl.pub.afx);
3822 /* Helper for quick_generate_keypair. */
3823 static struct para_data_s *
3824 quickgen_set_para (struct para_data_s *para, int for_subkey,
3825 int algo, int nbits, const char *curve, unsigned int use)
3827 struct para_data_s *r;
3829 r = xmalloc_clear (sizeof *r + 30);
3830 r->key = for_subkey? pSUBKEYUSAGE : pKEYUSAGE;
3832 snprintf (r->u.value, 30, "%s%s%s%s",
3833 (use & PUBKEY_USAGE_ENC)? "encr " : "",
3834 (use & PUBKEY_USAGE_SIG)? "sign " : "",
3835 (use & PUBKEY_USAGE_AUTH)? "auth " : "",
3836 (use & PUBKEY_USAGE_CERT)? "cert " : "");
3838 strcpy (r->u.value, for_subkey ? "encr" : "sign");
3841 r = xmalloc_clear (sizeof *r + 20);
3842 r->key = for_subkey? pSUBKEYTYPE : pKEYTYPE;
3843 snprintf (r->u.value, 20, "%d", algo);
3849 r = xmalloc_clear (sizeof *r + strlen (curve));
3850 r->key = for_subkey? pSUBKEYCURVE : pKEYCURVE;
3851 strcpy (r->u.value, curve);
3857 r = xmalloc_clear (sizeof *r + 20);
3858 r->key = for_subkey? pSUBKEYLENGTH : pKEYLENGTH;
3859 sprintf (r->u.value, "%u", nbits);
3869 * Unattended generation of a standard key.
3872 quick_generate_keypair (ctrl_t ctrl, const char *uid, const char *algostr,
3873 const char *usagestr, const char *expirestr)
3876 struct para_data_s *para = NULL;
3877 struct para_data_s *r;
3878 struct output_control_s outctrl;
3881 memset (&outctrl, 0, sizeof outctrl);
3883 use_tty = (!opt.batch && !opt.answer_yes
3884 && !*algostr && !*usagestr && !*expirestr
3886 && gnupg_isatty (fileno (stdin))
3887 && gnupg_isatty (fileno (stdout))
3888 && gnupg_isatty (fileno (stderr)));
3890 r = xmalloc_clear (sizeof *r + strlen (uid));
3892 strcpy (r->u.value, uid);
3896 uid = trim_spaces (r->u.value);
3897 if (!*uid || (!opt.allow_freeform_uid && !is_valid_user_id (uid)))
3899 log_error (_("Key generation failed: %s\n"),
3900 gpg_strerror (GPG_ERR_INV_USER_ID));
3904 /* If gpg is directly used on the console ask whether a key with the
3905 given user id shall really be created. */
3908 tty_printf (_("About to create a key for:\n \"%s\"\n\n"), uid);
3909 if (!cpr_get_answer_is_yes_def ("quick_keygen.okay",
3910 _("Continue? (Y/n) "), 1))
3914 /* Check whether such a user ID already exists. */
3917 KEYDB_SEARCH_DESC desc;
3919 memset (&desc, 0, sizeof desc);
3920 desc.mode = KEYDB_SEARCH_MODE_EXACT;
3923 kdbhd = keydb_new ();
3927 err = keydb_search (kdbhd, &desc, 1, NULL);
3928 keydb_release (kdbhd);
3929 if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
3931 log_info (_("A key for \"%s\" already exists\n"), uid);
3935 || !cpr_get_answer_is_yes_def ("quick_keygen.force",
3936 _("Create anyway? (y/N) "), 0))
3938 write_status_error ("genkey", gpg_error (304));
3939 log_inc_errorcount (); /* we used log_info */
3942 log_info (_("creating anyway\n"));
3946 if (!*expirestr || strcmp (expirestr, "-") == 0)
3947 expirestr = default_expiration_interval;
3949 if ((!*algostr || !strcmp (algostr, "default")
3950 || !strcmp (algostr, "future-default"))
3951 && (!*usagestr || !strcmp (usagestr, "default")
3952 || !strcmp (usagestr, "-")))
3954 /* Use default key parameters. */
3956 unsigned int size, subsize;
3957 unsigned int keyuse, subkeyuse;
3958 const char *curve, *subcurve;
3960 err = parse_key_parameter_string (algostr, -1,
3961 &algo, &size, &keyuse, &curve,
3962 &subalgo, &subsize, &subkeyuse,
3966 log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
3970 para = quickgen_set_para (para, 0, algo, size, curve, keyuse);
3972 para = quickgen_set_para (para, 1,
3973 subalgo, subsize, subcurve, subkeyuse);
3979 expire = parse_expire_string (expirestr);
3980 if (expire == (u32)-1 )
3982 err = gpg_error (GPG_ERR_INV_VALUE);
3983 log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
3986 r = xmalloc_clear (sizeof *r + 20);
3987 r->key = pKEYEXPIRE;
3988 r->u.expire = expire;
3995 /* Extended unattended mode. Creates only the primary key. */
4002 err = parse_algo_usage_expire (ctrl, 0, algostr, usagestr, expirestr,
4003 &algo, &use, &expire, &nbits, &curve);
4006 log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4010 para = quickgen_set_para (para, 0, algo, nbits, curve, use);
4011 r = xmalloc_clear (sizeof *r + 20);
4012 r->key = pKEYEXPIRE;
4013 r->u.expire = expire;
4018 /* If the pinentry loopback mode is not and we have a static
4019 passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
4020 mode), we use that passphrase for the new key. */
4021 if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
4022 && have_static_passphrase ())
4024 const char *s = get_static_passphrase ();
4026 r = xmalloc_clear (sizeof *r + strlen (s));
4027 r->key = pPASSPHRASE;
4028 strcpy (r->u.value, s);
4033 proc_parameter_file (ctrl, para, "[internal]", &outctrl, 0);
4036 release_parameter_list (para);
4041 * Generate a keypair (fname is only used in batch mode) If
4042 * CARD_SERIALNO is not NULL the function will create the keys on an
4043 * OpenPGP Card. If CARD_BACKUP_KEY has been set and CARD_SERIALNO is
4044 * NOT NULL, the encryption key for the card is generated on the host,
4045 * imported to the card and a backup file created by gpg-agent. If
4046 * FULL is not set only the basic prompts are used (except for batch
4050 generate_keypair (ctrl_t ctrl, int full, const char *fname,
4051 const char *card_serialno, int card_backup_key)
4060 struct para_data_s *para = NULL;
4061 struct para_data_s *r;
4062 struct output_control_s outctrl;
4064 #ifndef ENABLE_CARD_SUPPORT
4065 (void)card_backup_key;
4068 memset( &outctrl, 0, sizeof( outctrl ) );
4070 if (opt.batch && card_serialno)
4072 /* We don't yet support unattended key generation. */
4073 log_error (_("can't do this in batch mode\n"));
4079 read_parameter_file (ctrl, fname);
4085 #ifdef ENABLE_CARD_SUPPORT
4086 struct agent_card_info_s info;
4088 memset (&info, 0, sizeof (info));
4089 err = agent_scd_getattr ("KEY-ATTR", &info);
4092 log_error (_("error getting current key info: %s\n"),
4093 gpg_strerror (err));
4097 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
4099 strcpy( r->u.value, card_serialno);
4103 r = xcalloc (1, sizeof *r + 20 );
4105 sprintf( r->u.value, "%d", info.key_attr[0].algo );
4108 r = xcalloc (1, sizeof *r + 20 );
4110 strcpy (r->u.value, "sign");
4114 r = xcalloc (1, sizeof *r + 20 );
4115 r->key = pSUBKEYTYPE;
4116 sprintf( r->u.value, "%d", info.key_attr[1].algo );
4119 r = xcalloc (1, sizeof *r + 20 );
4120 r->key = pSUBKEYUSAGE;
4121 strcpy (r->u.value, "encrypt");
4124 if (info.key_attr[1].algo == PUBKEY_ALGO_RSA)
4126 r = xcalloc (1, sizeof *r + 20 );
4127 r->key = pSUBKEYLENGTH;
4128 sprintf( r->u.value, "%u", info.key_attr[1].nbits);
4132 else if (info.key_attr[1].algo == PUBKEY_ALGO_ECDSA
4133 || info.key_attr[1].algo == PUBKEY_ALGO_EDDSA
4134 || info.key_attr[1].algo == PUBKEY_ALGO_ECDH)
4136 r = xcalloc (1, sizeof *r + strlen (info.key_attr[1].curve));
4137 r->key = pSUBKEYCURVE;
4138 strcpy (r->u.value, info.key_attr[1].curve);
4143 r = xcalloc (1, sizeof *r + 20 );
4144 r->key = pAUTHKEYTYPE;
4145 sprintf( r->u.value, "%d", info.key_attr[2].algo );
4149 if (card_backup_key)
4151 r = xcalloc (1, sizeof *r + 1);
4152 r->key = pCARDBACKUPKEY;
4153 strcpy (r->u.value, "1");
4157 #endif /*ENABLE_CARD_SUPPORT*/
4159 else if (full) /* Full featured key generation. */
4164 /* Fixme: To support creating a primary key by keygrip we better
4165 also define the keyword for the parameter file. Note that
4166 the subkey case will never be asserted if a keygrip has been
4168 algo = ask_algo (ctrl, 0, &subkey_algo, &use, NULL);
4171 /* Create primary and subkey at once. */
4173 if (algo == PUBKEY_ALGO_ECDSA
4174 || algo == PUBKEY_ALGO_EDDSA
4175 || algo == PUBKEY_ALGO_ECDH)
4177 curve = ask_curve (&algo, &subkey_algo);
4178 r = xmalloc_clear( sizeof *r + 20 );
4180 sprintf( r->u.value, "%d", algo);
4184 r = xmalloc_clear (sizeof *r + strlen (curve));
4186 strcpy (r->u.value, curve);
4192 r = xmalloc_clear( sizeof *r + 20 );
4194 sprintf( r->u.value, "%d", algo);
4197 nbits = ask_keysize (algo, 0);
4198 r = xmalloc_clear( sizeof *r + 20 );
4199 r->key = pKEYLENGTH;
4200 sprintf( r->u.value, "%u", nbits);
4204 r = xmalloc_clear( sizeof *r + 20 );
4206 strcpy( r->u.value, "sign" );
4210 r = xmalloc_clear( sizeof *r + 20 );
4211 r->key = pSUBKEYTYPE;
4212 sprintf( r->u.value, "%d", subkey_algo);
4215 r = xmalloc_clear( sizeof *r + 20 );
4216 r->key = pSUBKEYUSAGE;
4217 strcpy( r->u.value, "encrypt" );
4221 if (algo == PUBKEY_ALGO_ECDSA
4222 || algo == PUBKEY_ALGO_EDDSA
4223 || algo == PUBKEY_ALGO_ECDH)
4225 if (algo == PUBKEY_ALGO_EDDSA
4226 && subkey_algo == PUBKEY_ALGO_ECDH)
4228 /* Need to switch to a different curve for the
4231 curve = xstrdup ("Curve25519");
4233 r = xmalloc_clear (sizeof *r + strlen (curve));
4234 r->key = pSUBKEYCURVE;
4235 strcpy (r->u.value, curve);
4240 else /* Create only a single key. */
4242 /* For ECC we need to ask for the curve before storing the
4243 algo because ask_curve may change the algo. */
4244 if (algo == PUBKEY_ALGO_ECDSA
4245 || algo == PUBKEY_ALGO_EDDSA
4246 || algo == PUBKEY_ALGO_ECDH)
4248 curve = ask_curve (&algo, NULL);
4249 r = xmalloc_clear (sizeof *r + strlen (curve));
4251 strcpy (r->u.value, curve);
4256 r = xmalloc_clear( sizeof *r + 20 );
4258 sprintf( r->u.value, "%d", algo );
4264 r = xmalloc_clear( sizeof *r + 25 );
4266 sprintf( r->u.value, "%s%s%s",
4267 (use & PUBKEY_USAGE_SIG)? "sign ":"",
4268 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
4269 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
4276 if (algo == PUBKEY_ALGO_ECDSA
4277 || algo == PUBKEY_ALGO_EDDSA
4278 || algo == PUBKEY_ALGO_ECDH)
4280 /* The curve has already been set. */
4284 nbits = ask_keysize (both? subkey_algo : algo, nbits);
4285 r = xmalloc_clear( sizeof *r + 20 );
4286 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
4287 sprintf( r->u.value, "%u", nbits);
4294 else /* Default key generation. */
4297 unsigned int size, subsize;
4298 unsigned int keyuse, subkeyuse;
4299 const char *curve, *subcurve;
4301 tty_printf ( _("Note: Use \"%s %s\""
4302 " for a full featured key generation dialog.\n"),
4308 , "--full-generate-key" );
4310 err = parse_key_parameter_string (NULL, -1,
4311 &algo, &size, &keyuse, &curve,
4313 &subkeyuse, &subcurve);
4316 log_error (_("Key generation failed: %s\n"), gpg_strerror (err));
4319 para = quickgen_set_para (para, 0, algo, size, curve, keyuse);
4321 para = quickgen_set_para (para, 1,
4322 subalgo, subsize, subcurve, subkeyuse);
4328 expire = full? ask_expire_interval (0, NULL)
4329 : parse_expire_string (default_expiration_interval);
4330 r = xcalloc (1, sizeof *r + 20);
4331 r->key = pKEYEXPIRE;
4332 r->u.expire = expire;
4335 r = xcalloc (1, sizeof *r + 20);
4336 r->key = pSUBKEYEXPIRE;
4337 r->u.expire = expire;
4341 uid = ask_user_id (0, full, NULL);
4344 log_error(_("Key generation canceled.\n"));
4345 release_parameter_list( para );
4348 r = xcalloc (1, sizeof *r + strlen (uid));
4350 strcpy (r->u.value, uid);
4354 proc_parameter_file (ctrl, para, "[internal]", &outctrl, !!card_serialno);
4355 release_parameter_list (para);
4359 /* Create and delete a dummy packet to start off a list of kbnodes. */
4361 start_tree(KBNODE *tree)
4365 pkt=xmalloc_clear(sizeof(*pkt));
4366 pkt->pkttype=PKT_NONE;
4367 *tree=new_kbnode(pkt);
4368 delete_kbnode(*tree);
4372 /* Write the *protected* secret key to the file. */
4374 card_write_key_to_backup_file (PKT_public_key *sk, const char *backup_dir)
4376 gpg_error_t err = 0;
4378 char keyid_buffer[2 * 8 + 1];
4379 char name_buffer[50];
4385 format_keyid (pk_keyid (sk), KF_LONG, keyid_buffer, sizeof (keyid_buffer));
4386 snprintf (name_buffer, sizeof name_buffer, "sk_%s.gpg", keyid_buffer);
4388 fname = make_filename (backup_dir, name_buffer, NULL);
4389 /* Note that the umask call is not anymore needed because
4390 iobuf_create now takes care of it. However, it does not harm
4391 and thus we keep it. */
4392 oldmask = umask (077);
4393 if (is_secured_filename (fname))
4396 gpg_err_set_errno (EPERM);
4399 fp = iobuf_create (fname, 1);
4403 err = gpg_error_from_syserror ();
4404 log_error (_("can't create backup file '%s': %s\n"), fname, strerror (errno) );
4408 pkt = xcalloc (1, sizeof *pkt);
4409 pkt->pkttype = PKT_SECRET_KEY;
4410 pkt->pkt.secret_key = sk;
4412 rc = build_packet (fp, pkt);
4415 log_error ("build packet failed: %s\n", gpg_strerror (rc));
4423 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
4424 log_info (_("Note: backup of card key saved to '%s'\n"), fname);
4426 fprbuf = hexfingerprint (sk, NULL, 0);
4427 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED, fprbuf,
4428 fname, strlen (fname), 0);
4439 /* Store key to card and make a backup file in OpenPGP format. */
4441 card_store_key_with_backup (ctrl_t ctrl, PKT_public_key *sub_psk,
4442 const char *backup_dir)
4445 gnupg_isotime_t timestamp;
4449 struct agent_card_info_s info;
4450 gcry_cipher_hd_t cipherhd = NULL;
4451 char *cache_nonce = NULL;
4455 sk = copy_public_key (NULL, sub_psk);
4457 return gpg_error_from_syserror ();
4459 epoch2isotime (timestamp, (time_t)sk->timestamp);
4460 err = hexkeygrip_from_pk (sk, &hexgrip);
4464 memset(&info, 0, sizeof (info));
4465 rc = agent_scd_getattr ("SERIALNO", &info);
4467 return (gpg_error_t)rc;
4469 rc = agent_keytocard (hexgrip, 2, 1, info.serialno, timestamp);
4470 xfree (info.serialno);
4473 err = (gpg_error_t)rc;
4477 err = agent_keywrap_key (ctrl, 1, &kek, &keklen);
4480 log_error ("error getting the KEK: %s\n", gpg_strerror (err));
4484 err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
4485 GCRY_CIPHER_MODE_AESWRAP, 0);
4487 err = gcry_cipher_setkey (cipherhd, kek, keklen);
4490 log_error ("error setting up an encryption context: %s\n",
4491 gpg_strerror (err));
4495 err = receive_seckey_from_agent (ctrl, cipherhd, 0,
4496 &cache_nonce, hexgrip, sk);
4499 log_error ("error getting secret key from agent: %s\n",
4500 gpg_strerror (err));
4504 err = card_write_key_to_backup_file (sk, backup_dir);
4506 log_error ("writing card key to backup file: %s\n", gpg_strerror (err));
4508 /* Remove secret key data in agent side. */
4509 agent_scd_learn (NULL, 1);
4512 xfree (cache_nonce);
4513 gcry_cipher_close (cipherhd);
4516 free_public_key (sk);
4522 do_generate_keypair (ctrl_t ctrl, struct para_data_s *para,
4523 struct output_control_s *outctrl, int card)
4526 KBNODE pub_root = NULL;
4528 PKT_public_key *pri_psk = NULL;
4529 PKT_public_key *sub_psk = NULL;
4530 struct revocation_key *revkey;
4533 char *cache_nonce = NULL;
4535 if (outctrl->dryrun)
4537 log_info("dry-run mode - key generation skipped\n");
4541 if ( outctrl->use_files )
4543 if ( outctrl->pub.newfname )
4545 iobuf_close(outctrl->pub.stream);
4546 outctrl->pub.stream = NULL;
4547 if (outctrl->pub.fname)
4548 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
4549 0, (char*)outctrl->pub.fname);
4550 xfree( outctrl->pub.fname );
4551 outctrl->pub.fname = outctrl->pub.newfname;
4552 outctrl->pub.newfname = NULL;
4554 if (is_secured_filename (outctrl->pub.fname) )
4556 outctrl->pub.stream = NULL;
4557 gpg_err_set_errno (EPERM);
4560 outctrl->pub.stream = iobuf_create (outctrl->pub.fname, 0);
4561 if (!outctrl->pub.stream)
4563 log_error(_("can't create '%s': %s\n"), outctrl->pub.newfname,
4569 outctrl->pub.afx->what = 1;
4570 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
4573 log_assert( outctrl->pub.stream );
4575 log_info (_("writing public key to '%s'\n"), outctrl->pub.fname );
4579 /* We create the packets as a tree of kbnodes. Because the
4580 structure we create is known in advance we simply generate a
4581 linked list. The first packet is a dummy packet which we flag as
4582 deleted. The very first packet must always be a KEY packet. */
4584 start_tree (&pub_root);
4586 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
4588 timestamp = make_timestamp ();
4590 /* Note that, depending on the backend (i.e. the used scdaemon
4591 version), the card key generation may update TIMESTAMP for each
4592 key. Thus we need to pass TIMESTAMP to all signing function to
4593 make sure that the binding signature is done using the timestamp
4594 of the corresponding (sub)key and not that of the primary key.
4595 An alternative implementation could tell the signing function the
4596 node of the subkey but that is more work than just to pass the
4597 current timestamp. */
4600 err = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
4601 get_parameter_uint( para, pKEYLENGTH ),
4602 get_parameter_value (para, pKEYCURVE),
4605 get_parameter_u32( para, pKEYEXPIRE ), 0,
4606 outctrl->keygen_flags,
4607 get_parameter_passphrase (para),
4608 &cache_nonce, NULL);
4610 err = gen_card_key (1, get_parameter_algo( para, pKEYTYPE, NULL ),
4611 1, pub_root, ×tamp,
4612 get_parameter_u32 (para, pKEYEXPIRE));
4614 /* Get the pointer to the generated public key packet. */
4617 pri_psk = pub_root->next->pkt->pkt.public_key;
4618 log_assert (pri_psk);
4620 /* Make sure a few fields are correctly set up before going
4622 pri_psk->flags.primary = 1;
4623 keyid_from_pk (pri_psk, NULL);
4624 /* We don't use pk_keyid to get keyid, because it also asserts
4625 that main_keyid is set! */
4626 keyid_copy (pri_psk->main_keyid, pri_psk->keyid);
4629 if (!err && (revkey = get_parameter_revkey (para, pREVOKER)))
4630 err = write_direct_sig (pub_root, pri_psk, revkey, timestamp, cache_nonce);
4632 if (!err && (s = get_parameter_value (para, pUSERID)))
4634 write_uid (pub_root, s );
4635 err = write_selfsigs (pub_root, pri_psk,
4636 get_parameter_uint (para, pKEYUSAGE), timestamp,
4640 /* Write the auth key to the card before the encryption key. This
4641 is a partial workaround for a PGP bug (as of this writing, all
4642 versions including 8.1), that causes it to try and encrypt to
4643 the most recent subkey regardless of whether that subkey is
4644 actually an encryption type. In this case, the auth key is an
4645 RSA key so it succeeds. */
4647 if (!err && card && get_parameter (para, pAUTHKEYTYPE))
4649 err = gen_card_key (3, get_parameter_algo( para, pAUTHKEYTYPE, NULL ),
4650 0, pub_root, ×tamp,
4651 get_parameter_u32 (para, pKEYEXPIRE));
4653 err = write_keybinding (pub_root, pri_psk, NULL,
4654 PUBKEY_USAGE_AUTH, timestamp, cache_nonce);
4657 if (!err && get_parameter (para, pSUBKEYTYPE))
4661 if (!card || (s = get_parameter_value (para, pCARDBACKUPKEY)))
4663 err = do_create (get_parameter_algo (para, pSUBKEYTYPE, NULL),
4664 get_parameter_uint (para, pSUBKEYLENGTH),
4665 get_parameter_value (para, pSUBKEYCURVE),
4668 get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
4669 s ? KEYGEN_FLAG_NO_PROTECTION : outctrl->keygen_flags,
4670 get_parameter_passphrase (para),
4671 &cache_nonce, NULL);
4672 /* Get the pointer to the generated public subkey packet. */
4677 for (node = pub_root; node; node = node->next)
4678 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4679 sub_psk = node->pkt->pkt.public_key;
4680 log_assert (sub_psk);
4683 err = card_store_key_with_backup (ctrl,
4684 sub_psk, gnupg_homedir ());
4689 err = gen_card_key (2, get_parameter_algo (para, pSUBKEYTYPE, NULL),
4690 0, pub_root, ×tamp,
4691 get_parameter_u32 (para, pKEYEXPIRE));
4695 err = write_keybinding (pub_root, pri_psk, sub_psk,
4696 get_parameter_uint (para, pSUBKEYUSAGE),
4697 timestamp, cache_nonce);
4701 if (!err && outctrl->use_files) /* Direct write to specified files. */
4703 err = write_keyblock (outctrl->pub.stream, pub_root);
4705 log_error ("can't write public key: %s\n", gpg_strerror (err));
4707 else if (!err) /* Write to the standard keyrings. */
4709 KEYDB_HANDLE pub_hd;
4711 pub_hd = keydb_new ();
4713 err = gpg_error_from_syserror ();
4716 err = keydb_locate_writable (pub_hd);
4718 log_error (_("no writable public keyring found: %s\n"),
4719 gpg_strerror (err));
4722 if (!err && opt.verbose)
4724 log_info (_("writing public key to '%s'\n"),
4725 keydb_get_resource_name (pub_hd));
4730 err = keydb_insert_keyblock (pub_hd, pub_root);
4732 log_error (_("error writing public keyring '%s': %s\n"),
4733 keydb_get_resource_name (pub_hd), gpg_strerror (err));
4736 keydb_release (pub_hd);
4743 no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
4745 && get_parameter_uint (para, pKEYUSAGE)
4746 && !((get_parameter_uint (para, pKEYUSAGE)
4747 & PUBKEY_USAGE_ENC)) );
4749 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4751 keyid_from_pk (pk, pk->main_keyid);
4752 register_trusted_keyid (pk->main_keyid);
4754 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
4755 | TRUST_ULTIMATE ));
4757 gen_standard_revoke (pk, cache_nonce);
4759 /* Get rid of the first empty packet. */
4760 commit_kbnode (&pub_root);
4764 tty_printf (_("public and secret key created and signed.\n") );
4766 merge_keys_and_selfsig (pub_root);
4767 list_keyblock_direct (ctrl, pub_root, 0, 1, 1, 1);
4772 && (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
4774 && !get_parameter (para, pSUBKEYTYPE) )
4776 tty_printf(_("Note that this key cannot be used for "
4777 "encryption. You may want to use\n"
4778 "the command \"--edit-key\" to generate a "
4779 "subkey for this purpose.\n") );
4787 log_error ("key generation failed: %s\n", gpg_strerror (err) );
4789 tty_printf (_("Key generation failed: %s\n"), gpg_strerror (err) );
4790 write_status_error (card? "card_key_generate":"key_generate", err);
4791 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
4795 PKT_public_key *pk = find_kbnode (pub_root,
4796 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4797 print_status_key_created (did_sub? 'B':'P', pk,
4798 get_parameter_value (para, pHANDLE));
4801 release_kbnode (pub_root);
4802 xfree (cache_nonce);
4807 parse_algo_usage_expire (ctrl_t ctrl, int for_subkey,
4808 const char *algostr, const char *usagestr,
4809 const char *expirestr,
4810 int *r_algo, unsigned int *r_usage, u32 *r_expire,
4811 unsigned int *r_nbits, char **r_curve)
4815 unsigned int use, nbits;
4818 const char *curve = NULL;
4824 /* Parse the algo string. */
4825 if (algostr && *algostr == '&' && strlen (algostr) == 41)
4827 /* Take algo from existing key. */
4828 algo = check_keygrip (ctrl, algostr+1);
4829 /* FIXME: We need the curve name as well. */
4830 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
4833 err = parse_key_parameter_string (algostr, for_subkey? 1 : 0,
4834 &algo, &nbits, &use, &curve,
4835 NULL, NULL, NULL, NULL);
4839 /* Parse the usage string. */
4840 if (!usagestr || !*usagestr
4841 || !strcmp (usagestr, "default") || !strcmp (usagestr, "-"))
4842 ; /* Keep usage from parse_key_parameter_string. */
4843 else if ((wantuse = parse_usagestr (usagestr)) != -1)
4846 return gpg_error (GPG_ERR_INV_VALUE);
4848 /* Make sure a primary key has the CERT usage. */
4850 use |= PUBKEY_USAGE_CERT;
4852 /* Check that usage is possible. NB: We have the same check in
4853 * parse_key_parameter_string but need it here again in case the
4854 * separate usage value has been given. */
4855 if (/**/((use & (PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH|PUBKEY_USAGE_CERT))
4856 && !pubkey_get_nsig (algo))
4857 || ((use & PUBKEY_USAGE_ENC)
4858 && !pubkey_get_nenc (algo))
4859 || (for_subkey && (use & PUBKEY_USAGE_CERT)))
4860 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
4862 /* Parse the expire string. */
4863 expire = parse_expire_string (expirestr);
4864 if (expire == (u32)-1 )
4865 return gpg_error (GPG_ERR_INV_VALUE);
4869 *r_curve = xtrystrdup (curve);
4871 return gpg_error_from_syserror ();
4881 /* Add a new subkey to an existing key. Returns 0 if a new key has
4882 been generated and put into the keyblocks. If any of ALGOSTR,
4883 USAGESTR, or EXPIRESTR is NULL interactive mode is used. */
4885 generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock, const char *algostr,
4886 const char *usagestr, const char *expirestr)
4888 gpg_error_t err = 0;
4891 PKT_public_key *pri_psk = NULL;
4892 PKT_public_key *sub_psk = NULL;
4896 unsigned int nbits = 0;
4899 char *key_from_hexgrip = NULL;
4900 char *hexgrip = NULL;
4901 char *serialno = NULL;
4902 char *cache_nonce = NULL;
4903 char *passwd_nonce = NULL;
4905 interactive = (!algostr || !usagestr || !expirestr);
4907 /* Break out the primary key. */
4908 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
4911 log_error ("Oops; primary key missing in keyblock!\n");
4912 err = gpg_error (GPG_ERR_BUG);
4915 pri_psk = node->pkt->pkt.public_key;
4917 cur_time = make_timestamp ();
4919 if (pri_psk->timestamp > cur_time)
4921 ulong d = pri_psk->timestamp - cur_time;
4922 log_info ( d==1 ? _("key has been created %lu second "
4923 "in future (time warp or clock problem)\n")
4924 : _("key has been created %lu seconds "
4925 "in future (time warp or clock problem)\n"), d );
4926 if (!opt.ignore_time_conflict)
4928 err = gpg_error (GPG_ERR_TIME_CONFLICT);
4933 if (pri_psk->version < 4)
4935 log_info (_("Note: creating subkeys for v3 keys "
4936 "is not OpenPGP compliant\n"));
4937 err = gpg_error (GPG_ERR_CONFLICT);
4941 err = hexkeygrip_from_pk (pri_psk, &hexgrip);
4944 if (agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
4947 tty_printf (_("Secret parts of primary key are not available.\n"));
4949 log_info ( _("Secret parts of primary key are not available.\n"));
4950 err = gpg_error (GPG_ERR_NO_SECKEY);
4956 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
4958 log_info ( _("Secret parts of primary key are stored on-card.\n"));
4963 algo = ask_algo (ctrl, 1, NULL, &use, &key_from_hexgrip);
4966 if (key_from_hexgrip)
4968 else if (algo == PUBKEY_ALGO_ECDSA
4969 || algo == PUBKEY_ALGO_EDDSA
4970 || algo == PUBKEY_ALGO_ECDH)
4971 curve = ask_curve (&algo, NULL);
4973 nbits = ask_keysize (algo, 0);
4975 expire = ask_expire_interval (0, NULL);
4976 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
4977 _("Really create? (y/N) ")))
4979 err = gpg_error (GPG_ERR_CANCELED);
4983 else /* Unattended mode. */
4985 err = parse_algo_usage_expire (ctrl, 1, algostr, usagestr, expirestr,
4986 &algo, &use, &expire, &nbits, &curve);
4991 /* Verify the passphrase now so that we get a cache item for the
4992 * primary key passphrase. The agent also returns a passphrase
4993 * nonce, which we can use to set the passphrase for the subkey to
4994 * that of the primary key. */
4996 char *desc = gpg_format_keydesc (pri_psk, FORMAT_KEYDESC_NORMAL, 1);
4997 err = agent_passwd (ctrl, hexgrip, desc, 1 /*=verify*/,
4998 &cache_nonce, &passwd_nonce);
5002 /* Start creation. */
5003 if (key_from_hexgrip)
5005 err = do_create_from_keygrip (ctrl, algo, key_from_hexgrip,
5006 keyblock, cur_time, expire, 1);
5012 /* If the pinentry loopback mode is not and we have a static
5013 passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
5014 mode), we use that passphrase for the new subkey. */
5015 if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
5016 && have_static_passphrase ())
5017 passwd = get_static_passphrase ();
5021 err = do_create (algo, nbits, curve,
5022 keyblock, cur_time, expire, 1, 0,
5023 passwd, &cache_nonce, &passwd_nonce);
5028 /* Get the pointer to the generated public subkey packet. */
5029 for (node = keyblock; node; node = node->next)
5030 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5031 sub_psk = node->pkt->pkt.public_key;
5033 /* Write the binding signature. */
5034 err = write_keybinding (keyblock, pri_psk, sub_psk, use, cur_time,
5039 print_status_key_created ('S', sub_psk, NULL);
5043 xfree (key_from_hexgrip);
5047 xfree (cache_nonce);
5048 xfree (passwd_nonce);
5050 log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
5055 #ifdef ENABLE_CARD_SUPPORT
5056 /* Generate a subkey on a card. */
5058 generate_card_subkeypair (kbnode_t pub_keyblock,
5059 int keyno, const char *serialno)
5061 gpg_error_t err = 0;
5063 PKT_public_key *pri_pk = NULL;
5067 struct para_data_s *para = NULL;
5068 PKT_public_key *sub_pk = NULL;
5070 struct agent_card_info_s info;
5072 log_assert (keyno >= 1 && keyno <= 3);
5074 memset (&info, 0, sizeof (info));
5075 err = agent_scd_getattr ("KEY-ATTR", &info);
5078 log_error (_("error getting current key info: %s\n"), gpg_strerror (err));
5081 algo = info.key_attr[keyno-1].algo;
5083 para = xtrycalloc (1, sizeof *para + strlen (serialno) );
5086 err = gpg_error_from_syserror ();
5089 para->key = pSERIALNO;
5090 strcpy (para->u.value, serialno);
5092 /* Break out the primary secret key */
5093 node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
5096 log_error ("Oops; publkic key lost!\n");
5097 err = gpg_error (GPG_ERR_INTERNAL);
5100 pri_pk = node->pkt->pkt.public_key;
5102 cur_time = make_timestamp();
5103 if (pri_pk->timestamp > cur_time)
5105 ulong d = pri_pk->timestamp - cur_time;
5106 log_info (d==1 ? _("key has been created %lu second "
5107 "in future (time warp or clock problem)\n")
5108 : _("key has been created %lu seconds "
5109 "in future (time warp or clock problem)\n"), d );
5110 if (!opt.ignore_time_conflict)
5112 err = gpg_error (GPG_ERR_TIME_CONFLICT);
5117 if (pri_pk->version < 4)
5119 log_info (_("Note: creating subkeys for v3 keys "
5120 "is not OpenPGP compliant\n"));
5121 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
5125 expire = ask_expire_interval (0, NULL);
5127 use = PUBKEY_USAGE_SIG;
5128 else if (keyno == 2)
5129 use = PUBKEY_USAGE_ENC;
5131 use = PUBKEY_USAGE_AUTH;
5132 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
5133 _("Really create? (y/N) ")))
5135 err = gpg_error (GPG_ERR_CANCELED);
5139 /* Note, that depending on the backend, the card key generation may
5141 err = gen_card_key (keyno, algo, 0, pub_keyblock, &cur_time, expire);
5142 /* Get the pointer to the generated public subkey packet. */
5145 for (node = pub_keyblock; node; node = node->next)
5146 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5147 sub_pk = node->pkt->pkt.public_key;
5148 log_assert (sub_pk);
5149 err = write_keybinding (pub_keyblock, pri_pk, sub_pk,
5150 use, cur_time, NULL);
5155 log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
5157 print_status_key_created ('S', sub_pk, NULL);
5158 release_parameter_list (para);
5161 #endif /* !ENABLE_CARD_SUPPORT */
5164 * Write a keyblock to an output stream
5167 write_keyblock( IOBUF out, KBNODE node )
5169 for( ; node ; node = node->next )
5171 if(!is_deleted_kbnode(node))
5173 int rc = build_packet( out, node->pkt );
5176 log_error("build_packet(%d) failed: %s\n",
5177 node->pkt->pkttype, gpg_strerror (rc) );
5187 /* Note that timestamp is an in/out arg. */
5189 gen_card_key (int keyno, int algo, int is_primary, kbnode_t pub_root,
5190 u32 *timestamp, u32 expireval)
5192 #ifdef ENABLE_CARD_SUPPORT
5197 unsigned char *public;
5200 snprintf (keyid, DIM(keyid), "OPENPGP.%d", keyno);
5202 pk = xtrycalloc (1, sizeof *pk );
5204 return gpg_error_from_syserror ();
5205 pkt = xtrycalloc (1, sizeof *pkt);
5209 return gpg_error_from_syserror ();
5212 /* Note: SCD knows the serialnumber, thus there is no point in passing it. */
5213 err = agent_scd_genkey (keyno, 1, timestamp);
5214 /* The code below is not used because we force creation of
5215 * the a card key (3rd arg).
5216 * if (gpg_err_code (rc) == GPG_ERR_EEXIST)
5218 * tty_printf ("\n");
5219 * log_error ("WARNING: key does already exists!\n");
5220 * tty_printf ("\n");
5221 * if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
5222 * _("Replace existing key? ")))
5223 * rc = agent_scd_genkey (keyno, 1, timestamp);
5228 log_error ("key generation failed: %s\n", gpg_strerror (err));
5234 /* Send the READKEY command so that the agent creates a shadow key for
5235 card key. We need to do that now so that we are able to create
5236 the self-signatures. */
5237 err = agent_readkey (NULL, 1, keyid, &public);
5240 err = gcry_sexp_sscan (&s_key, NULL, public,
5241 gcry_sexp_canon_len (public, 0, NULL, NULL));
5246 if (algo == PUBKEY_ALGO_RSA)
5247 err = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
5248 else if (algo == PUBKEY_ALGO_ECDSA
5249 || algo == PUBKEY_ALGO_EDDSA
5250 || algo == PUBKEY_ALGO_ECDH )
5251 err = ecckey_from_sexp (pk->pkey, s_key, algo);
5253 err = gpg_error (GPG_ERR_PUBKEY_ALGO);
5254 gcry_sexp_release (s_key);
5258 log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
5259 free_public_key (pk);
5263 pk->timestamp = *timestamp;
5266 pk->expiredate = pk->timestamp + expireval;
5267 pk->pubkey_algo = algo;
5269 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
5270 pkt->pkt.public_key = pk;
5271 add_kbnode (pub_root, new_kbnode (pkt));
5280 return gpg_error (GPG_ERR_NOT_SUPPORTED);
5281 #endif /*!ENABLE_CARD_SUPPORT*/