1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2009 Free Software Foundation, Inc.
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 <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
43 #include "keyserver-internal.h"
44 #include "call-agent.h"
47 /* The default algorithms. If you change them remember to change them
48 also in gpg.c:gpgconf_list. You should also check that the value
49 is inside the bounds enforced by ask_keysize and gen_xxx. */
50 #define DEFAULT_STD_ALGO GCRY_PK_RSA
51 #define DEFAULT_STD_KEYSIZE 2048
71 pKEYCREATIONDATE, /* Same in seconds since epoch. */
73 pKEYEXPIRE, /* in n seconds */
74 pSUBKEYEXPIRE, /* in n seconds */
85 struct para_data_s *next;
94 struct revocation_key revkey;
99 struct output_control_s {
108 armor_filter_context_t *afx;
114 armor_filter_context_t *afx;
119 struct opaque_data_usage_and_pk {
125 static int prefs_initialized = 0;
126 static byte sym_prefs[MAX_PREFS];
127 static int nsym_prefs;
128 static byte hash_prefs[MAX_PREFS];
129 static int nhash_prefs;
130 static byte zip_prefs[MAX_PREFS];
131 static int nzip_prefs;
132 static int mdc_available,ks_modify;
134 static void do_generate_keypair( struct para_data_s *para,
135 struct output_control_s *outctrl, int card );
136 static int write_keyblock( IOBUF out, KBNODE node );
137 static int gen_card_key (int algo, int keyno, int is_primary,
138 KBNODE pub_root, KBNODE sec_root,
139 PKT_secret_key **ret_sk,
141 u32 expireval, struct para_data_s *para);
142 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
143 KBNODE pub_root, KBNODE sec_root,
145 u32 expireval, struct para_data_s *para,
146 const char *backup_dir);
150 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
152 byte array[MAX_FINGERPRINT_LEN], *s;
159 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
166 fingerprint_from_pk (pk, array, &n);
168 for (i=0; i < n ; i++, s++, p += 2)
169 sprintf (p, "%02X", *s);
174 for (i=0; handle[i] && i < 100; i++)
175 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
178 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
184 print_status_key_not_created (const char *handle)
186 print_status_key_created (0, NULL, handle);
192 write_uid( KBNODE root, const char *s )
194 PACKET *pkt = xmalloc_clear(sizeof *pkt );
195 size_t n = strlen(s);
197 pkt->pkttype = PKT_USER_ID;
198 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
199 pkt->pkt.user_id->len = n;
200 pkt->pkt.user_id->ref = 1;
201 strcpy(pkt->pkt.user_id->name, s);
202 add_kbnode( root, new_kbnode( pkt ) );
206 do_add_key_flags (PKT_signature *sig, unsigned int use)
212 /* The spec says that all primary keys MUST be able to certify. */
213 if(sig->sig_class!=0x18)
216 if (use & PUBKEY_USAGE_SIG)
218 if (use & PUBKEY_USAGE_ENC)
219 buf[0] |= 0x04 | 0x08;
220 if (use & PUBKEY_USAGE_AUTH)
223 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
228 keygen_add_key_expire( PKT_signature *sig, void *opaque )
230 PKT_public_key *pk = opaque;
234 if( pk->expiredate ) {
235 if(pk->expiredate > pk->timestamp)
236 u= pk->expiredate - pk->timestamp;
240 buf[0] = (u >> 24) & 0xff;
241 buf[1] = (u >> 16) & 0xff;
242 buf[2] = (u >> 8) & 0xff;
244 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
248 /* Make sure we don't leave a key expiration subpacket lying
250 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
257 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
259 struct opaque_data_usage_and_pk *oduap = opaque;
261 do_add_key_flags (sig, oduap->usage);
262 return keygen_add_key_expire (sig, oduap->pk);
266 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
270 for (i=0; i < *nbuf; i++ )
273 log_info (_("preference `%s' duplicated\n"), item);
277 if (*nbuf >= MAX_PREFS)
280 log_info(_("too many cipher preferences\n"));
282 log_info(_("too many digest preferences\n"));
284 log_info(_("too many compression preferences\n"));
291 buf[(*nbuf)++] = val;
296 * Parse the supplied string and use it to set the standard
297 * preferences. The string may be in a form like the one printed by
298 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
299 * cipher/hash/compress names. Use NULL to set the default
300 * preferences. Returns: 0 = okay
303 keygen_set_std_prefs (const char *string,int personal)
305 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
306 int nsym=0, nhash=0, nzip=0, val, rc=0;
307 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
308 char dummy_string[20*4+1]; /* Enough for 20 items. */
310 if (!string || !ascii_strcasecmp (string, "default"))
312 if (opt.def_preference_list)
313 string=opt.def_preference_list;
316 dummy_string[0]='\0';
318 /* The rationale why we use the order AES256,192,128 is
319 for compatibility reasons with PGP. If gpg would
320 define AES128 first, we would get the somewhat
323 gpg -r pgpkey -r gpgkey ---gives--> AES256
324 gpg -r gpgkey -r pgpkey ---gives--> AES
326 Note that by using --personal-cipher-preferences it is
327 possible to prefer AES128.
330 /* Make sure we do not add more than 15 items here, as we
331 could overflow the size of dummy_string. We currently
333 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
334 strcat(dummy_string,"S9 ");
335 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
336 strcat(dummy_string,"S8 ");
337 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
338 strcat(dummy_string,"S7 ");
339 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_CAST5) )
340 strcat(dummy_string,"S3 ");
341 strcat(dummy_string,"S2 "); /* 3DES */
342 /* If we have it, IDEA goes *after* 3DES so it won't be
343 used unless we're encrypting along with a V3 key.
344 Ideally, we would only put the S1 preference in if the
345 key was RSA and <=2048 bits, as that is what won't
346 break PGP2, but that is difficult with the current
347 code, and not really worth checking as a non-RSA <=2048
348 bit key wouldn't be usable by PGP2 anyway. -dms */
349 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_IDEA) )
350 strcat(dummy_string,"S1 ");
353 /* The default hash algo order is:
354 SHA-256, SHA-1, SHA-384, SHA-512, SHA-224.
355 Ordering SHA-1 before SHA-384 might be viewed as a bit
356 strange; it is done because we expect that soon enough
357 SHA-3 will be available and at that point there should
358 be no more need for SHA-384 etc. Anyway this order is
359 just a default and can easily be changed by a config
361 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
362 strcat (dummy_string, "H8 ");
364 strcat (dummy_string, "H2 "); /* SHA-1 */
366 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
367 strcat (dummy_string, "H9 ");
369 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
370 strcat (dummy_string, "H10 ");
372 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
373 strcat (dummy_string, "H11 ");
377 strcat(dummy_string,"Z2 ");
379 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
380 strcat(dummy_string,"Z3 ");
383 strcat(dummy_string,"Z1");
388 else if (!ascii_strcasecmp (string, "none"))
393 char *tok,*prefstring;
395 prefstring=xstrdup(string); /* need a writable string! */
397 while((tok=strsep(&prefstring," ,")))
399 if((val=string_to_cipher_algo (tok)))
401 if(set_one_pref(val,1,tok,sym,&nsym))
404 else if((val=string_to_digest_algo (tok)))
406 if(set_one_pref(val,2,tok,hash,&nhash))
409 else if((val=string_to_compress_algo(tok))>-1)
411 if(set_one_pref(val,3,tok,zip,&nzip))
414 else if (ascii_strcasecmp(tok,"mdc")==0)
416 else if (ascii_strcasecmp(tok,"no-mdc")==0)
418 else if (ascii_strcasecmp(tok,"ks-modify")==0)
420 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
424 log_info (_("invalid item `%s' in preference string\n"),tok);
426 /* Complain if IDEA is not available. */
427 if(ascii_strcasecmp(tok,"s1")==0
428 || ascii_strcasecmp(tok,"idea")==0)
442 if(personal==PREFTYPE_SYM)
444 xfree(opt.personal_cipher_prefs);
447 opt.personal_cipher_prefs=NULL;
452 opt.personal_cipher_prefs=
453 xmalloc(sizeof(prefitem_t *)*(nsym+1));
455 for (i=0; i<nsym; i++)
457 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
458 opt.personal_cipher_prefs[i].value = sym[i];
461 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
462 opt.personal_cipher_prefs[i].value = 0;
465 else if(personal==PREFTYPE_HASH)
467 xfree(opt.personal_digest_prefs);
470 opt.personal_digest_prefs=NULL;
475 opt.personal_digest_prefs=
476 xmalloc(sizeof(prefitem_t *)*(nhash+1));
478 for (i=0; i<nhash; i++)
480 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
481 opt.personal_digest_prefs[i].value = hash[i];
484 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
485 opt.personal_digest_prefs[i].value = 0;
488 else if(personal==PREFTYPE_ZIP)
490 xfree(opt.personal_compress_prefs);
493 opt.personal_compress_prefs=NULL;
498 opt.personal_compress_prefs=
499 xmalloc(sizeof(prefitem_t *)*(nzip+1));
501 for (i=0; i<nzip; i++)
503 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
504 opt.personal_compress_prefs[i].value = zip[i];
507 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
508 opt.personal_compress_prefs[i].value = 0;
514 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
515 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
516 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
519 prefs_initialized = 1;
526 /* Return a fake user ID containing the preferences. Caller must
529 keygen_get_std_prefs(void)
532 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
534 if(!prefs_initialized)
535 keygen_set_std_prefs(NULL,0);
539 uid->prefs=xmalloc((sizeof(prefitem_t *)*
540 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
542 for(i=0;i<nsym_prefs;i++,j++)
544 uid->prefs[j].type=PREFTYPE_SYM;
545 uid->prefs[j].value=sym_prefs[i];
548 for(i=0;i<nhash_prefs;i++,j++)
550 uid->prefs[j].type=PREFTYPE_HASH;
551 uid->prefs[j].value=hash_prefs[i];
554 for(i=0;i<nzip_prefs;i++,j++)
556 uid->prefs[j].type=PREFTYPE_ZIP;
557 uid->prefs[j].value=zip_prefs[i];
560 uid->prefs[j].type=PREFTYPE_NONE;
561 uid->prefs[j].value=0;
563 uid->flags.mdc=mdc_available;
564 uid->flags.ks_modify=ks_modify;
570 add_feature_mdc (PKT_signature *sig,int enabled)
577 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
578 /* Already set or cleared */
580 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
583 if (!s || !n) { /* create a new one */
585 buf = xmalloc_clear (n);
593 buf[0] |= 0x01; /* MDC feature */
597 /* Are there any bits set? */
603 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
605 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
611 add_keyserver_modify (PKT_signature *sig,int enabled)
618 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
621 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
622 /* Already set or cleared */
624 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
627 if (!s || !n) { /* create a new one */
629 buf = xmalloc_clear (n);
637 buf[0] |= 0x80; /* no-modify flag */
641 /* Are there any bits set? */
647 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
649 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
656 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
660 if (!prefs_initialized)
661 keygen_set_std_prefs (NULL, 0);
664 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
667 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
668 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
672 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
675 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
676 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
680 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
683 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
684 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
687 /* Make sure that the MDC feature flag is set if needed. */
688 add_feature_mdc (sig,mdc_available);
689 add_keyserver_modify (sig,ks_modify);
690 keygen_add_keyserver_url(sig,NULL);
697 * Add preference to the self signature packet.
698 * This is only called for packets with version > 3.
702 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
704 PKT_public_key *pk = opaque;
706 do_add_key_flags (sig, pk->pubkey_usage);
707 keygen_add_key_expire( sig, opaque );
708 keygen_upd_std_prefs (sig, opaque);
709 keygen_add_keyserver_url(sig,NULL);
715 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
717 const char *url=opaque;
720 url=opt.def_keyserver_url;
723 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
725 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
731 keygen_add_notations(PKT_signature *sig,void *opaque)
733 struct notation *notation;
735 /* We always start clean */
736 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
737 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
738 sig->flags.notation=0;
740 for(notation=opaque;notation;notation=notation->next)
741 if(!notation->flags.ignore)
746 n1=strlen(notation->name);
747 if(notation->altvalue)
748 n2=strlen(notation->altvalue);
749 else if(notation->bdat)
752 n2=strlen(notation->value);
754 buf = xmalloc( 8 + n1 + n2 );
756 /* human readable or not */
757 buf[0] = notation->bdat?0:0x80;
758 buf[1] = buf[2] = buf[3] = 0;
763 memcpy(buf+8, notation->name, n1 );
764 if(notation->altvalue)
765 memcpy(buf+8+n1, notation->altvalue, n2 );
766 else if(notation->bdat)
767 memcpy(buf+8+n1, notation->bdat, n2 );
769 memcpy(buf+8+n1, notation->value, n2 );
770 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
771 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
780 keygen_add_revkey(PKT_signature *sig, void *opaque)
782 struct revocation_key *revkey=opaque;
783 byte buf[2+MAX_FINGERPRINT_LEN];
785 buf[0]=revkey->class;
786 buf[1]=revkey->algid;
787 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
789 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
791 /* All sigs with revocation keys set are nonrevocable */
792 sig->flags.revocable=0;
794 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
803 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
804 signature creation time. */
806 make_backsig (PKT_signature *sig,PKT_public_key *pk,
807 PKT_public_key *sub_pk,PKT_secret_key *sub_sk,
810 PKT_signature *backsig;
813 cache_public_key(sub_pk);
815 rc = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_sk, 0x19,
816 0, 0, timestamp, 0, NULL, NULL);
818 log_error("make_keysig_packet failed for backsig: %s\n",g10_errstr(rc));
821 /* Get it into a binary packed form. */
822 IOBUF backsig_out=iobuf_temp();
825 init_packet(&backsig_pkt);
826 backsig_pkt.pkttype=PKT_SIGNATURE;
827 backsig_pkt.pkt.signature=backsig;
828 rc=build_packet(backsig_out,&backsig_pkt);
829 free_packet(&backsig_pkt);
831 log_error("build_packet failed for backsig: %s\n",g10_errstr(rc));
835 byte *buf=iobuf_get_temp_buffer(backsig_out);
837 /* Remove the packet header */
847 pktlen=(buf[1]-192)*256;
853 pktlen = buf32_to_size_t (buf+2);
870 pktlen = (size_t)buf[mark++] << 24;
871 pktlen |= buf[mark++] << 16;
874 pktlen |= buf[mark++] << 8;
877 pktlen |= buf[mark++];
883 /* Now make the binary blob into a subpacket. */
884 build_sig_subpkt(sig,SIGSUBPKT_SIGNATURE,buf,pktlen);
886 iobuf_close(backsig_out);
895 write_direct_sig (KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
896 struct revocation_key *revkey, u32 timestamp)
905 log_info(_("writing direct signature\n"));
907 /* Get the pk packet from the pub_tree. */
908 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
911 pk = node->pkt->pkt.public_key;
913 /* We have to cache the key, so that the verification of the
914 signature creation is able to retrieve the public key. */
915 cache_public_key (pk);
917 /* Make the signature. */
918 rc = make_keysig_packet (&sig,pk,NULL,NULL,sk,0x1F,
920 keygen_add_revkey, revkey);
923 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
927 pkt = xmalloc_clear( sizeof *pkt );
928 pkt->pkttype = PKT_SIGNATURE;
929 pkt->pkt.signature = sig;
930 add_kbnode( root, new_kbnode( pkt ) );
936 write_selfsigs( KBNODE sec_root, KBNODE pub_root, PKT_secret_key *sk,
937 unsigned int use, u32 timestamp )
947 log_info(_("writing self signature\n"));
949 /* Get the uid packet from the list. */
950 node = find_kbnode( pub_root, PKT_USER_ID );
952 BUG(); /* No user id packet in tree. */
953 uid = node->pkt->pkt.user_id;
955 /* Get the pk packet from the pub_tree. */
956 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
959 pk = node->pkt->pkt.public_key;
960 pk->pubkey_usage = use;
962 /* We have to cache the key, so that the verification of the
963 signature creation is able to retrieve the public key. */
964 cache_public_key (pk);
966 /* Make the signature. */
967 rc = make_keysig_packet (&sig, pk, uid, NULL, sk, 0x13,
969 keygen_add_std_prefs, pk);
972 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
976 pkt = xmalloc_clear( sizeof *pkt );
977 pkt->pkttype = PKT_SIGNATURE;
978 pkt->pkt.signature = sig;
979 add_kbnode( sec_root, new_kbnode( pkt ) );
981 pkt = xmalloc_clear( sizeof *pkt );
982 pkt->pkttype = PKT_SIGNATURE;
983 pkt->pkt.signature = copy_signature(NULL,sig);
984 add_kbnode( pub_root, new_kbnode( pkt ) );
989 /* Write the key binding signature. If TIMESTAMP is not NULL use the
990 signature creation times. */
992 write_keybinding (KBNODE root, KBNODE pub_root,
993 PKT_secret_key *pri_sk, PKT_secret_key *sub_sk,
994 unsigned int use, u32 timestamp)
1000 PKT_public_key *pri_pk, *sub_pk;
1001 struct opaque_data_usage_and_pk oduap;
1004 log_info(_("writing key binding signature\n"));
1006 /* Get the pk packet from the pub_tree. */
1007 node = find_kbnode ( pub_root, PKT_PUBLIC_KEY );
1010 pri_pk = node->pkt->pkt.public_key;
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 (pri_pk);
1016 /* Find the last subkey. */
1018 for (node=pub_root; node; node = node->next )
1020 if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
1021 sub_pk = node->pkt->pkt.public_key;
1026 /* Make the signature. */
1029 rc = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_sk, 0x18,
1031 keygen_add_key_flags_and_expire, &oduap );
1034 log_error ("make_keysig_packet failed: %s\n", g10_errstr(rc) );
1038 /* Make a backsig. */
1039 if (use&PUBKEY_USAGE_SIG)
1041 rc = make_backsig (sig, pri_pk, sub_pk, sub_sk, timestamp);
1046 pkt = xmalloc_clear ( sizeof *pkt );
1047 pkt->pkttype = PKT_SIGNATURE;
1048 pkt->pkt.signature = sig;
1049 add_kbnode (root, new_kbnode (pkt) );
1056 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1057 const char *topname, const char *elems)
1059 gcry_sexp_t list, l2;
1064 list = gcry_sexp_find_token (sexp, topname, 0);
1066 return gpg_error (GPG_ERR_INV_OBJ);
1067 l2 = gcry_sexp_cadr (list);
1068 gcry_sexp_release (list);
1071 return gpg_error (GPG_ERR_NO_OBJ);
1073 for (idx=0,s=elems; *s; s++, idx++)
1075 l2 = gcry_sexp_find_token (list, s, 1);
1078 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1081 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1082 gcry_sexp_release (l2);
1085 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1089 gcry_sexp_release (list);
1094 for (i=0; i<idx; i++)
1096 gcry_mpi_release (array[i]);
1099 gcry_sexp_release (list);
1106 genhelp_protect (DEK *dek, STRING2KEY *s2k, PKT_secret_key *sk)
1112 sk->protect.algo = dek->algo;
1113 sk->protect.s2k = *s2k;
1114 rc = protect_secret_key (sk, dek);
1116 log_error ("protect_secret_key failed: %s\n", gpg_strerror (rc) );
1123 genhelp_factors (gcry_sexp_t misc_key_info, KBNODE sec_root)
1125 (void)misc_key_info;
1127 #if 0 /* Not used anymore */
1133 /* DSA: don't know whether it makes sense to have the factors, so for now
1134 we store them in the secret keyring (but they are not secret)
1135 p = 2 * q * f1 * f2 * ... * fn
1136 We store only f1 to f_n-1; fn can be calculated because p and q
1138 n = gcry_sexp_sprint (misc_key_info, 0, NULL, 0);
1139 buf = xmalloc (n+4);
1140 strcpy (buf, "#::");
1141 n = gcry_sexp_sprint (misc_key_info, 0, buf+3, n);
1145 add_kbnode (sec_root, make_comment_node_from_buffer (buf, n));
1148 gcry_sexp_release (misc_key_info);
1154 /* Generate an Elgamal encryption key pair. TIMESTAMP is the creatuion
1155 time to be put into the key structure. */
1157 gen_elg (int algo, unsigned int nbits,
1158 KBNODE pub_root, KBNODE sec_root, DEK *dek,
1159 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1160 u32 timestamp, u32 expireval, int is_subkey)
1166 gcry_sexp_t s_parms, s_key;
1167 gcry_sexp_t misc_key_info;
1169 assert( is_ELGAMAL(algo) );
1174 log_info (_("keysize invalid; using %u bits\n"), nbits );
1176 else if (nbits > 4096)
1179 log_info (_("keysize invalid; using %u bits\n"), nbits );
1184 nbits = ((nbits + 31) / 32) * 32;
1185 log_info (_("keysize rounded up to %u bits\n"), nbits );
1189 rc = gcry_sexp_build ( &s_parms, NULL,
1190 "(genkey(%s(nbits %d)))",
1191 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1192 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1195 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1197 rc = gcry_pk_genkey (&s_key, s_parms);
1198 gcry_sexp_release (s_parms);
1201 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1205 sk = xmalloc_clear( sizeof *sk );
1206 pk = xmalloc_clear( sizeof *pk );
1207 sk->timestamp = pk->timestamp = timestamp;
1208 sk->version = pk->version = 4;
1211 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1213 sk->pubkey_algo = pk->pubkey_algo = algo;
1215 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pgy");
1218 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1219 gcry_sexp_release (s_key);
1220 free_secret_key (sk);
1221 free_public_key (pk);
1224 rc = key_from_sexp (sk->skey, s_key, "private-key", "pgyx");
1227 log_error("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1228 gcry_sexp_release (s_key);
1229 free_secret_key (sk);
1230 free_public_key (pk);
1233 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1234 gcry_sexp_release (s_key);
1236 sk->is_protected = 0;
1237 sk->protect.algo = 0;
1239 sk->csum = checksum_mpi (sk->skey[3]);
1240 if (ret_sk) /* Return an unprotected version of the sk. */
1241 *ret_sk = copy_secret_key ( NULL, sk );
1243 rc = genhelp_protect (dek, s2k, sk);
1246 free_public_key (pk);
1247 free_secret_key (sk);
1248 gcry_sexp_release (misc_key_info);
1252 pkt = xmalloc_clear (sizeof *pkt);
1253 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1254 pkt->pkt.public_key = pk;
1255 add_kbnode (pub_root, new_kbnode( pkt ));
1257 /* Don't know whether it makes sense to have access to the factors,
1258 so for now we store them in the secret keyring (but they are not
1260 pkt = xmalloc_clear (sizeof *pkt);
1261 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1262 pkt->pkt.secret_key = sk;
1263 add_kbnode (sec_root, new_kbnode( pkt ));
1265 genhelp_factors (misc_key_info, sec_root);
1272 * Generate a DSA key
1275 gen_dsa (unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1276 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1277 u32 timestamp, u32 expireval, int is_subkey)
1283 gcry_sexp_t s_parms, s_key;
1284 gcry_sexp_t misc_key_info;
1290 log_info(_("keysize invalid; using %u bits\n"), nbits );
1292 else if ( nbits > 3072 )
1295 log_info(_("keysize invalid; using %u bits\n"), nbits );
1300 nbits = ((nbits + 63) / 64) * 64;
1301 log_info(_("keysize rounded up to %u bits\n"), nbits );
1304 /* To comply with FIPS rules we round up to the next value unless in
1306 if (!opt.expert && nbits > 1024 && (nbits % 1024))
1308 nbits = ((nbits + 1023) / 1024) * 1024;
1309 log_info(_("keysize rounded up to %u bits\n"), nbits );
1313 Figure out a q size based on the key size. FIPS 180-3 says:
1320 2048/256 is an odd pair since there is also a 2048/224 and
1321 3072/256. Matching sizes is not a very exact science.
1323 We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1324 but less than 2048, and 160 for 1024 (DSA1).
1329 else if ( nbits > 1024)
1335 log_info (_("WARNING: some OpenPGP programs can't"
1336 " handle a DSA key with this digest size\n"));
1338 rc = gcry_sexp_build (&s_parms, NULL,
1339 "(genkey(dsa(nbits %d)(qbits %d)))",
1340 (int)nbits, (int)qbits);
1342 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1344 rc = gcry_pk_genkey (&s_key, s_parms);
1345 gcry_sexp_release (s_parms);
1348 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1352 sk = xmalloc_clear( sizeof *sk );
1353 pk = xmalloc_clear( sizeof *pk );
1354 sk->timestamp = pk->timestamp = timestamp;
1355 sk->version = pk->version = 4;
1357 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1358 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
1360 rc = key_from_sexp (pk->pkey, s_key, "public-key", "pqgy");
1363 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1364 gcry_sexp_release (s_key);
1365 free_public_key(pk);
1366 free_secret_key(sk);
1369 rc = key_from_sexp (sk->skey, s_key, "private-key", "pqgyx");
1372 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1373 gcry_sexp_release (s_key);
1374 free_public_key(pk);
1375 free_secret_key(sk);
1378 misc_key_info = gcry_sexp_find_token (s_key, "misc-key-info", 0);
1379 gcry_sexp_release (s_key);
1381 sk->is_protected = 0;
1382 sk->protect.algo = 0;
1384 sk->csum = checksum_mpi ( sk->skey[4] );
1385 if( ret_sk ) /* return an unprotected version of the sk */
1386 *ret_sk = copy_secret_key( NULL, sk );
1388 rc = genhelp_protect (dek, s2k, sk);
1391 free_public_key (pk);
1392 free_secret_key (sk);
1393 gcry_sexp_release (misc_key_info);
1397 pkt = xmalloc_clear(sizeof *pkt);
1398 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1399 pkt->pkt.public_key = pk;
1400 add_kbnode(pub_root, new_kbnode( pkt ));
1402 /* Don't know whether it makes sense to have the factors, so for now
1403 * we store them in the secret keyring (but they are not secret)
1404 * p = 2 * q * f1 * f2 * ... * fn
1405 * We store only f1 to f_n-1; fn can be calculated because p and q
1408 pkt = xmalloc_clear(sizeof *pkt);
1409 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1410 pkt->pkt.secret_key = sk;
1411 add_kbnode(sec_root, new_kbnode( pkt ));
1413 genhelp_factors (misc_key_info, sec_root);
1420 * Generate an RSA key.
1423 gen_rsa (int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
1424 STRING2KEY *s2k, PKT_secret_key **ret_sk,
1425 u32 timestamp, u32 expireval, int is_subkey)
1431 gcry_sexp_t s_parms, s_key;
1432 const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
1434 assert (is_RSA(algo));
1437 nbits = DEFAULT_STD_KEYSIZE;
1442 log_info (_("keysize invalid; using %u bits\n"), nbits );
1444 else if (nbits > maxsize)
1447 log_info (_("keysize invalid; using %u bits\n"), nbits );
1452 nbits = ((nbits + 31) / 32) * 32;
1453 log_info (_("keysize rounded up to %u bits\n"), nbits );
1456 rc = gcry_sexp_build (&s_parms, NULL,
1457 "(genkey(rsa(nbits %d)))",
1460 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
1462 rc = gcry_pk_genkey (&s_key, s_parms);
1463 gcry_sexp_release (s_parms);
1466 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
1470 sk = xmalloc_clear( sizeof *sk );
1471 pk = xmalloc_clear( sizeof *pk );
1472 sk->timestamp = pk->timestamp = timestamp;
1473 sk->version = pk->version = 4;
1476 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
1478 sk->pubkey_algo = pk->pubkey_algo = algo;
1480 rc = key_from_sexp (pk->pkey, s_key, "public-key", "ne");
1483 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc));
1484 gcry_sexp_release (s_key);
1485 free_public_key(pk);
1486 free_secret_key(sk);
1489 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
1492 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
1493 gcry_sexp_release (s_key);
1494 free_public_key(pk);
1495 free_secret_key(sk);
1498 gcry_sexp_release (s_key);
1500 sk->is_protected = 0;
1501 sk->protect.algo = 0;
1503 sk->csum = checksum_mpi (sk->skey[2] );
1504 sk->csum += checksum_mpi (sk->skey[3] );
1505 sk->csum += checksum_mpi (sk->skey[4] );
1506 sk->csum += checksum_mpi (sk->skey[5] );
1507 if( ret_sk ) /* return an unprotected version of the sk */
1508 *ret_sk = copy_secret_key( NULL, sk );
1510 rc = genhelp_protect (dek, s2k, sk);
1513 free_public_key (pk);
1514 free_secret_key (sk);
1518 pkt = xmalloc_clear(sizeof *pkt);
1519 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1520 pkt->pkt.public_key = pk;
1521 add_kbnode(pub_root, new_kbnode( pkt ));
1523 pkt = xmalloc_clear(sizeof *pkt);
1524 pkt->pkttype = is_subkey ? PKT_SECRET_SUBKEY : PKT_SECRET_KEY;
1525 pkt->pkt.secret_key = sk;
1526 add_kbnode(sec_root, new_kbnode( pkt ));
1534 * return 0 on error or the multiplier
1537 check_valid_days( const char *s )
1547 return 0; /* e.g. "2323wc" */
1548 if( *s == 'd' || *s == 'D' )
1550 if( *s == 'w' || *s == 'W' )
1552 if( *s == 'm' || *s == 'M' )
1554 if( *s == 'y' || *s == 'Y' )
1561 print_key_flags(int flags)
1563 if(flags&PUBKEY_USAGE_SIG)
1564 tty_printf("%s ",_("Sign"));
1566 if(flags&PUBKEY_USAGE_CERT)
1567 tty_printf("%s ",_("Certify"));
1569 if(flags&PUBKEY_USAGE_ENC)
1570 tty_printf("%s ",_("Encrypt"));
1572 if(flags&PUBKEY_USAGE_AUTH)
1573 tty_printf("%s ",_("Authenticate"));
1577 /* Returns the key flags */
1579 ask_key_flags(int algo,int subkey)
1581 /* TRANSLATORS: Please use only plain ASCII characters for the
1582 translation. If this is not possible use single digits. The
1583 string needs to 8 bytes long. Here is a description of the
1586 s = Toggle signing capability
1587 e = Toggle encryption capability
1588 a = Toggle authentication capability
1591 const char *togglers=_("SsEeAaQq");
1594 unsigned int current=0;
1595 unsigned int possible=openpgp_pk_algo_usage(algo);
1597 if ( strlen(togglers) != 8 )
1599 tty_printf ("NOTE: Bad translation at %s:%d. "
1600 "Please report.\n", __FILE__, __LINE__);
1601 togglers = "11223300";
1604 /* Only primary keys may certify. */
1606 possible&=~PUBKEY_USAGE_CERT;
1608 /* Preload the current set with the possible set, minus
1609 authentication, since nobody really uses auth yet. */
1610 current=possible&~PUBKEY_USAGE_AUTH;
1615 tty_printf(_("Possible actions for a %s key: "),
1616 openpgp_pk_algo_name (algo));
1617 print_key_flags(possible);
1619 tty_printf(_("Current allowed actions: "));
1620 print_key_flags(current);
1623 if(possible&PUBKEY_USAGE_SIG)
1624 tty_printf(_(" (%c) Toggle the sign capability\n"),
1626 if(possible&PUBKEY_USAGE_ENC)
1627 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1629 if(possible&PUBKEY_USAGE_AUTH)
1630 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1633 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1637 answer = cpr_get("keygen.flags",_("Your selection? "));
1642 /* Hack to allow direct entry of the capabilities. */
1644 for (s=answer+1; *s; s++)
1646 if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
1647 current |= PUBKEY_USAGE_SIG;
1648 else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
1649 current |= PUBKEY_USAGE_ENC;
1650 else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
1651 current |= PUBKEY_USAGE_AUTH;
1655 else if (strlen(answer)>1)
1656 tty_printf(_("Invalid selection.\n"));
1657 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1659 else if((*answer==togglers[0] || *answer==togglers[1])
1660 && possible&PUBKEY_USAGE_SIG)
1662 if(current&PUBKEY_USAGE_SIG)
1663 current&=~PUBKEY_USAGE_SIG;
1665 current|=PUBKEY_USAGE_SIG;
1667 else if((*answer==togglers[2] || *answer==togglers[3])
1668 && possible&PUBKEY_USAGE_ENC)
1670 if(current&PUBKEY_USAGE_ENC)
1671 current&=~PUBKEY_USAGE_ENC;
1673 current|=PUBKEY_USAGE_ENC;
1675 else if((*answer==togglers[4] || *answer==togglers[5])
1676 && possible&PUBKEY_USAGE_AUTH)
1678 if(current&PUBKEY_USAGE_AUTH)
1679 current&=~PUBKEY_USAGE_AUTH;
1681 current|=PUBKEY_USAGE_AUTH;
1684 tty_printf(_("Invalid selection.\n"));
1693 /* Ask for an algorithm. The function returns the algorithm id to
1694 * create. If ADDMODE is false the function won't show an option to
1695 * create the primary and subkey combined and won't set R_USAGE
1696 * either. If a combined algorithm has been selected, the subkey
1697 * algorithm is stored at R_SUBKEY_ALGO. */
1699 ask_algo (int addmode, int *r_subkey_algo, unsigned int *r_usage)
1701 char *answer = NULL;
1706 r_subkey_algo = &dummy_algo;
1708 tty_printf (_("Please select what kind of key you want:\n"));
1711 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1713 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1715 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1716 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1720 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1721 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1725 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1726 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1734 answer = cpr_get ("keygen.algo", _("Your selection? "));
1736 algo = *answer? atoi (answer) : 1;
1737 if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
1739 algo = PUBKEY_ALGO_RSA;
1740 *r_subkey_algo = PUBKEY_ALGO_RSA;
1743 else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
1745 algo = PUBKEY_ALGO_DSA;
1746 *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1749 else if (algo == 3 || !strcmp (answer, "dsa"))
1751 algo = PUBKEY_ALGO_DSA;
1752 *r_usage = PUBKEY_USAGE_SIG;
1755 else if (algo == 4 || !strcmp (answer, "rsa/s"))
1757 algo = PUBKEY_ALGO_RSA;
1758 *r_usage = PUBKEY_USAGE_SIG;
1761 else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
1763 algo = PUBKEY_ALGO_ELGAMAL_E;
1764 *r_usage = PUBKEY_USAGE_ENC;
1767 else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
1769 algo = PUBKEY_ALGO_RSA;
1770 *r_usage = PUBKEY_USAGE_ENC;
1773 else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
1775 algo = PUBKEY_ALGO_DSA;
1776 *r_usage = ask_key_flags (algo, addmode);
1779 else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
1781 algo = PUBKEY_ALGO_RSA;
1782 *r_usage = ask_key_flags (algo, addmode);
1786 tty_printf (_("Invalid selection.\n"));
1795 /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
1796 is not 0, the function asks for the size of the encryption
1799 ask_keysize (int algo, unsigned int primary_keysize)
1801 unsigned int nbits, min, def = DEFAULT_STD_KEYSIZE, max=4096;
1802 int for_subkey = !!primary_keysize;
1810 if (primary_keysize && !opt.expert)
1812 /* Deduce the subkey size from the primary key size. */
1813 if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
1814 nbits = 3072; /* For performance reasons we don't support more
1815 than 3072 bit DSA. However we won't see this
1816 case anyway because DSA can't be used as an
1817 encryption subkey ;-). */
1819 nbits = primary_keysize;
1826 case PUBKEY_ALGO_DSA:
1831 case PUBKEY_ALGO_RSA:
1836 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
1837 openpgp_pk_algo_name (algo), min, max);
1841 char *prompt, *answer;
1844 prompt = xasprintf (_("What keysize do you want "
1845 "for the subkey? (%u) "), def);
1847 prompt = xasprintf (_("What keysize do you want? (%u) "), def);
1848 answer = cpr_get ("keygen.size", prompt);
1850 nbits = *answer? atoi (answer): def;
1854 if(nbits<min || nbits>max)
1855 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
1856 openpgp_pk_algo_name (algo), min, max);
1861 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1864 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) )
1866 nbits = ((nbits + 63) / 64) * 64;
1868 tty_printf(_("rounded up to %u bits\n"), nbits );
1870 else if( (nbits % 32) )
1872 nbits = ((nbits + 31) / 32) * 32;
1874 tty_printf(_("rounded up to %u bits\n"), nbits );
1882 * Parse an expire string and return its value in seconds.
1883 * Returns (u32)-1 on error.
1884 * This isn't perfect since scan_isodatestr returns unix time, and
1885 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
1886 * Because of this, we only permit setting expirations up to 2106, but
1887 * OpenPGP could theoretically allow up to 2242. I think we'll all
1888 * just cope for the next few years until we get a 64-bit time_t or
1892 parse_expire_string( const char *string )
1897 u32 curtime = make_timestamp ();
1902 else if (!strncmp (string, "seconds=", 8))
1903 seconds = atoi (string+8);
1904 else if ((abs_date = scan_isodatestr(string))
1905 && (abs_date+86400/2) > curtime)
1906 seconds = (abs_date+86400/2) - curtime;
1907 else if ((tt = isotime2epoch (string)) != (time_t)(-1))
1908 seconds = (u32)tt - curtime;
1909 else if ((mult = check_valid_days (string)))
1910 seconds = atoi (string) * 86400L * mult;
1912 seconds = (u32)(-1);
1917 /* Parsean Creation-Date string which is either "1986-04-26" or
1918 "19860426T042640". Returns 0 on error. */
1920 parse_creation_string (const char *string)
1926 else if ( !strncmp (string, "seconds=", 8) )
1927 seconds = atoi (string+8);
1928 else if ( !(seconds = scan_isodatestr (string)))
1930 time_t tmp = isotime2epoch (string);
1931 seconds = (tmp == (time_t)(-1))? 0 : tmp;
1937 /* object == 0 for a key, and 1 for a sig */
1939 ask_expire_interval(int object,const char *def_expire)
1949 tty_printf(_("Please specify how long the key should be valid.\n"
1950 " 0 = key does not expire\n"
1951 " <n> = key expires in n days\n"
1952 " <n>w = key expires in n weeks\n"
1953 " <n>m = key expires in n months\n"
1954 " <n>y = key expires in n years\n"));
1960 tty_printf(_("Please specify how long the signature should be valid.\n"
1961 " 0 = signature does not expire\n"
1962 " <n> = signature expires in n days\n"
1963 " <n>w = signature expires in n weeks\n"
1964 " <n>m = signature expires in n months\n"
1965 " <n>y = signature expires in n years\n"));
1972 /* Note: The elgamal subkey for DSA has no expiration date because
1973 * it must be signed with the DSA key and this one has the expiration
1983 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1988 #define PROMPTSTRING _("Signature is valid for? (%s) ")
1989 /* This will actually end up larger than necessary because
1990 of the 2 bytes for '%s' */
1991 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
1992 sprintf(prompt,PROMPTSTRING,def_expire);
1995 answer = cpr_get("siggen.valid",prompt);
1999 answer=xstrdup(def_expire);
2002 trim_spaces(answer);
2003 curtime = make_timestamp ();
2004 interval = parse_expire_string( answer );
2005 if( interval == (u32)-1 )
2007 tty_printf(_("invalid value\n"));
2013 tty_printf((object==0)
2014 ? _("Key does not expire at all\n")
2015 : _("Signature does not expire at all\n"));
2019 tty_printf(object==0
2020 ? _("Key expires at %s\n")
2021 : _("Signature expires at %s\n"),
2022 asctimestamp((ulong)(curtime + interval) ) );
2023 #if SIZEOF_TIME_T <= 4
2024 if ( (time_t)((ulong)(curtime+interval)) < 0 )
2025 tty_printf (_("Your system can't display dates beyond 2038.\n"
2026 "However, it will be correctly handled up to"
2029 #endif /*SIZEOF_TIME_T*/
2030 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
2032 tty_printf (_("invalid value\n"));
2037 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2038 _("Is this correct? (y/N) ")) )
2049 u32 x = ask_expire_interval(0,NULL);
2050 return x? make_timestamp() + x : 0;
2055 static PKT_user_id *
2056 uid_from_string (const char *string)
2061 n = strlen (string);
2062 uid = xmalloc_clear (sizeof *uid + n);
2064 strcpy (uid->name, string);
2070 /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2071 printed for use during a new key creation. If KEYBLOCK is not NULL
2072 the function prevents the creation of an already existing user
2075 ask_user_id (int mode, KBNODE keyblock)
2078 char *aname, *acomment, *amail, *uid;
2082 /* TRANSLATORS: This is the new string telling the user what
2083 gpg is now going to do (i.e. ask for the parts of the user
2084 ID). Note that if you do not tyranslated this string, a
2085 different string will be used used, which might still have
2086 a correct transaltion. */
2089 "GnuPG needs to construct a user ID to identify your key.\n"
2091 const char *s2 = _(s1);
2093 if (!strcmp (s1, s2))
2095 /* There is no translation for the string thus we to use
2096 the old info text. gettext has no way to tell whether
2097 a translation is actually available, thus we need to
2098 to compare again. */
2099 /* TRANSLATORS: This string is in general not anymore used
2100 but you should keep your existing translation. In case
2101 the new string is not translated this old string will
2103 const char *s3 = N_("\n"
2104 "You need a user ID to identify your key; "
2105 "the software constructs the user ID\n"
2106 "from the Real Name, Comment and Email Address in this form:\n"
2107 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2108 const char *s4 = _(s3);
2109 if (strcmp (s3, s4))
2110 s2 = s3; /* A translation exists - use it. */
2112 tty_printf ("%s", s2) ;
2114 uid = aname = acomment = amail = NULL;
2122 aname = cpr_get("keygen.name",_("Real name: "));
2126 if( opt.allow_freeform_uid )
2129 if( strpbrk( aname, "<>" ) )
2130 tty_printf(_("Invalid character in name\n"));
2131 else if( digitp(aname) )
2132 tty_printf(_("Name may not start with a digit\n"));
2133 else if( strlen(aname) < 5 )
2134 tty_printf(_("Name must be at least 5 characters long\n"));
2142 amail = cpr_get("keygen.email",_("Email address: "));
2145 if( !*amail || opt.allow_freeform_uid )
2146 break; /* no email address is okay */
2147 else if ( !is_valid_mailbox (amail) )
2148 tty_printf(_("Not a valid email address\n"));
2156 acomment = cpr_get("keygen.comment",_("Comment: "));
2157 trim_spaces(acomment);
2160 break; /* no comment is okay */
2161 else if( strpbrk( acomment, "()" ) )
2162 tty_printf(_("Invalid character in comment\n"));
2170 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2171 p = stpcpy(p, aname );
2173 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2175 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2177 /* Append a warning if the RNG is switched into fake mode. */
2178 if ( random_is_faked () )
2179 strcpy(p, " (insecure!)" );
2181 /* print a note in case that UTF8 mapping has to be done */
2182 for(p=uid; *p; p++ ) {
2184 tty_printf(_("You are using the `%s' character set.\n"),
2185 get_native_charset() );
2190 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2192 if( !*amail && !opt.allow_freeform_uid
2193 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2195 tty_printf(_("Please don't put the email address "
2196 "into the real name or the comment\n") );
2199 if (!fail && keyblock)
2201 PKT_user_id *uidpkt = uid_from_string (uid);
2204 for (node=keyblock; node && !fail; node=node->next)
2205 if (!is_deleted_kbnode (node)
2206 && node->pkt->pkttype == PKT_USER_ID
2207 && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2210 tty_printf (_("Such a user ID already exists on this key!\n"));
2211 free_user_id (uidpkt);
2215 /* TRANSLATORS: These are the allowed answers in
2216 lower and uppercase. Below you will find the matching
2217 string which should be translated accordingly and the
2218 letter changed to match the one in the answer string.
2223 o = Okay (ready, continue)
2226 const char *ansstr = _("NnCcEeOoQq");
2228 if( strlen(ansstr) != 10 )
2230 if( cpr_enabled() ) {
2231 answer = xstrdup (ansstr + (fail?8:6));
2235 answer = cpr_get("keygen.userid.cmd", fail?
2236 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2237 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2240 if( strlen(answer) > 1 )
2242 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2243 xfree(aname); aname = NULL;
2246 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2247 xfree(acomment); acomment = NULL;
2250 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2251 xfree(amail); amail = NULL;
2254 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2256 tty_printf(_("Please correct the error first\n"));
2259 xfree(aname); aname = NULL;
2260 xfree(acomment); acomment = NULL;
2261 xfree(amail); amail = NULL;
2265 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2266 xfree(aname); aname = NULL;
2267 xfree(acomment); acomment = NULL;
2268 xfree(amail); amail = NULL;
2269 xfree(uid); uid = NULL;
2275 if( !aname && !acomment && !amail )
2277 xfree(uid); uid = NULL;
2280 char *p = native_to_utf8( uid );
2288 /* MODE 0 - standard
2289 1 - Ask for passphrase of the card backup key. */
2291 do_ask_passphrase (STRING2KEY **ret_s2k, int mode, int *r_canceled)
2295 const char *errtext = NULL;
2296 const char *custdesc = NULL;
2298 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2301 custdesc = _("Please enter a passphrase to protect the off-card "
2302 "backup of the new encryption key.");
2304 s2k = xmalloc_secure( sizeof *s2k );
2306 s2k->mode = opt.s2k_mode;
2307 s2k->hash_algo = S2K_DIGEST_ALGO;
2308 dek = passphrase_to_dek_ext (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2309 errtext, custdesc, NULL, r_canceled);
2310 if (!dek && *r_canceled) {
2311 xfree(dek); dek = NULL;
2312 xfree(s2k); s2k = NULL;
2316 errtext = N_("passphrase not correctly repeated; try again");
2317 tty_printf(_("%s.\n"), _(errtext));
2319 else if( !dek->keylen ) {
2320 xfree(dek); dek = NULL;
2321 xfree(s2k); s2k = NULL;
2323 "You don't want a passphrase - this is probably a *bad* idea!\n"
2324 "I will do it anyway. You can change your passphrase at any time,\n"
2325 "using this program with the option \"--edit-key\".\n\n"));
2336 /* Basic key generation. Here we divert to the actual generation
2337 routines based on the requested algorithm. */
2339 do_create (int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
2340 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk,
2341 u32 timestamp, u32 expiredate, int is_subkey )
2347 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2348 "some other action (type on the keyboard, move the mouse, utilize the\n"
2349 "disks) during the prime generation; this gives the random number\n"
2350 "generator a better chance to gain enough entropy.\n") );
2352 if( algo == PUBKEY_ALGO_ELGAMAL_E )
2353 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2354 timestamp, expiredate, is_subkey);
2355 else if( algo == PUBKEY_ALGO_DSA )
2356 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk,
2357 timestamp, expiredate, is_subkey);
2358 else if( algo == PUBKEY_ALGO_RSA )
2359 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk,
2360 timestamp, expiredate, is_subkey);
2368 /* Generate a new user id packet or return NULL if canceled. If
2369 KEYBLOCK is not NULL the function prevents the creation of an
2370 already existing user ID. */
2372 generate_user_id (KBNODE keyblock)
2376 p = ask_user_id (1, keyblock);
2378 return NULL; /* Canceled. */
2379 return uid_from_string (p);
2384 release_parameter_list( struct para_data_s *r )
2386 struct para_data_s *r2;
2388 for( ; r ; r = r2 ) {
2390 if( r->key == pPASSPHRASE_DEK )
2392 else if( r->key == pPASSPHRASE_S2K )
2399 static struct para_data_s *
2400 get_parameter( struct para_data_s *para, enum para_name key )
2402 struct para_data_s *r;
2404 for( r = para; r && r->key != key; r = r->next )
2410 get_parameter_value( struct para_data_s *para, enum para_name key )
2412 struct para_data_s *r = get_parameter( para, key );
2413 return (r && *r->u.value)? r->u.value : NULL;
2417 get_parameter_algo( struct para_data_s *para, enum para_name key,
2421 struct para_data_s *r = get_parameter( para, key );
2429 if (!ascii_strcasecmp (r->u.value, "default"))
2431 /* Note: If you change this default algo, remember to change it
2432 also in gpg.c:gpgconf_list. */
2433 i = DEFAULT_STD_ALGO;
2437 else if (digitp (r->u.value))
2438 i = atoi( r->u.value );
2439 else if (!strcmp (r->u.value, "ELG-E")
2440 || !strcmp (r->u.value, "ELG"))
2443 i = gcry_pk_map_name (r->u.value);
2445 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2446 i = 0; /* we don't want to allow generation of these algorithms */
2451 * Parse the usage parameter and set the keyflags. Returns -1 on
2452 * error, 0 for no usage given or 1 for usage available.
2455 parse_parameter_usage (const char *fname,
2456 struct para_data_s *para, enum para_name key)
2458 struct para_data_s *r = get_parameter( para, key );
2463 return 0; /* none (this is an optional parameter)*/
2467 while ( (p = strsep (&pn, " \t,")) ) {
2470 else if ( !ascii_strcasecmp (p, "sign") )
2471 use |= PUBKEY_USAGE_SIG;
2472 else if ( !ascii_strcasecmp (p, "encrypt") )
2473 use |= PUBKEY_USAGE_ENC;
2474 else if ( !ascii_strcasecmp (p, "auth") )
2475 use |= PUBKEY_USAGE_AUTH;
2477 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2478 return -1; /* error */
2486 parse_revocation_key (const char *fname,
2487 struct para_data_s *para, enum para_name key)
2489 struct para_data_s *r = get_parameter( para, key );
2490 struct revocation_key revkey;
2495 return 0; /* none (this is an optional parameter) */
2500 revkey.algid=atoi(pn);
2504 /* Skip to the fpr */
2505 while(*pn && *pn!=':')
2513 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2515 int c=hextobyte(pn);
2522 /* skip to the tag */
2523 while(*pn && *pn!='s' && *pn!='S')
2526 if(ascii_strcasecmp(pn,"sensitive")==0)
2529 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
2534 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
2535 return -1; /* error */
2540 get_parameter_u32( struct para_data_s *para, enum para_name key )
2542 struct para_data_s *r = get_parameter( para, key );
2546 if( r->key == pKEYCREATIONDATE )
2547 return r->u.creation;
2548 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
2550 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
2553 return (unsigned int)strtoul( r->u.value, NULL, 10 );
2557 get_parameter_uint( struct para_data_s *para, enum para_name key )
2559 return get_parameter_u32( para, key );
2563 get_parameter_dek( struct para_data_s *para, enum para_name key )
2565 struct para_data_s *r = get_parameter( para, key );
2566 return r? r->u.dek : NULL;
2570 get_parameter_s2k( struct para_data_s *para, enum para_name key )
2572 struct para_data_s *r = get_parameter( para, key );
2573 return r? r->u.s2k : NULL;
2576 static struct revocation_key *
2577 get_parameter_revkey( struct para_data_s *para, enum para_name key )
2579 struct para_data_s *r = get_parameter( para, key );
2580 return r? &r->u.revkey : NULL;
2584 proc_parameter_file( struct para_data_s *para, const char *fname,
2585 struct output_control_s *outctrl, int card )
2587 struct para_data_s *r;
2588 const char *s1, *s2, *s3;
2592 int have_user_id = 0;
2595 /* Check that we have all required parameters. */
2596 r = get_parameter( para, pKEYTYPE );
2599 algo = get_parameter_algo (para, pKEYTYPE, &is_default);
2600 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
2602 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2608 log_error ("%s: no Key-Type specified\n",fname);
2612 err = parse_parameter_usage (fname, para, pKEYUSAGE);
2615 /* Default to algo capabilities if key-usage is not provided and
2616 no default algorithm has been requested. */
2617 r = xmalloc_clear(sizeof(*r));
2619 r->u.usage = (is_default
2620 ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
2621 : openpgp_pk_algo_usage(algo));
2629 r = get_parameter (para, pKEYUSAGE);
2630 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2632 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
2633 fname, r->lnr, algo);
2639 r = get_parameter( para, pSUBKEYTYPE );
2642 algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
2643 if (openpgp_pk_test_algo (algo))
2645 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
2649 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
2652 /* Default to algo capabilities if subkey-usage is not
2654 r = xmalloc_clear (sizeof(*r));
2655 r->key = pSUBKEYUSAGE;
2656 r->u.usage = (is_default
2658 : openpgp_pk_algo_usage (algo));
2666 r = get_parameter (para, pSUBKEYUSAGE);
2667 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
2669 log_error ("%s:%d: specified Subkey-Usage not allowed"
2670 " for algo %d\n", fname, r->lnr, algo);
2677 if( get_parameter_value( para, pUSERID ) )
2681 /* create the formatted user ID */
2682 s1 = get_parameter_value( para, pNAMEREAL );
2683 s2 = get_parameter_value( para, pNAMECOMMENT );
2684 s3 = get_parameter_value( para, pNAMEEMAIL );
2685 if( s1 || s2 || s3 )
2687 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
2688 r = xmalloc_clear( sizeof *r + n + 20 );
2694 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
2696 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
2705 log_error("%s: no User-ID specified\n",fname);
2709 /* Set preferences, if any. */
2710 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
2712 /* Set keyserver, if any. */
2713 s1=get_parameter_value( para, pKEYSERVER );
2716 struct keyserver_spec *spec;
2718 spec=parse_keyserver_uri(s1,1,NULL,0);
2721 free_keyserver_spec(spec);
2722 opt.def_keyserver_url=s1;
2726 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
2731 /* Set revoker, if any. */
2732 if (parse_revocation_key (fname, para, pREVOKER))
2735 /* Make DEK and S2K from the Passphrase. */
2736 if (outctrl->ask_passphrase)
2738 /* %ask-passphrase is active - ignore pPASSPRASE and ask. This
2739 feature is required so that GUIs are able to do a key
2740 creation but have gpg-agent ask for the passphrase. */
2745 dek = do_ask_passphrase (&s2k, 0, &canceled);
2748 r = xmalloc_clear( sizeof *r );
2749 r->key = pPASSPHRASE_DEK;
2753 r = xmalloc_clear( sizeof *r );
2754 r->key = pPASSPHRASE_S2K;
2762 log_error ("%s:%d: key generation canceled\n", fname, r->lnr );
2768 r = get_parameter( para, pPASSPHRASE );
2769 if ( r && *r->u.value )
2771 /* We have a plain text passphrase - create a DEK from it.
2772 * It is a little bit ridiculous to keep it in secure memory
2773 * but because we do this always, why not here. */
2777 s2k = xmalloc_secure ( sizeof *s2k );
2778 s2k->mode = opt.s2k_mode;
2779 s2k->hash_algo = S2K_DIGEST_ALGO;
2780 set_next_passphrase ( r->u.value );
2781 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2783 set_next_passphrase (NULL );
2785 memset (r->u.value, 0, strlen(r->u.value));
2787 r = xmalloc_clear (sizeof *r);
2788 r->key = pPASSPHRASE_S2K;
2792 r = xmalloc_clear (sizeof *r);
2793 r->key = pPASSPHRASE_DEK;
2800 /* Make KEYCREATIONDATE from Creation-Date. */
2801 r = get_parameter (para, pCREATIONDATE);
2802 if (r && *r->u.value)
2806 seconds = parse_creation_string (r->u.value);
2809 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
2812 r->u.creation = seconds;
2813 r->key = pKEYCREATIONDATE; /* Change that entry. */
2816 /* Make KEYEXPIRE from Expire-Date. */
2817 r = get_parameter( para, pEXPIREDATE );
2818 if( r && *r->u.value )
2822 seconds = parse_expire_string( r->u.value );
2823 if( seconds == (u32)-1 )
2825 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
2828 r->u.expire = seconds;
2829 r->key = pKEYEXPIRE; /* change hat entry */
2830 /* also set it for the subkey */
2831 r = xmalloc_clear( sizeof *r + 20 );
2832 r->key = pSUBKEYEXPIRE;
2833 r->u.expire = seconds;
2838 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
2839 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
2843 do_generate_keypair( para, outctrl, card );
2849 * Kludge to allow non interactive key generation controlled
2850 * by a parameter file.
2851 * Note, that string parameters are expected to be in UTF-8
2854 read_parameter_file( const char *fname )
2856 static struct { const char *name;
2859 { "Key-Type", pKEYTYPE},
2860 { "Key-Length", pKEYLENGTH },
2861 { "Key-Usage", pKEYUSAGE },
2862 { "Subkey-Type", pSUBKEYTYPE },
2863 { "Subkey-Length", pSUBKEYLENGTH },
2864 { "Subkey-Usage", pSUBKEYUSAGE },
2865 { "Name-Real", pNAMEREAL },
2866 { "Name-Email", pNAMEEMAIL },
2867 { "Name-Comment", pNAMECOMMENT },
2868 { "Expire-Date", pEXPIREDATE },
2869 { "Creation-Date", pCREATIONDATE },
2870 { "Passphrase", pPASSPHRASE },
2871 { "Preferences", pPREFERENCES },
2872 { "Revoker", pREVOKER },
2873 { "Handle", pHANDLE },
2874 { "Keyserver", pKEYSERVER },
2879 unsigned int maxlen, nline;
2882 const char *err = NULL;
2883 struct para_data_s *para, *r;
2885 struct output_control_s outctrl;
2887 memset( &outctrl, 0, sizeof( outctrl ) );
2888 outctrl.pub.afx = new_armor_context ();
2889 outctrl.sec.afx = new_armor_context ();
2891 if( !fname || !*fname)
2894 fp = iobuf_open (fname);
2895 if (fp && is_secured_file (iobuf_get_fd (fp)))
2902 log_error (_("can't open `%s': %s\n"), fname, strerror(errno) );
2905 iobuf_ioctl (fp, 3, 1, NULL); /* No file caching. */
2912 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
2913 char *keyword, *value;
2917 err = "line too long";
2920 for( p = line; isspace(*(byte*)p); p++ )
2922 if( !*p || *p == '#' )
2925 if( *keyword == '%' ) {
2926 for( ; !isspace(*(byte*)p); p++ )
2930 for( ; isspace(*(byte*)p); p++ )
2933 trim_trailing_ws( value, strlen(value) );
2934 if( !ascii_strcasecmp( keyword, "%echo" ) )
2935 log_info("%s\n", value );
2936 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
2938 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
2939 outctrl.ask_passphrase = 1;
2940 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
2941 outctrl.ask_passphrase = 0;
2942 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
2944 if (proc_parameter_file( para, fname, &outctrl, 0 ))
2945 print_status_key_not_created
2946 (get_parameter_value (para, pHANDLE));
2947 release_parameter_list( para );
2950 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
2951 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
2952 ; /* still the same file - ignore it */
2954 xfree( outctrl.pub.newfname );
2955 outctrl.pub.newfname = xstrdup( value );
2956 outctrl.use_files = 1;
2959 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
2960 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
2961 ; /* still the same file - ignore it */
2963 xfree( outctrl.sec.newfname );
2964 outctrl.sec.newfname = xstrdup( value );
2965 outctrl.use_files = 1;
2969 log_info("skipping control `%s' (%s)\n", keyword, value );
2976 if( !(p = strchr( p, ':' )) || p == keyword ) {
2977 err = "missing colon";
2982 for( ; isspace(*(byte*)p); p++ )
2985 err = "missing argument";
2989 trim_trailing_ws( value, strlen(value) );
2991 for(i=0; keywords[i].name; i++ ) {
2992 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
2995 if( !keywords[i].name ) {
2996 err = "unknown keyword";
2999 if( keywords[i].key != pKEYTYPE && !para ) {
3000 err = "parameter block does not start with \"Key-Type\"";
3004 if( keywords[i].key == pKEYTYPE && para ) {
3006 if (proc_parameter_file( para, fname, &outctrl, 0 ))
3007 print_status_key_not_created
3008 (get_parameter_value (para, pHANDLE));
3009 release_parameter_list( para );
3013 for( r = para; r; r = r->next ) {
3014 if( r->key == keywords[i].key )
3018 err = "duplicate keyword";
3022 r = xmalloc_clear( sizeof *r + strlen( value ) );
3024 r->key = keywords[i].key;
3025 strcpy( r->u.value, value );
3030 log_error("%s:%d: %s\n", fname, lnr, err );
3031 else if( iobuf_error (fp) ) {
3032 log_error("%s:%d: read error\n", fname, lnr);
3036 if (proc_parameter_file( para, fname, &outctrl, 0 ))
3037 print_status_key_not_created (get_parameter_value (para, pHANDLE));
3040 if( outctrl.use_files ) { /* close open streams */
3041 iobuf_close( outctrl.pub.stream );
3042 iobuf_close( outctrl.sec.stream );
3044 /* Must invalidate that ugly cache to actually close it. */
3045 if (outctrl.pub.fname)
3046 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.pub.fname);
3047 if (outctrl.sec.fname)
3048 iobuf_ioctl (NULL, 2, 0, (char*)outctrl.sec.fname);
3050 xfree( outctrl.pub.fname );
3051 xfree( outctrl.pub.newfname );
3052 xfree( outctrl.sec.fname );
3053 xfree( outctrl.sec.newfname );
3056 release_parameter_list( para );
3058 release_armor_context (outctrl.pub.afx);
3059 release_armor_context (outctrl.sec.afx);
3064 * Generate a keypair (fname is only used in batch mode) If
3065 * CARD_SERIALNO is not NULL the function will create the keys on an
3066 * OpenPGP Card. If BACKUP_ENCRYPTION_DIR has been set and
3067 * CARD_SERIALNO is NOT NULL, the encryption key for the card gets
3068 * generate in software, imported to the card and a backup file
3069 * written to directory given by this argument .
3072 generate_keypair (const char *fname, const char *card_serialno,
3073 const char *backup_encryption_dir)
3083 struct para_data_s *para = NULL;
3084 struct para_data_s *r;
3085 struct output_control_s outctrl;
3088 memset( &outctrl, 0, sizeof( outctrl ) );
3090 if (opt.batch && card_serialno)
3092 /* We don't yet support unattended key generation. */
3093 log_error (_("can't do this in batch mode\n"));
3099 read_parameter_file( fname );
3105 #ifdef ENABLE_CARD_SUPPORT
3106 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
3108 strcpy( r->u.value, card_serialno);
3112 algo = PUBKEY_ALGO_RSA;
3114 r = xcalloc (1, sizeof *r + 20 );
3116 sprintf( r->u.value, "%d", algo );
3119 r = xcalloc (1, sizeof *r + 20 );
3121 strcpy (r->u.value, "sign");
3125 r = xcalloc (1, sizeof *r + 20 );
3126 r->key = pSUBKEYTYPE;
3127 sprintf( r->u.value, "%d", algo );
3130 r = xcalloc (1, sizeof *r + 20 );
3131 r->key = pSUBKEYUSAGE;
3132 strcpy (r->u.value, "encrypt");
3136 r = xcalloc (1, sizeof *r + 20 );
3137 r->key = pAUTHKEYTYPE;
3138 sprintf( r->u.value, "%d", algo );
3142 if (backup_encryption_dir)
3144 r = xcalloc (1, sizeof *r + strlen (backup_encryption_dir) );
3145 r->key = pBACKUPENCDIR;
3146 strcpy (r->u.value, backup_encryption_dir);
3150 #endif /*ENABLE_CARD_SUPPORT*/
3156 algo = ask_algo (0, &subkey_algo, &use);
3159 /* Create primary and subkey at once. */
3161 r = xmalloc_clear( sizeof *r + 20 );
3163 sprintf( r->u.value, "%d", algo );
3166 nbits = ask_keysize (algo, 0);
3167 r = xmalloc_clear( sizeof *r + 20 );
3168 r->key = pKEYLENGTH;
3169 sprintf( r->u.value, "%u", nbits);
3172 r = xmalloc_clear( sizeof *r + 20 );
3174 strcpy( r->u.value, "sign" );
3178 r = xmalloc_clear( sizeof *r + 20 );
3179 r->key = pSUBKEYTYPE;
3180 sprintf( r->u.value, "%d", subkey_algo);
3183 r = xmalloc_clear( sizeof *r + 20 );
3184 r->key = pSUBKEYUSAGE;
3185 strcpy( r->u.value, "encrypt" );
3191 r = xmalloc_clear( sizeof *r + 20 );
3193 sprintf( r->u.value, "%d", algo );
3199 r = xmalloc_clear( sizeof *r + 25 );
3201 sprintf( r->u.value, "%s%s%s",
3202 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3203 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3204 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3211 nbits = ask_keysize (both? subkey_algo : algo, nbits);
3212 r = xmalloc_clear( sizeof *r + 20 );
3213 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3214 sprintf( r->u.value, "%u", nbits);
3219 expire = ask_expire_interval(0,NULL);
3220 r = xmalloc_clear( sizeof *r + 20 );
3221 r->key = pKEYEXPIRE;
3222 r->u.expire = expire;
3225 r = xmalloc_clear( sizeof *r + 20 );
3226 r->key = pSUBKEYEXPIRE;
3227 r->u.expire = expire;
3231 uid = ask_user_id (0, NULL);
3234 log_error(_("Key generation canceled.\n"));
3235 release_parameter_list( para );
3238 r = xmalloc_clear( sizeof *r + strlen(uid) );
3240 strcpy( r->u.value, uid );
3245 dek = card_serialno? NULL : do_ask_passphrase (&s2k, 0, &canceled);
3248 r = xmalloc_clear( sizeof *r );
3249 r->key = pPASSPHRASE_DEK;
3253 r = xmalloc_clear( sizeof *r );
3254 r->key = pPASSPHRASE_S2K;
3261 log_error (_("Key generation canceled.\n"));
3263 proc_parameter_file( para, "[internal]", &outctrl, !!card_serialno);
3264 release_parameter_list( para );
3268 #ifdef ENABLE_CARD_SUPPORT
3269 /* Generate a raw key and return it as a secret key packet. The
3270 function will ask for the passphrase and return a protected as well
3271 as an unprotected copy of a new secret key packet. 0 is returned
3272 on success and the caller must then free the returned values. */
3274 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3275 PKT_secret_key **r_sk_unprotected,
3276 PKT_secret_key **r_sk_protected)
3280 STRING2KEY *s2k = NULL;
3281 PKT_secret_key *sk = NULL;
3283 size_t nskey, npkey;
3284 gcry_sexp_t s_parms, s_key;
3287 npkey = pubkey_get_npkey (algo);
3288 nskey = pubkey_get_nskey (algo);
3289 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3294 log_info (_("keysize invalid; using %u bits\n"), nbits );
3299 nbits = ((nbits + 31) / 32) * 32;
3300 log_info(_("keysize rounded up to %u bits\n"), nbits );
3303 dek = do_ask_passphrase (&s2k, 1, &canceled);
3306 rc = gpg_error (GPG_ERR_CANCELED);
3310 sk = xmalloc_clear (sizeof *sk);
3311 sk->timestamp = created_at;
3313 sk->pubkey_algo = algo;
3315 if ( !is_RSA (algo) )
3317 log_error ("only RSA is supported for offline generated keys\n");
3318 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3321 rc = gcry_sexp_build (&s_parms, NULL,
3322 "(genkey(rsa(nbits %d)))",
3325 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3326 rc = gcry_pk_genkey (&s_key, s_parms);
3327 gcry_sexp_release (s_parms);
3330 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3333 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3334 gcry_sexp_release (s_key);
3337 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3341 for (i=npkey; i < nskey; i++)
3342 sk->csum += checksum_mpi (sk->skey[i]);
3344 if (r_sk_unprotected)
3345 *r_sk_unprotected = copy_secret_key (NULL, sk);
3347 rc = genhelp_protect (dek, s2k, sk);
3353 *r_sk_protected = sk;
3359 free_secret_key (sk);
3364 #endif /* ENABLE_CARD_SUPPORT */
3366 /* Create and delete a dummy packet to start off a list of kbnodes. */
3368 start_tree(KBNODE *tree)
3372 pkt=xmalloc_clear(sizeof(*pkt));
3373 pkt->pkttype=PKT_NONE;
3374 *tree=new_kbnode(pkt);
3375 delete_kbnode(*tree);
3380 do_generate_keypair (struct para_data_s *para,
3381 struct output_control_s *outctrl, int card)
3383 KBNODE pub_root = NULL;
3384 KBNODE sec_root = NULL;
3385 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3387 struct revocation_key *revkey;
3392 if( outctrl->dryrun )
3394 log_info("dry-run mode - key generation skipped\n");
3398 if ( outctrl->use_files )
3400 if ( outctrl->pub.newfname )
3402 iobuf_close(outctrl->pub.stream);
3403 outctrl->pub.stream = NULL;
3404 if (outctrl->pub.fname)
3405 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->pub.fname);
3406 xfree( outctrl->pub.fname );
3407 outctrl->pub.fname = outctrl->pub.newfname;
3408 outctrl->pub.newfname = NULL;
3410 if (is_secured_filename (outctrl->pub.fname) )
3412 outctrl->pub.stream = NULL;
3416 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
3417 if (!outctrl->pub.stream)
3419 log_error(_("can't create `%s': %s\n"), outctrl->pub.newfname,
3425 outctrl->pub.afx->what = 1;
3426 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
3429 if (outctrl->sec.newfname)
3433 iobuf_close(outctrl->sec.stream);
3434 outctrl->sec.stream = NULL;
3435 if (outctrl->sec.fname)
3436 iobuf_ioctl (NULL, 2, 0, (char*)outctrl->sec.fname);
3437 xfree( outctrl->sec.fname );
3438 outctrl->sec.fname = outctrl->sec.newfname;
3439 outctrl->sec.newfname = NULL;
3441 oldmask = umask (077);
3442 if (is_secured_filename (outctrl->sec.fname) )
3444 outctrl->sec.stream = NULL;
3448 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
3450 if (!outctrl->sec.stream)
3452 log_error(_("can't create `%s': %s\n"), outctrl->sec.newfname,
3458 outctrl->sec.afx->what = 5;
3459 push_armor_filter (outctrl->sec.afx, outctrl->sec.stream);
3462 assert( outctrl->pub.stream );
3463 assert( outctrl->sec.stream );
3466 log_info (_("writing public key to `%s'\n"), outctrl->pub.fname );
3468 log_info (_("writing secret key stub to `%s'\n"),
3469 outctrl->sec.fname);
3471 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
3476 /* We create the packets as a tree of kbnodes. Because the
3477 structure we create is known in advance we simply generate a
3478 linked list. The first packet is a dummy packet which we flag as
3479 deleted. The very first packet must always be a KEY packet. */
3481 start_tree (&pub_root);
3482 start_tree (&sec_root);
3484 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
3486 timestamp = make_timestamp ();
3488 /* Note that, depending on the backend (i.e. the used scdaemon
3489 version), the card key generation may update TIMESTAMP for each
3490 key. Thus we need to pass TIMESTAMP to all signing function to
3491 make sure that the binding signature is done using the timestamp
3492 of the corresponding (sub)key and not that of the primary key.
3493 An alternative implementation could tell the signing function the
3494 node of the subkey but that is more work than just to pass the
3495 current timestamp. */
3499 rc = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
3500 get_parameter_uint( para, pKEYLENGTH ),
3502 get_parameter_dek( para, pPASSPHRASE_DEK ),
3503 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3506 get_parameter_u32( para, pKEYEXPIRE ), 0 );
3510 rc = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root, sec_root, NULL,
3512 get_parameter_u32 (para, pKEYEXPIRE), para);
3515 pri_sk = sec_root->next->pkt->pkt.secret_key;
3520 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
3522 rc = write_direct_sig (pub_root, pub_root, pri_sk, revkey, timestamp);
3524 rc = write_direct_sig (sec_root, pub_root, pri_sk, revkey, timestamp);
3527 if( !rc && (s=get_parameter_value(para, pUSERID)) )
3529 write_uid (pub_root, s );
3530 write_uid (sec_root, s );
3532 rc = write_selfsigs (sec_root, pub_root, pri_sk,
3533 get_parameter_uint (para, pKEYUSAGE), timestamp);
3536 /* Write the auth key to the card before the encryption key. This
3537 is a partial workaround for a PGP bug (as of this writing, all
3538 versions including 8.1), that causes it to try and encrypt to
3539 the most recent subkey regardless of whether that subkey is
3540 actually an encryption type. In this case, the auth key is an
3541 RSA key so it succeeds. */
3543 if (!rc && card && get_parameter (para, pAUTHKEYTYPE))
3545 rc = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root, sec_root, NULL,
3547 get_parameter_u32 (para, pKEYEXPIRE), para);
3550 rc = write_keybinding (pub_root, pub_root, pri_sk, sub_sk,
3551 PUBKEY_USAGE_AUTH, timestamp);
3553 rc = write_keybinding (sec_root, pub_root, pri_sk, sub_sk,
3554 PUBKEY_USAGE_AUTH, timestamp);
3557 if( !rc && get_parameter( para, pSUBKEYTYPE ) )
3561 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE, NULL ),
3562 get_parameter_uint( para, pSUBKEYLENGTH ),
3564 get_parameter_dek( para, pPASSPHRASE_DEK ),
3565 get_parameter_s2k( para, pPASSPHRASE_S2K ),
3568 get_parameter_u32( para, pSUBKEYEXPIRE ), 1 );
3572 if ((s = get_parameter_value (para, pBACKUPENCDIR)))
3574 /* A backup of the encryption key has been requested.
3575 Generate the key in software and import it then to
3576 the card. Write a backup file. */
3577 rc = gen_card_key_with_backup (PUBKEY_ALGO_RSA, 2, 0,
3580 get_parameter_u32 (para,
3586 rc = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root, sec_root,
3589 get_parameter_u32 (para, pKEYEXPIRE), para);
3594 rc = write_keybinding(pub_root, pub_root, pri_sk, sub_sk,
3595 get_parameter_uint (para, pSUBKEYUSAGE),
3598 rc = write_keybinding(sec_root, pub_root, pri_sk, sub_sk,
3599 get_parameter_uint (para, pSUBKEYUSAGE),
3604 if (!rc && outctrl->use_files) /* Direct write to specified files. */
3606 rc = write_keyblock( outctrl->pub.stream, pub_root );
3608 log_error ("can't write public key: %s\n", g10_errstr(rc) );
3611 rc = write_keyblock( outctrl->sec.stream, sec_root );
3613 log_error ("can't write secret key: %s\n", g10_errstr(rc) );
3616 else if (!rc) /* Write to the standard keyrings. */
3618 KEYDB_HANDLE pub_hd = keydb_new (0);
3619 KEYDB_HANDLE sec_hd = keydb_new (1);
3621 rc = keydb_locate_writable (pub_hd, NULL);
3623 log_error (_("no writable public keyring found: %s\n"),
3628 rc = keydb_locate_writable (sec_hd, NULL);
3630 log_error (_("no writable secret keyring found: %s\n"),
3634 if (!rc && opt.verbose)
3636 log_info (_("writing public key to `%s'\n"),
3637 keydb_get_resource_name (pub_hd));
3639 log_info (_("writing secret key stub to `%s'\n"),
3640 keydb_get_resource_name (sec_hd));
3642 log_info (_("writing secret key to `%s'\n"),
3643 keydb_get_resource_name (sec_hd));
3648 rc = keydb_insert_keyblock (pub_hd, pub_root);
3650 log_error (_("error writing public keyring `%s': %s\n"),
3651 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3656 rc = keydb_insert_keyblock (sec_hd, sec_root);
3658 log_error (_("error writing secret keyring `%s': %s\n"),
3659 keydb_get_resource_name (pub_hd), g10_errstr(rc));
3662 keydb_release (pub_hd);
3663 keydb_release (sec_hd);
3670 no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
3672 && get_parameter_uint (para, pKEYUSAGE)
3673 && !((get_parameter_uint (para, pKEYUSAGE)
3674 & PUBKEY_USAGE_ENC)) );
3676 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3678 keyid_from_pk(pk,pk->main_keyid);
3679 register_trusted_keyid(pk->main_keyid);
3681 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
3682 | TRUST_ULTIMATE ));
3686 tty_printf (_("public and secret key created and signed.\n") );
3688 list_keyblock(pub_root,0,1,NULL);
3693 && (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
3695 && !get_parameter (para, pSUBKEYTYPE) )
3697 tty_printf(_("Note that this key cannot be used for "
3698 "encryption. You may want to use\n"
3699 "the command \"--edit-key\" to generate a "
3700 "subkey for this purpose.\n") );
3708 log_error ("key generation failed: %s\n", g10_errstr(rc) );
3710 tty_printf (_("Key generation failed: %s\n"), g10_errstr(rc) );
3711 write_status_error (card? "card_key_generate":"key_generate", rc);
3712 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
3716 PKT_public_key *pk = find_kbnode (pub_root,
3717 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
3718 print_status_key_created (did_sub? 'B':'P', pk,
3719 get_parameter_value (para, pHANDLE));
3721 release_kbnode( pub_root );
3722 release_kbnode( sec_root );
3724 if (pri_sk && !card) /* The unprotected secret key unless we */
3725 free_secret_key (pri_sk); /* have a shallow copy in card mode. */
3727 free_secret_key(sub_sk);
3731 /* Add a new subkey to an existing key. Returns true if a new key has
3732 been generated and put into the keyblocks. */
3734 generate_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock)
3738 PKT_secret_key *pri_sk = NULL, *sub_sk = NULL;
3743 char *passphrase = NULL;
3745 STRING2KEY *s2k = NULL;
3750 /* Break out the primary secret key. */
3751 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
3754 log_error ("Oops; secret key not found anymore!\n");
3758 /* Make a copy of the sk to keep the protected one in the keyblock. */
3759 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3761 cur_time = make_timestamp();
3763 if (pri_sk->timestamp > cur_time)
3765 ulong d = pri_sk->timestamp - cur_time;
3766 log_info ( d==1 ? _("key has been created %lu second "
3767 "in future (time warp or clock problem)\n")
3768 : _("key has been created %lu seconds "
3769 "in future (time warp or clock problem)\n"), d );
3770 if (!opt.ignore_time_conflict)
3772 rc = G10ERR_TIME_CONFLICT;
3777 if (pri_sk->version < 4)
3779 log_info (_("NOTE: creating subkeys for v3 keys "
3780 "is not OpenPGP compliant\n"));
3784 if (pri_sk->is_protected && pri_sk->protect.s2k.mode == 1001)
3786 tty_printf (_("Secret parts of primary key are not available.\n"));
3787 rc = G10ERR_NO_SECKEY;
3792 /* Unprotect to get the passphrase. */
3793 switch (is_secret_key_protected (pri_sk) )
3796 rc = G10ERR_PUBKEY_ALGO;
3799 tty_printf (_("This key is not protected.\n"));
3802 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
3806 tty_printf (_("Key is protected.\n"));
3807 rc = check_secret_key ( pri_sk, 0 );
3809 passphrase = get_last_passphrase();
3815 algo = ask_algo (1, NULL, &use);
3817 nbits = ask_keysize (algo, 0);
3818 expire = ask_expire_interval (0, NULL);
3819 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
3820 _("Really create? (y/N) ")))
3825 dek = do_ask_passphrase (&s2k, 0, &canceled);
3826 else if (passphrase)
3828 s2k = xmalloc_secure ( sizeof *s2k );
3829 s2k->mode = opt.s2k_mode;
3830 s2k->hash_algo = S2K_DIGEST_ALGO;
3831 set_next_passphrase ( passphrase );
3832 dek = passphrase_to_dek (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
3837 rc = GPG_ERR_CANCELED;
3840 rc = do_create (algo, nbits, pub_keyblock, sec_keyblock,
3841 dek, s2k, &sub_sk, cur_time, expire, 1 );
3844 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3847 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3852 write_status_text (STATUS_KEY_CREATED, "S");
3857 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3860 /* Release the copy of the (now unprotected) secret keys. */
3862 free_secret_key (pri_sk);
3864 free_secret_key (sub_sk);
3865 set_next_passphrase (NULL);
3870 #ifdef ENABLE_CARD_SUPPORT
3871 /* Generate a subkey on a card. */
3873 generate_card_subkeypair (KBNODE pub_keyblock, KBNODE sec_keyblock,
3874 int keyno, const char *serialno)
3878 PKT_secret_key *pri_sk = NULL, *sub_sk;
3882 char *passphrase = NULL;
3884 struct para_data_s *para = NULL;
3886 assert (keyno >= 1 && keyno <= 3);
3888 para = xcalloc (1, sizeof *para + strlen (serialno) );
3889 para->key = pSERIALNO;
3890 strcpy (para->u.value, serialno);
3892 /* Break out the primary secret key */
3893 node = find_kbnode (sec_keyblock, PKT_SECRET_KEY);
3896 log_error("Oops; secret key not found anymore!\n");
3900 /* Make a copy of the sk to keep the protected one in the keyblock */
3901 pri_sk = copy_secret_key (NULL, node->pkt->pkt.secret_key);
3903 cur_time = make_timestamp();
3904 if (pri_sk->timestamp > cur_time)
3906 ulong d = pri_sk->timestamp - cur_time;
3907 log_info (d==1 ? _("key has been created %lu second "
3908 "in future (time warp or clock problem)\n")
3909 : _("key has been created %lu seconds "
3910 "in future (time warp or clock problem)\n"), d );
3911 if (!opt.ignore_time_conflict)
3913 rc = G10ERR_TIME_CONFLICT;
3918 if (pri_sk->version < 4)
3920 log_info (_("NOTE: creating subkeys for v3 keys "
3921 "is not OpenPGP compliant\n"));
3925 /* Unprotect to get the passphrase. */
3926 switch( is_secret_key_protected (pri_sk) )
3929 rc = G10ERR_PUBKEY_ALGO;
3932 tty_printf("This key is not protected.\n");
3935 tty_printf("Key is protected.\n");
3936 rc = check_secret_key( pri_sk, 0 );
3938 passphrase = get_last_passphrase();
3944 algo = PUBKEY_ALGO_RSA;
3945 expire = ask_expire_interval (0,NULL);
3947 use = PUBKEY_USAGE_SIG;
3948 else if (keyno == 2)
3949 use = PUBKEY_USAGE_ENC;
3951 use = PUBKEY_USAGE_AUTH;
3952 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
3953 _("Really create? (y/N) ")))
3957 set_next_passphrase (passphrase);
3959 /* Note, that depending on the backend, the card key generation may
3961 rc = gen_card_key (algo, keyno, 0, pub_keyblock, sec_keyblock,
3962 &sub_sk, &cur_time, expire, para);
3964 rc = write_keybinding (pub_keyblock, pub_keyblock, pri_sk, sub_sk,
3967 rc = write_keybinding (sec_keyblock, pub_keyblock, pri_sk, sub_sk,
3972 write_status_text (STATUS_KEY_CREATED, "S");
3977 log_error (_("Key generation failed: %s\n"), g10_errstr(rc) );
3979 /* Release the copy of the (now unprotected) secret keys. */
3981 free_secret_key (pri_sk);
3982 set_next_passphrase( NULL );
3983 release_parameter_list (para);
3986 #endif /* !ENABLE_CARD_SUPPORT */
3990 * Write a keyblock to an output stream
3993 write_keyblock( IOBUF out, KBNODE node )
3995 for( ; node ; node = node->next )
3997 if(!is_deleted_kbnode(node))
3999 int rc = build_packet( out, node->pkt );
4002 log_error("build_packet(%d) failed: %s\n",
4003 node->pkt->pkttype, g10_errstr(rc) );
4013 /* Note that timestamp is an in/out arg. */
4015 gen_card_key (int algo, int keyno, int is_primary,
4016 KBNODE pub_root, KBNODE sec_root, PKT_secret_key **ret_sk,
4017 u32 *timestamp, u32 expireval, struct para_data_s *para)
4019 #ifdef ENABLE_CARD_SUPPORT
4022 struct agent_card_genkey_s info;
4027 assert (algo == PUBKEY_ALGO_RSA);
4029 /* Fixme: We don't have the serialnumber available, thus passing NULL. */
4030 rc = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
4031 /* if (gpg_err_code (rc) == GPG_ERR_EEXIST) */
4033 /* tty_printf ("\n"); */
4034 /* log_error ("WARNING: key does already exists!\n"); */
4035 /* tty_printf ("\n"); */
4036 /* if ( cpr_get_answer_is_yes( "keygen.card.replace_key", */
4037 /* _("Replace existing key? "))) */
4038 /* rc = agent_scd_genkey (&info, keyno, 1); */
4043 log_error ("key generation failed: %s\n", gpg_strerror (rc));
4046 if ( !info.n || !info.e )
4048 log_error ("communication error with SCD\n");
4049 gcry_mpi_release (info.n);
4050 gcry_mpi_release (info.e);
4051 return gpg_error (GPG_ERR_GENERAL);
4054 if (*timestamp != info.created_at)
4055 log_info ("Note that the key does not use the suggested creation date\n");
4056 *timestamp = info.created_at;
4058 pk = xcalloc (1, sizeof *pk );
4059 sk = xcalloc (1, sizeof *sk );
4060 sk->timestamp = pk->timestamp = info.created_at;
4061 sk->version = pk->version = 4;
4063 sk->expiredate = pk->expiredate = pk->timestamp + expireval;
4064 sk->pubkey_algo = pk->pubkey_algo = algo;
4065 pk->pkey[0] = info.n;
4066 pk->pkey[1] = info.e;
4067 sk->skey[0] = gcry_mpi_copy (pk->pkey[0]);
4068 sk->skey[1] = gcry_mpi_copy (pk->pkey[1]);
4069 sk->skey[2] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4070 sk->is_protected = 1;
4071 sk->protect.s2k.mode = 1002;
4072 s = get_parameter_value (para, pSERIALNO);
4075 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4076 sk->protect.ivlen++, s += 2)
4077 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4083 pkt = xcalloc (1,sizeof *pkt);
4084 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4085 pkt->pkt.public_key = pk;
4086 add_kbnode(pub_root, new_kbnode( pkt ));
4088 pkt = xcalloc (1,sizeof *pkt);
4089 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4090 pkt->pkt.secret_key = sk;
4091 add_kbnode(sec_root, new_kbnode( pkt ));
4096 #endif /*!ENABLE_CARD_SUPPORT*/
4102 gen_card_key_with_backup (int algo, int keyno, int is_primary,
4103 KBNODE pub_root, KBNODE sec_root,
4105 u32 expireval, struct para_data_s *para,
4106 const char *backup_dir)
4108 #ifdef ENABLE_CARD_SUPPORT
4112 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
4118 /* Get the size of the key directly from the card. */
4120 struct agent_card_info_s info;
4122 memset (&info, 0, sizeof info);
4123 if (!agent_scd_getattr ("KEY-ATTR", &info)
4124 && info.key_attr[1].algo)
4125 nbits = info.key_attr[1].nbits;
4127 nbits = 1024; /* All pre-v2.0 cards. */
4128 agent_release_card_info (&info);
4131 /* Create a key of this size in memory. */
4132 rc = generate_raw_key (algo, nbits, timestamp,
4133 &sk_unprotected, &sk_protected);
4137 /* Store the key to the card. */
4138 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
4141 log_error (_("storing key onto card failed: %s\n"), g10_errstr (rc));
4142 free_secret_key (sk_unprotected);
4143 free_secret_key (sk_protected);
4144 write_status_error ("save_key_to_card", rc);
4148 /* Get rid of the secret key parameters and store the serial numer. */
4149 sk = sk_unprotected;
4150 n = pubkey_get_nskey (sk->pubkey_algo);
4151 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
4153 gcry_mpi_release (sk->skey[i]);
4156 i = pubkey_get_npkey (sk->pubkey_algo);
4157 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4158 sk->is_protected = 1;
4159 sk->protect.s2k.mode = 1002;
4160 s = get_parameter_value (para, pSERIALNO);
4162 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4163 sk->protect.ivlen++, s += 2)
4164 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4166 /* Now write the *protected* secret key to the file. */
4168 char name_buffer[50];
4173 keyid_from_sk (sk, NULL);
4174 snprintf (name_buffer, sizeof name_buffer, "sk_%08lX%08lX.gpg",
4175 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
4177 fname = make_filename (backup_dir, name_buffer, NULL);
4178 oldmask = umask (077);
4179 if (is_secured_filename (fname))
4185 fp = iobuf_create (fname);
4189 rc = gpg_error_from_syserror ();
4190 log_error (_("can't create backup file `%s': %s\n"),
4191 fname, strerror(errno) );
4193 free_secret_key (sk_unprotected);
4194 free_secret_key (sk_protected);
4198 pkt = xcalloc (1, sizeof *pkt);
4199 pkt->pkttype = PKT_SECRET_KEY;
4200 pkt->pkt.secret_key = sk_protected;
4201 sk_protected = NULL;
4203 rc = build_packet (fp, pkt);
4206 log_error("build packet failed: %s\n", g10_errstr(rc) );
4211 unsigned char array[MAX_FINGERPRINT_LEN];
4215 iobuf_ioctl (NULL, 2, 0, (char*)fname);
4216 log_info (_("NOTE: backup of card key saved to `%s'\n"), fname);
4218 fingerprint_from_sk (sk, array, &n);
4219 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4220 for (i=0; i < n ; i++, p += 2)
4221 sprintf (p, "%02X", array[i]);
4225 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4227 fname, strlen (fname),
4236 free_secret_key (sk_unprotected);
4241 /* Create the public key from the secret key. */
4242 pk = xcalloc (1, sizeof *pk );
4243 pk->timestamp = sk->timestamp;
4244 pk->version = sk->version;
4246 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4247 pk->pubkey_algo = sk->pubkey_algo;
4248 n = pubkey_get_npkey (sk->pubkey_algo);
4249 for (i=0; i < n; i++)
4250 pk->pkey[i] = mpi_copy (sk->skey[i]);
4252 /* Build packets and add them to the node lists. */
4253 pkt = xcalloc (1,sizeof *pkt);
4254 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4255 pkt->pkt.public_key = pk;
4256 add_kbnode(pub_root, new_kbnode( pkt ));
4258 pkt = xcalloc (1,sizeof *pkt);
4259 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4260 pkt->pkt.secret_key = sk;
4261 add_kbnode(sec_root, new_kbnode( pkt ));
4266 #endif /*!ENABLE_CARD_SUPPORT*/
4270 #ifdef ENABLE_CARD_SUPPORT
4272 save_unprotected_key_to_card (PKT_secret_key *sk, int keyno)
4275 unsigned char *rsa_n = NULL;
4276 unsigned char *rsa_e = NULL;
4277 unsigned char *rsa_p = NULL;
4278 unsigned char *rsa_q = NULL;
4279 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4280 unsigned char *sexp = NULL;
4282 char numbuf[55], numbuf2[50];
4284 assert (is_RSA (sk->pubkey_algo));
4285 assert (!sk->is_protected);
4287 /* Copy the parameters into straight buffers. */
4288 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4289 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4290 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4291 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4292 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4294 rc = G10ERR_INV_ARG;
4298 /* Put the key into an S-expression. */
4299 sexp = p = xmalloc_secure (30
4300 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4301 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4303 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4304 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4305 p = stpcpy (p, numbuf);
4306 memcpy (p, rsa_n, rsa_n_len);
4309 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4310 p = stpcpy (p, numbuf);
4311 memcpy (p, rsa_e, rsa_e_len);
4314 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4315 p = stpcpy (p, numbuf);
4316 memcpy (p, rsa_p, rsa_p_len);
4319 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4320 p = stpcpy (p, numbuf);
4321 memcpy (p, rsa_q, rsa_q_len);
4324 p = stpcpy (p,"))(10:created-at");
4325 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4326 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4327 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4329 /* Fixme: Unfortunately we don't have the serialnumber available -
4330 thus we can't pass&n